toolchain.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608
  1. # SPDX-License-Identifier: GPL-2.0+
  2. # Copyright (c) 2012 The Chromium OS Authors.
  3. #
  4. import re
  5. import glob
  6. from html.parser import HTMLParser
  7. import os
  8. import sys
  9. import tempfile
  10. import urllib.request, urllib.error, urllib.parse
  11. import bsettings
  12. import command
  13. import terminal
  14. import tools
  15. (PRIORITY_FULL_PREFIX, PRIORITY_PREFIX_GCC, PRIORITY_PREFIX_GCC_PATH,
  16. PRIORITY_CALC) = list(range(4))
  17. # Simple class to collect links from a page
  18. class MyHTMLParser(HTMLParser):
  19. def __init__(self, arch):
  20. """Create a new parser
  21. After the parser runs, self.links will be set to a list of the links
  22. to .xz archives found in the page, and self.arch_link will be set to
  23. the one for the given architecture (or None if not found).
  24. Args:
  25. arch: Architecture to search for
  26. """
  27. HTMLParser.__init__(self)
  28. self.arch_link = None
  29. self.links = []
  30. self.re_arch = re.compile('[-_]%s-' % arch)
  31. def handle_starttag(self, tag, attrs):
  32. if tag == 'a':
  33. for tag, value in attrs:
  34. if tag == 'href':
  35. if value and value.endswith('.xz'):
  36. self.links.append(value)
  37. if self.re_arch.search(value):
  38. self.arch_link = value
  39. class Toolchain:
  40. """A single toolchain
  41. Public members:
  42. gcc: Full path to C compiler
  43. path: Directory path containing C compiler
  44. cross: Cross compile string, e.g. 'arm-linux-'
  45. arch: Architecture of toolchain as determined from the first
  46. component of the filename. E.g. arm-linux-gcc becomes arm
  47. priority: Toolchain priority (0=highest, 20=lowest)
  48. override_toolchain: Toolchain to use for sandbox, overriding the normal
  49. one
  50. """
  51. def __init__(self, fname, test, verbose=False, priority=PRIORITY_CALC,
  52. arch=None, override_toolchain=None):
  53. """Create a new toolchain object.
  54. Args:
  55. fname: Filename of the gcc component
  56. test: True to run the toolchain to test it
  57. verbose: True to print out the information
  58. priority: Priority to use for this toolchain, or PRIORITY_CALC to
  59. calculate it
  60. """
  61. self.gcc = fname
  62. self.path = os.path.dirname(fname)
  63. self.override_toolchain = override_toolchain
  64. # Find the CROSS_COMPILE prefix to use for U-Boot. For example,
  65. # 'arm-linux-gnueabihf-gcc' turns into 'arm-linux-gnueabihf-'.
  66. basename = os.path.basename(fname)
  67. pos = basename.rfind('-')
  68. self.cross = basename[:pos + 1] if pos != -1 else ''
  69. # The architecture is the first part of the name
  70. pos = self.cross.find('-')
  71. if arch:
  72. self.arch = arch
  73. else:
  74. self.arch = self.cross[:pos] if pos != -1 else 'sandbox'
  75. if self.arch == 'sandbox' and override_toolchain:
  76. self.gcc = override_toolchain
  77. env = self.MakeEnvironment(False)
  78. # As a basic sanity check, run the C compiler with --version
  79. cmd = [fname, '--version']
  80. if priority == PRIORITY_CALC:
  81. self.priority = self.GetPriority(fname)
  82. else:
  83. self.priority = priority
  84. if test:
  85. result = command.RunPipe([cmd], capture=True, env=env,
  86. raise_on_error=False)
  87. self.ok = result.return_code == 0
  88. if verbose:
  89. print('Tool chain test: ', end=' ')
  90. if self.ok:
  91. print("OK, arch='%s', priority %d" % (self.arch,
  92. self.priority))
  93. else:
  94. print('BAD')
  95. print('Command: ', cmd)
  96. print(result.stdout)
  97. print(result.stderr)
  98. else:
  99. self.ok = True
  100. def GetPriority(self, fname):
  101. """Return the priority of the toolchain.
  102. Toolchains are ranked according to their suitability by their
  103. filename prefix.
  104. Args:
  105. fname: Filename of toolchain
  106. Returns:
  107. Priority of toolchain, PRIORITY_CALC=highest, 20=lowest.
  108. """
  109. priority_list = ['-elf', '-unknown-linux-gnu', '-linux',
  110. '-none-linux-gnueabi', '-none-linux-gnueabihf', '-uclinux',
  111. '-none-eabi', '-gentoo-linux-gnu', '-linux-gnueabi',
  112. '-linux-gnueabihf', '-le-linux', '-uclinux']
  113. for prio in range(len(priority_list)):
  114. if priority_list[prio] in fname:
  115. return PRIORITY_CALC + prio
  116. return PRIORITY_CALC + prio
  117. def GetWrapper(self, show_warning=True):
  118. """Get toolchain wrapper from the setting file.
  119. """
  120. value = ''
  121. for name, value in bsettings.GetItems('toolchain-wrapper'):
  122. if not value:
  123. print("Warning: Wrapper not found")
  124. if value:
  125. value = value + ' '
  126. return value
  127. def MakeEnvironment(self, full_path):
  128. """Returns an environment for using the toolchain.
  129. Thie takes the current environment and adds CROSS_COMPILE so that
  130. the tool chain will operate correctly. This also disables localized
  131. output and possibly unicode encoded output of all build tools by
  132. adding LC_ALL=C.
  133. Args:
  134. full_path: Return the full path in CROSS_COMPILE and don't set
  135. PATH
  136. Returns:
  137. Dict containing the environemnt to use. This is based on the current
  138. environment, with changes as needed to CROSS_COMPILE, PATH and
  139. LC_ALL.
  140. """
  141. env = dict(os.environ)
  142. wrapper = self.GetWrapper()
  143. if self.override_toolchain:
  144. # We'll use MakeArgs() to provide this
  145. pass
  146. elif full_path:
  147. env['CROSS_COMPILE'] = wrapper + os.path.join(self.path, self.cross)
  148. else:
  149. env['CROSS_COMPILE'] = wrapper + self.cross
  150. env['PATH'] = self.path + ':' + env['PATH']
  151. env['LC_ALL'] = 'C'
  152. return env
  153. def MakeArgs(self):
  154. """Create the 'make' arguments for a toolchain
  155. This is only used when the toolchain is being overridden. Since the
  156. U-Boot Makefile sets CC and HOSTCC explicitly we cannot rely on the
  157. environment (and MakeEnvironment()) to override these values. This
  158. function returns the arguments to accomplish this.
  159. Returns:
  160. List of arguments to pass to 'make'
  161. """
  162. if self.override_toolchain:
  163. return ['HOSTCC=%s' % self.override_toolchain,
  164. 'CC=%s' % self.override_toolchain]
  165. return []
  166. class Toolchains:
  167. """Manage a list of toolchains for building U-Boot
  168. We select one toolchain for each architecture type
  169. Public members:
  170. toolchains: Dict of Toolchain objects, keyed by architecture name
  171. prefixes: Dict of prefixes to check, keyed by architecture. This can
  172. be a full path and toolchain prefix, for example
  173. {'x86', 'opt/i386-linux/bin/i386-linux-'}, or the name of
  174. something on the search path, for example
  175. {'arm', 'arm-linux-gnueabihf-'}. Wildcards are not supported.
  176. paths: List of paths to check for toolchains (may contain wildcards)
  177. """
  178. def __init__(self, override_toolchain=None):
  179. self.toolchains = {}
  180. self.prefixes = {}
  181. self.paths = []
  182. self.override_toolchain = override_toolchain
  183. self._make_flags = dict(bsettings.GetItems('make-flags'))
  184. def GetPathList(self, show_warning=True):
  185. """Get a list of available toolchain paths
  186. Args:
  187. show_warning: True to show a warning if there are no tool chains.
  188. Returns:
  189. List of strings, each a path to a toolchain mentioned in the
  190. [toolchain] section of the settings file.
  191. """
  192. toolchains = bsettings.GetItems('toolchain')
  193. if show_warning and not toolchains:
  194. print(("Warning: No tool chains. Please run 'buildman "
  195. "--fetch-arch all' to download all available toolchains, or "
  196. "add a [toolchain] section to your buildman config file "
  197. "%s. See README for details" %
  198. bsettings.config_fname))
  199. paths = []
  200. for name, value in toolchains:
  201. if '*' in value:
  202. paths += glob.glob(value)
  203. else:
  204. paths.append(value)
  205. return paths
  206. def GetSettings(self, show_warning=True):
  207. """Get toolchain settings from the settings file.
  208. Args:
  209. show_warning: True to show a warning if there are no tool chains.
  210. """
  211. self.prefixes = bsettings.GetItems('toolchain-prefix')
  212. self.paths += self.GetPathList(show_warning)
  213. def Add(self, fname, test=True, verbose=False, priority=PRIORITY_CALC,
  214. arch=None):
  215. """Add a toolchain to our list
  216. We select the given toolchain as our preferred one for its
  217. architecture if it is a higher priority than the others.
  218. Args:
  219. fname: Filename of toolchain's gcc driver
  220. test: True to run the toolchain to test it
  221. priority: Priority to use for this toolchain
  222. arch: Toolchain architecture, or None if not known
  223. """
  224. toolchain = Toolchain(fname, test, verbose, priority, arch,
  225. self.override_toolchain)
  226. add_it = toolchain.ok
  227. if toolchain.arch in self.toolchains:
  228. add_it = (toolchain.priority <
  229. self.toolchains[toolchain.arch].priority)
  230. if add_it:
  231. self.toolchains[toolchain.arch] = toolchain
  232. elif verbose:
  233. print(("Toolchain '%s' at priority %d will be ignored because "
  234. "another toolchain for arch '%s' has priority %d" %
  235. (toolchain.gcc, toolchain.priority, toolchain.arch,
  236. self.toolchains[toolchain.arch].priority)))
  237. def ScanPath(self, path, verbose):
  238. """Scan a path for a valid toolchain
  239. Args:
  240. path: Path to scan
  241. verbose: True to print out progress information
  242. Returns:
  243. Filename of C compiler if found, else None
  244. """
  245. fnames = []
  246. for subdir in ['.', 'bin', 'usr/bin']:
  247. dirname = os.path.join(path, subdir)
  248. if verbose: print(" - looking in '%s'" % dirname)
  249. for fname in glob.glob(dirname + '/*gcc'):
  250. if verbose: print(" - found '%s'" % fname)
  251. fnames.append(fname)
  252. return fnames
  253. def ScanPathEnv(self, fname):
  254. """Scan the PATH environment variable for a given filename.
  255. Args:
  256. fname: Filename to scan for
  257. Returns:
  258. List of matching pathanames, or [] if none
  259. """
  260. pathname_list = []
  261. for path in os.environ["PATH"].split(os.pathsep):
  262. path = path.strip('"')
  263. pathname = os.path.join(path, fname)
  264. if os.path.exists(pathname):
  265. pathname_list.append(pathname)
  266. return pathname_list
  267. def Scan(self, verbose):
  268. """Scan for available toolchains and select the best for each arch.
  269. We look for all the toolchains we can file, figure out the
  270. architecture for each, and whether it works. Then we select the
  271. highest priority toolchain for each arch.
  272. Args:
  273. verbose: True to print out progress information
  274. """
  275. if verbose: print('Scanning for tool chains')
  276. for name, value in self.prefixes:
  277. if verbose: print(" - scanning prefix '%s'" % value)
  278. if os.path.exists(value):
  279. self.Add(value, True, verbose, PRIORITY_FULL_PREFIX, name)
  280. continue
  281. fname = value + 'gcc'
  282. if os.path.exists(fname):
  283. self.Add(fname, True, verbose, PRIORITY_PREFIX_GCC, name)
  284. continue
  285. fname_list = self.ScanPathEnv(fname)
  286. for f in fname_list:
  287. self.Add(f, True, verbose, PRIORITY_PREFIX_GCC_PATH, name)
  288. if not fname_list:
  289. raise ValueError("No tool chain found for prefix '%s'" %
  290. value)
  291. for path in self.paths:
  292. if verbose: print(" - scanning path '%s'" % path)
  293. fnames = self.ScanPath(path, verbose)
  294. for fname in fnames:
  295. self.Add(fname, True, verbose)
  296. def List(self):
  297. """List out the selected toolchains for each architecture"""
  298. col = terminal.Color()
  299. print(col.Color(col.BLUE, 'List of available toolchains (%d):' %
  300. len(self.toolchains)))
  301. if len(self.toolchains):
  302. for key, value in sorted(self.toolchains.items()):
  303. print('%-10s: %s' % (key, value.gcc))
  304. else:
  305. print('None')
  306. def Select(self, arch):
  307. """Returns the toolchain for a given architecture
  308. Args:
  309. args: Name of architecture (e.g. 'arm', 'ppc_8xx')
  310. returns:
  311. toolchain object, or None if none found
  312. """
  313. for tag, value in bsettings.GetItems('toolchain-alias'):
  314. if arch == tag:
  315. for alias in value.split():
  316. if alias in self.toolchains:
  317. return self.toolchains[alias]
  318. if not arch in self.toolchains:
  319. raise ValueError("No tool chain found for arch '%s'" % arch)
  320. return self.toolchains[arch]
  321. def ResolveReferences(self, var_dict, args):
  322. """Resolve variable references in a string
  323. This converts ${blah} within the string to the value of blah.
  324. This function works recursively.
  325. Args:
  326. var_dict: Dictionary containing variables and their values
  327. args: String containing make arguments
  328. Returns:
  329. Resolved string
  330. >>> bsettings.Setup()
  331. >>> tcs = Toolchains()
  332. >>> tcs.Add('fred', False)
  333. >>> var_dict = {'oblique' : 'OBLIQUE', 'first' : 'fi${second}rst', \
  334. 'second' : '2nd'}
  335. >>> tcs.ResolveReferences(var_dict, 'this=${oblique}_set')
  336. 'this=OBLIQUE_set'
  337. >>> tcs.ResolveReferences(var_dict, 'this=${oblique}_set${first}nd')
  338. 'this=OBLIQUE_setfi2ndrstnd'
  339. """
  340. re_var = re.compile('(\$\{[-_a-z0-9A-Z]{1,}\})')
  341. while True:
  342. m = re_var.search(args)
  343. if not m:
  344. break
  345. lookup = m.group(0)[2:-1]
  346. value = var_dict.get(lookup, '')
  347. args = args[:m.start(0)] + value + args[m.end(0):]
  348. return args
  349. def GetMakeArguments(self, board):
  350. """Returns 'make' arguments for a given board
  351. The flags are in a section called 'make-flags'. Flags are named
  352. after the target they represent, for example snapper9260=TESTING=1
  353. will pass TESTING=1 to make when building the snapper9260 board.
  354. References to other boards can be added in the string also. For
  355. example:
  356. [make-flags]
  357. at91-boards=ENABLE_AT91_TEST=1
  358. snapper9260=${at91-boards} BUILD_TAG=442
  359. snapper9g45=${at91-boards} BUILD_TAG=443
  360. This will return 'ENABLE_AT91_TEST=1 BUILD_TAG=442' for snapper9260
  361. and 'ENABLE_AT91_TEST=1 BUILD_TAG=443' for snapper9g45.
  362. A special 'target' variable is set to the board target.
  363. Args:
  364. board: Board object for the board to check.
  365. Returns:
  366. 'make' flags for that board, or '' if none
  367. """
  368. self._make_flags['target'] = board.target
  369. arg_str = self.ResolveReferences(self._make_flags,
  370. self._make_flags.get(board.target, ''))
  371. args = arg_str.split(' ')
  372. i = 0
  373. while i < len(args):
  374. if not args[i]:
  375. del args[i]
  376. else:
  377. i += 1
  378. return args
  379. def LocateArchUrl(self, fetch_arch):
  380. """Find a toolchain available online
  381. Look in standard places for available toolchains. At present the
  382. only standard place is at kernel.org.
  383. Args:
  384. arch: Architecture to look for, or 'list' for all
  385. Returns:
  386. If fetch_arch is 'list', a tuple:
  387. Machine architecture (e.g. x86_64)
  388. List of toolchains
  389. else
  390. URL containing this toolchain, if avaialble, else None
  391. """
  392. arch = command.OutputOneLine('uname', '-m')
  393. base = 'https://www.kernel.org/pub/tools/crosstool/files/bin'
  394. versions = ['7.3.0', '6.4.0', '4.9.4']
  395. links = []
  396. for version in versions:
  397. url = '%s/%s/%s/' % (base, arch, version)
  398. print('Checking: %s' % url)
  399. response = urllib.request.urlopen(url)
  400. html = tools.ToString(response.read())
  401. parser = MyHTMLParser(fetch_arch)
  402. parser.feed(html)
  403. if fetch_arch == 'list':
  404. links += parser.links
  405. elif parser.arch_link:
  406. return url + parser.arch_link
  407. if fetch_arch == 'list':
  408. return arch, links
  409. return None
  410. def Download(self, url):
  411. """Download a file to a temporary directory
  412. Args:
  413. url: URL to download
  414. Returns:
  415. Tuple:
  416. Temporary directory name
  417. Full path to the downloaded archive file in that directory,
  418. or None if there was an error while downloading
  419. """
  420. print('Downloading: %s' % url)
  421. leaf = url.split('/')[-1]
  422. tmpdir = tempfile.mkdtemp('.buildman')
  423. response = urllib.request.urlopen(url)
  424. fname = os.path.join(tmpdir, leaf)
  425. fd = open(fname, 'wb')
  426. meta = response.info()
  427. size = int(meta.get('Content-Length'))
  428. done = 0
  429. block_size = 1 << 16
  430. status = ''
  431. # Read the file in chunks and show progress as we go
  432. while True:
  433. buffer = response.read(block_size)
  434. if not buffer:
  435. print(chr(8) * (len(status) + 1), '\r', end=' ')
  436. break
  437. done += len(buffer)
  438. fd.write(buffer)
  439. status = r'%10d MiB [%3d%%]' % (done // 1024 // 1024,
  440. done * 100 // size)
  441. status = status + chr(8) * (len(status) + 1)
  442. print(status, end=' ')
  443. sys.stdout.flush()
  444. fd.close()
  445. if done != size:
  446. print('Error, failed to download')
  447. os.remove(fname)
  448. fname = None
  449. return tmpdir, fname
  450. def Unpack(self, fname, dest):
  451. """Unpack a tar file
  452. Args:
  453. fname: Filename to unpack
  454. dest: Destination directory
  455. Returns:
  456. Directory name of the first entry in the archive, without the
  457. trailing /
  458. """
  459. stdout = command.Output('tar', 'xvfJ', fname, '-C', dest)
  460. dirs = stdout.splitlines()[1].split('/')[:2]
  461. return '/'.join(dirs)
  462. def TestSettingsHasPath(self, path):
  463. """Check if buildman will find this toolchain
  464. Returns:
  465. True if the path is in settings, False if not
  466. """
  467. paths = self.GetPathList(False)
  468. return path in paths
  469. def ListArchs(self):
  470. """List architectures with available toolchains to download"""
  471. host_arch, archives = self.LocateArchUrl('list')
  472. re_arch = re.compile('[-a-z0-9.]*[-_]([^-]*)-.*')
  473. arch_set = set()
  474. for archive in archives:
  475. # Remove the host architecture from the start
  476. arch = re_arch.match(archive[len(host_arch):])
  477. if arch:
  478. if arch.group(1) != '2.0' and arch.group(1) != '64':
  479. arch_set.add(arch.group(1))
  480. return sorted(arch_set)
  481. def FetchAndInstall(self, arch):
  482. """Fetch and install a new toolchain
  483. arch:
  484. Architecture to fetch, or 'list' to list
  485. """
  486. # Fist get the URL for this architecture
  487. col = terminal.Color()
  488. print(col.Color(col.BLUE, "Downloading toolchain for arch '%s'" % arch))
  489. url = self.LocateArchUrl(arch)
  490. if not url:
  491. print(("Cannot find toolchain for arch '%s' - use 'list' to list" %
  492. arch))
  493. return 2
  494. home = os.environ['HOME']
  495. dest = os.path.join(home, '.buildman-toolchains')
  496. if not os.path.exists(dest):
  497. os.mkdir(dest)
  498. # Download the tar file for this toolchain and unpack it
  499. tmpdir, tarfile = self.Download(url)
  500. if not tarfile:
  501. return 1
  502. print(col.Color(col.GREEN, 'Unpacking to: %s' % dest), end=' ')
  503. sys.stdout.flush()
  504. path = self.Unpack(tarfile, dest)
  505. os.remove(tarfile)
  506. os.rmdir(tmpdir)
  507. print()
  508. # Check that the toolchain works
  509. print(col.Color(col.GREEN, 'Testing'))
  510. dirpath = os.path.join(dest, path)
  511. compiler_fname_list = self.ScanPath(dirpath, True)
  512. if not compiler_fname_list:
  513. print('Could not locate C compiler - fetch failed.')
  514. return 1
  515. if len(compiler_fname_list) != 1:
  516. print(col.Color(col.RED, 'Warning, ambiguous toolchains: %s' %
  517. ', '.join(compiler_fname_list)))
  518. toolchain = Toolchain(compiler_fname_list[0], True, True)
  519. # Make sure that it will be found by buildman
  520. if not self.TestSettingsHasPath(dirpath):
  521. print(("Adding 'download' to config file '%s'" %
  522. bsettings.config_fname))
  523. bsettings.SetItem('toolchain', 'download', '%s/*/*' % dest)
  524. return 0