toolchain.py 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  1. # Copyright (c) 2012 The Chromium OS Authors.
  2. #
  3. # SPDX-License-Identifier: GPL-2.0+
  4. #
  5. import re
  6. import glob
  7. import os
  8. import bsettings
  9. import command
  10. class Toolchain:
  11. """A single toolchain
  12. Public members:
  13. gcc: Full path to C compiler
  14. path: Directory path containing C compiler
  15. cross: Cross compile string, e.g. 'arm-linux-'
  16. arch: Architecture of toolchain as determined from the first
  17. component of the filename. E.g. arm-linux-gcc becomes arm
  18. """
  19. def __init__(self, fname, test, verbose=False):
  20. """Create a new toolchain object.
  21. Args:
  22. fname: Filename of the gcc component
  23. test: True to run the toolchain to test it
  24. """
  25. self.gcc = fname
  26. self.path = os.path.dirname(fname)
  27. self.cross = os.path.basename(fname)[:-3]
  28. pos = self.cross.find('-')
  29. self.arch = self.cross[:pos] if pos != -1 else 'sandbox'
  30. env = self.MakeEnvironment()
  31. # As a basic sanity check, run the C compiler with --version
  32. cmd = [fname, '--version']
  33. if test:
  34. result = command.RunPipe([cmd], capture=True, env=env,
  35. raise_on_error=False)
  36. self.ok = result.return_code == 0
  37. if verbose:
  38. print 'Tool chain test: ',
  39. if self.ok:
  40. print 'OK'
  41. else:
  42. print 'BAD'
  43. print 'Command: ', cmd
  44. print result.stdout
  45. print result.stderr
  46. else:
  47. self.ok = True
  48. self.priority = self.GetPriority(fname)
  49. def GetPriority(self, fname):
  50. """Return the priority of the toolchain.
  51. Toolchains are ranked according to their suitability by their
  52. filename prefix.
  53. Args:
  54. fname: Filename of toolchain
  55. Returns:
  56. Priority of toolchain, 0=highest, 20=lowest.
  57. """
  58. priority_list = ['-elf', '-unknown-linux-gnu', '-linux', '-elf',
  59. '-none-linux-gnueabi', '-uclinux', '-none-eabi',
  60. '-gentoo-linux-gnu', '-linux-gnueabi', '-le-linux', '-uclinux']
  61. for prio in range(len(priority_list)):
  62. if priority_list[prio] in fname:
  63. return prio
  64. return prio
  65. def MakeEnvironment(self):
  66. """Returns an environment for using the toolchain.
  67. Thie takes the current environment, adds CROSS_COMPILE and
  68. augments PATH so that the toolchain will operate correctly.
  69. """
  70. env = dict(os.environ)
  71. env['CROSS_COMPILE'] = self.cross
  72. env['PATH'] += (':' + self.path)
  73. return env
  74. class Toolchains:
  75. """Manage a list of toolchains for building U-Boot
  76. We select one toolchain for each architecture type
  77. Public members:
  78. toolchains: Dict of Toolchain objects, keyed by architecture name
  79. paths: List of paths to check for toolchains (may contain wildcards)
  80. """
  81. def __init__(self):
  82. self.toolchains = {}
  83. self.paths = []
  84. toolchains = bsettings.GetItems('toolchain')
  85. if not toolchains:
  86. print ("Warning: No tool chains - please add a [toolchain] section"
  87. " to your buildman config file %s. See README for details" %
  88. config_fname)
  89. for name, value in toolchains:
  90. if '*' in value:
  91. self.paths += glob.glob(value)
  92. else:
  93. self.paths.append(value)
  94. self._make_flags = dict(bsettings.GetItems('make-flags'))
  95. def Add(self, fname, test=True, verbose=False):
  96. """Add a toolchain to our list
  97. We select the given toolchain as our preferred one for its
  98. architecture if it is a higher priority than the others.
  99. Args:
  100. fname: Filename of toolchain's gcc driver
  101. test: True to run the toolchain to test it
  102. """
  103. toolchain = Toolchain(fname, test, verbose)
  104. add_it = toolchain.ok
  105. if toolchain.arch in self.toolchains:
  106. add_it = (toolchain.priority <
  107. self.toolchains[toolchain.arch].priority)
  108. if add_it:
  109. self.toolchains[toolchain.arch] = toolchain
  110. def Scan(self, verbose):
  111. """Scan for available toolchains and select the best for each arch.
  112. We look for all the toolchains we can file, figure out the
  113. architecture for each, and whether it works. Then we select the
  114. highest priority toolchain for each arch.
  115. Args:
  116. verbose: True to print out progress information
  117. """
  118. if verbose: print 'Scanning for tool chains'
  119. for path in self.paths:
  120. if verbose: print " - scanning path '%s'" % path
  121. for subdir in ['.', 'bin', 'usr/bin']:
  122. dirname = os.path.join(path, subdir)
  123. if verbose: print " - looking in '%s'" % dirname
  124. for fname in glob.glob(dirname + '/*gcc'):
  125. if verbose: print " - found '%s'" % fname
  126. self.Add(fname, True, verbose)
  127. def List(self):
  128. """List out the selected toolchains for each architecture"""
  129. print 'List of available toolchains (%d):' % len(self.toolchains)
  130. if len(self.toolchains):
  131. for key, value in sorted(self.toolchains.iteritems()):
  132. print '%-10s: %s' % (key, value.gcc)
  133. else:
  134. print 'None'
  135. def Select(self, arch):
  136. """Returns the toolchain for a given architecture
  137. Args:
  138. args: Name of architecture (e.g. 'arm', 'ppc_8xx')
  139. returns:
  140. toolchain object, or None if none found
  141. """
  142. for name, value in bsettings.GetItems('toolchain-alias'):
  143. if arch == name:
  144. arch = value
  145. if not arch in self.toolchains:
  146. raise ValueError, ("No tool chain found for arch '%s'" % arch)
  147. return self.toolchains[arch]
  148. def ResolveReferences(self, var_dict, args):
  149. """Resolve variable references in a string
  150. This converts ${blah} within the string to the value of blah.
  151. This function works recursively.
  152. Args:
  153. var_dict: Dictionary containing variables and their values
  154. args: String containing make arguments
  155. Returns:
  156. Resolved string
  157. >>> bsettings.Setup()
  158. >>> tcs = Toolchains()
  159. >>> tcs.Add('fred', False)
  160. >>> var_dict = {'oblique' : 'OBLIQUE', 'first' : 'fi${second}rst', \
  161. 'second' : '2nd'}
  162. >>> tcs.ResolveReferences(var_dict, 'this=${oblique}_set')
  163. 'this=OBLIQUE_set'
  164. >>> tcs.ResolveReferences(var_dict, 'this=${oblique}_set${first}nd')
  165. 'this=OBLIQUE_setfi2ndrstnd'
  166. """
  167. re_var = re.compile('(\$\{[a-z0-9A-Z]{1,}\})')
  168. while True:
  169. m = re_var.search(args)
  170. if not m:
  171. break
  172. lookup = m.group(0)[2:-1]
  173. value = var_dict.get(lookup, '')
  174. args = args[:m.start(0)] + value + args[m.end(0):]
  175. return args
  176. def GetMakeArguments(self, board):
  177. """Returns 'make' arguments for a given board
  178. The flags are in a section called 'make-flags'. Flags are named
  179. after the target they represent, for example snapper9260=TESTING=1
  180. will pass TESTING=1 to make when building the snapper9260 board.
  181. References to other boards can be added in the string also. For
  182. example:
  183. [make-flags]
  184. at91-boards=ENABLE_AT91_TEST=1
  185. snapper9260=${at91-boards} BUILD_TAG=442
  186. snapper9g45=${at91-boards} BUILD_TAG=443
  187. This will return 'ENABLE_AT91_TEST=1 BUILD_TAG=442' for snapper9260
  188. and 'ENABLE_AT91_TEST=1 BUILD_TAG=443' for snapper9g45.
  189. A special 'target' variable is set to the board target.
  190. Args:
  191. board: Board object for the board to check.
  192. Returns:
  193. 'make' flags for that board, or '' if none
  194. """
  195. self._make_flags['target'] = board.target
  196. arg_str = self.ResolveReferences(self._make_flags,
  197. self._make_flags.get(board.target, ''))
  198. args = arg_str.split(' ')
  199. i = 0
  200. while i < len(args):
  201. if not args[i]:
  202. del args[i]
  203. else:
  204. i += 1
  205. return args