blob: ca6d311c821776deb8f0d9dd5f28fd159292e73d [file] [log] [blame]
Zdenek Behan508dcce2011-12-05 15:39:32 +01001# Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
2# Use of this source code is governed by a BSD-style license that can be
3# found in the LICENSE file.
4
Mike Frysinger750c5f52014-09-16 16:16:57 -04005"""This script manages the installed toolchains in the chroot."""
Zdenek Behan508dcce2011-12-05 15:39:32 +01006
Mike Frysinger383367e2014-09-16 15:06:17 -04007from __future__ import print_function
8
Zdenek Behan508dcce2011-12-05 15:39:32 +01009import copy
Mike Frysinger35247af2012-11-16 18:58:06 -050010import glob
Mike Frysinger7ccee992012-06-01 21:27:59 -040011import json
Zdenek Behan508dcce2011-12-05 15:39:32 +010012import os
Zdenek Behan508dcce2011-12-05 15:39:32 +010013
Don Garrett88b8d782014-05-13 17:30:55 -070014from chromite.cbuildbot import constants
Mike Frysinger506e75f2012-12-17 14:21:13 -050015from chromite.lib import commandline
Brian Harring503f3ab2012-03-09 21:39:41 -080016from chromite.lib import cros_build_lib
Ralph Nathan03047282015-03-23 11:09:32 -070017from chromite.lib import cros_logging as logging
Brian Harringaf019fb2012-05-10 15:06:13 -070018from chromite.lib import osutils
Mike Frysinger35247af2012-11-16 18:58:06 -050019from chromite.lib import parallel
David James27ac4ae2012-12-03 23:16:15 -080020from chromite.lib import toolchain
Mike Frysinger35247af2012-11-16 18:58:06 -050021
22# Needs to be after chromite imports.
23import lddtree
Zdenek Behan508dcce2011-12-05 15:39:32 +010024
Mike Frysinger31596002012-12-03 23:54:24 -050025if cros_build_lib.IsInsideChroot():
26 # Only import portage after we've checked that we're inside the chroot.
27 # Outside may not have portage, in which case the above may not happen.
28 # We'll check in main() if the operation needs portage.
Don Garrett25f309a2014-03-19 14:02:12 -070029 # pylint: disable=F0401
Mike Frysinger31596002012-12-03 23:54:24 -050030 import portage
Zdenek Behan508dcce2011-12-05 15:39:32 +010031
32
Matt Tennantf1e30972012-03-02 16:30:07 -080033EMERGE_CMD = os.path.join(constants.CHROMITE_BIN_DIR, 'parallel_emerge')
Zdenek Behan508dcce2011-12-05 15:39:32 +010034PACKAGE_STABLE = '[stable]'
35PACKAGE_NONE = '[none]'
36SRC_ROOT = os.path.realpath(constants.SOURCE_ROOT)
Zdenek Behan4eb6fd22012-03-12 17:00:56 +010037
38CHROMIUMOS_OVERLAY = '/usr/local/portage/chromiumos'
Christopher Wileyb22c0712015-06-02 10:37:03 -070039ECLASS_OVERLAY = '/usr/local/portage/eclass-overlay'
Zdenek Behan4eb6fd22012-03-12 17:00:56 +010040STABLE_OVERLAY = '/usr/local/portage/stable'
41CROSSDEV_OVERLAY = '/usr/local/portage/crossdev'
Zdenek Behan508dcce2011-12-05 15:39:32 +010042
43
44# TODO: The versions are stored here very much like in setup_board.
45# The goal for future is to differentiate these using a config file.
46# This is done essentially by messing with GetDesiredPackageVersions()
47DEFAULT_VERSION = PACKAGE_STABLE
48DEFAULT_TARGET_VERSION_MAP = {
Zdenek Behan508dcce2011-12-05 15:39:32 +010049}
50TARGET_VERSION_MAP = {
Mike Frysingerd6e2df02014-11-26 02:55:04 -050051 'host' : {
52 'gdb' : PACKAGE_NONE,
Rahul Chaudhry4b803052015-05-13 15:25:56 -070053 'ex_go' : PACKAGE_NONE,
Mike Frysingerd6e2df02014-11-26 02:55:04 -050054 },
Zdenek Behan508dcce2011-12-05 15:39:32 +010055}
Rahul Chaudhry4b803052015-05-13 15:25:56 -070056
57# Enable the Go compiler for these targets.
58TARGET_GO_ENABLED = (
59 'x86_64-cros-linux-gnu',
60 'i686-pc-linux-gnu',
61 'armv7a-cros-linux-gnueabi',
62)
63CROSSDEV_GO_ARGS = ['--ex-pkg', 'dev-lang/go']
64
Zdenek Behan508dcce2011-12-05 15:39:32 +010065# Overrides for {gcc,binutils}-config, pick a package with particular suffix.
66CONFIG_TARGET_SUFFIXES = {
Mike Frysingerd6e2df02014-11-26 02:55:04 -050067 'binutils' : {
Mike Frysinger8a83c622015-05-28 00:35:05 -040068 'armv6j-cros-linux-gnueabi': '-gold',
Han Shen43b84422015-02-19 11:38:13 -080069 'armv7a-cros-linux-gnueabi': '-gold',
Mike Frysingerd6e2df02014-11-26 02:55:04 -050070 'i686-pc-linux-gnu' : '-gold',
71 'x86_64-cros-linux-gnu' : '-gold',
72 },
Zdenek Behan508dcce2011-12-05 15:39:32 +010073}
Zdenek Behan508dcce2011-12-05 15:39:32 +010074# Global per-run cache that will be filled ondemand in by GetPackageMap()
75# function as needed.
76target_version_map = {
77}
78
79
David James66a09c42012-11-05 13:31:38 -080080class Crossdev(object):
81 """Class for interacting with crossdev and caching its output."""
82
83 _CACHE_FILE = os.path.join(CROSSDEV_OVERLAY, '.configured.json')
84 _CACHE = {}
85
86 @classmethod
87 def Load(cls, reconfig):
88 """Load crossdev cache from disk."""
David James90239b92012-11-05 15:31:34 -080089 crossdev_version = GetStablePackageVersion('sys-devel/crossdev', True)
90 cls._CACHE = {'crossdev_version': crossdev_version}
David James66a09c42012-11-05 13:31:38 -080091 if os.path.exists(cls._CACHE_FILE) and not reconfig:
92 with open(cls._CACHE_FILE) as f:
93 data = json.load(f)
David James90239b92012-11-05 15:31:34 -080094 if crossdev_version == data.get('crossdev_version'):
David James66a09c42012-11-05 13:31:38 -080095 cls._CACHE = data
96
97 @classmethod
98 def Save(cls):
99 """Store crossdev cache on disk."""
100 # Save the cache from the successful run.
101 with open(cls._CACHE_FILE, 'w') as f:
102 json.dump(cls._CACHE, f)
103
104 @classmethod
105 def GetConfig(cls, target):
106 """Returns a map of crossdev provided variables about a tuple."""
107 CACHE_ATTR = '_target_tuple_map'
108
109 val = cls._CACHE.setdefault(CACHE_ATTR, {})
110 if not target in val:
111 # Find out the crossdev tuple.
112 target_tuple = target
113 if target == 'host':
David James27ac4ae2012-12-03 23:16:15 -0800114 target_tuple = toolchain.GetHostTuple()
Rahul Chaudhry4b803052015-05-13 15:25:56 -0700115 # Build the crossdev command.
116 cmd = ['crossdev', '--show-target-cfg', '--ex-gdb']
117 if target in TARGET_GO_ENABLED:
118 cmd.extend(CROSSDEV_GO_ARGS)
119 cmd.extend(['-t', target_tuple])
David James66a09c42012-11-05 13:31:38 -0800120 # Catch output of crossdev.
Rahul Chaudhry4b803052015-05-13 15:25:56 -0700121 out = cros_build_lib.RunCommand(cmd, print_cmd=False,
122 redirect_stdout=True).output.splitlines()
David James66a09c42012-11-05 13:31:38 -0800123 # List of tuples split at the first '=', converted into dict.
124 val[target] = dict([x.split('=', 1) for x in out])
125 return val[target]
126
127 @classmethod
128 def UpdateTargets(cls, targets, usepkg, config_only=False):
129 """Calls crossdev to initialize a cross target.
130
131 Args:
Don Garrett25f309a2014-03-19 14:02:12 -0700132 targets: The list of targets to initialize using crossdev.
133 usepkg: Copies the commandline opts.
134 config_only: Just update.
David James66a09c42012-11-05 13:31:38 -0800135 """
136 configured_targets = cls._CACHE.setdefault('configured_targets', [])
137
138 cmdbase = ['crossdev', '--show-fail-log']
139 cmdbase.extend(['--env', 'FEATURES=splitdebug'])
140 # Pick stable by default, and override as necessary.
141 cmdbase.extend(['-P', '--oneshot'])
142 if usepkg:
143 cmdbase.extend(['-P', '--getbinpkg',
144 '-P', '--usepkgonly',
145 '--without-headers'])
146
Christopher Wileyb22c0712015-06-02 10:37:03 -0700147 overlays = ' '.join((CHROMIUMOS_OVERLAY, ECLASS_OVERLAY, STABLE_OVERLAY))
David James66a09c42012-11-05 13:31:38 -0800148 cmdbase.extend(['--overlays', overlays])
149 cmdbase.extend(['--ov-output', CROSSDEV_OVERLAY])
150
151 for target in targets:
152 if config_only and target in configured_targets:
153 continue
154
155 cmd = cmdbase + ['-t', target]
156
157 for pkg in GetTargetPackages(target):
158 if pkg == 'gdb':
159 # Gdb does not have selectable versions.
160 cmd.append('--ex-gdb')
Rahul Chaudhry4b803052015-05-13 15:25:56 -0700161 elif pkg == 'ex_go':
162 # Go does not have selectable versions.
163 cmd.extend(CROSSDEV_GO_ARGS)
164 else:
165 # The first of the desired versions is the "primary" one.
166 version = GetDesiredPackageVersions(target, pkg)[0]
167 cmd.extend(['--%s' % pkg, version])
David James66a09c42012-11-05 13:31:38 -0800168
169 cmd.extend(targets[target]['crossdev'].split())
170 if config_only:
171 # In this case we want to just quietly reinit
172 cmd.append('--init-target')
173 cros_build_lib.RunCommand(cmd, print_cmd=False, redirect_stdout=True)
174 else:
175 cros_build_lib.RunCommand(cmd)
176
177 configured_targets.append(target)
178
Zdenek Behan4eb6fd22012-03-12 17:00:56 +0100179
Zdenek Behan508dcce2011-12-05 15:39:32 +0100180def GetPackageMap(target):
181 """Compiles a package map for the given target from the constants.
182
183 Uses a cache in target_version_map, that is dynamically filled in as needed,
184 since here everything is static data and the structuring is for ease of
185 configurability only.
186
Mike Frysingerdc649ae2014-11-26 19:29:24 -0500187 Args:
188 target: The target for which to return a version map
Zdenek Behan508dcce2011-12-05 15:39:32 +0100189
Mike Frysingerdc649ae2014-11-26 19:29:24 -0500190 Returns:
191 A map between packages and desired versions in internal format
192 (using the PACKAGE_* constants)
Zdenek Behan508dcce2011-12-05 15:39:32 +0100193 """
194 if target in target_version_map:
195 return target_version_map[target]
196
197 # Start from copy of the global defaults.
198 result = copy.copy(DEFAULT_TARGET_VERSION_MAP)
199
Zdenek Behanf4d18a02012-03-22 15:45:05 +0100200 for pkg in GetTargetPackages(target):
Zdenek Behan508dcce2011-12-05 15:39:32 +0100201 # prefer any specific overrides
202 if pkg in TARGET_VERSION_MAP.get(target, {}):
203 result[pkg] = TARGET_VERSION_MAP[target][pkg]
204 else:
205 # finally, if not already set, set a sane default
206 result.setdefault(pkg, DEFAULT_VERSION)
207 target_version_map[target] = result
208 return result
209
210
Zdenek Behanf4d18a02012-03-22 15:45:05 +0100211def GetTargetPackages(target):
212 """Returns a list of packages for a given target."""
David James66a09c42012-11-05 13:31:38 -0800213 conf = Crossdev.GetConfig(target)
Zdenek Behanf4d18a02012-03-22 15:45:05 +0100214 # Undesired packages are denoted by empty ${pkg}_pn variable.
215 return [x for x in conf['crosspkgs'].strip("'").split() if conf[x+'_pn']]
216
217
Zdenek Behan4eb6fd22012-03-12 17:00:56 +0100218# Portage helper functions:
219def GetPortagePackage(target, package):
220 """Returns a package name for the given target."""
David James66a09c42012-11-05 13:31:38 -0800221 conf = Crossdev.GetConfig(target)
Zdenek Behan4eb6fd22012-03-12 17:00:56 +0100222 # Portage category:
Zdenek Behan508dcce2011-12-05 15:39:32 +0100223 if target == 'host':
Zdenek Behan4eb6fd22012-03-12 17:00:56 +0100224 category = conf[package + '_category']
Zdenek Behan508dcce2011-12-05 15:39:32 +0100225 else:
Zdenek Behan4eb6fd22012-03-12 17:00:56 +0100226 category = conf['category']
227 # Portage package:
228 pn = conf[package + '_pn']
229 # Final package name:
Mike Frysinger422faf42014-11-12 23:16:48 -0500230 assert category
231 assert pn
Zdenek Behan4eb6fd22012-03-12 17:00:56 +0100232 return '%s/%s' % (category, pn)
233
234
Zdenek Behan4eb6fd22012-03-12 17:00:56 +0100235def IsPackageDisabled(target, package):
236 """Returns if the given package is not used for the target."""
237 return GetDesiredPackageVersions(target, package) == [PACKAGE_NONE]
238
Liam McLoughlinf54a0782012-05-17 23:36:52 +0100239
Gilad Arnold2dab78c2015-05-21 14:43:33 -0700240def PortageTrees(root):
241 """Return the portage trees for a given root."""
242 if root == '/':
243 return portage.db['/']
244 # The portage logic requires the path always end in a slash.
245 root = root.rstrip('/') + '/'
246 return portage.create_trees(target_root=root, config_root=root)[root]
247
248
249def GetInstalledPackageVersions(atom, root='/'):
Zdenek Behan508dcce2011-12-05 15:39:32 +0100250 """Extracts the list of current versions of a target, package pair.
251
Mike Frysingerdc649ae2014-11-26 19:29:24 -0500252 Args:
253 atom: The atom to operate on (e.g. sys-devel/gcc)
Gilad Arnold2dab78c2015-05-21 14:43:33 -0700254 root: The root to check for installed packages.
Zdenek Behan508dcce2011-12-05 15:39:32 +0100255
Mike Frysingerdc649ae2014-11-26 19:29:24 -0500256 Returns:
257 The list of versions of the package currently installed.
Zdenek Behan508dcce2011-12-05 15:39:32 +0100258 """
Zdenek Behan508dcce2011-12-05 15:39:32 +0100259 versions = []
Mike Frysinger506e75f2012-12-17 14:21:13 -0500260 # pylint: disable=E1101
Gilad Arnold2dab78c2015-05-21 14:43:33 -0700261 for pkg in PortageTrees(root)['vartree'].dbapi.match(atom, use_cache=0):
Zdenek Behan508dcce2011-12-05 15:39:32 +0100262 version = portage.versions.cpv_getversion(pkg)
263 versions.append(version)
264 return versions
265
266
Gilad Arnold2dab78c2015-05-21 14:43:33 -0700267def GetStablePackageVersion(atom, installed, root='/'):
Zdenek Behan508dcce2011-12-05 15:39:32 +0100268 """Extracts the current stable version for a given package.
269
Mike Frysingerdc649ae2014-11-26 19:29:24 -0500270 Args:
271 atom: The target/package to operate on eg. i686-pc-linux-gnu,gcc
272 installed: Whether we want installed packages or ebuilds
Gilad Arnold2dab78c2015-05-21 14:43:33 -0700273 root: The root to use when querying packages.
Zdenek Behan508dcce2011-12-05 15:39:32 +0100274
Mike Frysingerdc649ae2014-11-26 19:29:24 -0500275 Returns:
276 A string containing the latest version.
Zdenek Behan508dcce2011-12-05 15:39:32 +0100277 """
David James90239b92012-11-05 15:31:34 -0800278 pkgtype = 'vartree' if installed else 'porttree'
Mike Frysinger506e75f2012-12-17 14:21:13 -0500279 # pylint: disable=E1101
Gilad Arnold2dab78c2015-05-21 14:43:33 -0700280 cpv = portage.best(PortageTrees(root)[pkgtype].dbapi.match(atom, use_cache=0))
David James90239b92012-11-05 15:31:34 -0800281 return portage.versions.cpv_getversion(cpv) if cpv else None
Zdenek Behan508dcce2011-12-05 15:39:32 +0100282
283
Gilad Arnold2dab78c2015-05-21 14:43:33 -0700284def VersionListToNumeric(target, package, versions, installed, root='/'):
Zdenek Behan508dcce2011-12-05 15:39:32 +0100285 """Resolves keywords in a given version list for a particular package.
286
287 Resolving means replacing PACKAGE_STABLE with the actual number.
288
Mike Frysingerdc649ae2014-11-26 19:29:24 -0500289 Args:
290 target: The target to operate on (e.g. i686-pc-linux-gnu)
291 package: The target/package to operate on (e.g. gcc)
292 versions: List of versions to resolve
293 installed: Query installed packages
Gilad Arnold2dab78c2015-05-21 14:43:33 -0700294 root: The install root to use; ignored if |installed| is False.
Zdenek Behan508dcce2011-12-05 15:39:32 +0100295
Mike Frysingerdc649ae2014-11-26 19:29:24 -0500296 Returns:
297 List of purely numeric versions equivalent to argument
Zdenek Behan508dcce2011-12-05 15:39:32 +0100298 """
299 resolved = []
David James90239b92012-11-05 15:31:34 -0800300 atom = GetPortagePackage(target, package)
Gilad Arnold2dab78c2015-05-21 14:43:33 -0700301 if not installed:
302 root = '/'
Zdenek Behan508dcce2011-12-05 15:39:32 +0100303 for version in versions:
304 if version == PACKAGE_STABLE:
Gilad Arnold2dab78c2015-05-21 14:43:33 -0700305 resolved.append(GetStablePackageVersion(atom, installed, root=root))
Zdenek Behan508dcce2011-12-05 15:39:32 +0100306 elif version != PACKAGE_NONE:
307 resolved.append(version)
308 return resolved
309
310
311def GetDesiredPackageVersions(target, package):
312 """Produces the list of desired versions for each target, package pair.
313
314 The first version in the list is implicitly treated as primary, ie.
315 the version that will be initialized by crossdev and selected.
316
317 If the version is PACKAGE_STABLE, it really means the current version which
318 is emerged by using the package atom with no particular version key.
319 Since crossdev unmasks all packages by default, this will actually
320 mean 'unstable' in most cases.
321
Mike Frysingerdc649ae2014-11-26 19:29:24 -0500322 Args:
323 target: The target to operate on (e.g. i686-pc-linux-gnu)
324 package: The target/package to operate on (e.g. gcc)
Zdenek Behan508dcce2011-12-05 15:39:32 +0100325
Mike Frysingerdc649ae2014-11-26 19:29:24 -0500326 Returns:
327 A list composed of either a version string, PACKAGE_STABLE
Zdenek Behan508dcce2011-12-05 15:39:32 +0100328 """
329 packagemap = GetPackageMap(target)
330
331 versions = []
332 if package in packagemap:
333 versions.append(packagemap[package])
334
335 return versions
336
337
338def TargetIsInitialized(target):
339 """Verifies if the given list of targets has been correctly initialized.
340
341 This determines whether we have to call crossdev while emerging
342 toolchain packages or can do it using emerge. Emerge is naturally
343 preferred, because all packages can be updated in a single pass.
344
Mike Frysingerdc649ae2014-11-26 19:29:24 -0500345 Args:
346 target: The target to operate on (e.g. i686-pc-linux-gnu)
Zdenek Behan508dcce2011-12-05 15:39:32 +0100347
Mike Frysingerdc649ae2014-11-26 19:29:24 -0500348 Returns:
349 True if |target| is completely initialized, else False
Zdenek Behan508dcce2011-12-05 15:39:32 +0100350 """
351 # Check if packages for the given target all have a proper version.
352 try:
Zdenek Behanf4d18a02012-03-22 15:45:05 +0100353 for package in GetTargetPackages(target):
David James66a09c42012-11-05 13:31:38 -0800354 atom = GetPortagePackage(target, package)
Zdenek Behan4eb6fd22012-03-12 17:00:56 +0100355 # Do we even want this package && is it initialized?
David James90239b92012-11-05 15:31:34 -0800356 if not IsPackageDisabled(target, package) and not (
357 GetStablePackageVersion(atom, True) and
358 GetStablePackageVersion(atom, False)):
Zdenek Behan508dcce2011-12-05 15:39:32 +0100359 return False
360 return True
361 except cros_build_lib.RunCommandError:
362 # Fails - The target has likely never been initialized before.
363 return False
364
365
366def RemovePackageMask(target):
367 """Removes a package.mask file for the given platform.
368
369 The pre-existing package.mask files can mess with the keywords.
370
Mike Frysingerdc649ae2014-11-26 19:29:24 -0500371 Args:
372 target: The target to operate on (e.g. i686-pc-linux-gnu)
Zdenek Behan508dcce2011-12-05 15:39:32 +0100373 """
374 maskfile = os.path.join('/etc/portage/package.mask', 'cross-' + target)
Brian Harringaf019fb2012-05-10 15:06:13 -0700375 osutils.SafeUnlink(maskfile)
Zdenek Behan508dcce2011-12-05 15:39:32 +0100376
377
Zdenek Behan508dcce2011-12-05 15:39:32 +0100378# Main functions performing the actual update steps.
Gilad Arnold2dab78c2015-05-21 14:43:33 -0700379def RebuildLibtool(root='/'):
Mike Frysingerc880a962013-11-08 13:59:06 -0500380 """Rebuild libtool as needed
381
382 Libtool hardcodes full paths to internal gcc files, so whenever we upgrade
383 gcc, libtool will break. We can't use binary packages either as those will
384 most likely be compiled against the previous version of gcc.
Gilad Arnold2dab78c2015-05-21 14:43:33 -0700385
386 Args:
387 root: The install root where we want libtool rebuilt.
Mike Frysingerc880a962013-11-08 13:59:06 -0500388 """
389 needs_update = False
Gilad Arnold2dab78c2015-05-21 14:43:33 -0700390 with open(os.path.join(root, 'usr/bin/libtool')) as f:
Mike Frysingerc880a962013-11-08 13:59:06 -0500391 for line in f:
392 # Look for a line like:
393 # sys_lib_search_path_spec="..."
394 # It'll be a list of paths and gcc will be one of them.
395 if line.startswith('sys_lib_search_path_spec='):
396 line = line.rstrip()
397 for path in line.split('=', 1)[1].strip('"').split():
Gilad Arnold2dab78c2015-05-21 14:43:33 -0700398 if not os.path.exists(os.path.join(root, path.lstrip(os.path.sep))):
Mike Frysinger383367e2014-09-16 15:06:17 -0400399 print('Rebuilding libtool after gcc upgrade')
400 print(' %s' % line)
401 print(' missing path: %s' % path)
Mike Frysingerc880a962013-11-08 13:59:06 -0500402 needs_update = True
403 break
404
405 if needs_update:
406 break
407
408 if needs_update:
Gilad Arnold2dab78c2015-05-21 14:43:33 -0700409 cmd = [EMERGE_CMD, '--oneshot']
410 if root != '/':
411 cmd.extend(['--sysroot=%s' % root, '--root=%s' % root])
412 cmd.append('sys-devel/libtool')
Mike Frysingerc880a962013-11-08 13:59:06 -0500413 cros_build_lib.RunCommand(cmd)
414
415
Gilad Arnold2dab78c2015-05-21 14:43:33 -0700416def UpdateTargets(targets, usepkg, root='/'):
Zdenek Behan508dcce2011-12-05 15:39:32 +0100417 """Determines which packages need update/unmerge and defers to portage.
418
Mike Frysingerdc649ae2014-11-26 19:29:24 -0500419 Args:
420 targets: The list of targets to update
421 usepkg: Copies the commandline option
Gilad Arnold2dab78c2015-05-21 14:43:33 -0700422 root: The install root in which we want packages updated.
Zdenek Behan508dcce2011-12-05 15:39:32 +0100423 """
David James90239b92012-11-05 15:31:34 -0800424 # Remove keyword files created by old versions of cros_setup_toolchains.
425 osutils.SafeUnlink('/etc/portage/package.keywords/cross-host')
Zdenek Behan508dcce2011-12-05 15:39:32 +0100426
427 # For each target, we do two things. Figure out the list of updates,
428 # and figure out the appropriate keywords/masks. Crossdev will initialize
429 # these, but they need to be regenerated on every update.
Mike Frysinger383367e2014-09-16 15:06:17 -0400430 print('Determining required toolchain updates...')
David James90239b92012-11-05 15:31:34 -0800431 mergemap = {}
Zdenek Behan508dcce2011-12-05 15:39:32 +0100432 for target in targets:
433 # Record the highest needed version for each target, for masking purposes.
434 RemovePackageMask(target)
Zdenek Behanf4d18a02012-03-22 15:45:05 +0100435 for package in GetTargetPackages(target):
Zdenek Behan508dcce2011-12-05 15:39:32 +0100436 # Portage name for the package
Zdenek Behan4eb6fd22012-03-12 17:00:56 +0100437 if IsPackageDisabled(target, package):
438 continue
439 pkg = GetPortagePackage(target, package)
Gilad Arnold2dab78c2015-05-21 14:43:33 -0700440 current = GetInstalledPackageVersions(pkg, root=root)
Zdenek Behan508dcce2011-12-05 15:39:32 +0100441 desired = GetDesiredPackageVersions(target, package)
Zdenek Behan699ddd32012-04-13 07:14:08 +0200442 desired_num = VersionListToNumeric(target, package, desired, False)
Zdenek Behan4eb6fd22012-03-12 17:00:56 +0100443 mergemap[pkg] = set(desired_num).difference(current)
Zdenek Behan508dcce2011-12-05 15:39:32 +0100444
Zdenek Behan508dcce2011-12-05 15:39:32 +0100445 packages = []
446 for pkg in mergemap:
447 for ver in mergemap[pkg]:
Zdenek Behan677b6d82012-04-11 05:31:47 +0200448 if ver != PACKAGE_NONE:
David James90239b92012-11-05 15:31:34 -0800449 packages.append(pkg)
Zdenek Behan508dcce2011-12-05 15:39:32 +0100450
451 if not packages:
Mike Frysinger383367e2014-09-16 15:06:17 -0400452 print('Nothing to update!')
David Jamesf8c672f2012-11-06 13:38:11 -0800453 return False
Zdenek Behan508dcce2011-12-05 15:39:32 +0100454
Mike Frysinger383367e2014-09-16 15:06:17 -0400455 print('Updating packages:')
456 print(packages)
Zdenek Behan508dcce2011-12-05 15:39:32 +0100457
Zdenek Behan7e33b4e2012-03-12 17:00:56 +0100458 cmd = [EMERGE_CMD, '--oneshot', '--update']
Zdenek Behan508dcce2011-12-05 15:39:32 +0100459 if usepkg:
460 cmd.extend(['--getbinpkg', '--usepkgonly'])
Gilad Arnold2dab78c2015-05-21 14:43:33 -0700461 if root != '/':
462 cmd.extend(['--sysroot=%s' % root, '--root=%s' % root])
Zdenek Behan508dcce2011-12-05 15:39:32 +0100463
464 cmd.extend(packages)
465 cros_build_lib.RunCommand(cmd)
David Jamesf8c672f2012-11-06 13:38:11 -0800466 return True
Zdenek Behan508dcce2011-12-05 15:39:32 +0100467
468
Gilad Arnold2dab78c2015-05-21 14:43:33 -0700469def CleanTargets(targets, root='/'):
470 """Unmerges old packages that are assumed unnecessary.
471
472 Args:
473 targets: The list of targets to clean up.
474 root: The install root in which we want packages cleaned up.
475 """
Zdenek Behan508dcce2011-12-05 15:39:32 +0100476 unmergemap = {}
477 for target in targets:
Zdenek Behanf4d18a02012-03-22 15:45:05 +0100478 for package in GetTargetPackages(target):
Zdenek Behan4eb6fd22012-03-12 17:00:56 +0100479 if IsPackageDisabled(target, package):
480 continue
481 pkg = GetPortagePackage(target, package)
Gilad Arnold2dab78c2015-05-21 14:43:33 -0700482 current = GetInstalledPackageVersions(pkg, root=root)
Zdenek Behan508dcce2011-12-05 15:39:32 +0100483 desired = GetDesiredPackageVersions(target, package)
Gilad Arnold2fcb0aa2015-05-21 14:51:41 -0700484 # NOTE: This refers to installed packages (vartree) rather than the
485 # Portage version (porttree and/or bintree) when determining the current
486 # version. While this isn't the most accurate thing to do, it is probably
487 # a good simple compromise, which should have the desired result of
488 # uninstalling everything but the latest installed version. In
489 # particular, using the bintree (--usebinpkg) requires a non-trivial
490 # binhost sync and is probably more complex than useful.
Zdenek Behan699ddd32012-04-13 07:14:08 +0200491 desired_num = VersionListToNumeric(target, package, desired, True)
492 if not set(desired_num).issubset(current):
Gilad Arnold2fcb0aa2015-05-21 14:51:41 -0700493 print('Error detecting stable version for %s, skipping clean!' % pkg)
Zdenek Behan699ddd32012-04-13 07:14:08 +0200494 return
Zdenek Behan508dcce2011-12-05 15:39:32 +0100495 unmergemap[pkg] = set(current).difference(desired_num)
496
497 # Cleaning doesn't care about consistency and rebuilding package.* files.
498 packages = []
499 for pkg, vers in unmergemap.iteritems():
500 packages.extend('=%s-%s' % (pkg, ver) for ver in vers if ver != '9999')
501
502 if packages:
Mike Frysinger383367e2014-09-16 15:06:17 -0400503 print('Cleaning packages:')
504 print(packages)
Zdenek Behan7e33b4e2012-03-12 17:00:56 +0100505 cmd = [EMERGE_CMD, '--unmerge']
Gilad Arnold2dab78c2015-05-21 14:43:33 -0700506 if root != '/':
507 cmd.extend(['--sysroot=%s' % root, '--root=%s' % root])
Zdenek Behan508dcce2011-12-05 15:39:32 +0100508 cmd.extend(packages)
509 cros_build_lib.RunCommand(cmd)
510 else:
Mike Frysinger383367e2014-09-16 15:06:17 -0400511 print('Nothing to clean!')
Zdenek Behan508dcce2011-12-05 15:39:32 +0100512
513
Gilad Arnold2dab78c2015-05-21 14:43:33 -0700514def SelectActiveToolchains(targets, suffixes, root='/'):
Zdenek Behan508dcce2011-12-05 15:39:32 +0100515 """Runs gcc-config and binutils-config to select the desired.
516
Mike Frysingerdc649ae2014-11-26 19:29:24 -0500517 Args:
518 targets: The targets to select
519 suffixes: Optional target-specific hacks
Gilad Arnold2dab78c2015-05-21 14:43:33 -0700520 root: The root where we want to select toolchain versions.
Zdenek Behan508dcce2011-12-05 15:39:32 +0100521 """
522 for package in ['gcc', 'binutils']:
523 for target in targets:
524 # Pick the first version in the numbered list as the selected one.
525 desired = GetDesiredPackageVersions(target, package)
Gilad Arnold2dab78c2015-05-21 14:43:33 -0700526 desired_num = VersionListToNumeric(target, package, desired, True,
527 root=root)
Zdenek Behan508dcce2011-12-05 15:39:32 +0100528 desired = desired_num[0]
529 # *-config does not play revisions, strip them, keep just PV.
530 desired = portage.versions.pkgsplit('%s-%s' % (package, desired))[1]
531
532 if target == 'host':
533 # *-config is the only tool treating host identically (by tuple).
David James27ac4ae2012-12-03 23:16:15 -0800534 target = toolchain.GetHostTuple()
Zdenek Behan508dcce2011-12-05 15:39:32 +0100535
536 # And finally, attach target to it.
537 desired = '%s-%s' % (target, desired)
538
539 # Target specific hacks
540 if package in suffixes:
541 if target in suffixes[package]:
542 desired += suffixes[package][target]
543
David James7ec5efc2012-11-06 09:39:49 -0800544 extra_env = {'CHOST': target}
Gilad Arnold2dab78c2015-05-21 14:43:33 -0700545 if root != '/':
546 extra_env['ROOT'] = root
David James7ec5efc2012-11-06 09:39:49 -0800547 cmd = ['%s-config' % package, '-c', target]
Mike Frysingerd6e2df02014-11-26 02:55:04 -0500548 result = cros_build_lib.RunCommand(
549 cmd, print_cmd=False, redirect_stdout=True, extra_env=extra_env)
550 current = result.output.splitlines()[0]
Gilad Arnold2dab78c2015-05-21 14:43:33 -0700551
552 # Do not reconfig when the current is live or nothing needs to be done.
553 extra_env = {'ROOT': root} if root != '/' else None
Zdenek Behan508dcce2011-12-05 15:39:32 +0100554 if current != desired and current != '9999':
Mike Frysingerd6e2df02014-11-26 02:55:04 -0500555 cmd = [package + '-config', desired]
Gilad Arnold2dab78c2015-05-21 14:43:33 -0700556 cros_build_lib.RunCommand(cmd, print_cmd=False, extra_env=extra_env)
Zdenek Behan508dcce2011-12-05 15:39:32 +0100557
558
Mike Frysinger35247af2012-11-16 18:58:06 -0500559def ExpandTargets(targets_wanted):
560 """Expand any possible toolchain aliases into full targets
561
562 This will expand 'all' and 'sdk' into the respective toolchain tuples.
563
564 Args:
565 targets_wanted: The targets specified by the user.
Mike Frysinger1a736a82013-12-12 01:50:59 -0500566
Mike Frysinger35247af2012-11-16 18:58:06 -0500567 Returns:
Gilad Arnold8195b532015-04-07 10:56:30 +0300568 Dictionary of concrete targets and their toolchain tuples.
Mike Frysinger35247af2012-11-16 18:58:06 -0500569 """
Mike Frysinger35247af2012-11-16 18:58:06 -0500570 targets_wanted = set(targets_wanted)
Don Garrettc0c74002015-10-09 12:58:19 -0700571 if targets_wanted == set(['boards']):
572 # Only pull targets from the included boards.
Gilad Arnold8195b532015-04-07 10:56:30 +0300573 return {}
574
575 all_targets = toolchain.GetAllTargets()
Mike Frysinger35247af2012-11-16 18:58:06 -0500576 if targets_wanted == set(['all']):
Gilad Arnold8195b532015-04-07 10:56:30 +0300577 return all_targets
578 if targets_wanted == set(['sdk']):
Mike Frysinger35247af2012-11-16 18:58:06 -0500579 # Filter out all the non-sdk toolchains as we don't want to mess
580 # with those in all of our builds.
Gilad Arnold8195b532015-04-07 10:56:30 +0300581 return toolchain.FilterToolchains(all_targets, 'sdk', True)
582
583 # Verify user input.
584 nonexistent = targets_wanted.difference(all_targets)
585 if nonexistent:
586 raise ValueError('Invalid targets: %s', ','.join(nonexistent))
587 return {t: all_targets[t] for t in targets_wanted}
Mike Frysinger35247af2012-11-16 18:58:06 -0500588
589
David Jamesf8c672f2012-11-06 13:38:11 -0800590def UpdateToolchains(usepkg, deleteold, hostonly, reconfig,
Don Garrettc0c74002015-10-09 12:58:19 -0700591 targets_wanted, boards_wanted, root='/'):
Zdenek Behan508dcce2011-12-05 15:39:32 +0100592 """Performs all steps to create a synchronized toolchain enviroment.
593
Mike Frysingerdc649ae2014-11-26 19:29:24 -0500594 Args:
595 usepkg: Use prebuilt packages
596 deleteold: Unmerge deprecated packages
597 hostonly: Only setup the host toolchain
598 reconfig: Reload crossdev config and reselect toolchains
599 targets_wanted: All the targets to update
600 boards_wanted: Load targets from these boards
Gilad Arnold2dab78c2015-05-21 14:43:33 -0700601 root: The root in which to install the toolchains.
Zdenek Behan508dcce2011-12-05 15:39:32 +0100602 """
David Jamesf8c672f2012-11-06 13:38:11 -0800603 targets, crossdev_targets, reconfig_targets = {}, {}, {}
Zdenek Behan7e33b4e2012-03-12 17:00:56 +0100604 if not hostonly:
605 # For hostonly, we can skip most of the below logic, much of which won't
606 # work on bare systems where this is useful.
Mike Frysinger35247af2012-11-16 18:58:06 -0500607 targets = ExpandTargets(targets_wanted)
Mike Frysinger7ccee992012-06-01 21:27:59 -0400608
Don Garrettc0c74002015-10-09 12:58:19 -0700609 # Now re-add any targets that might be from this board. This is to
Gilad Arnold8195b532015-04-07 10:56:30 +0300610 # allow unofficial boards to declare their own toolchains.
Mike Frysinger7ccee992012-06-01 21:27:59 -0400611 for board in boards_wanted:
David James27ac4ae2012-12-03 23:16:15 -0800612 targets.update(toolchain.GetToolchainsForBoard(board))
Zdenek Behan508dcce2011-12-05 15:39:32 +0100613
Zdenek Behan7e33b4e2012-03-12 17:00:56 +0100614 # First check and initialize all cross targets that need to be.
Mike Frysinger7ccee992012-06-01 21:27:59 -0400615 for target in targets:
616 if TargetIsInitialized(target):
617 reconfig_targets[target] = targets[target]
618 else:
619 crossdev_targets[target] = targets[target]
Zdenek Behan7e33b4e2012-03-12 17:00:56 +0100620 if crossdev_targets:
Mike Frysinger383367e2014-09-16 15:06:17 -0400621 print('The following targets need to be re-initialized:')
622 print(crossdev_targets)
David James66a09c42012-11-05 13:31:38 -0800623 Crossdev.UpdateTargets(crossdev_targets, usepkg)
Zdenek Behan8be29ba2012-05-29 23:10:34 +0200624 # Those that were not initialized may need a config update.
David James66a09c42012-11-05 13:31:38 -0800625 Crossdev.UpdateTargets(reconfig_targets, usepkg, config_only=True)
Zdenek Behan508dcce2011-12-05 15:39:32 +0100626
Zdenek Behan7e33b4e2012-03-12 17:00:56 +0100627 # We want host updated.
Mike Frysinger7ccee992012-06-01 21:27:59 -0400628 targets['host'] = {}
Zdenek Behan7e33b4e2012-03-12 17:00:56 +0100629
630 # Now update all packages.
Gilad Arnold2dab78c2015-05-21 14:43:33 -0700631 if UpdateTargets(targets, usepkg, root=root) or crossdev_targets or reconfig:
632 SelectActiveToolchains(targets, CONFIG_TARGET_SUFFIXES, root=root)
David James7ec5efc2012-11-06 09:39:49 -0800633
634 if deleteold:
Gilad Arnold2dab78c2015-05-21 14:43:33 -0700635 CleanTargets(targets, root=root)
Zdenek Behan508dcce2011-12-05 15:39:32 +0100636
Mike Frysingerc880a962013-11-08 13:59:06 -0500637 # Now that we've cleared out old versions, see if we need to rebuild
638 # anything. Can't do this earlier as it might not be broken.
Gilad Arnold2dab78c2015-05-21 14:43:33 -0700639 RebuildLibtool(root=root)
Mike Frysingerc880a962013-11-08 13:59:06 -0500640
Zdenek Behan508dcce2011-12-05 15:39:32 +0100641
Bertrand SIMONNETcae9d5f2015-03-09 15:58:01 -0700642def ShowConfig(name):
643 """Show the toolchain tuples used by |name|
Mike Frysinger35247af2012-11-16 18:58:06 -0500644
645 Args:
Don Garrettc0c74002015-10-09 12:58:19 -0700646 name: The board name to query.
Mike Frysinger35247af2012-11-16 18:58:06 -0500647 """
Don Garrettc0c74002015-10-09 12:58:19 -0700648 toolchains = toolchain.GetToolchainsForBoard(name)
Mike Frysinger35247af2012-11-16 18:58:06 -0500649 # Make sure we display the default toolchain first.
Mike Frysinger383367e2014-09-16 15:06:17 -0400650 print(','.join(
David James27ac4ae2012-12-03 23:16:15 -0800651 toolchain.FilterToolchains(toolchains, 'default', True).keys() +
Mike Frysinger383367e2014-09-16 15:06:17 -0400652 toolchain.FilterToolchains(toolchains, 'default', False).keys()))
Mike Frysinger35247af2012-11-16 18:58:06 -0500653
654
Mike Frysinger35247af2012-11-16 18:58:06 -0500655def GeneratePathWrapper(root, wrappath, path):
656 """Generate a shell script to execute another shell script
657
658 Since we can't symlink a wrapped ELF (see GenerateLdsoWrapper) because the
659 argv[0] won't be pointing to the correct path, generate a shell script that
660 just executes another program with its full path.
661
662 Args:
663 root: The root tree to generate scripts inside of
664 wrappath: The full path (inside |root|) to create the wrapper
665 path: The target program which this wrapper will execute
666 """
667 replacements = {
668 'path': path,
669 'relroot': os.path.relpath('/', os.path.dirname(wrappath)),
670 }
671 wrapper = """#!/bin/sh
672base=$(realpath "$0")
673basedir=${base%%/*}
674exec "${basedir}/%(relroot)s%(path)s" "$@"
675""" % replacements
676 root_wrapper = root + wrappath
677 if os.path.islink(root_wrapper):
678 os.unlink(root_wrapper)
679 else:
680 osutils.SafeMakedirs(os.path.dirname(root_wrapper))
681 osutils.WriteFile(root_wrapper, wrapper)
Mike Frysinger60ec1012013-10-21 00:11:10 -0400682 os.chmod(root_wrapper, 0o755)
Mike Frysinger35247af2012-11-16 18:58:06 -0500683
684
685def FileIsCrosSdkElf(elf):
686 """Determine if |elf| is an ELF that we execute in the cros_sdk
687
688 We don't need this to be perfect, just quick. It makes sure the ELF
689 is a 64bit LSB x86_64 ELF. That is the native type of cros_sdk.
690
691 Args:
692 elf: The file to check
Mike Frysinger1a736a82013-12-12 01:50:59 -0500693
Mike Frysinger35247af2012-11-16 18:58:06 -0500694 Returns:
695 True if we think |elf| is a native ELF
696 """
697 with open(elf) as f:
698 data = f.read(20)
699 # Check the magic number, EI_CLASS, EI_DATA, and e_machine.
700 return (data[0:4] == '\x7fELF' and
701 data[4] == '\x02' and
702 data[5] == '\x01' and
703 data[18] == '\x3e')
704
705
706def IsPathPackagable(ptype, path):
707 """Should the specified file be included in a toolchain package?
708
709 We only need to handle files as we'll create dirs as we need them.
710
711 Further, trim files that won't be useful:
712 - non-english translations (.mo) since it'd require env vars
713 - debug files since these are for the host compiler itself
714 - info/man pages as they're big, and docs are online, and the
715 native docs should work fine for the most part (`man gcc`)
716
717 Args:
718 ptype: A string describing the path type (i.e. 'file' or 'dir' or 'sym')
719 path: The full path to inspect
Mike Frysinger1a736a82013-12-12 01:50:59 -0500720
Mike Frysinger35247af2012-11-16 18:58:06 -0500721 Returns:
722 True if we want to include this path in the package
723 """
724 return not (ptype in ('dir',) or
725 path.startswith('/usr/lib/debug/') or
726 os.path.splitext(path)[1] == '.mo' or
727 ('/man/' in path or '/info/' in path))
728
729
730def ReadlinkRoot(path, root):
731 """Like os.readlink(), but relative to a |root|
732
733 Args:
734 path: The symlink to read
735 root: The path to use for resolving absolute symlinks
Mike Frysinger1a736a82013-12-12 01:50:59 -0500736
Mike Frysinger35247af2012-11-16 18:58:06 -0500737 Returns:
738 A fully resolved symlink path
739 """
740 while os.path.islink(root + path):
741 path = os.path.join(os.path.dirname(path), os.readlink(root + path))
742 return path
743
744
745def _GetFilesForTarget(target, root='/'):
746 """Locate all the files to package for |target|
747
748 This does not cover ELF dependencies.
749
750 Args:
751 target: The toolchain target name
752 root: The root path to pull all packages from
Mike Frysinger1a736a82013-12-12 01:50:59 -0500753
Mike Frysinger35247af2012-11-16 18:58:06 -0500754 Returns:
755 A tuple of a set of all packable paths, and a set of all paths which
756 are also native ELFs
757 """
758 paths = set()
759 elfs = set()
760
761 # Find all the files owned by the packages for this target.
762 for pkg in GetTargetPackages(target):
763 # Ignore packages that are part of the target sysroot.
764 if pkg in ('kernel', 'libc'):
765 continue
766
Rahul Chaudhry4b803052015-05-13 15:25:56 -0700767 # Skip Go compiler from redistributable packages.
768 # The "go" executable has GOROOT=/usr/lib/go/${CTARGET} hardcoded
769 # into it. Due to this, the toolchain cannot be unpacked anywhere
770 # else and be readily useful. To enable packaging Go, we need to:
771 # -) Tweak the wrappers/environment to override GOROOT
772 # automatically based on the unpack location.
773 # -) Make sure the ELF dependency checking and wrapping logic
774 # below skips the Go toolchain executables and libraries.
775 # -) Make sure the packaging process maintains the relative
776 # timestamps of precompiled standard library packages.
777 # (see dev-lang/go ebuild for details).
778 if pkg == 'ex_go':
779 continue
780
Mike Frysinger35247af2012-11-16 18:58:06 -0500781 atom = GetPortagePackage(target, pkg)
782 cat, pn = atom.split('/')
Gilad Arnold2dab78c2015-05-21 14:43:33 -0700783 ver = GetInstalledPackageVersions(atom, root=root)[0]
Ralph Nathan03047282015-03-23 11:09:32 -0700784 logging.info('packaging %s-%s', atom, ver)
Mike Frysinger35247af2012-11-16 18:58:06 -0500785
786 # pylint: disable=E1101
787 dblink = portage.dblink(cat, pn + '-' + ver, myroot=root,
788 settings=portage.settings)
789 contents = dblink.getcontents()
790 for obj in contents:
791 ptype = contents[obj][0]
792 if not IsPathPackagable(ptype, obj):
793 continue
794
795 if ptype == 'obj':
796 # For native ELFs, we need to pull in their dependencies too.
797 if FileIsCrosSdkElf(obj):
798 elfs.add(obj)
799 paths.add(obj)
800
801 return paths, elfs
802
803
804def _BuildInitialPackageRoot(output_dir, paths, elfs, ldpaths,
Mike Frysingerd6e2df02014-11-26 02:55:04 -0500805 path_rewrite_func=lambda x: x, root='/'):
Mike Frysinger35247af2012-11-16 18:58:06 -0500806 """Link in all packable files and their runtime dependencies
807
808 This also wraps up executable ELFs with helper scripts.
809
810 Args:
811 output_dir: The output directory to store files
812 paths: All the files to include
813 elfs: All the files which are ELFs (a subset of |paths|)
814 ldpaths: A dict of static ldpath information
815 path_rewrite_func: User callback to rewrite paths in output_dir
816 root: The root path to pull all packages/files from
817 """
818 # Link in all the files.
819 sym_paths = []
820 for path in paths:
821 new_path = path_rewrite_func(path)
822 dst = output_dir + new_path
823 osutils.SafeMakedirs(os.path.dirname(dst))
824
825 # Is this a symlink which we have to rewrite or wrap?
826 # Delay wrap check until after we have created all paths.
827 src = root + path
828 if os.path.islink(src):
829 tgt = os.readlink(src)
830 if os.path.sep in tgt:
831 sym_paths.append((new_path, lddtree.normpath(ReadlinkRoot(src, root))))
832
833 # Rewrite absolute links to relative and then generate the symlink
834 # ourselves. All other symlinks can be hardlinked below.
835 if tgt[0] == '/':
836 tgt = os.path.relpath(tgt, os.path.dirname(new_path))
837 os.symlink(tgt, dst)
838 continue
839
840 os.link(src, dst)
841
842 # Now see if any of the symlinks need to be wrapped.
843 for sym, tgt in sym_paths:
844 if tgt in elfs:
845 GeneratePathWrapper(output_dir, sym, tgt)
846
847 # Locate all the dependencies for all the ELFs. Stick them all in the
848 # top level "lib" dir to make the wrapper simpler. This exact path does
849 # not matter since we execute ldso directly, and we tell the ldso the
850 # exact path to search for its libraries.
851 libdir = os.path.join(output_dir, 'lib')
852 osutils.SafeMakedirs(libdir)
853 donelibs = set()
854 for elf in elfs:
Mike Frysingerea7688e2014-07-31 22:40:33 -0400855 e = lddtree.ParseELF(elf, root=root, ldpaths=ldpaths)
Mike Frysinger35247af2012-11-16 18:58:06 -0500856 interp = e['interp']
857 if interp:
858 # Generate a wrapper if it is executable.
Mike Frysingerc2ec0902013-03-26 01:28:45 -0400859 interp = os.path.join('/lib', os.path.basename(interp))
860 lddtree.GenerateLdsoWrapper(output_dir, path_rewrite_func(elf), interp,
861 libpaths=e['rpath'] + e['runpath'])
Mike Frysinger35247af2012-11-16 18:58:06 -0500862
863 for lib, lib_data in e['libs'].iteritems():
864 if lib in donelibs:
865 continue
866
867 src = path = lib_data['path']
868 if path is None:
Ralph Nathan446aee92015-03-23 14:44:56 -0700869 logging.warning('%s: could not locate %s', elf, lib)
Mike Frysinger35247af2012-11-16 18:58:06 -0500870 continue
871 donelibs.add(lib)
872
873 # Needed libs are the SONAME, but that is usually a symlink, not a
874 # real file. So link in the target rather than the symlink itself.
875 # We have to walk all the possible symlinks (SONAME could point to a
876 # symlink which points to a symlink), and we have to handle absolute
877 # ourselves (since we have a "root" argument).
878 dst = os.path.join(libdir, os.path.basename(path))
879 src = ReadlinkRoot(src, root)
880
881 os.link(root + src, dst)
882
883
884def _EnvdGetVar(envd, var):
885 """Given a Gentoo env.d file, extract a var from it
886
887 Args:
888 envd: The env.d file to load (may be a glob path)
889 var: The var to extract
Mike Frysinger1a736a82013-12-12 01:50:59 -0500890
Mike Frysinger35247af2012-11-16 18:58:06 -0500891 Returns:
892 The value of |var|
893 """
894 envds = glob.glob(envd)
895 assert len(envds) == 1, '%s: should have exactly 1 env.d file' % envd
896 envd = envds[0]
897 return cros_build_lib.LoadKeyValueFile(envd)[var]
898
899
900def _ProcessBinutilsConfig(target, output_dir):
901 """Do what binutils-config would have done"""
902 binpath = os.path.join('/bin', target + '-')
Mike Frysingerd4d40fd2014-11-06 17:30:57 -0500903
904 # Locate the bin dir holding the gold linker.
905 binutils_bin_path = os.path.join(output_dir, 'usr', toolchain.GetHostTuple(),
906 target, 'binutils-bin')
907 globpath = os.path.join(binutils_bin_path, '*-gold')
Mike Frysinger35247af2012-11-16 18:58:06 -0500908 srcpath = glob.glob(globpath)
Mike Frysingerd4d40fd2014-11-06 17:30:57 -0500909 if not srcpath:
910 # Maybe this target doesn't support gold.
911 globpath = os.path.join(binutils_bin_path, '*')
912 srcpath = glob.glob(globpath)
913 assert len(srcpath) == 1, ('%s: matched more than one path (but not *-gold)'
914 % globpath)
915 srcpath = srcpath[0]
916 ld_path = os.path.join(srcpath, 'ld')
917 assert os.path.exists(ld_path), '%s: linker is missing!' % ld_path
918 ld_path = os.path.join(srcpath, 'ld.bfd')
919 assert os.path.exists(ld_path), '%s: linker is missing!' % ld_path
920 ld_path = os.path.join(srcpath, 'ld.gold')
921 assert not os.path.exists(ld_path), ('%s: exists, but gold dir does not!'
922 % ld_path)
923
924 # Nope, no gold support to be found.
925 gold_supported = False
Ralph Nathan446aee92015-03-23 14:44:56 -0700926 logging.warning('%s: binutils lacks support for the gold linker', target)
Mike Frysingerd4d40fd2014-11-06 17:30:57 -0500927 else:
928 assert len(srcpath) == 1, '%s: did not match exactly 1 path' % globpath
929 gold_supported = True
Mike Frysinger78b7a812014-11-26 19:45:23 -0500930 srcpath = srcpath[0]
Mike Frysingerd4d40fd2014-11-06 17:30:57 -0500931
Mike Frysinger78b7a812014-11-26 19:45:23 -0500932 srcpath = srcpath[len(output_dir):]
Mike Frysinger35247af2012-11-16 18:58:06 -0500933 gccpath = os.path.join('/usr', 'libexec', 'gcc')
934 for prog in os.listdir(output_dir + srcpath):
935 # Skip binaries already wrapped.
936 if not prog.endswith('.real'):
937 GeneratePathWrapper(output_dir, binpath + prog,
938 os.path.join(srcpath, prog))
939 GeneratePathWrapper(output_dir, os.path.join(gccpath, prog),
940 os.path.join(srcpath, prog))
941
David James27ac4ae2012-12-03 23:16:15 -0800942 libpath = os.path.join('/usr', toolchain.GetHostTuple(), target, 'lib')
Mike Frysingerd4d40fd2014-11-06 17:30:57 -0500943 envd = os.path.join(output_dir, 'etc', 'env.d', 'binutils', '*')
944 if gold_supported:
945 envd += '-gold'
Mike Frysinger35247af2012-11-16 18:58:06 -0500946 srcpath = _EnvdGetVar(envd, 'LIBPATH')
947 os.symlink(os.path.relpath(srcpath, os.path.dirname(libpath)),
948 output_dir + libpath)
949
950
951def _ProcessGccConfig(target, output_dir):
952 """Do what gcc-config would have done"""
953 binpath = '/bin'
954 envd = os.path.join(output_dir, 'etc', 'env.d', 'gcc', '*')
955 srcpath = _EnvdGetVar(envd, 'GCC_PATH')
956 for prog in os.listdir(output_dir + srcpath):
957 # Skip binaries already wrapped.
958 if (not prog.endswith('.real') and
959 not prog.endswith('.elf') and
960 prog.startswith(target)):
961 GeneratePathWrapper(output_dir, os.path.join(binpath, prog),
962 os.path.join(srcpath, prog))
963 return srcpath
964
965
Frank Henigman179ec7c2015-02-06 03:01:09 -0500966def _ProcessSysrootWrappers(_target, output_dir, srcpath):
967 """Remove chroot-specific things from our sysroot wrappers"""
Mike Frysinger35247af2012-11-16 18:58:06 -0500968 # Disable ccache since we know it won't work outside of chroot.
Frank Henigman179ec7c2015-02-06 03:01:09 -0500969 for sysroot_wrapper in glob.glob(os.path.join(
970 output_dir + srcpath, 'sysroot_wrapper*')):
971 contents = osutils.ReadFile(sysroot_wrapper).splitlines()
972 for num in xrange(len(contents)):
973 if '@CCACHE_DEFAULT@' in contents[num]:
974 contents[num] = 'use_ccache = False'
975 break
976 # Can't update the wrapper in place since it's a hardlink to a file in /.
977 os.unlink(sysroot_wrapper)
978 osutils.WriteFile(sysroot_wrapper, '\n'.join(contents))
979 os.chmod(sysroot_wrapper, 0o755)
Mike Frysinger35247af2012-11-16 18:58:06 -0500980
981
982def _ProcessDistroCleanups(target, output_dir):
983 """Clean up the tree and remove all distro-specific requirements
984
985 Args:
986 target: The toolchain target name
987 output_dir: The output directory to clean up
988 """
989 _ProcessBinutilsConfig(target, output_dir)
990 gcc_path = _ProcessGccConfig(target, output_dir)
Frank Henigman179ec7c2015-02-06 03:01:09 -0500991 _ProcessSysrootWrappers(target, output_dir, gcc_path)
Mike Frysinger35247af2012-11-16 18:58:06 -0500992
993 osutils.RmDir(os.path.join(output_dir, 'etc'))
994
995
996def CreatePackagableRoot(target, output_dir, ldpaths, root='/'):
997 """Setup a tree from the packages for the specified target
998
999 This populates a path with all the files from toolchain packages so that
1000 a tarball can easily be generated from the result.
1001
1002 Args:
1003 target: The target to create a packagable root from
1004 output_dir: The output directory to place all the files
1005 ldpaths: A dict of static ldpath information
1006 root: The root path to pull all packages/files from
1007 """
1008 # Find all the files owned by the packages for this target.
1009 paths, elfs = _GetFilesForTarget(target, root=root)
1010
1011 # Link in all the package's files, any ELF dependencies, and wrap any
1012 # executable ELFs with helper scripts.
1013 def MoveUsrBinToBin(path):
1014 """Move /usr/bin to /bin so people can just use that toplevel dir"""
1015 return path[4:] if path.startswith('/usr/bin/') else path
1016 _BuildInitialPackageRoot(output_dir, paths, elfs, ldpaths,
1017 path_rewrite_func=MoveUsrBinToBin, root=root)
1018
1019 # The packages, when part of the normal distro, have helper scripts
1020 # that setup paths and such. Since we are making this standalone, we
1021 # need to preprocess all that ourselves.
1022 _ProcessDistroCleanups(target, output_dir)
1023
1024
1025def CreatePackages(targets_wanted, output_dir, root='/'):
1026 """Create redistributable cross-compiler packages for the specified targets
1027
1028 This creates toolchain packages that should be usable in conjunction with
1029 a downloaded sysroot (created elsewhere).
1030
1031 Tarballs (one per target) will be created in $PWD.
1032
1033 Args:
Don Garrett25f309a2014-03-19 14:02:12 -07001034 targets_wanted: The targets to package up.
1035 output_dir: The directory to put the packages in.
1036 root: The root path to pull all packages/files from.
Mike Frysinger35247af2012-11-16 18:58:06 -05001037 """
Ralph Nathan03047282015-03-23 11:09:32 -07001038 logging.info('Writing tarballs to %s', output_dir)
Mike Frysinger35247af2012-11-16 18:58:06 -05001039 osutils.SafeMakedirs(output_dir)
1040 ldpaths = lddtree.LoadLdpaths(root)
1041 targets = ExpandTargets(targets_wanted)
1042
David James4bc13702013-03-26 08:08:04 -07001043 with osutils.TempDir() as tempdir:
Mike Frysinger35247af2012-11-16 18:58:06 -05001044 # We have to split the root generation from the compression stages. This is
1045 # because we hardlink in all the files (to avoid overhead of reading/writing
1046 # the copies multiple times). But tar gets angry if a file's hardlink count
1047 # changes from when it starts reading a file to when it finishes.
1048 with parallel.BackgroundTaskRunner(CreatePackagableRoot) as queue:
1049 for target in targets:
1050 output_target_dir = os.path.join(tempdir, target)
1051 queue.put([target, output_target_dir, ldpaths, root])
1052
1053 # Build the tarball.
1054 with parallel.BackgroundTaskRunner(cros_build_lib.CreateTarball) as queue:
1055 for target in targets:
1056 tar_file = os.path.join(output_dir, target + '.tar.xz')
1057 queue.put([tar_file, os.path.join(tempdir, target)])
1058
1059
Brian Harring30675052012-02-29 12:18:22 -08001060def main(argv):
Mike Frysinger0c808452014-11-06 17:30:23 -05001061 parser = commandline.ArgumentParser(description=__doc__)
1062 parser.add_argument('-u', '--nousepkg',
1063 action='store_false', dest='usepkg', default=True,
1064 help='Use prebuilt packages if possible')
1065 parser.add_argument('-d', '--deleteold',
1066 action='store_true', dest='deleteold', default=False,
1067 help='Unmerge deprecated packages')
1068 parser.add_argument('-t', '--targets',
1069 dest='targets', default='sdk',
Gilad Arnold8195b532015-04-07 10:56:30 +03001070 help="Comma separated list of tuples. Special keywords "
Don Garrettc0c74002015-10-09 12:58:19 -07001071 "'host', 'sdk', 'boards', and 'all' are "
Gilad Arnold8195b532015-04-07 10:56:30 +03001072 "allowed. Defaults to 'sdk'.")
1073 parser.add_argument('--include-boards', default='', metavar='BOARDS',
1074 help='Comma separated list of boards whose toolchains we '
1075 'will always include. Default: none')
Mike Frysinger0c808452014-11-06 17:30:23 -05001076 parser.add_argument('--hostonly',
1077 dest='hostonly', default=False, action='store_true',
1078 help='Only setup the host toolchain. '
1079 'Useful for bootstrapping chroot')
Bertrand SIMONNETcae9d5f2015-03-09 15:58:01 -07001080 parser.add_argument('--show-board-cfg', '--show-cfg',
1081 dest='cfg_name', default=None,
Don Garrettc0c74002015-10-09 12:58:19 -07001082 help='Board to list toolchains tuples for')
Mike Frysinger0c808452014-11-06 17:30:23 -05001083 parser.add_argument('--create-packages',
1084 action='store_true', default=False,
1085 help='Build redistributable packages')
1086 parser.add_argument('--output-dir', default=os.getcwd(), type='path',
1087 help='Output directory')
1088 parser.add_argument('--reconfig', default=False, action='store_true',
1089 help='Reload crossdev config and reselect toolchains')
Gilad Arnold2dab78c2015-05-21 14:43:33 -07001090 parser.add_argument('--sysroot', type='path',
1091 help='The sysroot in which to install the toolchains')
Zdenek Behan508dcce2011-12-05 15:39:32 +01001092
Mike Frysinger0c808452014-11-06 17:30:23 -05001093 options = parser.parse_args(argv)
1094 options.Freeze()
Zdenek Behan508dcce2011-12-05 15:39:32 +01001095
Mike Frysinger35247af2012-11-16 18:58:06 -05001096 # Figure out what we're supposed to do and reject conflicting options.
Bertrand SIMONNETcae9d5f2015-03-09 15:58:01 -07001097 if options.cfg_name and options.create_packages:
Mike Frysinger35247af2012-11-16 18:58:06 -05001098 parser.error('conflicting options: create-packages & show-board-cfg')
Mike Frysinger984d0622012-06-01 16:08:44 -04001099
Gilad Arnold8195b532015-04-07 10:56:30 +03001100 targets_wanted = set(options.targets.split(','))
1101 boards_wanted = (set(options.include_boards.split(','))
1102 if options.include_boards else set())
Mike Frysinger35247af2012-11-16 18:58:06 -05001103
Bertrand SIMONNETcae9d5f2015-03-09 15:58:01 -07001104 if options.cfg_name:
1105 ShowConfig(options.cfg_name)
Mike Frysinger35247af2012-11-16 18:58:06 -05001106 elif options.create_packages:
1107 cros_build_lib.AssertInsideChroot()
1108 Crossdev.Load(False)
Gilad Arnold8195b532015-04-07 10:56:30 +03001109 CreatePackages(targets_wanted, options.output_dir)
Mike Frysinger35247af2012-11-16 18:58:06 -05001110 else:
1111 cros_build_lib.AssertInsideChroot()
1112 # This has to be always run as root.
1113 if os.geteuid() != 0:
1114 cros_build_lib.Die('this script must be run as root')
1115
1116 Crossdev.Load(options.reconfig)
Gilad Arnold2dab78c2015-05-21 14:43:33 -07001117 root = options.sysroot or '/'
Mike Frysinger35247af2012-11-16 18:58:06 -05001118 UpdateToolchains(options.usepkg, options.deleteold, options.hostonly,
Gilad Arnold8195b532015-04-07 10:56:30 +03001119 options.reconfig, targets_wanted, boards_wanted,
Don Garrettc0c74002015-10-09 12:58:19 -07001120 root=root)
Mike Frysinger35247af2012-11-16 18:58:06 -05001121 Crossdev.Save()
1122
1123 return 0