toolchain.py 8.3 KB

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