Debian Codegraph @

internal/elfdeps/elfdeps.go

raw symbols SCIP
1 package elfdeps
2
3 import (
4 "debug/elf"
5 "io"
6 "os"
7 osexec "os/exec"
8 "path/filepath"
9 "strings"
10 )
11
12 // ldconfigRunner runs `ldconfig -p` and returns its output. Tests may override
13 // this variable to inject fake output. It is unexported on purpose to allow
14 // test injection within the package.
15 var ldconfigRunner = func() ([]byte, error) {
16 return osexec.Command("ldconfig", "-p").Output()
17 }
18
19 // knownMachineTags are architecture qualifiers that appear in `ldconfig -p`
20 // output (e.g. "libc.so.6 (libc6,x86-64) => ...").
21 var knownMachineTags = []string{
22 "x86-64",
23 "x32",
24 "AArch64",
25 "ARM",
26 "IA-64",
27 "PPC64",
28 "PPC",
29 "RISCV64",
30 "RISCV32",
31 "S390X",
32 "S390",
33 "SPARC64",
34 "SPARC",
35 "MIPS64",
36 "MIPS",
37 }
38
39 type ldEntry struct {
40 path string
41 info string // parenthetical flags from ldconfig, e.g. "libc6,x86-64"
42 }
43
44 // ldconfigMachineTag returns the ldconfig arch qualifier that should be
45 // preferred when resolving libraries for the given ELF class/machine.
46 // An empty string means "no machine qualifier" (typical for i386).
47 func ldconfigMachineTag(class elf.Class, machine elf.Machine) string {
48 switch machine {
49 case elf.EM_X86_64:
50 if class == elf.ELFCLASS32 {
51 return "x32"
52 }
53 return "x86-64"
54 case elf.EM_AARCH64:
55 return "AArch64"
56 case elf.EM_ARM:
57 return "ARM"
58 case elf.EM_386:
59 return ""
60 case elf.EM_PPC64:
61 return "PPC64"
62 case elf.EM_PPC:
63 return "PPC"
64 case elf.EM_RISCV:
65 if class == elf.ELFCLASS64 {
66 return "RISCV64"
67 }
68 return "RISCV32"
69 case elf.EM_S390:
70 if class == elf.ELFCLASS64 {
71 return "S390X"
72 }
73 return "S390"
74 case elf.EM_IA_64:
75 return "IA-64"
76 case elf.EM_SPARCV9:
77 return "SPARC64"
78 case elf.EM_SPARC:
79 return "SPARC"
80 case elf.EM_MIPS:
81 if class == elf.ELFCLASS64 {
82 return "MIPS64"
83 }
84 return "MIPS"
85 default:
86 return ""
87 }
88 }
89
90 // standardLibDirs returns library directories to search for the given ELF arch,
91 // including Debian/Ubuntu multiarch paths.
92 func standardLibDirs(class elf.Class, machine elf.Machine) []string {
93 var dirs []string
94 switch {
95 case machine == elf.EM_X86_64 && class == elf.ELFCLASS64:
96 dirs = []string{
97 "/lib64", "/usr/lib64",
98 "/lib/x86_64-linux-gnu", "/usr/lib/x86_64-linux-gnu",
99 }
100 case machine == elf.EM_X86_64 && class == elf.ELFCLASS32: // x32
101 dirs = []string{"/libx32", "/usr/libx32"}
102 case machine == elf.EM_386:
103 dirs = []string{
104 "/lib32", "/usr/lib32",
105 "/lib/i386-linux-gnu", "/usr/lib/i386-linux-gnu",
106 }
107 case machine == elf.EM_AARCH64:
108 dirs = []string{
109 "/lib64", "/usr/lib64",
110 "/lib/aarch64-linux-gnu", "/usr/lib/aarch64-linux-gnu",
111 }
112 case machine == elf.EM_ARM:
113 dirs = []string{
114 "/lib/arm-linux-gnueabihf", "/usr/lib/arm-linux-gnueabihf",
115 "/lib/arm-linux-gnueabi", "/usr/lib/arm-linux-gnueabi",
116 }
117 case machine == elf.EM_RISCV && class == elf.ELFCLASS64:
118 dirs = []string{
119 "/lib64", "/usr/lib64",
120 "/lib/riscv64-linux-gnu", "/usr/lib/riscv64-linux-gnu",
121 }
122 case machine == elf.EM_PPC64:
123 dirs = []string{
124 "/lib64", "/usr/lib64",
125 "/lib/powerpc64le-linux-gnu", "/usr/lib/powerpc64le-linux-gnu",
126 "/lib/powerpc64-linux-gnu", "/usr/lib/powerpc64-linux-gnu",
127 }
128 case machine == elf.EM_S390 && class == elf.ELFCLASS64:
129 dirs = []string{
130 "/lib64", "/usr/lib64",
131 "/lib/s390x-linux-gnu", "/usr/lib/s390x-linux-gnu",
132 }
133 }
134 return append(dirs, "/lib", "/usr/lib", "/usr/local/lib")
135 }
136
137 func hasKnownMachineTag(info string) bool {
138 for _, tag := range knownMachineTags {
139 if tokenInInfo(info, tag) {
140 return true
141 }
142 }
143 return false
144 }
145
146 func tokenInInfo(info, token string) bool {
147 if token == "" || info == "" {
148 return false
149 }
150 for _, part := range strings.Split(info, ",") {
151 if strings.TrimSpace(part) == token {
152 return true
153 }
154 }
155 return false
156 }
157
158 func pickLdEntry(entries []ldEntry, preferredTag string) string {
159 if len(entries) == 0 {
160 return ""
161 }
162 if preferredTag != "" {
163 for _, e := range entries {
164 if tokenInInfo(e.info, preferredTag) {
165 return e.path
166 }
167 }
168 } else {
169 // Prefer entries without a machine qualifier (e.g. plain i386 "(libc6)").
170 for _, e := range entries {
171 if !hasKnownMachineTag(e.info) {
172 return e.path
173 }
174 }
175 }
176 // Fall back only when there is a single candidate, to avoid picking a
177 // library for the wrong architecture when several exist.
178 if len(entries) == 1 {
179 return entries[0].path
180 }
181 return ""
182 }
183
184 // getLdmap runs `ldconfig -p` and returns a map of soname -> path, preferring
185 // entries that match preferredTag (from ldconfigMachineTag).
186 func getLdmap(preferredTag string) map[string]string {
187 m := map[string]string{}
188 out, err := ldconfigRunner()
189 if err != nil {
190 return m
191 }
192
193 bySoname := map[string][]ldEntry{}
194 lines := strings.Split(string(out), "\n")
195 for _, line := range lines {
196 if !strings.Contains(line, "=>") {
197 continue
198 }
199 parts := strings.Split(line, "=>")
200 if len(parts) < 2 {
201 continue
202 }
203 path := strings.TrimSpace(parts[len(parts)-1])
204 left := strings.TrimSpace(parts[0])
205 toks := strings.Fields(left)
206 if len(toks) == 0 {
207 continue
208 }
209 soname := toks[0]
210 if path == "" || soname == "" {
211 continue
212 }
213 info := ""
214 if i := strings.Index(left, "("); i >= 0 {
215 if j := strings.Index(left[i:], ")"); j >= 0 {
216 info = strings.TrimSpace(left[i+1 : i+j])
217 }
218 }
219 if _, err := os.Stat(path); err == nil {
220 bySoname[soname] = append(bySoname[soname], ldEntry{path: path, info: info})
221 }
222 }
223
224 for soname, entries := range bySoname {
225 if p := pickLdEntry(entries, preferredTag); p != "" {
226 m[soname] = p
227 }
228 }
229 return m
230 }
231
232 // parseInterp extracts the PT_INTERP interpreter path from an ELF file.
233 func parseInterp(f *elf.File) string {
234 for _, prog := range f.Progs {
235 if prog.Type == elf.PT_INTERP {
236 r := prog.Open()
237 if r == nil {
238 // Can't read interpreter
239 return ""
240 }
241 if data, err := io.ReadAll(r); err == nil {
242 return strings.TrimRight(string(data), "\x00")
243 }
244 }
245 }
246 return ""
247 }
248
249 // parseDynamic extracts DT_NEEDED and RPATH/RUNPATH entries from the .dynamic section.
250 func parseDynamic(f *elf.File) (needed []string, rpaths []string) {
251 needed = []string{}
252 rpaths = []string{}
253
254 if libs, err := f.DynString(elf.DT_NEEDED); err == nil {
255 needed = append(needed, libs...)
256 }
257
258 // DT_RPATH and DT_RUNPATH may both be present; split on ':' and append
259 if rp, err := f.DynString(elf.DT_RPATH); err == nil {
260 for _, v := range rp {
261 if v == "" {
262 continue
263 }
264 rpaths = append(rpaths, strings.Split(v, ":")...)
265 }
266 }
267 if rp, err := f.DynString(elf.DT_RUNPATH); err == nil {
268 for _, v := range rp {
269 if v == "" {
270 continue
271 }
272 rpaths = append(rpaths, strings.Split(v, ":")...)
273 }
274 }
275 return
276 }
277
278 // normalizeRpaths expands common tokens like $ORIGIN and makes relative
279 // rpath entries absolute using the provided origin directory.
280 func normalizeRpaths(rpaths []string, origin string) []string {
281 out := []string{}
282 for _, rp := range rpaths {
283 if rp == "" {
284 continue
285 }
286 // expand $ORIGIN (common token in RPATH/RUNPATH)
287 rp = strings.ReplaceAll(rp, "$ORIGIN", origin)
288 rp = strings.ReplaceAll(rp, "${ORIGIN}", origin)
289 // make relative rpath entries absolute using origin
290 if !filepath.IsAbs(rp) {
291 rp = filepath.Join(origin, rp)
292 }
293 out = append(out, rp)
294 }
295 return out
296 }
297
298 // resolveSingleSoname attempts to resolve a single soname using rpaths,
299 // standard dirs and ldconfig fallback. It takes a pointer to ldmap so the
300 // caller can lazily populate and reuse it.
301 func resolveSingleSoname(soname string, rpaths []string, stdDirs []string, preferredTag string, ldmap *map[string]string) string {
302 // check rpaths first
303 for _, rp := range rpaths {
304 candidate := filepath.Join(rp, soname)
305 if _, err := os.Stat(candidate); err == nil {
306 return candidate
307 }
308 }
309
310 // then check standard dirs
311 for _, d := range stdDirs {
312 candidate := filepath.Join(d, soname)
313 if _, err := os.Stat(candidate); err == nil {
314 return candidate
315 }
316 }
317
318 // fallback: consult parsed ldconfig map (populate lazily)
319 if *ldmap == nil {
320 *ldmap = getLdmap(preferredTag)
321 }
322 if p, ok := (*ldmap)[soname]; ok {
323 return p
324 }
325
326 return ""
327 }
328
329 // resolveSonames attempts to resolve sonames to absolute paths using rpaths,
330 // standard library directories and falling back to parsing `ldconfig -p` output.
331 func resolveSonames(needed []string, rpaths []string, class elf.Class, machine elf.Machine) []string {
332 resolved := map[string]string{}
333 stdDirs := standardLibDirs(class, machine)
334 preferredTag := ldconfigMachineTag(class, machine)
335 var ldmap map[string]string
336
337 for _, soname := range needed {
338 if _, ok := resolved[soname]; ok {
339 continue
340 }
341 resolved[soname] = resolveSingleSoname(soname, rpaths, stdDirs, preferredTag, &ldmap)
342 }
343
344 out := []string{}
345 for _, r := range resolved {
346 if r != "" {
347 out = append(out, r)
348 }
349 }
350 return out
351 }
352
353 // GetLibraryDependencies returns a list of library paths that the given binary depends on
354 func GetLibraryDependencies(binary string) ([]string, error) {
355 queue := []string{binary}
356 processed := map[string]struct{}{}
357 finalMap := map[string]struct{}{}
358
359 // Add /etc/ld.so.cache if present
360 if _, err := os.Stat("/etc/ld.so.cache"); err == nil {
361 finalMap["/etc/ld.so.cache"] = struct{}{}
362 }
363
364 for len(queue) > 0 {
365 // Dequeue
366 curr := queue[0]
367 queue = queue[1:]
368
369 if _, ok := processed[curr]; ok {
370 continue
371 }
372 processed[curr] = struct{}{}
373
374 f, err := elf.Open(curr)
375 if err != nil {
376 // This can happen with non-ELF files in the dependency chain
377 // (e.g. ld.so.cache). Ignore them.
378 continue
379 }
380
381 // The first binary in the queue is the main one; grab its interpreter
382 if curr == binary {
383 if interpPath := parseInterp(f); interpPath != "" {
384 finalMap[interpPath] = struct{}{}
385 queue = append(queue, interpPath)
386 }
387 }
388
389 needed, rpaths := parseDynamic(f)
390 origin := filepath.Dir(curr)
391 rpaths = normalizeRpaths(rpaths, origin)
392 libPaths := resolveSonames(needed, rpaths, f.Class, f.Machine)
393 f.Close()
394
395 for _, p := range libPaths {
396 if _, ok := finalMap[p]; !ok {
397 finalMap[p] = struct{}{}
398 queue = append(queue, p)
399 }
400 }
401 }
402
403 out := make([]string, 0, len(finalMap))
404 for p := range finalMap {
405 out = append(out, p)
406 }
407
408 return out, nil
409 }