blob: eda9206480245fd007f5fceef99277262ed3a6e3 [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()
131 self.db = self.sdk_db if root == "/" else portage_util.PortageDB(root)
132 self.provided_libs_cache = {}
133
Allen Webbe8c1da02023-09-08 18:25:22 +0000134 # Lazy initialize since it might not be needed.
135 self.lib_to_package_map = None
136
Allen Webb3e498aa2023-09-05 14:40:49 +0000137 def get_package(
138 self, query: str, from_sdk=False
139 ) -> Optional[portage_util.InstalledPackage]:
140 """Try to find an InstalledPackage for the provided package string"""
141 packages = (self.sdk_db if from_sdk else self.db).InstalledPackages()
142 info = package_info.parse(query)
143 for package in packages:
144 if info.package != package.package:
145 continue
146 if info.category != package.category:
147 continue
148 dep_info = package.package_info
149 if info.revision and info.revision != dep_info.revision:
150 continue
151 if info.pv and info.pv != dep_info.pv:
152 continue
153 return package
154 return None
155
156 def get_required_libs(self, package) -> Set[str]:
157 """Return a set of required .so files."""
Allen Webb8fc0bba2023-09-11 14:37:25 +0000158 requires = package.requires
159 if requires is not None:
160 return set(env_to_libs(package.requires))
161 # Fallback to needed if requires is not available.
162 aggregate = set()
163 needed = package.needed
164 if needed is not None:
165 for libs in needed.values():
166 aggregate.update(libs)
167 return aggregate
Allen Webb3e498aa2023-09-05 14:40:49 +0000168
Allen Webb7cc7cd92023-09-11 16:16:33 +0000169 def get_deps(self, package) -> List[portage_util.InstalledPackage]:
170 """Return a list of dependencies.
171
172 This expands the virtuals listed below.
173 """
Allen Webb3e498aa2023-09-05 14:40:49 +0000174 cpvr = f"{package.category}/{package.pf}"
Allen Webb7cc7cd92023-09-11 16:16:33 +0000175 expanded = []
176 deps = []
177 for dep in portage_util.GetFlattenedDepsForPackage(
Allen Webb3e498aa2023-09-05 14:40:49 +0000178 cpvr, board=self.board, depth=1
Allen Webb7cc7cd92023-09-11 16:16:33 +0000179 ):
180 info = package_info.parse(dep)
181 if not info:
182 continue
183
184 cp = info.cp
185 if cp in VIRTUALS:
186 expanded += VIRTUALS[cp]
187 continue
188
189 pkg = self.db.GetInstalledPackage(info.category, info.pvr)
190 if pkg:
191 deps.append(pkg)
192
193 for dep in expanded:
194 pkg = self.get_package(dep)
195 if pkg:
196 deps.append(pkg)
197
198 return deps
Allen Webb3e498aa2023-09-05 14:40:49 +0000199
200 def get_implicit_libs(self):
201 """Return a set of .so files that are provided by the system."""
Allen Webb611e8b12023-09-13 15:54:52 +0000202 # libstdc++ comes from the toolchain so always ignore it.
203 implicit_libs = {"libstdc++.so", "libstdc++.so.6"}
Allen Webb3e498aa2023-09-05 14:40:49 +0000204 for dep, from_sdk in (
205 ("cross-aarch64-cros-linux-gnu/glibc", True),
206 ("cross-armv7a-cros-linux-gnueabihf/glibc", True),
207 ("cross-i686-cros-linux-gnu/glibc", True),
208 ("cross-x86_64-cros-linux-gnu/glibc", True),
209 ("sys-libs/glibc", False),
210 ("sys-libs/libcxx", False),
211 ("sys-libs/llvm-libunwind", False),
212 ):
213 pkg = self.get_package(dep, from_sdk)
214 if not pkg:
215 continue
216 implicit_libs.update(self.provided_libs(pkg))
217 return implicit_libs
218
219 def provided_libs(self, package: portage_util.InstalledPackage) -> Set[str]:
220 """Return a set of .so files provided by |package|."""
221 cpvr = f"{package.category}/{package.pf}"
222 if cpvr in self.provided_libs_cache:
223 return self.provided_libs_cache[cpvr]
224
225 libs = set()
226 contents = package.ListContents()
227 # Keep only the .so files
228 for typ, path in contents:
229 if typ == package.DIR:
230 continue
231 filename = os.path.basename(path)
Mike Frysinger28f7b952023-09-21 11:40:01 -0400232 if filename.endswith(".so") or (
233 ".so." in filename and not filename.endswith(".debug")
234 ):
Allen Webb3e498aa2023-09-05 14:40:49 +0000235 libs.add(filename)
236 self.provided_libs_cache[cpvr] = libs
237 return libs
238
Allen Webb8fc0bba2023-09-11 14:37:25 +0000239 def cache_libs_from_build(
240 self, package: portage_util.InstalledPackage, image_dir: Path
241 ):
242 """Populate the provided_libs_cache for the package from the image dir.
243
244 When using build-info, CONTENTS might not be available yet. so provide
245 alternative using the destination directory of the ebuild.
246 """
247
248 cpvr = f"{package.category}/{package.pf}"
249 libs = set()
250 for _, _, files in os.walk(image_dir):
251 for file in files:
Mike Frysinger28f7b952023-09-21 11:40:01 -0400252 if file.endswith(".so") or (
253 ".so." in file and not file.endswith(".debug")
254 ):
Allen Webb8fc0bba2023-09-11 14:37:25 +0000255 libs.add(os.path.basename(file))
256 self.provided_libs_cache[cpvr] = libs
257
Allen Webb3e498aa2023-09-05 14:40:49 +0000258 def get_provided_from_all_deps(
259 self, package: portage_util.InstalledPackage
260 ) -> Set[str]:
261 """Return a set of .so files provided by the immediate dependencies."""
262 provided_libs = set()
Allen Webb8fc0bba2023-09-11 14:37:25 +0000263 # |package| may not actually be installed yet so manually add it to the
264 # since a package can depend on its own libs.
265 provided_libs.update(self.provided_libs(package))
Allen Webb7cc7cd92023-09-11 16:16:33 +0000266 for pkg in self.get_deps(package):
267 provided_libs.update(self.provided_libs(pkg))
Allen Webb3e498aa2023-09-05 14:40:49 +0000268 return provided_libs
269
Allen Webbe8c1da02023-09-08 18:25:22 +0000270 def lib_to_package(self, lib_filename: str = None) -> Set[str]:
271 """Return a set of packages that contain the library."""
272 if self.lib_to_package_map is None:
273 lookup = collections.defaultdict(set)
274 for pkg in self.db.InstalledPackages():
275 cpvr = f"{pkg.category}/{pkg.pf}"
276 # Packages with bundled libs for internal use and/or standaline
277 # binary packages.
278 if f"{pkg.category}/{pkg.package}" in (
279 "app-emulation/qemu",
280 "chromeos-base/aosp-frameworks-ml-nn-vts",
281 "chromeos-base/factory",
282 "chromeos-base/signingtools-bin",
283 "sys-devel/gcc-bin",
284 ):
285 continue
286 for lib in set(self.provided_libs(pkg)):
287 lookup[lib].add(cpvr)
288 self.lib_to_package_map = lookup
289 else:
290 lookup = self.lib_to_package_map
291 if not lib_filename:
292 return set()
293 try:
294 return lookup[lib_filename]
295 except KeyError:
296 return set()
Allen Webb3e498aa2023-09-05 14:40:49 +0000297
298
299def get_parser() -> commandline.ArgumentParser:
300 """Build the argument parser."""
301 parser = commandline.ArgumentParser(description=__doc__)
302
303 parser.add_argument("package", nargs="*", help="package atom")
304
305 parser.add_argument(
306 "-b",
307 "--board",
308 "--build-target",
309 default=cros_build_lib.GetDefaultBoard(),
310 help="ChromeOS board (Uses the SDK if not specified)",
311 )
312
313 parser.add_argument(
Allen Webb7d34a9a2023-09-18 09:02:15 -0500314 "--no-default-board",
315 dest="board",
316 const=None,
317 action="store_const",
318 help="Ignore the default board",
319 )
320
321 parser.add_argument(
Allen Webbe8c1da02023-09-08 18:25:22 +0000322 "-i",
323 "--build-info",
324 default=None,
325 type=Path,
326 help="Path to build-info folder post src_install",
327 )
328
329 parser.add_argument(
Allen Webb8fc0bba2023-09-11 14:37:25 +0000330 "-x",
331 "--image",
332 default=None,
333 type=Path,
334 help="Path to image folder post src_install (${D} if unspecified)",
335 )
336
337 parser.add_argument(
Allen Webb3e498aa2023-09-05 14:40:49 +0000338 "--match",
339 default=False,
340 action="store_true",
341 help="Try to match missing libraries",
342 )
343
344 parser.add_argument(
345 "-j",
346 "--jobs",
347 default=None,
348 type=int,
349 help="Number of parallel processes",
350 )
351
352 return parser
353
354
355def parse_arguments(argv: List[str]) -> argparse.Namespace:
356 """Parse and validate arguments."""
357 parser = get_parser()
358 opts = parser.parse_args(argv)
Allen Webbe8c1da02023-09-08 18:25:22 +0000359 if opts.build_info and opts.package:
Allen Webb8fc0bba2023-09-11 14:37:25 +0000360 parser.error("Do not specify a package when setting --board-info")
361 if opts.image and not opts.build_info:
362 parser.error("--image requires --board-info")
Allen Webbe8c1da02023-09-08 18:25:22 +0000363 if opts.build_info or len(opts.package) == 1:
Allen Webb3e498aa2023-09-05 14:40:49 +0000364 opts.jobs = 1
365 return opts
366
367
368def check_package(
Allen Webbe8c1da02023-09-08 18:25:22 +0000369 package: portage_util.InstalledPackage,
Allen Webb3e498aa2023-09-05 14:40:49 +0000370 implicit: Set[str],
371 resolver: DotSoResolver,
372 match: bool,
373 debug: bool,
374) -> bool:
375 """Returns false if the package has missing dependencies"""
376 if not package:
377 print("missing package")
378 return False
379
380 provided = resolver.get_provided_from_all_deps(package)
381 if debug:
382 print("provided")
383 pprint.pprint(provided)
384
385 available = provided.union(implicit)
386 required = resolver.get_required_libs(package)
387 if debug:
388 print("required")
389 pprint.pprint(required)
390 unsatisfied = required - available
391 if unsatisfied:
392 cpvr = package.package_info.cpvr
393 print(f"'{cpvr}' missing deps for: ", end="")
394 pprint.pprint(unsatisfied)
395 if match:
396 missing = set()
397 for lib in unsatisfied:
Allen Webbe8c1da02023-09-08 18:25:22 +0000398 missing.update(resolver.lib_to_package(lib))
Allen Webb3e498aa2023-09-05 14:40:49 +0000399 if missing:
400 print(f"'{cpvr}' needs: ", end="")
401 pprint.pprint(missing)
402 return False
403 return True
404
405
406def main(argv: Optional[List[str]]):
407 """Main."""
408 opts = parse_arguments(argv)
409 opts.Freeze()
410
411 board = opts.board
412 root = build_target_lib.get_default_sysroot_path(board)
413 if board:
414 os.environ["PORTAGE_CONFIGROOT"] = root
415 os.environ["SYSROOT"] = root
416 os.environ["ROOT"] = root
417
418 failed = False
419 resolver = DotSoResolver(board, root)
Allen Webb3e498aa2023-09-05 14:40:49 +0000420
421 if not opts.package:
Allen Webbe8c1da02023-09-08 18:25:22 +0000422 if opts.build_info:
Allen Webb8fc0bba2023-09-11 14:37:25 +0000423 pkg = portage_util.InstalledPackage(resolver.db, opts.build_info)
424 image_path = opts.image or os.environ.get("D")
425 if image_path:
426 resolver.cache_libs_from_build(pkg, Path(image_path))
427 packages = [pkg]
Allen Webbe8c1da02023-09-08 18:25:22 +0000428 else:
429 packages = resolver.db.InstalledPackages()
Allen Webb3e498aa2023-09-05 14:40:49 +0000430 else:
431 packages = [resolver.get_package(p) for p in opts.package]
432
433 implicit = resolver.get_implicit_libs()
434 if opts.debug:
435 print("implicit")
436 pprint.pprint(implicit)
437
438 if opts.jobs == 1:
439 for package in packages:
440 if not check_package(
441 package,
Allen Webb3e498aa2023-09-05 14:40:49 +0000442 implicit,
443 resolver,
444 opts.match,
445 opts.debug,
446 ):
447 failed = True
448 else:
Allen Webbe8c1da02023-09-08 18:25:22 +0000449 if opts.match:
450 # Pre initialize the map before starting jobs.
451 resolver.lib_to_package()
Allen Webb3e498aa2023-09-05 14:40:49 +0000452 for ret in parallel.RunTasksInProcessPool(
453 lambda p: check_package(
Allen Webbe8c1da02023-09-08 18:25:22 +0000454 p, implicit, resolver, opts.match, opts.debug
Allen Webb3e498aa2023-09-05 14:40:49 +0000455 ),
456 [[p] for p in packages],
457 opts.jobs,
458 ):
459 if not ret:
460 failed = True
461
462 if failed:
463 sys.exit(1)
464
465
466if __name__ == "__main__":
467 main(sys.argv[1:])