OSDN Git Service

Remove /usr/X11R6/lib from search path.
[uclinux-h8/uClibc.git] / utils / ldd.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * A small little ldd implementation for uClibc
4  *
5  * Copyright (C) 2000-2004 Erik Andersen <andersee@debian.org>
6  *
7  * Several functions in this file (specifically, elf_find_section_type(),
8  * elf_find_phdr_type(), and elf_find_dynamic(), were stolen from elflib.c from
9  * elfvector (http://www.BitWagon.com/elfvector.html) by John F. Reiser
10  * <jreiser@BitWagon.com>, which is copyright 2000 BitWagon Software LLC
11  * (GPL2).
12  *
13  * This program is free software; you can redistribute it and/or modify
14  * it under the terms of the GNU General Public License as published by
15  * the Free Software Foundation; either version 2 of the License, or
16  * (at your option) any later version.
17  *
18  * This program is distributed in the hope that it will be useful,
19  * but WITHOUT ANY WARRANTY; without even the implied warranty of
20  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
21  * General Public License for more details.
22  *
23  * You should have received a copy of the GNU General Public License
24  * along with this program; if not, write to the Free Software
25  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
26  *
27  */
28
29
30 #define _GNU_SOURCE
31 #include <stdlib.h>
32 #include <stdio.h>
33 #include <fcntl.h>
34 #include <string.h>
35 #include <unistd.h>
36 #include <sys/mman.h>
37 #include <sys/stat.h>
38 #include <sys/types.h>
39 #include <sys/types.h>
40 #include <sys/wait.h>
41
42 #include "bswap.h"
43 #if defined (sun)
44 #include "link.h"
45 #else
46 #include "elf.h"
47 #endif
48
49 #ifdef DMALLOC
50 #include <dmalloc.h>
51 #endif
52
53 #if defined(__arm__)
54 #define MATCH_MACHINE(x) (x == EM_ARM)
55 #define ELFCLASSM       ELFCLASS32
56 #endif
57
58 #if defined(__s390__)
59 #define MATCH_MACHINE(x) (x == EM_S390)
60 #define ELFCLASSM       ELFCLASS32
61 #endif
62
63 #if defined(__i386__)
64 #ifndef EM_486
65 #define MATCH_MACHINE(x) (x == EM_386)
66 #else
67 #define MATCH_MACHINE(x) (x == EM_386 || x == EM_486)
68 #endif
69 #define ELFCLASSM       ELFCLASS32
70 #endif
71
72 #if defined(__mc68000__)
73 #define MATCH_MACHINE(x) (x == EM_68K)
74 #define ELFCLASSM       ELFCLASS32
75 #endif
76
77 #if defined(__mips__)
78 #define MATCH_MACHINE(x) (x == EM_MIPS || x == EM_MIPS_RS3_LE)
79 #define ELFCLASSM       ELFCLASS32
80 #endif
81
82 #if defined(__powerpc__)
83 #define MATCH_MACHINE(x) (x == EM_PPC)
84 #define ELFCLASSM       ELFCLASS32
85 #endif
86
87 #if defined(__sh__)
88 #define MATCH_MACHINE(x) (x == EM_SH)
89 #define ELFCLASSM       ELFCLASS32
90 #endif
91
92 #if defined (__v850e__)
93 #define MATCH_MACHINE(x) ((x) == EM_V850 || (x) == EM_CYGNUS_V850)
94 #define ELFCLASSM       ELFCLASS32
95 #endif
96
97 #if defined (__sparc__)
98 #define MATCH_MACHINE(x) ((x) == EM_SPARC || (x) == EM_SPARC32PLUS)
99 #define ELFCLASSM    ELFCLASS32
100 #endif
101
102 #if defined(__cris__)
103 #define MATCH_MACHINE(x) (x == EM_CRIS)
104 #define ELFCLASSM       ELFCLASS32
105 #endif
106
107 #ifndef MATCH_MACHINE
108 #warning "You really should add a MATCH_MACHINE() macro for your architecture"
109 #endif
110
111 #if __BYTE_ORDER == __LITTLE_ENDIAN
112 #define ELFDATAM        ELFDATA2LSB
113 #elif __BYTE_ORDER == __BIG_ENDIAN
114 #define ELFDATAM        ELFDATA2MSB
115 #endif
116
117 struct library {
118         char *name;
119         int resolved;
120         char *path;
121         struct library *next;
122 };
123 struct library *lib_list = NULL;
124 char not_found[] = "not found";
125 char *interp = NULL;
126 char *interp_dir = NULL;
127 int byteswap;
128 static int interpreter_already_found=0;
129
130 inline uint32_t byteswap32_to_host(uint32_t value)
131 {
132         if (byteswap==1) {
133                 return(bswap_32(value));
134         } else {
135                 return(value);
136         }
137 }
138
139 Elf32_Shdr * elf_find_section_type( int key, Elf32_Ehdr *ehdr)
140 {
141         int j;
142         Elf32_Shdr *shdr;
143         shdr = (Elf32_Shdr *)(ehdr->e_shoff + (char *)ehdr);
144         for (j = ehdr->e_shnum; --j>=0; ++shdr) {
145                 if (key==(int)byteswap32_to_host(shdr->sh_type)) {
146                         return shdr;
147                 }
148         }
149         return NULL;
150 }
151
152 Elf32_Phdr * elf_find_phdr_type( int type, Elf32_Ehdr *ehdr)
153 {
154         int j;
155         Elf32_Phdr *phdr = (Elf32_Phdr *)(ehdr->e_phoff + (char *)ehdr);
156         for (j = ehdr->e_phnum; --j>=0; ++phdr) {
157                 if (type==(int)byteswap32_to_host(phdr->p_type)) {
158                         return phdr;
159                 }
160         }
161         return NULL;
162 }
163
164 /* Returns value if return_val==1, ptr otherwise */
165 void * elf_find_dynamic(int const key, Elf32_Dyn *dynp,
166         Elf32_Ehdr *ehdr, int return_val)
167 {
168         Elf32_Phdr *pt_text = elf_find_phdr_type(PT_LOAD, ehdr);
169         unsigned tx_reloc = byteswap32_to_host(pt_text->p_vaddr) - byteswap32_to_host(pt_text->p_offset);
170         for (; DT_NULL!=byteswap32_to_host(dynp->d_tag); ++dynp) {
171                 if (key == (int)byteswap32_to_host(dynp->d_tag)) {
172                         if (return_val == 1)
173                                 return (void *)(intptr_t)byteswap32_to_host(dynp->d_un.d_val);
174                         else
175                                 return (void *)(byteswap32_to_host(dynp->d_un.d_val) - tx_reloc + (char *)ehdr );
176                 }
177         }
178         return NULL;
179 }
180
181 static char * elf_find_rpath(Elf32_Ehdr* ehdr, Elf32_Dyn* dynamic)
182 {
183         Elf32_Dyn  *dyns;
184
185         for (dyns=dynamic; byteswap32_to_host(dyns->d_tag)!=DT_NULL; ++dyns) {
186                 if (DT_RPATH == byteswap32_to_host(dyns->d_tag)) {
187                         char *strtab;
188                         strtab = (char *)elf_find_dynamic(DT_STRTAB, dynamic, ehdr, 0);
189                         return ((char*)strtab + byteswap32_to_host(dyns->d_un.d_val));
190                 }
191         }
192         return NULL;
193 }
194
195 int check_elf_header(Elf32_Ehdr *const ehdr)
196 {
197         if (! ehdr || strncmp((void *)ehdr, ELFMAG, SELFMAG) != 0 ||
198                         ehdr->e_ident[EI_CLASS] != ELFCLASS32 ||
199                         ehdr->e_ident[EI_VERSION] != EV_CURRENT)
200         {
201                 return 1;
202         }
203
204         /* Check if the target endianness matches the host's endianness */
205         byteswap = 0;
206 #if __BYTE_ORDER == __LITTLE_ENDIAN
207         if (ehdr->e_ident[5] == ELFDATA2MSB) {
208                 /* Ick -- we will have to byte-swap everything */
209                 byteswap = 1;
210         }
211 #elif __BYTE_ORDER == __BIG_ENDIAN
212         if (ehdr->e_ident[5] == ELFDATA2LSB) {
213                 /* Ick -- we will have to byte-swap everything */
214                 byteswap = 1;
215         }
216 #else
217 #error Unknown host byte order!
218 #endif
219
220         /* Be vary lazy, and only byteswap the stuff we use */
221         if (byteswap==1) {
222                 ehdr->e_type=bswap_16(ehdr->e_type);
223                 ehdr->e_phoff=bswap_32(ehdr->e_phoff);
224                 ehdr->e_shoff=bswap_32(ehdr->e_shoff);
225                 ehdr->e_phnum=bswap_16(ehdr->e_phnum);
226                 ehdr->e_shnum=bswap_16(ehdr->e_shnum);
227         }
228
229         return 0;
230 }
231
232 /* This function's behavior must exactly match that
233  * in uClibc/ldso/ldso/dl-elf.c */
234 static void search_for_named_library(char *name, char *result, const char *path_list)
235 {
236         int i, count = 1;
237         char *path, *path_n;
238         struct stat filestat;
239
240         /* We need a writable copy of this string */
241         path = strdup(path_list);
242         if (!path) {
243                 fprintf(stderr, "Out of memory!\n");
244                 exit(EXIT_FAILURE);
245         }
246         /* Eliminate all double //s */
247         path_n=path;
248         while((path_n=strstr(path_n, "//"))) {
249                 i = strlen(path_n);
250                 memmove(path_n, path_n+1, i-1);
251                 *(path_n + i - 1)='\0';
252         }
253
254         /* Replace colons with zeros in path_list and count them */
255         for(i=strlen(path); i > 0; i--) {
256                 if (path[i]==':') {
257                         path[i]=0;
258                         count++;
259                 }
260         }
261         path_n = path;
262         for (i = 0; i < count; i++) {
263                 strcpy(result, path_n);
264                 strcat(result, "/");
265                 strcat(result, name);
266                 if (stat (result, &filestat) == 0 && filestat.st_mode & S_IRUSR) {
267                         free(path);
268                         return;
269                 }
270                 path_n += (strlen(path_n) + 1);
271         }
272         free(path);
273         *result = '\0';
274 }
275
276 void locate_library_file(Elf32_Ehdr* ehdr, Elf32_Dyn* dynamic, int is_suid, struct library *lib)
277 {
278         char *buf;
279         char *path;
280         struct stat filestat;
281
282         /* If this is a fully resolved name, our job is easy */
283         if (stat (lib->name, &filestat) == 0) {
284                 lib->path = strdup(lib->name);
285                 return;
286         }
287
288         /* We need some elbow room here.  Make some room...*/
289         buf = malloc(1024);
290         if (!buf) {
291                 fprintf(stderr, "Out of memory!\n");
292                 exit(EXIT_FAILURE);
293         }
294
295         /* This function must match the behavior of _dl_load_shared_library
296          * in readelflib1.c or things won't work out as expected... */
297
298         /* The ABI specifies that RPATH is searched first, so do that now.  */
299         path = elf_find_rpath(ehdr, dynamic);
300         if (path) {
301                 search_for_named_library(lib->name, buf, path);
302                 if (*buf != '\0') {
303                         lib->path = buf;
304                         return;
305                 }
306         }
307
308         /* Next check LD_{ELF_}LIBRARY_PATH if specified and allowed.
309          * Since this app doesn't actually run an executable I will skip
310          * the suid check, and just use LD_{ELF_}LIBRARY_PATH if set */
311         if (is_suid==1)
312                 path = NULL;
313         else
314                 path = getenv("LD_LIBRARY_PATH");
315         if (path) {
316                 search_for_named_library(lib->name, buf, path);
317                 if (*buf != '\0') {
318                         lib->path = buf;
319                         return;
320                 }
321         }
322
323 #ifdef USE_CACHE
324         /* FIXME -- add code to check the Cache here */
325 #endif
326
327
328         /* Next look for libraries wherever the shared library
329          * loader was installed -- this is usually where we
330          * should find things... */
331         if (interp_dir) {
332                 search_for_named_library(lib->name, buf, interp_dir);
333                 if (*buf != '\0') {
334                         lib->path = buf;
335                         return;
336                 }
337         }
338
339         /* Lastly, search the standard list of paths for the library.
340            This list must exactly match the list in uClibc/ldso/ldso/dl-elf.c */
341         path =  UCLIBC_RUNTIME_PREFIX "lib:"
342                 UCLIBC_RUNTIME_PREFIX "usr/lib";
343         search_for_named_library(lib->name, buf, path);
344         if (*buf != '\0') {
345                 lib->path = buf;
346         } else {
347                 free(buf);
348                 lib->path = not_found;
349         }
350 }
351
352 static int add_library(Elf32_Ehdr* ehdr, Elf32_Dyn* dynamic, int is_setuid, char *s)
353 {
354         char *tmp, *tmp1, *tmp2;
355         struct library *cur, *newlib=lib_list;
356
357         if (!s || !strlen(s))
358                 return 1;
359
360         tmp = s;
361         while (*tmp) {
362                 if (*tmp == '/')
363                         s = tmp + 1;
364                 tmp++;
365         }
366
367         /* We add ldso elsewhere */
368         if (interpreter_already_found && (tmp=strrchr(interp, '/')) != NULL)
369         {
370                 int len = strlen(interp_dir);
371                 if (strcmp(s, interp+1+len)==0)
372                         return 1;
373         }
374
375         for (cur = lib_list; cur; cur=cur->next) {
376                 /* Check if this library is already in the list */
377                 tmp1 = tmp2 = cur->name;
378                 while (*tmp1) {
379                         if (*tmp1 == '/')
380                                 tmp2 = tmp1 + 1;
381                         tmp1++;
382                 }
383                 if(strcmp(tmp2, s)==0) {
384                         //printf("find_elf_interpreter is skipping '%s' (already in list)\n", cur->name);
385                         return 0;
386                 }
387         }
388
389         /* Ok, this lib needs to be added to the list */
390         newlib = malloc(sizeof(struct library));
391         if (!newlib)
392                 return 1;
393         newlib->name = malloc(strlen(s)+1);
394         strcpy(newlib->name, s);
395         newlib->resolved = 0;
396         newlib->path = NULL;
397         newlib->next = NULL;
398
399         /* Now try and locate where this library might be living... */
400         locate_library_file(ehdr, dynamic, is_setuid, newlib);
401
402         //printf("add_library is adding '%s' to '%s'\n", newlib->name, newlib->path);
403         if (!lib_list) {
404                 lib_list = newlib;
405         } else {
406                 for (cur = lib_list;  cur->next; cur=cur->next); /* nothing */
407                 cur->next = newlib;
408         }
409         return 0;
410 }
411
412 static void find_needed_libraries(Elf32_Ehdr* ehdr,
413                 Elf32_Dyn* dynamic, int is_setuid)
414 {
415         Elf32_Dyn  *dyns;
416
417         for (dyns=dynamic; byteswap32_to_host(dyns->d_tag)!=DT_NULL; ++dyns) {
418                 if (DT_NEEDED == byteswap32_to_host(dyns->d_tag)) {
419                         char *strtab;
420                         strtab = (char *)elf_find_dynamic(DT_STRTAB, dynamic, ehdr, 0);
421                         add_library(ehdr, dynamic, is_setuid,
422                                         (char*)strtab + byteswap32_to_host(dyns->d_un.d_val));
423                 }
424         }
425 }
426
427 static struct library * find_elf_interpreter(Elf32_Ehdr* ehdr)
428 {
429         Elf32_Phdr *phdr;
430
431         if (interpreter_already_found==1)
432                 return NULL;
433         phdr = elf_find_phdr_type(PT_INTERP, ehdr);
434         if (phdr) {
435                 struct library *cur, *newlib=NULL;
436                 char *s = (char*)ehdr + byteswap32_to_host(phdr->p_offset);
437
438                 char *tmp, *tmp1;
439                 interp = strdup(s);
440                 interp_dir = strdup(s);
441                 tmp = strrchr(interp_dir, '/');
442                 if (*tmp)
443                         *tmp = '\0';
444                 else {
445                         free(interp_dir);
446                         interp_dir = interp;
447                 }
448                 tmp1 = tmp = s;
449                 while (*tmp) {
450                         if (*tmp == '/')
451                                 tmp1 = tmp + 1;
452                         tmp++;
453                 }
454                 for (cur = lib_list; cur; cur=cur->next) {
455                         /* Check if this library is already in the list */
456                         if(strcmp(cur->name, tmp1)==0) {
457                                 //printf("find_elf_interpreter is replacing '%s' (already in list)\n", cur->name);
458                                 newlib = cur;
459                                 free(newlib->name);
460                                 if (newlib->path != not_found) {
461                                         free(newlib->path);
462                                 }
463                                 newlib->name = NULL;
464                                 newlib->path = NULL;
465                                 return NULL;
466                         }
467                 }
468                 if (newlib == NULL)
469                         newlib = malloc(sizeof(struct library));
470                 if (!newlib)
471                         return NULL;
472                 newlib->name = malloc(strlen(s)+1);
473                 strcpy(newlib->name, s);
474                 newlib->path = strdup(newlib->name);
475                 newlib->resolved = 1;
476                 newlib->next = NULL;
477
478 #if 0
479                 //printf("find_elf_interpreter is adding '%s' to '%s'\n", newlib->name, newlib->path);
480                 if (!lib_list) {
481                         lib_list = newlib;
482                 } else {
483                         for (cur = lib_list;  cur->next; cur=cur->next); /* nothing */
484                         cur->next = newlib;
485                 }
486 #endif
487                 interpreter_already_found=1;
488                 return newlib;
489         }
490         return NULL;
491 }
492
493 /* map the .so, and locate interesting pieces */
494 int find_dependancies(char* filename)
495 {
496         int is_suid = 0;
497         FILE *thefile;
498         struct stat statbuf;
499         Elf32_Ehdr *ehdr = NULL;
500         Elf32_Shdr *dynsec = NULL;
501         Elf32_Dyn *dynamic = NULL;
502         struct library *interp;
503
504         if (filename == not_found)
505                 return 0;
506
507         if (!filename) {
508                 fprintf(stderr, "No filename specified.\n");
509                 return -1;
510         }
511         if (!(thefile = fopen(filename, "r"))) {
512                 perror(filename);
513                 return -1;
514         }
515         if (fstat(fileno(thefile), &statbuf) < 0) {
516                 perror(filename);
517                 fclose(thefile);
518                 return -1;
519         }
520
521         if ((size_t)statbuf.st_size < sizeof(Elf32_Ehdr))
522                 goto foo;
523
524         if (!S_ISREG(statbuf.st_mode))
525                 goto foo;
526
527         /* mmap the file to make reading stuff from it effortless */
528         ehdr = (Elf32_Ehdr *)mmap(0, statbuf.st_size,
529                         PROT_READ|PROT_WRITE, MAP_PRIVATE, fileno(thefile), 0);
530         if (ehdr == MAP_FAILED) {
531                 fclose(thefile);
532                 fprintf(stderr, "Out of memory!\n");
533                 return -1;
534         }
535
536 foo:
537         fclose(thefile);
538
539         /* Check if this looks like a legit ELF file */
540         if (check_elf_header(ehdr)) {
541                 fprintf(stderr, "%s: not an ELF file.\n", filename);
542                 return -1;
543         }
544         /* Check if this is the right kind of ELF file */
545         if (ehdr->e_type != ET_EXEC && ehdr->e_type != ET_DYN) {
546                 fprintf(stderr, "%s: not a dynamic executable\n", filename);
547                 return -1;
548         }
549         if (ehdr->e_type == ET_EXEC || ehdr->e_type != ET_DYN) {
550                 if (statbuf.st_mode & S_ISUID)
551                         is_suid = 1;
552                 if ((statbuf.st_mode & (S_ISGID | S_IXGRP)) == (S_ISGID | S_IXGRP))
553                         is_suid = 1;
554                 /* FIXME */
555                 if (is_suid)
556                         fprintf(stderr, "%s: is setuid\n", filename);
557         }
558
559         interpreter_already_found=0;
560         interp = find_elf_interpreter(ehdr);
561
562 #ifdef __LDSO_LDD_SUPPORT
563         if (interp && (ehdr->e_type == ET_EXEC || ehdr->e_type == ET_DYN) && ehdr->e_ident[EI_CLASS] == ELFCLASSM &&
564                         ehdr->e_ident[EI_DATA] == ELFDATAM
565                         && ehdr->e_ident[EI_VERSION] == EV_CURRENT && MATCH_MACHINE(ehdr->e_machine))
566         {
567                 struct stat statbuf;
568                 if (stat(interp->path, &statbuf) == 0 && S_ISREG(statbuf.st_mode)) {
569                         pid_t pid;
570                         int status;
571                         static const char * const environment[] = {
572                                 "PATH=/usr/bin:/bin:/usr/sbin:/sbin",
573                                 "SHELL=/bin/sh",
574                                 "LD_TRACE_LOADED_OBJECTS=1",
575                                 NULL
576                         };
577
578                         if ((pid = fork()) == 0) {
579                                 /* Cool, it looks like we should be able to actually
580                                  * run this puppy.  Do so now... */
581                                 execle(filename, filename, NULL, environment);
582                                 _exit(0xdead);
583                         }
584
585                         /* Wait till it returns */
586                         waitpid(pid, &status, 0);
587                         if (WIFEXITED(status) && WEXITSTATUS(status)==0) {
588                                 return 1;
589                         }
590
591                         /* If the exec failed, we fall through to trying to find
592                          * all the needed libraries ourselves by rummaging about
593                          * in the ELF headers... */
594                 }
595         }
596 #endif
597
598         dynsec = elf_find_section_type(SHT_DYNAMIC, ehdr);
599         if (dynsec) {
600                 dynamic = (Elf32_Dyn*)(byteswap32_to_host(dynsec->sh_offset) + (intptr_t)ehdr);
601                 find_needed_libraries(ehdr, dynamic, is_suid);
602         }
603
604         return 0;
605 }
606
607 int main( int argc, char** argv)
608 {
609         int multi=0;
610         int got_em_all=1;
611         char *filename = NULL;
612         struct library *cur;
613
614         if (argc < 2) {
615                 fprintf(stderr, "ldd: missing file arguments\n");
616                 fprintf(stderr, "Try `ldd --help' for more information.\n");
617                 exit(EXIT_FAILURE);
618         }
619         if (argc > 2) {
620                 multi++;
621         }
622
623         while (--argc > 0) {
624                 ++argv;
625
626                 if(strcmp(*argv, "--")==0) {
627                         /* Ignore "--" */
628                         continue;
629                 }
630
631                 if(strcmp(*argv, "--help")==0) {
632                         fprintf(stderr, "Usage: ldd [OPTION]... FILE...\n");
633                         fprintf(stderr, "\t--help\t\tprint this help and exit\n");
634                         exit(EXIT_FAILURE);
635                 }
636
637                 filename=*argv;
638                 if (!filename) {
639                         fprintf(stderr, "No filename specified.\n");
640                         exit(EXIT_FAILURE);
641                 }
642
643                 if (multi) {
644                         printf("%s:\n", *argv);
645                 }
646
647                 if (find_dependancies(filename)!=0)
648                         continue;
649
650                 while(got_em_all) {
651                         got_em_all=0;
652                         /* Keep walking the list till everybody is resolved */
653                         for (cur = lib_list; cur; cur=cur->next) {
654                                 if (cur->resolved == 0 && cur->path) {
655                                         got_em_all=1;
656                                         //printf("checking sub-depends for '%s\n", cur->path);
657                                         find_dependancies(cur->path);
658                                         cur->resolved = 1;
659                                 }
660                         }
661                 }
662
663
664                 /* Print the list */
665                 got_em_all=0;
666                 for (cur = lib_list; cur; cur=cur->next) {
667                         got_em_all=1;
668                         printf("\t%s => %s (0x00000000)\n", cur->name, cur->path);
669                 }
670                 if (interp && interpreter_already_found==1)
671                         printf("\t%s => %s (0x00000000)\n", interp, interp);
672                 else
673                         printf("\tnot a dynamic executable\n");
674
675                 for (cur = lib_list; cur; cur=cur->next) {
676                         free(cur->name);
677                         cur->name=NULL;
678                         if (cur->path && cur->path != not_found) {
679                                 free(cur->path);
680                                 cur->path=NULL;
681                         }
682                 }
683                 lib_list=NULL;
684         }
685
686         return 0;
687 }
688