blob: dce7e50e6e0c5e2de8597f9c3744db04454db1d8 [file] [log] [blame]
Zdenek Behan508dcce2011-12-05 15:39:32 +01001#!/usr/bin/env python
2# Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
3# Use of this source code is governed by a BSD-style license that can be
4# found in the LICENSE file.
5
6"""This script manages the installed toolchains in the chroot.
7"""
8
9import 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
Brian Harring503f3ab2012-03-09 21:39:41 -080014from chromite.buildbot 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
Brian Harringaf019fb2012-05-10 15:06:13 -070017from chromite.lib import osutils
Mike Frysinger35247af2012-11-16 18:58:06 -050018from chromite.lib import parallel
David James27ac4ae2012-12-03 23:16:15 -080019from chromite.lib import toolchain
Mike Frysinger35247af2012-11-16 18:58:06 -050020
21# Needs to be after chromite imports.
22import lddtree
Zdenek Behan508dcce2011-12-05 15:39:32 +010023
Mike Frysinger31596002012-12-03 23:54:24 -050024if cros_build_lib.IsInsideChroot():
25 # Only import portage after we've checked that we're inside the chroot.
26 # Outside may not have portage, in which case the above may not happen.
27 # We'll check in main() if the operation needs portage.
28 import portage
Zdenek Behan508dcce2011-12-05 15:39:32 +010029
30
Matt Tennantf1e30972012-03-02 16:30:07 -080031EMERGE_CMD = os.path.join(constants.CHROMITE_BIN_DIR, 'parallel_emerge')
Zdenek Behan508dcce2011-12-05 15:39:32 +010032PACKAGE_STABLE = '[stable]'
33PACKAGE_NONE = '[none]'
34SRC_ROOT = os.path.realpath(constants.SOURCE_ROOT)
Zdenek Behan4eb6fd22012-03-12 17:00:56 +010035
36CHROMIUMOS_OVERLAY = '/usr/local/portage/chromiumos'
37STABLE_OVERLAY = '/usr/local/portage/stable'
38CROSSDEV_OVERLAY = '/usr/local/portage/crossdev'
Zdenek Behan508dcce2011-12-05 15:39:32 +010039
40
41# TODO: The versions are stored here very much like in setup_board.
42# The goal for future is to differentiate these using a config file.
43# This is done essentially by messing with GetDesiredPackageVersions()
44DEFAULT_VERSION = PACKAGE_STABLE
45DEFAULT_TARGET_VERSION_MAP = {
Zdenek Behan508dcce2011-12-05 15:39:32 +010046}
47TARGET_VERSION_MAP = {
Zdenek Behan508dcce2011-12-05 15:39:32 +010048 'host' : {
Zdenek Behan508dcce2011-12-05 15:39:32 +010049 'gdb' : PACKAGE_NONE,
50 },
51}
52# Overrides for {gcc,binutils}-config, pick a package with particular suffix.
53CONFIG_TARGET_SUFFIXES = {
54 'binutils' : {
55 'i686-pc-linux-gnu' : '-gold',
56 'x86_64-cros-linux-gnu' : '-gold',
57 },
58}
Zdenek Behan508dcce2011-12-05 15:39:32 +010059# Global per-run cache that will be filled ondemand in by GetPackageMap()
60# function as needed.
61target_version_map = {
62}
63
64
David James66a09c42012-11-05 13:31:38 -080065class Crossdev(object):
66 """Class for interacting with crossdev and caching its output."""
67
68 _CACHE_FILE = os.path.join(CROSSDEV_OVERLAY, '.configured.json')
69 _CACHE = {}
70
71 @classmethod
72 def Load(cls, reconfig):
73 """Load crossdev cache from disk."""
David James90239b92012-11-05 15:31:34 -080074 crossdev_version = GetStablePackageVersion('sys-devel/crossdev', True)
75 cls._CACHE = {'crossdev_version': crossdev_version}
David James66a09c42012-11-05 13:31:38 -080076 if os.path.exists(cls._CACHE_FILE) and not reconfig:
77 with open(cls._CACHE_FILE) as f:
78 data = json.load(f)
David James90239b92012-11-05 15:31:34 -080079 if crossdev_version == data.get('crossdev_version'):
David James66a09c42012-11-05 13:31:38 -080080 cls._CACHE = data
81
82 @classmethod
83 def Save(cls):
84 """Store crossdev cache on disk."""
85 # Save the cache from the successful run.
86 with open(cls._CACHE_FILE, 'w') as f:
87 json.dump(cls._CACHE, f)
88
89 @classmethod
90 def GetConfig(cls, target):
91 """Returns a map of crossdev provided variables about a tuple."""
92 CACHE_ATTR = '_target_tuple_map'
93
94 val = cls._CACHE.setdefault(CACHE_ATTR, {})
95 if not target in val:
96 # Find out the crossdev tuple.
97 target_tuple = target
98 if target == 'host':
David James27ac4ae2012-12-03 23:16:15 -080099 target_tuple = toolchain.GetHostTuple()
David James66a09c42012-11-05 13:31:38 -0800100 # Catch output of crossdev.
101 out = cros_build_lib.RunCommand(['crossdev', '--show-target-cfg',
102 '--ex-gdb', target_tuple],
103 print_cmd=False, redirect_stdout=True).output.splitlines()
104 # List of tuples split at the first '=', converted into dict.
105 val[target] = dict([x.split('=', 1) for x in out])
106 return val[target]
107
108 @classmethod
109 def UpdateTargets(cls, targets, usepkg, config_only=False):
110 """Calls crossdev to initialize a cross target.
111
112 Args:
113 targets - the list of targets to initialize using crossdev
114 usepkg - copies the commandline opts
115 config_only - Just update
116 """
117 configured_targets = cls._CACHE.setdefault('configured_targets', [])
118
119 cmdbase = ['crossdev', '--show-fail-log']
120 cmdbase.extend(['--env', 'FEATURES=splitdebug'])
121 # Pick stable by default, and override as necessary.
122 cmdbase.extend(['-P', '--oneshot'])
123 if usepkg:
124 cmdbase.extend(['-P', '--getbinpkg',
125 '-P', '--usepkgonly',
126 '--without-headers'])
127
128 overlays = '%s %s' % (CHROMIUMOS_OVERLAY, STABLE_OVERLAY)
129 cmdbase.extend(['--overlays', overlays])
130 cmdbase.extend(['--ov-output', CROSSDEV_OVERLAY])
131
132 for target in targets:
133 if config_only and target in configured_targets:
134 continue
135
136 cmd = cmdbase + ['-t', target]
137
138 for pkg in GetTargetPackages(target):
139 if pkg == 'gdb':
140 # Gdb does not have selectable versions.
141 cmd.append('--ex-gdb')
142 continue
143 # The first of the desired versions is the "primary" one.
144 version = GetDesiredPackageVersions(target, pkg)[0]
145 cmd.extend(['--%s' % pkg, version])
146
147 cmd.extend(targets[target]['crossdev'].split())
148 if config_only:
149 # In this case we want to just quietly reinit
150 cmd.append('--init-target')
151 cros_build_lib.RunCommand(cmd, print_cmd=False, redirect_stdout=True)
152 else:
153 cros_build_lib.RunCommand(cmd)
154
155 configured_targets.append(target)
156
Zdenek Behan4eb6fd22012-03-12 17:00:56 +0100157
Zdenek Behan508dcce2011-12-05 15:39:32 +0100158def GetPackageMap(target):
159 """Compiles a package map for the given target from the constants.
160
161 Uses a cache in target_version_map, that is dynamically filled in as needed,
162 since here everything is static data and the structuring is for ease of
163 configurability only.
164
165 args:
166 target - the target for which to return a version map
167
168 returns a map between packages and desired versions in internal format
169 (using the PACKAGE_* constants)
170 """
171 if target in target_version_map:
172 return target_version_map[target]
173
174 # Start from copy of the global defaults.
175 result = copy.copy(DEFAULT_TARGET_VERSION_MAP)
176
Zdenek Behanf4d18a02012-03-22 15:45:05 +0100177 for pkg in GetTargetPackages(target):
Zdenek Behan508dcce2011-12-05 15:39:32 +0100178 # prefer any specific overrides
179 if pkg in TARGET_VERSION_MAP.get(target, {}):
180 result[pkg] = TARGET_VERSION_MAP[target][pkg]
181 else:
182 # finally, if not already set, set a sane default
183 result.setdefault(pkg, DEFAULT_VERSION)
184 target_version_map[target] = result
185 return result
186
187
Zdenek Behanf4d18a02012-03-22 15:45:05 +0100188def GetTargetPackages(target):
189 """Returns a list of packages for a given target."""
David James66a09c42012-11-05 13:31:38 -0800190 conf = Crossdev.GetConfig(target)
Zdenek Behanf4d18a02012-03-22 15:45:05 +0100191 # Undesired packages are denoted by empty ${pkg}_pn variable.
192 return [x for x in conf['crosspkgs'].strip("'").split() if conf[x+'_pn']]
193
194
Zdenek Behan4eb6fd22012-03-12 17:00:56 +0100195# Portage helper functions:
196def GetPortagePackage(target, package):
197 """Returns a package name for the given target."""
David James66a09c42012-11-05 13:31:38 -0800198 conf = Crossdev.GetConfig(target)
Zdenek Behan4eb6fd22012-03-12 17:00:56 +0100199 # Portage category:
Zdenek Behan508dcce2011-12-05 15:39:32 +0100200 if target == 'host':
Zdenek Behan4eb6fd22012-03-12 17:00:56 +0100201 category = conf[package + '_category']
Zdenek Behan508dcce2011-12-05 15:39:32 +0100202 else:
Zdenek Behan4eb6fd22012-03-12 17:00:56 +0100203 category = conf['category']
204 # Portage package:
205 pn = conf[package + '_pn']
206 # Final package name:
207 assert(category)
208 assert(pn)
209 return '%s/%s' % (category, pn)
210
211
Zdenek Behan4eb6fd22012-03-12 17:00:56 +0100212def IsPackageDisabled(target, package):
213 """Returns if the given package is not used for the target."""
214 return GetDesiredPackageVersions(target, package) == [PACKAGE_NONE]
215
Liam McLoughlinf54a0782012-05-17 23:36:52 +0100216
David James66a09c42012-11-05 13:31:38 -0800217def GetInstalledPackageVersions(atom):
Zdenek Behan508dcce2011-12-05 15:39:32 +0100218 """Extracts the list of current versions of a target, package pair.
219
220 args:
David James66a09c42012-11-05 13:31:38 -0800221 atom - the atom to operate on (e.g. sys-devel/gcc)
Zdenek Behan508dcce2011-12-05 15:39:32 +0100222
223 returns the list of versions of the package currently installed.
224 """
Zdenek Behan508dcce2011-12-05 15:39:32 +0100225 versions = []
Mike Frysinger506e75f2012-12-17 14:21:13 -0500226 # pylint: disable=E1101
David James90239b92012-11-05 15:31:34 -0800227 for pkg in portage.db['/']['vartree'].dbapi.match(atom, use_cache=0):
Zdenek Behan508dcce2011-12-05 15:39:32 +0100228 version = portage.versions.cpv_getversion(pkg)
229 versions.append(version)
230 return versions
231
232
David James90239b92012-11-05 15:31:34 -0800233def GetStablePackageVersion(atom, installed):
Zdenek Behan508dcce2011-12-05 15:39:32 +0100234 """Extracts the current stable version for a given package.
235
236 args:
237 target, package - the target/package to operate on eg. i686-pc-linux-gnu,gcc
Zdenek Behan699ddd32012-04-13 07:14:08 +0200238 installed - Whether we want installed packages or ebuilds
Zdenek Behan508dcce2011-12-05 15:39:32 +0100239
240 returns a string containing the latest version.
241 """
David James90239b92012-11-05 15:31:34 -0800242 pkgtype = 'vartree' if installed else 'porttree'
Mike Frysinger506e75f2012-12-17 14:21:13 -0500243 # pylint: disable=E1101
David James90239b92012-11-05 15:31:34 -0800244 cpv = portage.best(portage.db['/'][pkgtype].dbapi.match(atom, use_cache=0))
245 return portage.versions.cpv_getversion(cpv) if cpv else None
Zdenek Behan508dcce2011-12-05 15:39:32 +0100246
247
Zdenek Behan699ddd32012-04-13 07:14:08 +0200248def VersionListToNumeric(target, package, versions, installed):
Zdenek Behan508dcce2011-12-05 15:39:32 +0100249 """Resolves keywords in a given version list for a particular package.
250
251 Resolving means replacing PACKAGE_STABLE with the actual number.
252
253 args:
254 target, package - the target/package to operate on eg. i686-pc-linux-gnu,gcc
255 versions - list of versions to resolve
256
257 returns list of purely numeric versions equivalent to argument
258 """
259 resolved = []
David James90239b92012-11-05 15:31:34 -0800260 atom = GetPortagePackage(target, package)
Zdenek Behan508dcce2011-12-05 15:39:32 +0100261 for version in versions:
262 if version == PACKAGE_STABLE:
David James90239b92012-11-05 15:31:34 -0800263 resolved.append(GetStablePackageVersion(atom, installed))
Zdenek Behan508dcce2011-12-05 15:39:32 +0100264 elif version != PACKAGE_NONE:
265 resolved.append(version)
266 return resolved
267
268
269def GetDesiredPackageVersions(target, package):
270 """Produces the list of desired versions for each target, package pair.
271
272 The first version in the list is implicitly treated as primary, ie.
273 the version that will be initialized by crossdev and selected.
274
275 If the version is PACKAGE_STABLE, it really means the current version which
276 is emerged by using the package atom with no particular version key.
277 Since crossdev unmasks all packages by default, this will actually
278 mean 'unstable' in most cases.
279
280 args:
281 target, package - the target/package to operate on eg. i686-pc-linux-gnu,gcc
282
283 returns a list composed of either a version string, PACKAGE_STABLE
284 """
285 packagemap = GetPackageMap(target)
286
287 versions = []
288 if package in packagemap:
289 versions.append(packagemap[package])
290
291 return versions
292
293
294def TargetIsInitialized(target):
295 """Verifies if the given list of targets has been correctly initialized.
296
297 This determines whether we have to call crossdev while emerging
298 toolchain packages or can do it using emerge. Emerge is naturally
299 preferred, because all packages can be updated in a single pass.
300
301 args:
302 targets - list of individual cross targets which are checked
303
304 returns True if target is completely initialized
305 returns False otherwise
306 """
307 # Check if packages for the given target all have a proper version.
308 try:
Zdenek Behanf4d18a02012-03-22 15:45:05 +0100309 for package in GetTargetPackages(target):
David James66a09c42012-11-05 13:31:38 -0800310 atom = GetPortagePackage(target, package)
Zdenek Behan4eb6fd22012-03-12 17:00:56 +0100311 # Do we even want this package && is it initialized?
David James90239b92012-11-05 15:31:34 -0800312 if not IsPackageDisabled(target, package) and not (
313 GetStablePackageVersion(atom, True) and
314 GetStablePackageVersion(atom, False)):
Zdenek Behan508dcce2011-12-05 15:39:32 +0100315 return False
316 return True
317 except cros_build_lib.RunCommandError:
318 # Fails - The target has likely never been initialized before.
319 return False
320
321
322def RemovePackageMask(target):
323 """Removes a package.mask file for the given platform.
324
325 The pre-existing package.mask files can mess with the keywords.
326
327 args:
328 target - the target for which to remove the file
329 """
330 maskfile = os.path.join('/etc/portage/package.mask', 'cross-' + target)
Brian Harringaf019fb2012-05-10 15:06:13 -0700331 osutils.SafeUnlink(maskfile)
Zdenek Behan508dcce2011-12-05 15:39:32 +0100332
333
Zdenek Behan508dcce2011-12-05 15:39:32 +0100334# Main functions performing the actual update steps.
Mike Frysingerc880a962013-11-08 13:59:06 -0500335def RebuildLibtool():
336 """Rebuild libtool as needed
337
338 Libtool hardcodes full paths to internal gcc files, so whenever we upgrade
339 gcc, libtool will break. We can't use binary packages either as those will
340 most likely be compiled against the previous version of gcc.
341 """
342 needs_update = False
343 with open('/usr/bin/libtool') as f:
344 for line in f:
345 # Look for a line like:
346 # sys_lib_search_path_spec="..."
347 # It'll be a list of paths and gcc will be one of them.
348 if line.startswith('sys_lib_search_path_spec='):
349 line = line.rstrip()
350 for path in line.split('=', 1)[1].strip('"').split():
351 if not os.path.exists(path):
352 print 'Rebuilding libtool after gcc upgrade'
353 print ' %s' % line
354 print ' missing path: %s' % path
355 needs_update = True
356 break
357
358 if needs_update:
359 break
360
361 if needs_update:
362 cmd = [EMERGE_CMD, '--oneshot', 'sys-devel/libtool']
363 cros_build_lib.RunCommand(cmd)
364
365
Zdenek Behan508dcce2011-12-05 15:39:32 +0100366def UpdateTargets(targets, usepkg):
367 """Determines which packages need update/unmerge and defers to portage.
368
369 args:
370 targets - the list of targets to update
371 usepkg - copies the commandline option
372 """
David James90239b92012-11-05 15:31:34 -0800373 # Remove keyword files created by old versions of cros_setup_toolchains.
374 osutils.SafeUnlink('/etc/portage/package.keywords/cross-host')
Zdenek Behan508dcce2011-12-05 15:39:32 +0100375
376 # For each target, we do two things. Figure out the list of updates,
377 # and figure out the appropriate keywords/masks. Crossdev will initialize
378 # these, but they need to be regenerated on every update.
379 print 'Determining required toolchain updates...'
David James90239b92012-11-05 15:31:34 -0800380 mergemap = {}
Zdenek Behan508dcce2011-12-05 15:39:32 +0100381 for target in targets:
382 # Record the highest needed version for each target, for masking purposes.
383 RemovePackageMask(target)
Zdenek Behanf4d18a02012-03-22 15:45:05 +0100384 for package in GetTargetPackages(target):
Zdenek Behan508dcce2011-12-05 15:39:32 +0100385 # Portage name for the package
Zdenek Behan4eb6fd22012-03-12 17:00:56 +0100386 if IsPackageDisabled(target, package):
387 continue
388 pkg = GetPortagePackage(target, package)
David James66a09c42012-11-05 13:31:38 -0800389 current = GetInstalledPackageVersions(pkg)
Zdenek Behan508dcce2011-12-05 15:39:32 +0100390 desired = GetDesiredPackageVersions(target, package)
Zdenek Behan699ddd32012-04-13 07:14:08 +0200391 desired_num = VersionListToNumeric(target, package, desired, False)
Zdenek Behan4eb6fd22012-03-12 17:00:56 +0100392 mergemap[pkg] = set(desired_num).difference(current)
Zdenek Behan508dcce2011-12-05 15:39:32 +0100393
Zdenek Behan508dcce2011-12-05 15:39:32 +0100394 packages = []
395 for pkg in mergemap:
396 for ver in mergemap[pkg]:
Zdenek Behan677b6d82012-04-11 05:31:47 +0200397 if ver != PACKAGE_NONE:
David James90239b92012-11-05 15:31:34 -0800398 packages.append(pkg)
Zdenek Behan508dcce2011-12-05 15:39:32 +0100399
400 if not packages:
401 print 'Nothing to update!'
David Jamesf8c672f2012-11-06 13:38:11 -0800402 return False
Zdenek Behan508dcce2011-12-05 15:39:32 +0100403
404 print 'Updating packages:'
405 print packages
406
Zdenek Behan7e33b4e2012-03-12 17:00:56 +0100407 cmd = [EMERGE_CMD, '--oneshot', '--update']
Zdenek Behan508dcce2011-12-05 15:39:32 +0100408 if usepkg:
409 cmd.extend(['--getbinpkg', '--usepkgonly'])
410
411 cmd.extend(packages)
412 cros_build_lib.RunCommand(cmd)
David Jamesf8c672f2012-11-06 13:38:11 -0800413 return True
Zdenek Behan508dcce2011-12-05 15:39:32 +0100414
415
416def CleanTargets(targets):
417 """Unmerges old packages that are assumed unnecessary."""
418 unmergemap = {}
419 for target in targets:
Zdenek Behanf4d18a02012-03-22 15:45:05 +0100420 for package in GetTargetPackages(target):
Zdenek Behan4eb6fd22012-03-12 17:00:56 +0100421 if IsPackageDisabled(target, package):
422 continue
423 pkg = GetPortagePackage(target, package)
David James66a09c42012-11-05 13:31:38 -0800424 current = GetInstalledPackageVersions(pkg)
Zdenek Behan508dcce2011-12-05 15:39:32 +0100425 desired = GetDesiredPackageVersions(target, package)
Zdenek Behan699ddd32012-04-13 07:14:08 +0200426 desired_num = VersionListToNumeric(target, package, desired, True)
427 if not set(desired_num).issubset(current):
428 print 'Some packages have been held back, skipping clean!'
429 return
Zdenek Behan508dcce2011-12-05 15:39:32 +0100430 unmergemap[pkg] = set(current).difference(desired_num)
431
432 # Cleaning doesn't care about consistency and rebuilding package.* files.
433 packages = []
434 for pkg, vers in unmergemap.iteritems():
435 packages.extend('=%s-%s' % (pkg, ver) for ver in vers if ver != '9999')
436
437 if packages:
438 print 'Cleaning packages:'
439 print packages
Zdenek Behan7e33b4e2012-03-12 17:00:56 +0100440 cmd = [EMERGE_CMD, '--unmerge']
Zdenek Behan508dcce2011-12-05 15:39:32 +0100441 cmd.extend(packages)
442 cros_build_lib.RunCommand(cmd)
443 else:
444 print 'Nothing to clean!'
445
446
447def SelectActiveToolchains(targets, suffixes):
448 """Runs gcc-config and binutils-config to select the desired.
449
450 args:
451 targets - the targets to select
452 """
453 for package in ['gcc', 'binutils']:
454 for target in targets:
455 # Pick the first version in the numbered list as the selected one.
456 desired = GetDesiredPackageVersions(target, package)
Zdenek Behan699ddd32012-04-13 07:14:08 +0200457 desired_num = VersionListToNumeric(target, package, desired, True)
Zdenek Behan508dcce2011-12-05 15:39:32 +0100458 desired = desired_num[0]
459 # *-config does not play revisions, strip them, keep just PV.
460 desired = portage.versions.pkgsplit('%s-%s' % (package, desired))[1]
461
462 if target == 'host':
463 # *-config is the only tool treating host identically (by tuple).
David James27ac4ae2012-12-03 23:16:15 -0800464 target = toolchain.GetHostTuple()
Zdenek Behan508dcce2011-12-05 15:39:32 +0100465
466 # And finally, attach target to it.
467 desired = '%s-%s' % (target, desired)
468
469 # Target specific hacks
470 if package in suffixes:
471 if target in suffixes[package]:
472 desired += suffixes[package][target]
473
David James7ec5efc2012-11-06 09:39:49 -0800474 extra_env = {'CHOST': target}
475 cmd = ['%s-config' % package, '-c', target]
Zdenek Behan508dcce2011-12-05 15:39:32 +0100476 current = cros_build_lib.RunCommand(cmd, print_cmd=False,
David James7ec5efc2012-11-06 09:39:49 -0800477 redirect_stdout=True, extra_env=extra_env).output.splitlines()[0]
Zdenek Behan508dcce2011-12-05 15:39:32 +0100478 # Do not gcc-config when the current is live or nothing needs to be done.
479 if current != desired and current != '9999':
480 cmd = [ package + '-config', desired ]
Zdenek Behan7e33b4e2012-03-12 17:00:56 +0100481 cros_build_lib.RunCommand(cmd, print_cmd=False)
Zdenek Behan508dcce2011-12-05 15:39:32 +0100482
483
Mike Frysinger35247af2012-11-16 18:58:06 -0500484def ExpandTargets(targets_wanted):
485 """Expand any possible toolchain aliases into full targets
486
487 This will expand 'all' and 'sdk' into the respective toolchain tuples.
488
489 Args:
490 targets_wanted: The targets specified by the user.
Mike Frysinger1a736a82013-12-12 01:50:59 -0500491
Mike Frysinger35247af2012-11-16 18:58:06 -0500492 Returns:
493 Full list of tuples with pseudo targets removed.
494 """
David James27ac4ae2012-12-03 23:16:15 -0800495 alltargets = toolchain.GetAllTargets()
Mike Frysinger35247af2012-11-16 18:58:06 -0500496 targets_wanted = set(targets_wanted)
497 if targets_wanted == set(['all']):
498 targets = alltargets
499 elif targets_wanted == set(['sdk']):
500 # Filter out all the non-sdk toolchains as we don't want to mess
501 # with those in all of our builds.
David James27ac4ae2012-12-03 23:16:15 -0800502 targets = toolchain.FilterToolchains(alltargets, 'sdk', True)
Mike Frysinger35247af2012-11-16 18:58:06 -0500503 else:
504 # Verify user input.
505 nonexistent = targets_wanted.difference(alltargets)
506 if nonexistent:
507 raise ValueError('Invalid targets: %s', ','.join(nonexistent))
508 targets = dict((t, alltargets[t]) for t in targets_wanted)
509 return targets
510
511
David Jamesf8c672f2012-11-06 13:38:11 -0800512def UpdateToolchains(usepkg, deleteold, hostonly, reconfig,
513 targets_wanted, boards_wanted):
Zdenek Behan508dcce2011-12-05 15:39:32 +0100514 """Performs all steps to create a synchronized toolchain enviroment.
515
516 args:
517 arguments correspond to the given commandline flags
518 """
David Jamesf8c672f2012-11-06 13:38:11 -0800519 targets, crossdev_targets, reconfig_targets = {}, {}, {}
Zdenek Behan7e33b4e2012-03-12 17:00:56 +0100520 if not hostonly:
521 # For hostonly, we can skip most of the below logic, much of which won't
522 # work on bare systems where this is useful.
Mike Frysinger35247af2012-11-16 18:58:06 -0500523 targets = ExpandTargets(targets_wanted)
Mike Frysinger7ccee992012-06-01 21:27:59 -0400524
Mike Frysinger7ccee992012-06-01 21:27:59 -0400525 # Now re-add any targets that might be from this board. This is
526 # to allow unofficial boards to declare their own toolchains.
527 for board in boards_wanted:
David James27ac4ae2012-12-03 23:16:15 -0800528 targets.update(toolchain.GetToolchainsForBoard(board))
Zdenek Behan508dcce2011-12-05 15:39:32 +0100529
Zdenek Behan7e33b4e2012-03-12 17:00:56 +0100530 # First check and initialize all cross targets that need to be.
Mike Frysinger7ccee992012-06-01 21:27:59 -0400531 for target in targets:
532 if TargetIsInitialized(target):
533 reconfig_targets[target] = targets[target]
534 else:
535 crossdev_targets[target] = targets[target]
Zdenek Behan7e33b4e2012-03-12 17:00:56 +0100536 if crossdev_targets:
Zdenek Behan8be29ba2012-05-29 23:10:34 +0200537 print 'The following targets need to be re-initialized:'
538 print crossdev_targets
David James66a09c42012-11-05 13:31:38 -0800539 Crossdev.UpdateTargets(crossdev_targets, usepkg)
Zdenek Behan8be29ba2012-05-29 23:10:34 +0200540 # Those that were not initialized may need a config update.
David James66a09c42012-11-05 13:31:38 -0800541 Crossdev.UpdateTargets(reconfig_targets, usepkg, config_only=True)
Zdenek Behan508dcce2011-12-05 15:39:32 +0100542
Zdenek Behan7e33b4e2012-03-12 17:00:56 +0100543 # We want host updated.
Mike Frysinger7ccee992012-06-01 21:27:59 -0400544 targets['host'] = {}
Zdenek Behan7e33b4e2012-03-12 17:00:56 +0100545
546 # Now update all packages.
David Jamesf8c672f2012-11-06 13:38:11 -0800547 if UpdateTargets(targets, usepkg) or crossdev_targets or reconfig:
548 SelectActiveToolchains(targets, CONFIG_TARGET_SUFFIXES)
David James7ec5efc2012-11-06 09:39:49 -0800549
550 if deleteold:
551 CleanTargets(targets)
Zdenek Behan508dcce2011-12-05 15:39:32 +0100552
Mike Frysingerc880a962013-11-08 13:59:06 -0500553 # Now that we've cleared out old versions, see if we need to rebuild
554 # anything. Can't do this earlier as it might not be broken.
555 RebuildLibtool()
556
Zdenek Behan508dcce2011-12-05 15:39:32 +0100557
Mike Frysinger35247af2012-11-16 18:58:06 -0500558def ShowBoardConfig(board):
559 """Show the toolchain tuples used by |board|
560
561 Args:
562 board: The board to query.
563 """
David James27ac4ae2012-12-03 23:16:15 -0800564 toolchains = toolchain.GetToolchainsForBoard(board)
Mike Frysinger35247af2012-11-16 18:58:06 -0500565 # Make sure we display the default toolchain first.
David James27ac4ae2012-12-03 23:16:15 -0800566 print ','.join(
567 toolchain.FilterToolchains(toolchains, 'default', True).keys() +
568 toolchain.FilterToolchains(toolchains, 'default', False).keys())
Mike Frysinger35247af2012-11-16 18:58:06 -0500569
570
Mike Frysinger35247af2012-11-16 18:58:06 -0500571def GeneratePathWrapper(root, wrappath, path):
572 """Generate a shell script to execute another shell script
573
574 Since we can't symlink a wrapped ELF (see GenerateLdsoWrapper) because the
575 argv[0] won't be pointing to the correct path, generate a shell script that
576 just executes another program with its full path.
577
578 Args:
579 root: The root tree to generate scripts inside of
580 wrappath: The full path (inside |root|) to create the wrapper
581 path: The target program which this wrapper will execute
582 """
583 replacements = {
584 'path': path,
585 'relroot': os.path.relpath('/', os.path.dirname(wrappath)),
586 }
587 wrapper = """#!/bin/sh
588base=$(realpath "$0")
589basedir=${base%%/*}
590exec "${basedir}/%(relroot)s%(path)s" "$@"
591""" % replacements
592 root_wrapper = root + wrappath
593 if os.path.islink(root_wrapper):
594 os.unlink(root_wrapper)
595 else:
596 osutils.SafeMakedirs(os.path.dirname(root_wrapper))
597 osutils.WriteFile(root_wrapper, wrapper)
Mike Frysinger60ec1012013-10-21 00:11:10 -0400598 os.chmod(root_wrapper, 0o755)
Mike Frysinger35247af2012-11-16 18:58:06 -0500599
600
601def FileIsCrosSdkElf(elf):
602 """Determine if |elf| is an ELF that we execute in the cros_sdk
603
604 We don't need this to be perfect, just quick. It makes sure the ELF
605 is a 64bit LSB x86_64 ELF. That is the native type of cros_sdk.
606
607 Args:
608 elf: The file to check
Mike Frysinger1a736a82013-12-12 01:50:59 -0500609
Mike Frysinger35247af2012-11-16 18:58:06 -0500610 Returns:
611 True if we think |elf| is a native ELF
612 """
613 with open(elf) as f:
614 data = f.read(20)
615 # Check the magic number, EI_CLASS, EI_DATA, and e_machine.
616 return (data[0:4] == '\x7fELF' and
617 data[4] == '\x02' and
618 data[5] == '\x01' and
619 data[18] == '\x3e')
620
621
622def IsPathPackagable(ptype, path):
623 """Should the specified file be included in a toolchain package?
624
625 We only need to handle files as we'll create dirs as we need them.
626
627 Further, trim files that won't be useful:
628 - non-english translations (.mo) since it'd require env vars
629 - debug files since these are for the host compiler itself
630 - info/man pages as they're big, and docs are online, and the
631 native docs should work fine for the most part (`man gcc`)
632
633 Args:
634 ptype: A string describing the path type (i.e. 'file' or 'dir' or 'sym')
635 path: The full path to inspect
Mike Frysinger1a736a82013-12-12 01:50:59 -0500636
Mike Frysinger35247af2012-11-16 18:58:06 -0500637 Returns:
638 True if we want to include this path in the package
639 """
640 return not (ptype in ('dir',) or
641 path.startswith('/usr/lib/debug/') or
642 os.path.splitext(path)[1] == '.mo' or
643 ('/man/' in path or '/info/' in path))
644
645
646def ReadlinkRoot(path, root):
647 """Like os.readlink(), but relative to a |root|
648
649 Args:
650 path: The symlink to read
651 root: The path to use for resolving absolute symlinks
Mike Frysinger1a736a82013-12-12 01:50:59 -0500652
Mike Frysinger35247af2012-11-16 18:58:06 -0500653 Returns:
654 A fully resolved symlink path
655 """
656 while os.path.islink(root + path):
657 path = os.path.join(os.path.dirname(path), os.readlink(root + path))
658 return path
659
660
661def _GetFilesForTarget(target, root='/'):
662 """Locate all the files to package for |target|
663
664 This does not cover ELF dependencies.
665
666 Args:
667 target: The toolchain target name
668 root: The root path to pull all packages from
Mike Frysinger1a736a82013-12-12 01:50:59 -0500669
Mike Frysinger35247af2012-11-16 18:58:06 -0500670 Returns:
671 A tuple of a set of all packable paths, and a set of all paths which
672 are also native ELFs
673 """
674 paths = set()
675 elfs = set()
676
677 # Find all the files owned by the packages for this target.
678 for pkg in GetTargetPackages(target):
679 # Ignore packages that are part of the target sysroot.
680 if pkg in ('kernel', 'libc'):
681 continue
682
683 atom = GetPortagePackage(target, pkg)
684 cat, pn = atom.split('/')
685 ver = GetInstalledPackageVersions(atom)[0]
686 cros_build_lib.Info('packaging %s-%s', atom, ver)
687
688 # pylint: disable=E1101
689 dblink = portage.dblink(cat, pn + '-' + ver, myroot=root,
690 settings=portage.settings)
691 contents = dblink.getcontents()
692 for obj in contents:
693 ptype = contents[obj][0]
694 if not IsPathPackagable(ptype, obj):
695 continue
696
697 if ptype == 'obj':
698 # For native ELFs, we need to pull in their dependencies too.
699 if FileIsCrosSdkElf(obj):
700 elfs.add(obj)
701 paths.add(obj)
702
703 return paths, elfs
704
705
706def _BuildInitialPackageRoot(output_dir, paths, elfs, ldpaths,
707 path_rewrite_func=lambda x:x, root='/'):
708 """Link in all packable files and their runtime dependencies
709
710 This also wraps up executable ELFs with helper scripts.
711
712 Args:
713 output_dir: The output directory to store files
714 paths: All the files to include
715 elfs: All the files which are ELFs (a subset of |paths|)
716 ldpaths: A dict of static ldpath information
717 path_rewrite_func: User callback to rewrite paths in output_dir
718 root: The root path to pull all packages/files from
719 """
720 # Link in all the files.
721 sym_paths = []
722 for path in paths:
723 new_path = path_rewrite_func(path)
724 dst = output_dir + new_path
725 osutils.SafeMakedirs(os.path.dirname(dst))
726
727 # Is this a symlink which we have to rewrite or wrap?
728 # Delay wrap check until after we have created all paths.
729 src = root + path
730 if os.path.islink(src):
731 tgt = os.readlink(src)
732 if os.path.sep in tgt:
733 sym_paths.append((new_path, lddtree.normpath(ReadlinkRoot(src, root))))
734
735 # Rewrite absolute links to relative and then generate the symlink
736 # ourselves. All other symlinks can be hardlinked below.
737 if tgt[0] == '/':
738 tgt = os.path.relpath(tgt, os.path.dirname(new_path))
739 os.symlink(tgt, dst)
740 continue
741
742 os.link(src, dst)
743
744 # Now see if any of the symlinks need to be wrapped.
745 for sym, tgt in sym_paths:
746 if tgt in elfs:
747 GeneratePathWrapper(output_dir, sym, tgt)
748
749 # Locate all the dependencies for all the ELFs. Stick them all in the
750 # top level "lib" dir to make the wrapper simpler. This exact path does
751 # not matter since we execute ldso directly, and we tell the ldso the
752 # exact path to search for its libraries.
753 libdir = os.path.join(output_dir, 'lib')
754 osutils.SafeMakedirs(libdir)
755 donelibs = set()
756 for elf in elfs:
757 e = lddtree.ParseELF(elf, root, ldpaths)
758 interp = e['interp']
759 if interp:
760 # Generate a wrapper if it is executable.
Mike Frysingerc2ec0902013-03-26 01:28:45 -0400761 interp = os.path.join('/lib', os.path.basename(interp))
762 lddtree.GenerateLdsoWrapper(output_dir, path_rewrite_func(elf), interp,
763 libpaths=e['rpath'] + e['runpath'])
Mike Frysinger35247af2012-11-16 18:58:06 -0500764
765 for lib, lib_data in e['libs'].iteritems():
766 if lib in donelibs:
767 continue
768
769 src = path = lib_data['path']
770 if path is None:
771 cros_build_lib.Warning('%s: could not locate %s', elf, lib)
772 continue
773 donelibs.add(lib)
774
775 # Needed libs are the SONAME, but that is usually a symlink, not a
776 # real file. So link in the target rather than the symlink itself.
777 # We have to walk all the possible symlinks (SONAME could point to a
778 # symlink which points to a symlink), and we have to handle absolute
779 # ourselves (since we have a "root" argument).
780 dst = os.path.join(libdir, os.path.basename(path))
781 src = ReadlinkRoot(src, root)
782
783 os.link(root + src, dst)
784
785
786def _EnvdGetVar(envd, var):
787 """Given a Gentoo env.d file, extract a var from it
788
789 Args:
790 envd: The env.d file to load (may be a glob path)
791 var: The var to extract
Mike Frysinger1a736a82013-12-12 01:50:59 -0500792
Mike Frysinger35247af2012-11-16 18:58:06 -0500793 Returns:
794 The value of |var|
795 """
796 envds = glob.glob(envd)
797 assert len(envds) == 1, '%s: should have exactly 1 env.d file' % envd
798 envd = envds[0]
799 return cros_build_lib.LoadKeyValueFile(envd)[var]
800
801
802def _ProcessBinutilsConfig(target, output_dir):
803 """Do what binutils-config would have done"""
804 binpath = os.path.join('/bin', target + '-')
David James27ac4ae2012-12-03 23:16:15 -0800805 globpath = os.path.join(output_dir, 'usr', toolchain.GetHostTuple(), target,
Mike Frysinger35247af2012-11-16 18:58:06 -0500806 'binutils-bin', '*-gold')
807 srcpath = glob.glob(globpath)
808 assert len(srcpath) == 1, '%s: did not match 1 path' % globpath
809 srcpath = srcpath[0][len(output_dir):]
810 gccpath = os.path.join('/usr', 'libexec', 'gcc')
811 for prog in os.listdir(output_dir + srcpath):
812 # Skip binaries already wrapped.
813 if not prog.endswith('.real'):
814 GeneratePathWrapper(output_dir, binpath + prog,
815 os.path.join(srcpath, prog))
816 GeneratePathWrapper(output_dir, os.path.join(gccpath, prog),
817 os.path.join(srcpath, prog))
818
David James27ac4ae2012-12-03 23:16:15 -0800819 libpath = os.path.join('/usr', toolchain.GetHostTuple(), target, 'lib')
Mike Frysinger35247af2012-11-16 18:58:06 -0500820 envd = os.path.join(output_dir, 'etc', 'env.d', 'binutils', '*-gold')
821 srcpath = _EnvdGetVar(envd, 'LIBPATH')
822 os.symlink(os.path.relpath(srcpath, os.path.dirname(libpath)),
823 output_dir + libpath)
824
825
826def _ProcessGccConfig(target, output_dir):
827 """Do what gcc-config would have done"""
828 binpath = '/bin'
829 envd = os.path.join(output_dir, 'etc', 'env.d', 'gcc', '*')
830 srcpath = _EnvdGetVar(envd, 'GCC_PATH')
831 for prog in os.listdir(output_dir + srcpath):
832 # Skip binaries already wrapped.
833 if (not prog.endswith('.real') and
834 not prog.endswith('.elf') and
835 prog.startswith(target)):
836 GeneratePathWrapper(output_dir, os.path.join(binpath, prog),
837 os.path.join(srcpath, prog))
838 return srcpath
839
840
841def _ProcessSysrootWrapper(_target, output_dir, srcpath):
842 """Remove chroot-specific things from our sysroot wrapper"""
843 # Disable ccache since we know it won't work outside of chroot.
844 sysroot_wrapper = glob.glob(os.path.join(
845 output_dir + srcpath, 'sysroot_wrapper*'))[0]
846 contents = osutils.ReadFile(sysroot_wrapper).splitlines()
847 for num in xrange(len(contents)):
848 if '@CCACHE_DEFAULT@' in contents[num]:
849 contents[num] = 'use_ccache = False'
850 break
851 # Can't update the wrapper in place since it's a hardlink to a file in /.
852 os.unlink(sysroot_wrapper)
853 osutils.WriteFile(sysroot_wrapper, '\n'.join(contents))
Mike Frysinger60ec1012013-10-21 00:11:10 -0400854 os.chmod(sysroot_wrapper, 0o755)
Mike Frysinger35247af2012-11-16 18:58:06 -0500855
856
857def _ProcessDistroCleanups(target, output_dir):
858 """Clean up the tree and remove all distro-specific requirements
859
860 Args:
861 target: The toolchain target name
862 output_dir: The output directory to clean up
863 """
864 _ProcessBinutilsConfig(target, output_dir)
865 gcc_path = _ProcessGccConfig(target, output_dir)
866 _ProcessSysrootWrapper(target, output_dir, gcc_path)
867
868 osutils.RmDir(os.path.join(output_dir, 'etc'))
869
870
871def CreatePackagableRoot(target, output_dir, ldpaths, root='/'):
872 """Setup a tree from the packages for the specified target
873
874 This populates a path with all the files from toolchain packages so that
875 a tarball can easily be generated from the result.
876
877 Args:
878 target: The target to create a packagable root from
879 output_dir: The output directory to place all the files
880 ldpaths: A dict of static ldpath information
881 root: The root path to pull all packages/files from
882 """
883 # Find all the files owned by the packages for this target.
884 paths, elfs = _GetFilesForTarget(target, root=root)
885
886 # Link in all the package's files, any ELF dependencies, and wrap any
887 # executable ELFs with helper scripts.
888 def MoveUsrBinToBin(path):
889 """Move /usr/bin to /bin so people can just use that toplevel dir"""
890 return path[4:] if path.startswith('/usr/bin/') else path
891 _BuildInitialPackageRoot(output_dir, paths, elfs, ldpaths,
892 path_rewrite_func=MoveUsrBinToBin, root=root)
893
894 # The packages, when part of the normal distro, have helper scripts
895 # that setup paths and such. Since we are making this standalone, we
896 # need to preprocess all that ourselves.
897 _ProcessDistroCleanups(target, output_dir)
898
899
900def CreatePackages(targets_wanted, output_dir, root='/'):
901 """Create redistributable cross-compiler packages for the specified targets
902
903 This creates toolchain packages that should be usable in conjunction with
904 a downloaded sysroot (created elsewhere).
905
906 Tarballs (one per target) will be created in $PWD.
907
908 Args:
909 targets_wanted: The targets to package up
910 root: The root path to pull all packages/files from
911 """
912 osutils.SafeMakedirs(output_dir)
913 ldpaths = lddtree.LoadLdpaths(root)
914 targets = ExpandTargets(targets_wanted)
915
David James4bc13702013-03-26 08:08:04 -0700916 with osutils.TempDir() as tempdir:
Mike Frysinger35247af2012-11-16 18:58:06 -0500917 # We have to split the root generation from the compression stages. This is
918 # because we hardlink in all the files (to avoid overhead of reading/writing
919 # the copies multiple times). But tar gets angry if a file's hardlink count
920 # changes from when it starts reading a file to when it finishes.
921 with parallel.BackgroundTaskRunner(CreatePackagableRoot) as queue:
922 for target in targets:
923 output_target_dir = os.path.join(tempdir, target)
924 queue.put([target, output_target_dir, ldpaths, root])
925
926 # Build the tarball.
927 with parallel.BackgroundTaskRunner(cros_build_lib.CreateTarball) as queue:
928 for target in targets:
929 tar_file = os.path.join(output_dir, target + '.tar.xz')
930 queue.put([tar_file, os.path.join(tempdir, target)])
931
932
Brian Harring30675052012-02-29 12:18:22 -0800933def main(argv):
Zdenek Behan508dcce2011-12-05 15:39:32 +0100934 usage = """usage: %prog [options]
935
Mike Frysinger506e75f2012-12-17 14:21:13 -0500936 The script installs and updates the toolchains in your chroot."""
937 parser = commandline.OptionParser(usage)
Zdenek Behan508dcce2011-12-05 15:39:32 +0100938 parser.add_option('-u', '--nousepkg',
939 action='store_false', dest='usepkg', default=True,
Mike Frysinger506e75f2012-12-17 14:21:13 -0500940 help='Use prebuilt packages if possible')
Zdenek Behan508dcce2011-12-05 15:39:32 +0100941 parser.add_option('-d', '--deleteold',
942 action='store_true', dest='deleteold', default=False,
Mike Frysinger506e75f2012-12-17 14:21:13 -0500943 help='Unmerge deprecated packages')
Zdenek Behan508dcce2011-12-05 15:39:32 +0100944 parser.add_option('-t', '--targets',
Mike Frysingereaebb582012-06-19 13:04:53 -0400945 dest='targets', default='sdk',
Mike Frysinger506e75f2012-12-17 14:21:13 -0500946 help='Comma separated list of tuples. '
947 'Special keyword \'host\' is allowed. Default: sdk')
Mike Frysinger7ccee992012-06-01 21:27:59 -0400948 parser.add_option('--include-boards',
949 dest='include_boards', default='',
Mike Frysinger506e75f2012-12-17 14:21:13 -0500950 help='Comma separated list of boards whose toolchains we'
951 ' will always include. Default: none')
Liam McLoughlinf54a0782012-05-17 23:36:52 +0100952 parser.add_option('--hostonly',
Zdenek Behan7e33b4e2012-03-12 17:00:56 +0100953 dest='hostonly', default=False, action='store_true',
Mike Frysinger506e75f2012-12-17 14:21:13 -0500954 help='Only setup the host toolchain. '
955 'Useful for bootstrapping chroot')
Liam McLoughlinf54a0782012-05-17 23:36:52 +0100956 parser.add_option('--show-board-cfg',
957 dest='board_cfg', default=None,
Mike Frysinger506e75f2012-12-17 14:21:13 -0500958 help='Board to list toolchain tuples for')
Mike Frysinger35247af2012-11-16 18:58:06 -0500959 parser.add_option('--create-packages',
960 action='store_true', default=False,
961 help='Build redistributable packages')
962 parser.add_option('--output-dir', default=os.getcwd(), type='path',
963 help='Output directory')
David James66a09c42012-11-05 13:31:38 -0800964 parser.add_option('--reconfig', default=False, action='store_true',
Mike Frysinger506e75f2012-12-17 14:21:13 -0500965 help='Reload crossdev config and reselect toolchains')
Zdenek Behan508dcce2011-12-05 15:39:32 +0100966
Mike Frysinger35247af2012-11-16 18:58:06 -0500967 (options, remaining_arguments) = parser.parse_args(argv)
968 if len(remaining_arguments):
969 parser.error('script does not take arguments: %s' % remaining_arguments)
Zdenek Behan508dcce2011-12-05 15:39:32 +0100970
Mike Frysinger35247af2012-11-16 18:58:06 -0500971 # Figure out what we're supposed to do and reject conflicting options.
972 if options.board_cfg and options.create_packages:
973 parser.error('conflicting options: create-packages & show-board-cfg')
Mike Frysinger984d0622012-06-01 16:08:44 -0400974
Zdenek Behan508dcce2011-12-05 15:39:32 +0100975 targets = set(options.targets.split(','))
Mike Frysinger7ccee992012-06-01 21:27:59 -0400976 boards = set(options.include_boards.split(',')) if options.include_boards \
977 else set()
Mike Frysinger35247af2012-11-16 18:58:06 -0500978
979 if options.board_cfg:
980 ShowBoardConfig(options.board_cfg)
981 elif options.create_packages:
982 cros_build_lib.AssertInsideChroot()
983 Crossdev.Load(False)
984 CreatePackages(targets, options.output_dir)
985 else:
986 cros_build_lib.AssertInsideChroot()
987 # This has to be always run as root.
988 if os.geteuid() != 0:
989 cros_build_lib.Die('this script must be run as root')
990
991 Crossdev.Load(options.reconfig)
992 UpdateToolchains(options.usepkg, options.deleteold, options.hostonly,
993 options.reconfig, targets, boards)
994 Crossdev.Save()
995
996 return 0