blob: aba02c86efac0e8ae159945fe0c7f8369b223590 [file] [log] [blame]
Allen Webb3e498aa2023-09-05 14:40:49 +00001# Copyright 2023 The ChromiumOS Authors
2# Use of this source code is governed by a BSD-style license that can be
3# found in the LICENSE file.
4
5"""Check whether a package links libraries not in RDEPEND.
6
7If no argument is provided it will check all installed packages. It takes the
8BOARD environment variable into account.
9
10Example:
11 package_hash_missing_deps.py --board=amd64-generic --match \
12 chromeos-base/cryptohome
13"""
14
15import argparse
16import collections
17import os
Allen Webbe8c1da02023-09-08 18:25:22 +000018from pathlib import Path
Allen Webb3e498aa2023-09-05 14:40:49 +000019import pprint
20import sys
Allen Webbe8c1da02023-09-08 18:25:22 +000021from typing import List, Optional, Set, Union
Allen Webb3e498aa2023-09-05 14:40:49 +000022
23from chromite.lib import build_target_lib
24from chromite.lib import chroot_lib
25from chromite.lib import commandline
26from chromite.lib import cros_build_lib
27from chromite.lib import parallel
28from chromite.lib import portage_util
29from chromite.lib.parser import package_info
30
31
Allen Webb7cc7cd92023-09-11 16:16:33 +000032VIRTUALS = {
Allen Webb4c582aa2023-09-12 17:20:49 +000033 "virtual/acl": ("sys-apps/acl", "media-libs/img-ddk-bin"),
34 "virtual/arc-opengles": (
35 "media-libs/arc-img-ddk",
36 "media-libs/arc-mesa-img",
37 "media-libs/arc-mali-drivers",
38 "media-libs/arc-mali-drivers-bifrost",
39 "media-libs/arc-mali-drivers-bifrost-bin",
40 "media-libs/arc-mali-drivers-valhall",
41 "media-libs/arc-mali-drivers-valhall-bin",
42 "media-libs/arc-mesa",
43 "media-libs/arc-mesa-amd",
44 "media-libs/arc-mesa-freedreno",
45 "media-libs/arc-mesa-iris",
46 "media-libs/arc-mesa-virgl",
47 "x11-drivers/opengles-headers",
48 ),
49 "virtual/cros-camera-hal": (
50 "media-libs/cros-camera-hal-intel-ipu3",
51 "media-libs/cros-camera-hal-intel-ipu6",
52 "media-libs/cros-camera-hal-mtk",
53 "media-libs/cros-camera-hal-qti",
54 "media-libs/cros-camera-hal-rockchip-isp1",
55 "media-libs/cros-camera-hal-usb",
56 "media-libs/qti-7c-camera-tuning",
57 ),
58 "virtual/img-ddk": ("media-libs/img-ddk", "media-libs/img-ddk-bin"),
59 "virtual/jpeg": ("media-libs/libjpeg-turbo", "media-libs/jpeg"),
60 "virtual/krb5": ("app-crypt/mit-krb5", "app-crypt/heimdal"),
Allen Webb7cc7cd92023-09-11 16:16:33 +000061 "virtual/libcrypt": ("sys-libs/libxcrypt",),
62 "virtual/libelf": ("dev-libs/elfutils", "sys-freebsd/freebsd-lib"),
63 "virtual/libiconv": ("dev-libs/libiconv",),
64 "virtual/libintl": ("dev-libs/libintl",),
65 "virtual/libudev": (
66 "sys-apps/systemd-utils",
67 "sys-fs/udev",
68 "sys-fs/eudev",
69 "sys-apps/systemd",
70 ),
71 "virtual/libusb": ("dev-libs/libusb", "sys-freebsd/freebsd-lib"),
Allen Webb4c582aa2023-09-12 17:20:49 +000072 "virtual/opengles": (
73 "media-libs/img-ddk",
74 "media-libs/img-ddk-bin",
Ricky Liangd5f64432023-09-15 15:50:04 +080075 "media-libs/libglvnd",
Allen Webb4c582aa2023-09-12 17:20:49 +000076 "media-libs/mali-drivers-bin",
77 "media-libs/mali-drivers-bifrost",
78 "media-libs/mali-drivers-bifrost-bin",
79 "media-libs/mali-drivers-valhall",
80 "media-libs/mali-drivers-valhall-bin",
81 "media-libs/mesa",
82 "media-libs/mesa-amd",
83 "media-libs/mesa-freedreno",
84 "media-libs/mesa-iris",
85 "media-libs/mesa-llvmpipe",
86 "media-libs/mesa-panfrost",
87 "media-libs/mesa-reven",
88 "x11-drivers/opengles-headers",
89 ),
90 "virtual/vulkan-icd": (
91 "media-libs/img-ddk",
92 "media-libs/img-ddk-bin",
93 "media-libs/mali-drivers-bifrost",
94 "media-libs/mali-drivers-bifrost-bin",
95 "media-libs/mali-drivers-valhall",
96 "media-libs/mali-drivers-valhall-bin",
97 "media-libs/mesa",
98 "media-libs/mesa-freedreno",
99 "media-libs/mesa-iris",
100 "media-libs/mesa-llvmpipe",
101 "media-libs/mesa-radv",
102 "media-libs/vulkan-loader",
103 ),
Allen Webb7cc7cd92023-09-11 16:16:33 +0000104}
105
106
Allen Webb3e498aa2023-09-05 14:40:49 +0000107def env_to_libs(var: str) -> List[str]:
108 """Converts value of REQUIRES to a list of .so files.
109
110 For example:
111 "arm_32: libRSSupport.so libblasV8.so libc.so ..."
112 Becomes:
113 ["libRSSupport.so", "libblasV8.so", "libc.so", ...]
114 """
115 return [x for x in var.split() if not x.endswith(":")]
116
117
118class DotSoResolver:
119 """Provides shared library related dependency operations."""
120
121 def __init__(
122 self,
123 board: Optional[str] = None,
124 root: Union[os.PathLike, str] = "/",
125 chroot: Optional[chroot_lib.Chroot] = None,
126 ):
127 self.board = board
128 self.chroot = chroot if chroot else chroot_lib.Chroot()
129
130 self.sdk_db = portage_util.PortageDB()
Mike Frysinger2c65b082023-09-21 12:22:58 -0400131 self._sdk_db_packges = None
Allen Webb3e498aa2023-09-05 14:40:49 +0000132 self.db = self.sdk_db if root == "/" else portage_util.PortageDB(root)
Mike Frysinger2c65b082023-09-21 12:22:58 -0400133 self._db_packges = None
Allen Webb3e498aa2023-09-05 14:40:49 +0000134 self.provided_libs_cache = {}
135
Allen Webbe8c1da02023-09-08 18:25:22 +0000136 # Lazy initialize since it might not be needed.
137 self.lib_to_package_map = None
138
Mike Frysinger2c65b082023-09-21 12:22:58 -0400139 @property
140 def sdk_db_packages(self):
141 """Cache sdk_db.InstalledPackages().
142
143 We won't be modifying it, so it's safe for us to reuse the results.
144 """
145 if self._sdk_db_packges is None:
146 self._sdk_db_packges = self.sdk_db.InstalledPackages()
147 return self._sdk_db_packges
148
149 @property
150 def db_packages(self):
151 """Cache db.InstalledPackages().
152
153 We won't be modifying it, so it's safe for us to reuse the results.
154 """
155 if self._db_packges is None:
156 self._db_packges = self.db.InstalledPackages()
157 return self._db_packges
158
Allen Webb3e498aa2023-09-05 14:40:49 +0000159 def get_package(
160 self, query: str, from_sdk=False
161 ) -> Optional[portage_util.InstalledPackage]:
162 """Try to find an InstalledPackage for the provided package string"""
Mike Frysinger2c65b082023-09-21 12:22:58 -0400163 packages = self.sdk_db_packages if from_sdk else self.db_packages
Allen Webb3e498aa2023-09-05 14:40:49 +0000164 info = package_info.parse(query)
165 for package in packages:
166 if info.package != package.package:
167 continue
168 if info.category != package.category:
169 continue
170 dep_info = package.package_info
171 if info.revision and info.revision != dep_info.revision:
172 continue
173 if info.pv and info.pv != dep_info.pv:
174 continue
175 return package
176 return None
177
178 def get_required_libs(self, package) -> Set[str]:
179 """Return a set of required .so files."""
Allen Webb8fc0bba2023-09-11 14:37:25 +0000180 requires = package.requires
181 if requires is not None:
182 return set(env_to_libs(package.requires))
183 # Fallback to needed if requires is not available.
184 aggregate = set()
185 needed = package.needed
186 if needed is not None:
187 for libs in needed.values():
188 aggregate.update(libs)
189 return aggregate
Allen Webb3e498aa2023-09-05 14:40:49 +0000190
Allen Webb7cc7cd92023-09-11 16:16:33 +0000191 def get_deps(self, package) -> List[portage_util.InstalledPackage]:
192 """Return a list of dependencies.
193
194 This expands the virtuals listed below.
195 """
Allen Webb3e498aa2023-09-05 14:40:49 +0000196 cpvr = f"{package.category}/{package.pf}"
Allen Webb7cc7cd92023-09-11 16:16:33 +0000197 expanded = []
198 deps = []
199 for dep in portage_util.GetFlattenedDepsForPackage(
Allen Webb3e498aa2023-09-05 14:40:49 +0000200 cpvr, board=self.board, depth=1
Allen Webb7cc7cd92023-09-11 16:16:33 +0000201 ):
202 info = package_info.parse(dep)
203 if not info:
204 continue
205
206 cp = info.cp
207 if cp in VIRTUALS:
208 expanded += VIRTUALS[cp]
209 continue
210
211 pkg = self.db.GetInstalledPackage(info.category, info.pvr)
212 if pkg:
213 deps.append(pkg)
214
215 for dep in expanded:
216 pkg = self.get_package(dep)
217 if pkg:
218 deps.append(pkg)
219
220 return deps
Allen Webb3e498aa2023-09-05 14:40:49 +0000221
222 def get_implicit_libs(self):
223 """Return a set of .so files that are provided by the system."""
Allen Webb611e8b12023-09-13 15:54:52 +0000224 # libstdc++ comes from the toolchain so always ignore it.
225 implicit_libs = {"libstdc++.so", "libstdc++.so.6"}
Allen Webb3e498aa2023-09-05 14:40:49 +0000226 for dep, from_sdk in (
227 ("cross-aarch64-cros-linux-gnu/glibc", True),
228 ("cross-armv7a-cros-linux-gnueabihf/glibc", True),
229 ("cross-i686-cros-linux-gnu/glibc", True),
230 ("cross-x86_64-cros-linux-gnu/glibc", True),
231 ("sys-libs/glibc", False),
232 ("sys-libs/libcxx", False),
233 ("sys-libs/llvm-libunwind", False),
234 ):
235 pkg = self.get_package(dep, from_sdk)
236 if not pkg:
237 continue
238 implicit_libs.update(self.provided_libs(pkg))
239 return implicit_libs
240
241 def provided_libs(self, package: portage_util.InstalledPackage) -> Set[str]:
242 """Return a set of .so files provided by |package|."""
243 cpvr = f"{package.category}/{package.pf}"
244 if cpvr in self.provided_libs_cache:
245 return self.provided_libs_cache[cpvr]
246
247 libs = set()
248 contents = package.ListContents()
249 # Keep only the .so files
250 for typ, path in contents:
251 if typ == package.DIR:
252 continue
253 filename = os.path.basename(path)
Mike Frysinger28f7b952023-09-21 11:40:01 -0400254 if filename.endswith(".so") or (
255 ".so." in filename and not filename.endswith(".debug")
256 ):
Allen Webb3e498aa2023-09-05 14:40:49 +0000257 libs.add(filename)
258 self.provided_libs_cache[cpvr] = libs
259 return libs
260
Allen Webb8fc0bba2023-09-11 14:37:25 +0000261 def cache_libs_from_build(
262 self, package: portage_util.InstalledPackage, image_dir: Path
263 ):
264 """Populate the provided_libs_cache for the package from the image dir.
265
266 When using build-info, CONTENTS might not be available yet. so provide
267 alternative using the destination directory of the ebuild.
268 """
269
270 cpvr = f"{package.category}/{package.pf}"
271 libs = set()
272 for _, _, files in os.walk(image_dir):
273 for file in files:
Mike Frysinger28f7b952023-09-21 11:40:01 -0400274 if file.endswith(".so") or (
275 ".so." in file and not file.endswith(".debug")
276 ):
Allen Webb8fc0bba2023-09-11 14:37:25 +0000277 libs.add(os.path.basename(file))
278 self.provided_libs_cache[cpvr] = libs
279
Allen Webb3e498aa2023-09-05 14:40:49 +0000280 def get_provided_from_all_deps(
281 self, package: portage_util.InstalledPackage
282 ) -> Set[str]:
283 """Return a set of .so files provided by the immediate dependencies."""
284 provided_libs = set()
Allen Webb8fc0bba2023-09-11 14:37:25 +0000285 # |package| may not actually be installed yet so manually add it to the
286 # since a package can depend on its own libs.
287 provided_libs.update(self.provided_libs(package))
Allen Webb7cc7cd92023-09-11 16:16:33 +0000288 for pkg in self.get_deps(package):
289 provided_libs.update(self.provided_libs(pkg))
Allen Webb3e498aa2023-09-05 14:40:49 +0000290 return provided_libs
291
Allen Webbe8c1da02023-09-08 18:25:22 +0000292 def lib_to_package(self, lib_filename: str = None) -> Set[str]:
293 """Return a set of packages that contain the library."""
294 if self.lib_to_package_map is None:
295 lookup = collections.defaultdict(set)
296 for pkg in self.db.InstalledPackages():
297 cpvr = f"{pkg.category}/{pkg.pf}"
298 # Packages with bundled libs for internal use and/or standaline
299 # binary packages.
300 if f"{pkg.category}/{pkg.package}" in (
301 "app-emulation/qemu",
302 "chromeos-base/aosp-frameworks-ml-nn-vts",
303 "chromeos-base/factory",
304 "chromeos-base/signingtools-bin",
305 "sys-devel/gcc-bin",
306 ):
307 continue
308 for lib in set(self.provided_libs(pkg)):
309 lookup[lib].add(cpvr)
310 self.lib_to_package_map = lookup
311 else:
312 lookup = self.lib_to_package_map
313 if not lib_filename:
314 return set()
315 try:
316 return lookup[lib_filename]
317 except KeyError:
318 return set()
Allen Webb3e498aa2023-09-05 14:40:49 +0000319
320
321def get_parser() -> commandline.ArgumentParser:
322 """Build the argument parser."""
323 parser = commandline.ArgumentParser(description=__doc__)
324
325 parser.add_argument("package", nargs="*", help="package atom")
326
327 parser.add_argument(
328 "-b",
329 "--board",
330 "--build-target",
331 default=cros_build_lib.GetDefaultBoard(),
332 help="ChromeOS board (Uses the SDK if not specified)",
333 )
334
335 parser.add_argument(
Allen Webb7d34a9a2023-09-18 09:02:15 -0500336 "--no-default-board",
337 dest="board",
338 const=None,
339 action="store_const",
340 help="Ignore the default board",
341 )
342
343 parser.add_argument(
Allen Webbe8c1da02023-09-08 18:25:22 +0000344 "-i",
345 "--build-info",
346 default=None,
347 type=Path,
348 help="Path to build-info folder post src_install",
349 )
350
351 parser.add_argument(
Allen Webb8fc0bba2023-09-11 14:37:25 +0000352 "-x",
353 "--image",
354 default=None,
355 type=Path,
356 help="Path to image folder post src_install (${D} if unspecified)",
357 )
358
359 parser.add_argument(
Allen Webb3e498aa2023-09-05 14:40:49 +0000360 "--match",
361 default=False,
362 action="store_true",
363 help="Try to match missing libraries",
364 )
365
366 parser.add_argument(
367 "-j",
368 "--jobs",
369 default=None,
370 type=int,
371 help="Number of parallel processes",
372 )
373
374 return parser
375
376
377def parse_arguments(argv: List[str]) -> argparse.Namespace:
378 """Parse and validate arguments."""
379 parser = get_parser()
380 opts = parser.parse_args(argv)
Allen Webbe8c1da02023-09-08 18:25:22 +0000381 if opts.build_info and opts.package:
Allen Webb8fc0bba2023-09-11 14:37:25 +0000382 parser.error("Do not specify a package when setting --board-info")
383 if opts.image and not opts.build_info:
384 parser.error("--image requires --board-info")
Allen Webbe8c1da02023-09-08 18:25:22 +0000385 if opts.build_info or len(opts.package) == 1:
Allen Webb3e498aa2023-09-05 14:40:49 +0000386 opts.jobs = 1
387 return opts
388
389
390def check_package(
Allen Webbe8c1da02023-09-08 18:25:22 +0000391 package: portage_util.InstalledPackage,
Allen Webb3e498aa2023-09-05 14:40:49 +0000392 implicit: Set[str],
393 resolver: DotSoResolver,
394 match: bool,
395 debug: bool,
396) -> bool:
397 """Returns false if the package has missing dependencies"""
398 if not package:
399 print("missing package")
400 return False
401
402 provided = resolver.get_provided_from_all_deps(package)
403 if debug:
404 print("provided")
405 pprint.pprint(provided)
406
407 available = provided.union(implicit)
408 required = resolver.get_required_libs(package)
409 if debug:
410 print("required")
411 pprint.pprint(required)
412 unsatisfied = required - available
413 if unsatisfied:
414 cpvr = package.package_info.cpvr
415 print(f"'{cpvr}' missing deps for: ", end="")
416 pprint.pprint(unsatisfied)
417 if match:
418 missing = set()
419 for lib in unsatisfied:
Allen Webbe8c1da02023-09-08 18:25:22 +0000420 missing.update(resolver.lib_to_package(lib))
Allen Webb3e498aa2023-09-05 14:40:49 +0000421 if missing:
422 print(f"'{cpvr}' needs: ", end="")
423 pprint.pprint(missing)
424 return False
425 return True
426
427
428def main(argv: Optional[List[str]]):
429 """Main."""
430 opts = parse_arguments(argv)
431 opts.Freeze()
432
433 board = opts.board
434 root = build_target_lib.get_default_sysroot_path(board)
435 if board:
436 os.environ["PORTAGE_CONFIGROOT"] = root
437 os.environ["SYSROOT"] = root
438 os.environ["ROOT"] = root
439
440 failed = False
441 resolver = DotSoResolver(board, root)
Allen Webb3e498aa2023-09-05 14:40:49 +0000442
443 if not opts.package:
Allen Webbe8c1da02023-09-08 18:25:22 +0000444 if opts.build_info:
Allen Webb8fc0bba2023-09-11 14:37:25 +0000445 pkg = portage_util.InstalledPackage(resolver.db, opts.build_info)
446 image_path = opts.image or os.environ.get("D")
447 if image_path:
448 resolver.cache_libs_from_build(pkg, Path(image_path))
449 packages = [pkg]
Allen Webbe8c1da02023-09-08 18:25:22 +0000450 else:
451 packages = resolver.db.InstalledPackages()
Allen Webb3e498aa2023-09-05 14:40:49 +0000452 else:
453 packages = [resolver.get_package(p) for p in opts.package]
454
455 implicit = resolver.get_implicit_libs()
456 if opts.debug:
457 print("implicit")
458 pprint.pprint(implicit)
459
460 if opts.jobs == 1:
461 for package in packages:
462 if not check_package(
463 package,
Allen Webb3e498aa2023-09-05 14:40:49 +0000464 implicit,
465 resolver,
466 opts.match,
467 opts.debug,
468 ):
469 failed = True
470 else:
Allen Webbe8c1da02023-09-08 18:25:22 +0000471 if opts.match:
472 # Pre initialize the map before starting jobs.
473 resolver.lib_to_package()
Allen Webb3e498aa2023-09-05 14:40:49 +0000474 for ret in parallel.RunTasksInProcessPool(
475 lambda p: check_package(
Allen Webbe8c1da02023-09-08 18:25:22 +0000476 p, implicit, resolver, opts.match, opts.debug
Allen Webb3e498aa2023-09-05 14:40:49 +0000477 ),
478 [[p] for p in packages],
479 opts.jobs,
480 ):
481 if not ret:
482 failed = True
483
484 if failed:
485 sys.exit(1)
486
487
488if __name__ == "__main__":
489 main(sys.argv[1:])