Debian Codegraph @

thirdparty/folly/build/fbcode_builder/getdeps/dyndeps.py

raw
1 # Copyright (c) Meta Platforms, Inc. and affiliates.
2 #
3 # This source code is licensed under the MIT license found in the
4 # LICENSE file in the root directory of this source tree.
5
6 import errno
7 import glob
8 import os
9 import re
10 import shlex
11 import shutil
12 import stat
13 import subprocess
14 import sys
15 from struct import unpack
16 from typing import List, Optional
17
18 OBJECT_SUBDIRS = ("bin", "lib", "lib64")
19
20
21 def copyfile(src, dest) -> None:
22 shutil.copyfile(src, dest)
23 shutil.copymode(src, dest)
24
25
26 class DepBase(object):
27 def __init__(self, buildopts, install_dirs, strip) -> None:
28 self.buildopts = buildopts
29 self.env = buildopts.compute_env_for_install_dirs(install_dirs)
30 self.install_dirs = install_dirs
31 self.strip = strip
32
33 # Deduplicates dependency processing. Keyed on the library
34 # destination path.
35 self.processed_deps = set()
36
37 def list_dynamic_deps(self, objfile):
38 raise RuntimeError("list_dynamic_deps not implemented")
39
40 def interesting_dep(self, d) -> bool:
41 return True
42
43 # final_install_prefix must be the equivalent path to `destdir` on the
44 # installed system. For example, if destdir is `/tmp/RANDOM/usr/local' which
45 # is intended to map to `/usr/local` in the install image, then
46 # final_install_prefix='/usr/local'.
47 # If left unspecified, destdir will be used.
48 def process_deps(self, destdir, final_install_prefix=None) -> None:
49 if self.buildopts.is_windows():
50 lib_dir = "bin"
51 else:
52 lib_dir = "lib"
53 # pyre-fixme[16]: `DepBase` has no attribute `munged_lib_dir`.
54 self.munged_lib_dir = os.path.join(destdir, lib_dir)
55
56 final_lib_dir = os.path.join(final_install_prefix or destdir, lib_dir)
57
58 if not os.path.isdir(self.munged_lib_dir):
59 os.makedirs(self.munged_lib_dir)
60
61 # Look only at the things that got installed in the leaf package,
62 # which will be the last entry in the install dirs list
63 inst_dir = self.install_dirs[-1]
64 print("Process deps under %s" % inst_dir, file=sys.stderr)
65
66 for dir in OBJECT_SUBDIRS:
67 src_dir = os.path.join(inst_dir, dir)
68 if not os.path.isdir(src_dir):
69 continue
70 dest_dir = os.path.join(destdir, dir)
71 if not os.path.exists(dest_dir):
72 os.makedirs(dest_dir)
73
74 for objfile in self.list_objs_in_dir(src_dir):
75 print("Consider %s/%s" % (dir, objfile))
76 dest_obj = os.path.join(dest_dir, objfile)
77 copyfile(os.path.join(src_dir, objfile), dest_obj)
78 self.munge_in_place(dest_obj, final_lib_dir)
79
80 def find_all_dependencies(self, build_dir):
81 all_deps = set()
82 for objfile in self.list_objs_in_dir(
83 build_dir, recurse=True, output_prefix=build_dir
84 ):
85 for d in self.list_dynamic_deps(objfile):
86 all_deps.add(d)
87
88 interesting_deps = {d for d in all_deps if self.interesting_dep(d)}
89 dep_paths = []
90 for dep in interesting_deps:
91 dep_path = self.resolve_loader_path(dep)
92 if dep_path:
93 dep_paths.append(dep_path)
94
95 return dep_paths
96
97 def munge_in_place(self, objfile, final_lib_dir) -> None:
98 print("Munging %s" % objfile)
99 for d in self.list_dynamic_deps(objfile):
100 if not self.interesting_dep(d):
101 continue
102
103 # Resolve this dep: does it exist in any of our installation
104 # directories? If so, then it is a candidate for processing
105 dep = self.resolve_loader_path(d)
106 if dep:
107 # pyre-fixme[16]: `DepBase` has no attribute `munged_lib_dir`.
108 dest_dep = os.path.join(self.munged_lib_dir, os.path.basename(dep))
109 print("dep: %s -> %s" % (d, dest_dep))
110 if dest_dep in self.processed_deps:
111 # A previous dependency with the same name has already
112 # been installed at dest_dep, so there is no need to copy
113 # or munge the dependency again.
114 # TODO: audit that both source paths have the same inode number
115 pass
116 else:
117 self.processed_deps.add(dest_dep)
118 copyfile(dep, dest_dep)
119 self.munge_in_place(dest_dep, final_lib_dir)
120
121 self.rewrite_dep(objfile, d, dep, dest_dep, final_lib_dir)
122
123 if self.strip:
124 self.strip_debug_info(objfile)
125
126 def rewrite_dep(self, objfile, depname, old_dep, new_dep, final_lib_dir):
127 raise RuntimeError("rewrite_dep not implemented")
128
129 def resolve_loader_path(self, dep: str) -> Optional[str]:
130 if os.path.isabs(dep):
131 return dep
132 d = os.path.basename(dep)
133 for inst_dir in self.install_dirs:
134 for libdir in OBJECT_SUBDIRS:
135 candidate = os.path.join(inst_dir, libdir, d)
136 if os.path.exists(candidate):
137 return candidate
138 return None
139
140 def list_objs_in_dir(self, dir, recurse: bool = False, output_prefix: str = ""):
141 for entry in os.listdir(dir):
142 entry_path = os.path.join(dir, entry)
143 st = os.lstat(entry_path)
144 if stat.S_ISREG(st.st_mode):
145 if self.is_objfile(entry_path):
146 relative_result = os.path.join(output_prefix, entry)
147 yield os.path.normcase(relative_result)
148 elif recurse and stat.S_ISDIR(st.st_mode):
149 child_prefix = os.path.join(output_prefix, entry)
150 for result in self.list_objs_in_dir(
151 entry_path, recurse=recurse, output_prefix=child_prefix
152 ):
153 yield result
154
155 def is_objfile(self, objfile) -> bool:
156 return True
157
158 def strip_debug_info(self, objfile) -> None:
159 """override this to define how to remove debug information
160 from an object file"""
161 pass
162
163 def check_call_verbose(self, args: List[str]) -> None:
164 print(" ".join(map(shlex.quote, args)))
165 subprocess.check_call(args)
166
167
168 class WinDeps(DepBase):
169 def __init__(self, buildopts, install_dirs, strip) -> None:
170 super(WinDeps, self).__init__(buildopts, install_dirs, strip)
171 self.dumpbin = self.find_dumpbin()
172
173 def find_dumpbin(self) -> str:
174 # Looking for dumpbin in the following hardcoded paths.
175 # The registry option to find the install dir doesn't work anymore.
176 globs = [
177 (
178 "C:/Program Files (x86)/"
179 "Microsoft Visual Studio/"
180 "*/*/VC/Tools/"
181 "MSVC/*/bin/Hostx64/x64/dumpbin.exe"
182 ),
183 (
184 "C:/Program Files (x86)/"
185 "Common Files/"
186 "Microsoft/Visual C++ for Python/*/"
187 "VC/bin/dumpbin.exe"
188 ),
189 ("c:/Program Files (x86)/Microsoft Visual Studio */VC/bin/dumpbin.exe"),
190 (
191 "C:/Program Files/Microsoft Visual Studio/*/Professional/VC/Tools/MSVC/*/bin/HostX64/x64/dumpbin.exe"
192 ),
193 ]
194 for pattern in globs:
195 for exe in glob.glob(pattern):
196 return exe
197
198 raise RuntimeError("could not find dumpbin.exe")
199
200 def list_dynamic_deps(self, exe):
201 deps = []
202 print("Resolve deps for %s" % exe)
203 output = subprocess.check_output(
204 [self.dumpbin, "/nologo", "/dependents", exe]
205 ).decode("utf-8")
206
207 lines = output.split("\n")
208 for line in lines:
209 m = re.match("\\s+(\\S+.dll)", line, re.IGNORECASE)
210 if m:
211 deps.append(m.group(1).lower())
212
213 return deps
214
215 def rewrite_dep(self, objfile, depname, old_dep, new_dep, final_lib_dir) -> None:
216 # We can't rewrite on windows, but we will
217 # place the deps alongside the exe so that
218 # they end up in the search path
219 pass
220
221 # These are the Windows system dll, which we don't want to copy while
222 # packaging.
223 SYSTEM_DLLS = set( # noqa: C405
224 [
225 "advapi32.dll",
226 "dbghelp.dll",
227 "kernel32.dll",
228 "msvcp140.dll",
229 "vcruntime140.dll",
230 "ws2_32.dll",
231 "ntdll.dll",
232 "shlwapi.dll",
233 ]
234 )
235
236 def interesting_dep(self, d) -> bool:
237 if "api-ms-win-crt" in d:
238 return False
239 if d in self.SYSTEM_DLLS:
240 return False
241 return True
242
243 def is_objfile(self, objfile) -> bool:
244 if not os.path.isfile(objfile):
245 return False
246 if objfile.lower().endswith(".exe"):
247 return True
248 return False
249
250 def emit_dev_run_script(self, script_path, dep_dirs) -> None:
251 """Emit a script that can be used to run build artifacts directly from the
252 build directory, without installing them.
253
254 The dep_dirs parameter should be a list of paths that need to be added to $PATH.
255 This can be computed by calling compute_dependency_paths() or
256 compute_dependency_paths_fast().
257
258 This is only necessary on Windows, which does not have RPATH, and instead
259 requires the $PATH environment variable be updated in order to find the proper
260 library dependencies.
261 """
262 contents = self._get_dev_run_script_contents(dep_dirs)
263 with open(script_path, "w") as f:
264 f.write(contents)
265
266 def compute_dependency_paths(self, build_dir):
267 """Return a list of all directories that need to be added to $PATH to ensure
268 that library dependencies can be found correctly. This is computed by scanning
269 binaries to determine exactly the right list of dependencies.
270
271 The compute_dependency_paths_fast() is a alternative function that runs faster
272 but may return additional extraneous paths.
273 """
274 dep_dirs = set()
275 # Find paths by scanning the binaries.
276 for dep in self.find_all_dependencies(build_dir):
277 dep_dirs.add(os.path.dirname(dep))
278
279 dep_dirs.update(self.read_custom_dep_dirs(build_dir))
280 return sorted(dep_dirs)
281
282 def compute_dependency_paths_fast(self, build_dir):
283 """Similar to compute_dependency_paths(), but rather than actually scanning
284 binaries, just add all library paths from the specified installation
285 directories. This is much faster than scanning the binaries, but may result in
286 more paths being returned than actually necessary.
287 """
288 dep_dirs = set()
289 for inst_dir in self.install_dirs:
290 for subdir in OBJECT_SUBDIRS:
291 path = os.path.join(inst_dir, subdir)
292 if os.path.exists(path):
293 dep_dirs.add(path)
294
295 dep_dirs.update(self.read_custom_dep_dirs(build_dir))
296 return sorted(dep_dirs)
297
298 def read_custom_dep_dirs(self, build_dir):
299 # The build system may also have included libraries from other locations that
300 # we might not be able to find normally in find_all_dependencies().
301 # To handle this situation we support reading additional library paths
302 # from a LIBRARY_DEP_DIRS.txt file that may have been generated in the build
303 # output directory.
304 dep_dirs = set()
305 try:
306 explicit_dep_dirs_path = os.path.join(build_dir, "LIBRARY_DEP_DIRS.txt")
307 with open(explicit_dep_dirs_path, "r") as f:
308 for line in f.read().splitlines():
309 dep_dirs.add(line)
310 except OSError as ex:
311 if ex.errno != errno.ENOENT:
312 raise
313
314 return dep_dirs
315
316 def _get_dev_run_script_contents(self, path_dirs) -> str:
317 path_entries = ["$env:PATH"] + path_dirs
318 path_str = ";".join(path_entries)
319 return """\
320 $orig_env = $env:PATH
321 $env:PATH = "{path_str}"
322
323 try {{
324 $cmd_args = $args[1..$args.length]
325 & $args[0] @cmd_args
326 }} finally {{
327 $env:PATH = $orig_env
328 }}
329 """.format(
330 path_str=path_str
331 )
332
333
334 class ElfDeps(DepBase):
335 def __init__(self, buildopts, install_dirs, strip) -> None:
336 super(ElfDeps, self).__init__(buildopts, install_dirs, strip)
337
338 # We need patchelf to rewrite deps, so ensure that it is built...
339 args = [sys.executable, sys.argv[0]]
340 if buildopts.allow_system_packages:
341 args.append("--allow-system-packages")
342 subprocess.check_call(args + ["build", "patchelf"])
343
344 # ... and that we know where it lives
345 patchelf_install = os.fsdecode(
346 subprocess.check_output(args + ["show-inst-dir", "patchelf"]).strip()
347 )
348 if not patchelf_install:
349 # its a system package, so we assume it is in the path
350 patchelf_install = "patchelf"
351 else:
352 patchelf_install = os.path.join(patchelf_install, "bin", "patchelf")
353 self.patchelf = patchelf_install
354
355 def list_dynamic_deps(self, objfile):
356 out = (
357 subprocess.check_output(
358 [self.patchelf, "--print-needed", objfile], env=dict(self.env.items())
359 )
360 .decode("utf-8")
361 .strip()
362 )
363 lines = out.split("\n")
364 return lines
365
366 def rewrite_dep(self, objfile, depname, old_dep, new_dep, final_lib_dir) -> None:
367 final_dep = os.path.join(
368 final_lib_dir,
369 # pyre-fixme[16]: `ElfDeps` has no attribute `munged_lib_dir`.
370 os.path.relpath(new_dep, self.munged_lib_dir),
371 )
372 self.check_call_verbose(
373 [self.patchelf, "--replace-needed", depname, final_dep, objfile]
374 )
375
376 def is_objfile(self, objfile) -> bool:
377 if not os.path.isfile(objfile):
378 return False
379 with open(objfile, "rb") as f:
380 # https://en.wikipedia.org/wiki/Executable_and_Linkable_Format#File_header
381 magic = f.read(4)
382 return magic == b"\x7fELF"
383
384 def strip_debug_info(self, objfile) -> None:
385 self.check_call_verbose(["strip", objfile])
386
387
388 # MACH-O magic number
389 MACH_MAGIC = 0xFEEDFACF
390
391
392 class MachDeps(DepBase):
393 def interesting_dep(self, d) -> bool:
394 if d.startswith("/usr/lib/") or d.startswith("/System/"):
395 return False
396 return True
397
398 def is_objfile(self, objfile):
399 if not os.path.isfile(objfile):
400 return False
401 with open(objfile, "rb") as f:
402 # mach stores the magic number in native endianness,
403 # so unpack as native here and compare
404 header = f.read(4)
405 if len(header) != 4:
406 return False
407 magic = unpack("I", header)[0]
408 return magic == MACH_MAGIC
409
410 def list_dynamic_deps(self, objfile):
411 if not self.interesting_dep(objfile):
412 return
413 out = (
414 subprocess.check_output(
415 ["otool", "-L", objfile], env=dict(self.env.items())
416 )
417 .decode("utf-8")
418 .strip()
419 )
420 lines = out.split("\n")
421 deps = []
422 for line in lines:
423 m = re.match("\t(\\S+)\\s", line)
424 if m:
425 if os.path.basename(m.group(1)) != os.path.basename(objfile):
426 deps.append(os.path.normcase(m.group(1)))
427 return deps
428
429 def rewrite_dep(self, objfile, depname, old_dep, new_dep, final_lib_dir) -> None:
430 if objfile.endswith(".dylib"):
431 # Erase the original location from the id of the shared
432 # object. It doesn't appear to hurt to retain it, but
433 # it does look weird, so let's rewrite it to be sure.
434 self.check_call_verbose(
435 ["install_name_tool", "-id", os.path.basename(objfile), objfile]
436 )
437 final_dep = os.path.join(
438 final_lib_dir,
439 # pyre-fixme[16]: `MachDeps` has no attribute `munged_lib_dir`.
440 os.path.relpath(new_dep, self.munged_lib_dir),
441 )
442
443 self.check_call_verbose(
444 ["install_name_tool", "-change", depname, final_dep, objfile]
445 )
446
447
448 def create_dyn_dep_munger(
449 buildopts, install_dirs, strip: bool = False
450 ) -> Optional[DepBase]:
451 if buildopts.is_linux():
452 return ElfDeps(buildopts, install_dirs, strip)
453 if buildopts.is_darwin():
454 return MachDeps(buildopts, install_dirs, strip)
455 if buildopts.is_windows():
456 return WinDeps(buildopts, install_dirs, strip)
457 if buildopts.is_freebsd():
458 return ElfDeps(buildopts, install_dirs, strip)
459 return None