toolchain.py 8.6 KB

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