toolchain.py 23 KB

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