blob: 5c6b73f215ebded16e4d68eac88cb68e1f188a8b [file] [log] [blame]
Alex Deymo3cfb9cd2014-08-18 15:56:35 -07001# Copyright 2014 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"""Script to discover dependencies and other file information from a build.
Alex Deymo3cfb9cd2014-08-18 15:56:35 -07006
7Some files in the image are installed to provide some functionality, such as
8chrome, shill or bluetoothd provide different functionality that can be
9present or not on a given build. Many other files are dependencies from these
10files that need to be present in the image for them to work. These dependencies
11come from needed shared libraries, executed files and other configuration files
12read.
13
14This script currently discovers dependencies between ELF files for libraries
15required at load time (libraries loaded by the dynamic linker) but not
Alex Deymo365b10c2014-08-25 13:14:28 -070016libraries loaded at runtime with dlopen(). It also computes size and file type
17in several cases to help understand the contents of the built image.
Alex Deymo3cfb9cd2014-08-18 15:56:35 -070018"""
19
Alex Deymo3cfb9cd2014-08-18 15:56:35 -070020import json
Chris McDonald59650c32021-07-20 15:29:28 -060021import logging
Alex Deymo3cfb9cd2014-08-18 15:56:35 -070022import multiprocessing
23import os
Alex Deymo3cfb9cd2014-08-18 15:56:35 -070024import stat
Mike Frysinger00688e12022-04-21 21:22:35 -040025from typing import Union
Alex Deymo3cfb9cd2014-08-18 15:56:35 -070026
Chris McDonald59650c32021-07-20 15:29:28 -060027from chromite.third_party import lddtree
28
Alex Deymo3cfb9cd2014-08-18 15:56:35 -070029from chromite.lib import commandline
Alex Deymo365b10c2014-08-25 13:14:28 -070030from chromite.lib import filetype
Alex Deymo3cfb9cd2014-08-18 15:56:35 -070031from chromite.lib import parseelf
Alex Deymoc99dd0b2014-09-09 16:15:17 -070032from chromite.lib import portage_util
Alex Deymo3cfb9cd2014-08-18 15:56:35 -070033
34
35# Regex to parse Gentoo atoms. This should match the following ebuild names,
36# splitting the package name from the version.
37# without version:
38# chromeos-base/tty
39# chromeos-base/libchrome-271506
40# sys-kernel/chromeos-kernel-3_8
41# with version:
42# chromeos-base/tty-0.0.1-r4
43# chromeos-base/libchrome-271506-r5
44# sys-kernel/chromeos-kernel-3_8-3.8.11-r35
45RE_EBUILD_WITHOUT_VERSION = r'^([a-z0-9\-]+/[a-zA-Z0-9\_\+\-]+)$'
46RE_EBUILD_WITH_VERSION = (
47 r'^=?([a-z0-9\-]+/[a-zA-Z0-9\_\+\-]+)\-([^\-]+(\-r\d+)?)$')
48
49
50def ParseELFWithArgs(args):
51 """Wrapper to parseelf.ParseELF accepting a single arg.
52
53 This wrapper is required to use multiprocessing.Pool.map function.
54
55 Returns:
56 A 2-tuple with the passed relative path and the result of ParseELF(). On
57 error, when ParseELF() returns None, this function returns None.
58 """
59 elf = parseelf.ParseELF(*args)
60 if elf is None:
61 return
62 return args[1], elf
63
64
65class DepTracker(object):
66 """Tracks dependencies and file information in a root directory.
67
68 This class computes dependencies and other information related to the files
69 in the root image.
70 """
71
Mike Frysinger00688e12022-04-21 21:22:35 -040072 def __init__(
73 self,
74 root: Union[str, os.PathLike],
75 jobs: int = 1):
76 # TODO(vapier): Convert this to Path.
77 root = str(root)
Alex Deymo3cfb9cd2014-08-18 15:56:35 -070078 root_st = os.lstat(root)
79 if not stat.S_ISDIR(root_st.st_mode):
80 raise Exception('root (%s) must be a directory' % root)
81 self._root = root.rstrip('/') + '/'
Alex Deymo365b10c2014-08-25 13:14:28 -070082 self._file_type_decoder = filetype.FileTypeDecoder(root)
Alex Deymo3cfb9cd2014-08-18 15:56:35 -070083
84 # A wrapper to the multiprocess map function. We avoid launching a pool
85 # of processes when jobs is 1 so python exceptions kill the main process,
86 # useful for debugging.
87 if jobs > 1:
88 self._pool = multiprocessing.Pool(jobs)
89 self._imap = self._pool.map
90 else:
Mike Frysingere852b072021-05-21 12:39:03 -040091 self._imap = map
Alex Deymo3cfb9cd2014-08-18 15:56:35 -070092
93 self._files = {}
94 self._ebuilds = {}
95
96 # Mapping of rel_paths for symlinks and hardlinks. Hardlinks are assumed
97 # to point to the lowest lexicographically file with the same inode.
98 self._symlinks = {}
99 self._hardlinks = {}
100
Alex Deymo3cfb9cd2014-08-18 15:56:35 -0700101 def Init(self):
102 """Generates the initial list of files."""
103 # First iteration over all the files in root searching for symlinks and
104 # non-regular files.
105 seen_inodes = {}
106 for basepath, _, filenames in sorted(os.walk(self._root)):
107 for filename in sorted(filenames):
108 full_path = os.path.join(basepath, filename)
109 rel_path = full_path[len(self._root):]
110 st = os.lstat(full_path)
111
112 file_data = {
113 'size': st.st_size,
114 }
115 self._files[rel_path] = file_data
116
117 # Track symlinks.
118 if stat.S_ISLNK(st.st_mode):
119 link_path = os.readlink(full_path)
120 # lddtree's normpath handles a little more cases than the os.path
121 # version. In particular, it handles the '//' case.
122 self._symlinks[rel_path] = (
123 link_path.lstrip('/') if link_path and link_path[0] == '/' else
124 lddtree.normpath(os.path.join(os.path.dirname(rel_path),
125 link_path)))
126 file_data['deps'] = {
Mike Frysingere65f3752014-12-08 00:46:39 -0500127 'symlink': [self._symlinks[rel_path]]
Alex Deymo3cfb9cd2014-08-18 15:56:35 -0700128 }
129
130 # Track hardlinks.
131 if st.st_ino in seen_inodes:
132 self._hardlinks[rel_path] = seen_inodes[st.st_ino]
133 continue
134 seen_inodes[st.st_ino] = rel_path
135
136 def SaveJSON(self, filename):
137 """Save the computed information to a JSON file.
138
139 Args:
140 filename: The destination JSON file.
141 """
142 data = {
143 'files': self._files,
144 'ebuilds': self._ebuilds,
145 }
146 json.dump(data, open(filename, 'w'))
147
Alex Deymoc99dd0b2014-09-09 16:15:17 -0700148 def ComputeEbuildDeps(self, sysroot):
Alex Deymo3cfb9cd2014-08-18 15:56:35 -0700149 """Compute the dependencies between ebuilds and files.
150
151 Iterates over the list of ebuilds in the database and annotates the files
152 with the ebuilds they are in. For each ebuild installing a file in the root,
153 also compute the direct dependencies. Stores the information internally.
154
155 Args:
Alex Deymoc99dd0b2014-09-09 16:15:17 -0700156 sysroot: The path to the sysroot, for example "/build/link".
Alex Deymo3cfb9cd2014-08-18 15:56:35 -0700157 """
Alex Deymoc99dd0b2014-09-09 16:15:17 -0700158 portage_db = portage_util.PortageDB(sysroot)
159 if not os.path.exists(portage_db.db_path):
Ralph Nathan446aee92015-03-23 14:44:56 -0700160 logging.warning('PortageDB directory not found: %s', portage_db.db_path)
Alex Deymoc99dd0b2014-09-09 16:15:17 -0700161 return
162
163 for pkg in portage_db.InstalledPackages():
164 pkg_files = []
165 pkg_size = 0
166 cpf = '%s/%s' % (pkg.category, pkg.pf)
167 for typ, rel_path in pkg.ListContents():
168 # We ignore other entries like for example "dir".
169 if not typ in (pkg.OBJ, pkg.SYM):
170 continue
171 # We ignore files installed in the SYSROOT that weren't copied to the
172 # image.
173 if not rel_path in self._files:
174 continue
175 pkg_files.append(rel_path)
176 file_data = self._files[rel_path]
177 if 'ebuild' in file_data:
Lann Martinffb95162018-08-28 12:02:54 -0600178 logging.warning('Duplicated entry for %s: %s and %s',
Ralph Nathan446aee92015-03-23 14:44:56 -0700179 rel_path, file_data['ebuild'], cpf)
Alex Deymoc99dd0b2014-09-09 16:15:17 -0700180 file_data['ebuild'] = cpf
181 pkg_size += file_data['size']
182 # Ignore packages that don't install any file.
183 if not pkg_files:
184 continue
185 self._ebuilds[cpf] = {
186 'size': pkg_size,
187 'files': len(pkg_files),
188 'atom': '%s/%s' % (pkg.category, pkg.package),
189 'version': pkg.version,
190 }
Alex Deymo3cfb9cd2014-08-18 15:56:35 -0700191 # TODO(deymo): Parse dependencies between ebuilds.
192
193 def ComputeELFFileDeps(self):
194 """Computes the dependencies between files.
195
196 Computes the dependencies between the files in the root directory passed
197 during construction. The dependencies are inferred for ELF files.
198 The list of dependencies for each file in the passed rootfs as a dict().
199 The result's keys are the relative path of the files and the value of each
200 file is a list of dependencies. A dependency is a tuple (dep_path,
201 dep_type) where the dep_path is relative path from the passed root to the
202 dependent file and dep_type is one the following strings stating how the
203 dependency was discovered:
204 'ldd': The dependent ELF file is listed as needed in the dynamic section.
205 'symlink': The dependent file is a symlink to the depending.
206 If there are dependencies of a given type whose target file wasn't
207 determined, a tuple (None, dep_type) is included. This is the case for
208 example is a program uses library that wasn't found.
209 """
210 ldpaths = lddtree.LoadLdpaths(self._root)
211
212 # First iteration over all the files in root searching for symlinks and
213 # non-regular files.
214 parseelf_args = []
Mike Frysinger0bdbc102019-06-13 15:27:29 -0400215 for rel_path, file_data in self._files.items():
Alex Deymo3cfb9cd2014-08-18 15:56:35 -0700216 if rel_path in self._symlinks or rel_path in self._hardlinks:
217 continue
218
219 full_path = os.path.join(self._root, rel_path)
220 st = os.lstat(full_path)
221 if not stat.S_ISREG(st.st_mode):
222 continue
223 parseelf_args.append((self._root, rel_path, ldpaths))
224
225 # Parallelize the ELF lookup step since it is quite expensive.
226 elfs = dict(x for x in self._imap(ParseELFWithArgs, parseelf_args)
227 if not x is None)
228
Mike Frysinger0bdbc102019-06-13 15:27:29 -0400229 for rel_path, elf in elfs.items():
Alex Deymo3cfb9cd2014-08-18 15:56:35 -0700230 file_data = self._files[rel_path]
Alex Deymo365b10c2014-08-25 13:14:28 -0700231 # Fill in the ftype if not set yet. We complete this value at this point
232 # to avoid re-parsing the ELF file later.
233 if not 'ftype' in file_data:
234 ftype = self._file_type_decoder.GetType(rel_path, elf=elf)
235 if ftype:
236 file_data['ftype'] = ftype
237
Alex Deymo3cfb9cd2014-08-18 15:56:35 -0700238 file_deps = file_data.get('deps', {})
239 # Dependencies based on the result of ldd.
240 for lib in elf.get('needed', []):
241 lib_path = elf['libs'][lib]['path']
242 if not 'ldd' in file_deps:
243 file_deps['ldd'] = []
244 file_deps['ldd'].append(lib_path)
245
246 if file_deps:
247 file_data['deps'] = file_deps
248
Alex Deymo365b10c2014-08-25 13:14:28 -0700249 def ComputeFileTypes(self):
250 """Computes all the missing file type for the files in the root."""
Mike Frysinger0bdbc102019-06-13 15:27:29 -0400251 for rel_path, file_data in self._files.items():
Alex Deymo365b10c2014-08-25 13:14:28 -0700252 if 'ftype' in file_data:
253 continue
254 ftype = self._file_type_decoder.GetType(rel_path)
255 if ftype:
256 file_data['ftype'] = ftype
257
Alex Deymo3cfb9cd2014-08-18 15:56:35 -0700258
259def ParseArgs(argv):
260 """Return parsed commandline arguments."""
261
262 parser = commandline.ArgumentParser()
263 parser.add_argument(
264 '-j', '--jobs', type=int, default=multiprocessing.cpu_count(),
265 help='number of simultaneous jobs.')
266 parser.add_argument(
Alex Deymoc99dd0b2014-09-09 16:15:17 -0700267 '--sysroot', type='path', metavar='SYSROOT',
268 help='parse portage DB for ebuild information from the provided sysroot.')
Alex Deymo3cfb9cd2014-08-18 15:56:35 -0700269 parser.add_argument(
270 '--json', type='path',
Alex Deymoc99dd0b2014-09-09 16:15:17 -0700271 help='store information in JSON file.')
Alex Deymo3cfb9cd2014-08-18 15:56:35 -0700272
273 parser.add_argument(
274 'root', type='path',
275 help='path to the directory where the rootfs is mounted.')
276
277 opts = parser.parse_args(argv)
278 opts.Freeze()
279 return opts
280
281
282def main(argv):
283 """Main function to start the script."""
284 opts = ParseArgs(argv)
Ralph Nathan5a582ff2015-03-20 18:18:30 -0700285 logging.debug('Options are %s', opts)
Alex Deymo3cfb9cd2014-08-18 15:56:35 -0700286
287 dt = DepTracker(opts.root, jobs=opts.jobs)
288 dt.Init()
289
290 dt.ComputeELFFileDeps()
Alex Deymo365b10c2014-08-25 13:14:28 -0700291 dt.ComputeFileTypes()
Alex Deymo3cfb9cd2014-08-18 15:56:35 -0700292
Alex Deymoc99dd0b2014-09-09 16:15:17 -0700293 if opts.sysroot:
294 dt.ComputeEbuildDeps(opts.sysroot)
Alex Deymo3cfb9cd2014-08-18 15:56:35 -0700295
296 if opts.json:
297 dt.SaveJSON(opts.json)