Debian Codegraph @

src/auditwheel/elfutils.py

raw
1 from __future__ import annotations
2
3 from typing import TYPE_CHECKING
4
5 from elftools.common.exceptions import ELFError
6 from elftools.elf.elffile import ELFFile
7
8 if TYPE_CHECKING:
9 from collections.abc import Iterable, Iterator
10 from pathlib import Path
11
12
13 def elf_read_dt_needed(fn: Path) -> list[str]:
14 needed: list[str] = []
15 with fn.open("rb") as f:
16 elf = ELFFile(f)
17 section = elf.get_section_by_name(".dynamic")
18 if section is None:
19 msg = f"Could not find soname in {fn}"
20 raise ValueError(msg)
21 needed.extend(t.needed for t in section.iter_tags() if t.entry.d_tag == "DT_NEEDED")
22 return needed
23
24
25 def elf_file_filter(paths: Iterable[Path]) -> Iterator[tuple[Path, ELFFile]]:
26 """Filter through an iterator of filenames and load up only ELF
27 files
28 """
29 for path in paths:
30 if path.name.endswith(".py"):
31 continue
32 else:
33 try:
34 with path.open("rb") as f:
35 candidate = ELFFile(f)
36 yield path, candidate
37 except ELFError:
38 # not an elf file
39 continue
40
41
42 def elf_find_versioned_symbols(elf: ELFFile) -> Iterator[tuple[str, str]]:
43 section = elf.get_section_by_name(".gnu.version_r")
44
45 if section is not None:
46 for verneed, verneed_iter in section.iter_versions():
47 if verneed.name.startswith("ld-linux") or verneed.name in [
48 "ld64.so.2",
49 "ld64.so.1",
50 ]:
51 continue
52 for vernaux in verneed_iter:
53 yield (verneed.name, vernaux.name)
54
55
56 def elf_find_ucs2_symbols(elf: ELFFile) -> Iterator[str]:
57 section = elf.get_section_by_name(".dynsym")
58 if section is not None:
59 # look for UCS2 symbols that are externally referenced
60 for sym in section.iter_symbols():
61 if (
62 "PyUnicodeUCS2_" in sym.name
63 and sym["st_shndx"] == "SHN_UNDEF"
64 and sym["st_info"]["type"] == "STT_FUNC"
65 ):
66 yield sym.name
67
68
69 def elf_references_pyfpe_jbuf(elf: ELFFile) -> bool:
70 offending_symbol_names = ("PyFPE_jbuf", "PyFPE_dummy", "PyFPE_counter")
71 section = elf.get_section_by_name(".dynsym")
72 if section is not None:
73 # look for symbols that are externally referenced
74 for sym in section.iter_symbols():
75 if (
76 sym.name in offending_symbol_names
77 and sym["st_shndx"] == "SHN_UNDEF"
78 and sym["st_info"]["type"] in ("STT_FUNC", "STT_NOTYPE")
79 ):
80 return True
81 return False
82
83
84 def elf_is_python_extension(fn: Path, elf: ELFFile) -> tuple[bool, int | None]:
85 modname = fn.name.split(".", 1)[0]
86 module_init_f = {
87 "init" + modname: 2,
88 "PyInit_" + modname: 3,
89 "_cffi_pypyinit_" + modname: 2,
90 }
91
92 sect = elf.get_section_by_name(".dynsym")
93 if sect is None:
94 return False, None
95
96 for sym in sect.iter_symbols():
97 if (
98 sym.name in module_init_f
99 and sym["st_shndx"] != "SHN_UNDEF"
100 and sym["st_info"]["type"] == "STT_FUNC"
101 ):
102 return True, module_init_f[sym.name]
103
104 return False, None
105
106
107 def get_undefined_symbols(path: Path) -> set[str]:
108 undef_symbols = set()
109 with path.open("rb") as f:
110 elf = ELFFile(f)
111 section = elf.get_section_by_name(".dynsym")
112 if section is not None:
113 # look for all undef symbols
114 # if the symbol is weak don't consider it as undefined, it's "optional"
115 for sym in section.iter_symbols():
116 if sym["st_shndx"] == "SHN_UNDEF" and sym["st_info"]["bind"] != "STB_WEAK":
117 undef_symbols.add(sym.name)
118 return undef_symbols
119
120
121 def filter_undefined_symbols(
122 path: Path,
123 symbols: dict[str, frozenset[str]],
124 ) -> dict[str, list[str]]:
125 if not symbols:
126 return {}
127 undef_symbols = set("*") | get_undefined_symbols(path)
128 result = {}
129 for lib, sym_list in symbols.items():
130 intersection = sym_list & undef_symbols
131 if intersection:
132 result[lib] = sorted(intersection)
133 return result