OSDN Git Service

Make ldd work for ET_DYN executables. From Peter Mazinger.
[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 "usr/X11R6/lib:"
342                 UCLIBC_RUNTIME_PREFIX "usr/lib:"
343                 UCLIBC_RUNTIME_PREFIX "lib:"
344                 "/usr/X11R6/lib:"
345                 "/usr/lib:"
346                 "/lib";
347         search_for_named_library(lib->name, buf, path);
348         if (*buf != '\0') {
349                 lib->path = buf;
350         } else {
351                 free(buf);
352                 lib->path = not_found;
353         }
354 }
355
356 static int add_library(Elf32_Ehdr* ehdr, Elf32_Dyn* dynamic, int is_setuid, char *s)
357 {
358         char *tmp, *tmp1, *tmp2;
359         struct library *cur, *newlib=lib_list;
360
361         if (!s || !strlen(s))
362                 return 1;
363
364         tmp = s;
365         while (*tmp) {
366                 if (*tmp == '/')
367                         s = tmp + 1;
368                 tmp++;
369         }
370
371         /* We add ldso elsewhere */
372         if (interpreter_already_found && (tmp=strrchr(interp, '/')) != NULL)
373         {
374                 int len = strlen(interp_dir);
375                 if (strcmp(s, interp+1+len)==0)
376                         return 1;
377         }
378
379         for (cur = lib_list; cur; cur=cur->next) {
380                 /* Check if this library is already in the list */
381                 tmp1 = tmp2 = cur->name;
382                 while (*tmp1) {
383                         if (*tmp1 == '/')
384                                 tmp2 = tmp1 + 1;
385                         tmp1++;
386                 }
387                 if(strcmp(tmp2, s)==0) {
388                         //printf("find_elf_interpreter is skipping '%s' (already in list)\n", cur->name);
389                         return 0;
390                 }
391         }
392
393         /* Ok, this lib needs to be added to the list */
394         newlib = malloc(sizeof(struct library));
395         if (!newlib)
396                 return 1;
397         newlib->name = malloc(strlen(s)+1);
398         strcpy(newlib->name, s);
399         newlib->resolved = 0;
400         newlib->path = NULL;
401         newlib->next = NULL;
402
403         /* Now try and locate where this library might be living... */
404         locate_library_file(ehdr, dynamic, is_setuid, newlib);
405
406         //printf("add_library is adding '%s' to '%s'\n", newlib->name, newlib->path);
407         if (!lib_list) {
408                 lib_list = newlib;
409         } else {
410                 for (cur = lib_list;  cur->next; cur=cur->next); /* nothing */
411                 cur->next = newlib;
412         }
413         return 0;
414 }
415
416 static void find_needed_libraries(Elf32_Ehdr* ehdr,
417                 Elf32_Dyn* dynamic, int is_setuid)
418 {
419         Elf32_Dyn  *dyns;
420
421         for (dyns=dynamic; byteswap32_to_host(dyns->d_tag)!=DT_NULL; ++dyns) {
422                 if (DT_NEEDED == byteswap32_to_host(dyns->d_tag)) {
423                         char *strtab;
424                         strtab = (char *)elf_find_dynamic(DT_STRTAB, dynamic, ehdr, 0);
425                         add_library(ehdr, dynamic, is_setuid,
426                                         (char*)strtab + byteswap32_to_host(dyns->d_un.d_val));
427                 }
428         }
429 }
430
431 static struct library * find_elf_interpreter(Elf32_Ehdr* ehdr)
432 {
433         Elf32_Phdr *phdr;
434
435         if (interpreter_already_found==1)
436                 return NULL;
437         phdr = elf_find_phdr_type(PT_INTERP, ehdr);
438         if (phdr) {
439                 struct library *cur, *newlib=NULL;
440                 char *s = (char*)ehdr + byteswap32_to_host(phdr->p_offset);
441
442                 char *tmp, *tmp1;
443                 interp = strdup(s);
444                 interp_dir = strdup(s);
445                 tmp = strrchr(interp_dir, '/');
446                 if (*tmp)
447                         *tmp = '\0';
448                 else {
449                         free(interp_dir);
450                         interp_dir = interp;
451                 }
452                 tmp1 = tmp = s;
453                 while (*tmp) {
454                         if (*tmp == '/')
455                                 tmp1 = tmp + 1;
456                         tmp++;
457                 }
458                 for (cur = lib_list; cur; cur=cur->next) {
459                         /* Check if this library is already in the list */
460                         if(strcmp(cur->name, tmp1)==0) {
461                                 //printf("find_elf_interpreter is replacing '%s' (already in list)\n", cur->name);
462                                 newlib = cur;
463                                 free(newlib->name);
464                                 if (newlib->path != not_found) {
465                                         free(newlib->path);
466                                 }
467                                 newlib->name = NULL;
468                                 newlib->path = NULL;
469                                 return NULL;
470                         }
471                 }
472                 if (newlib == NULL)
473                         newlib = malloc(sizeof(struct library));
474                 if (!newlib)
475                         return NULL;
476                 newlib->name = malloc(strlen(s)+1);
477                 strcpy(newlib->name, s);
478                 newlib->path = strdup(newlib->name);
479                 newlib->resolved = 1;
480                 newlib->next = NULL;
481
482 #if 0
483                 //printf("find_elf_interpreter is adding '%s' to '%s'\n", newlib->name, newlib->path);
484                 if (!lib_list) {
485                         lib_list = newlib;
486                 } else {
487                         for (cur = lib_list;  cur->next; cur=cur->next); /* nothing */
488                         cur->next = newlib;
489                 }
490 #endif
491                 interpreter_already_found=1;
492                 return newlib;
493         }
494         return NULL;
495 }
496
497 /* map the .so, and locate interesting pieces */
498 int find_dependancies(char* filename)
499 {
500         int is_suid = 0;
501         FILE *thefile;
502         struct stat statbuf;
503         Elf32_Ehdr *ehdr = NULL;
504         Elf32_Shdr *dynsec = NULL;
505         Elf32_Dyn *dynamic = NULL;
506         struct library *interp;
507
508         if (filename == not_found)
509                 return 0;
510
511         if (!filename) {
512                 fprintf(stderr, "No filename specified.\n");
513                 return -1;
514         }
515         if (!(thefile = fopen(filename, "r"))) {
516                 perror(filename);
517                 return -1;
518         }
519         if (fstat(fileno(thefile), &statbuf) < 0) {
520                 perror(filename);
521                 fclose(thefile);
522                 return -1;
523         }
524
525         if ((size_t)statbuf.st_size < sizeof(Elf32_Ehdr))
526                 goto foo;
527
528         if (!S_ISREG(statbuf.st_mode))
529                 goto foo;
530
531         /* mmap the file to make reading stuff from it effortless */
532         ehdr = (Elf32_Ehdr *)mmap(0, statbuf.st_size,
533                         PROT_READ|PROT_WRITE, MAP_PRIVATE, fileno(thefile), 0);
534         if (ehdr == MAP_FAILED) {
535                 fclose(thefile);
536                 fprintf(stderr, "Out of memory!\n");
537                 return -1;
538         }
539
540 foo:
541         fclose(thefile);
542
543         /* Check if this looks like a legit ELF file */
544         if (check_elf_header(ehdr)) {
545                 fprintf(stderr, "%s: not an ELF file.\n", filename);
546                 return -1;
547         }
548         /* Check if this is the right kind of ELF file */
549         if (ehdr->e_type != ET_EXEC && ehdr->e_type != ET_DYN) {
550                 fprintf(stderr, "%s: not a dynamic executable\n", filename);
551                 return -1;
552         }
553         if (ehdr->e_type == ET_EXEC || ehdr->e_type != ET_DYN) {
554                 if (statbuf.st_mode & S_ISUID)
555                         is_suid = 1;
556                 if ((statbuf.st_mode & (S_ISGID | S_IXGRP)) == (S_ISGID | S_IXGRP))
557                         is_suid = 1;
558                 /* FIXME */
559                 if (is_suid)
560                         fprintf(stderr, "%s: is setuid\n", filename);
561         }
562
563         interpreter_already_found=0;
564         interp = find_elf_interpreter(ehdr);
565
566 #ifdef __LDSO_LDD_SUPPORT
567         if (interp && (ehdr->e_type == ET_EXEC || ehdr->e_type == ET_DYN) && ehdr->e_ident[EI_CLASS] == ELFCLASSM &&
568                         ehdr->e_ident[EI_DATA] == ELFDATAM
569                         && ehdr->e_ident[EI_VERSION] == EV_CURRENT && MATCH_MACHINE(ehdr->e_machine))
570         {
571                 struct stat statbuf;
572                 if (stat(interp->path, &statbuf) == 0 && S_ISREG(statbuf.st_mode)) {
573                         pid_t pid;
574                         int status;
575                         static const char * const environment[] = {
576                                 "PATH=/usr/bin:/bin:/usr/sbin:/sbin",
577                                 "SHELL=/bin/sh",
578                                 "LD_TRACE_LOADED_OBJECTS=1",
579                                 NULL
580                         };
581
582                         if ((pid = fork()) == 0) {
583                                 /* Cool, it looks like we should be able to actually
584                                  * run this puppy.  Do so now... */
585                                 execle(filename, filename, NULL, environment);
586                                 _exit(0xdead);
587                         }
588
589                         /* Wait till it returns */
590                         waitpid(pid, &status, 0);
591                         if (WIFEXITED(status) && WEXITSTATUS(status)==0) {
592                                 return 1;
593                         }
594
595                         /* If the exec failed, we fall through to trying to find
596                          * all the needed libraries ourselves by rummaging about
597                          * in the ELF headers... */
598                 }
599         }
600 #endif
601
602         dynsec = elf_find_section_type(SHT_DYNAMIC, ehdr);
603         if (dynsec) {
604                 dynamic = (Elf32_Dyn*)(byteswap32_to_host(dynsec->sh_offset) + (intptr_t)ehdr);
605                 find_needed_libraries(ehdr, dynamic, is_suid);
606         }
607
608         return 0;
609 }
610
611 int main( int argc, char** argv)
612 {
613         int multi=0;
614         int got_em_all=1;
615         char *filename = NULL;
616         struct library *cur;
617
618         if (argc < 2) {
619                 fprintf(stderr, "ldd: missing file arguments\n");
620                 fprintf(stderr, "Try `ldd --help' for more information.\n");
621                 exit(EXIT_FAILURE);
622         }
623         if (argc > 2) {
624                 multi++;
625         }
626
627         while (--argc > 0) {
628                 ++argv;
629
630                 if(strcmp(*argv, "--")==0) {
631                         /* Ignore "--" */
632                         continue;
633                 }
634
635                 if(strcmp(*argv, "--help")==0) {
636                         fprintf(stderr, "Usage: ldd [OPTION]... FILE...\n");
637                         fprintf(stderr, "\t--help\t\tprint this help and exit\n");
638                         exit(EXIT_FAILURE);
639                 }
640
641                 filename=*argv;
642                 if (!filename) {
643                         fprintf(stderr, "No filename specified.\n");
644                         exit(EXIT_FAILURE);
645                 }
646
647                 if (multi) {
648                         printf("%s:\n", *argv);
649                 }
650
651                 if (find_dependancies(filename)!=0)
652                         continue;
653
654                 while(got_em_all) {
655                         got_em_all=0;
656                         /* Keep walking the list till everybody is resolved */
657                         for (cur = lib_list; cur; cur=cur->next) {
658                                 if (cur->resolved == 0 && cur->path) {
659                                         got_em_all=1;
660                                         //printf("checking sub-depends for '%s\n", cur->path);
661                                         find_dependancies(cur->path);
662                                         cur->resolved = 1;
663                                 }
664                         }
665                 }
666
667
668                 /* Print the list */
669                 got_em_all=0;
670                 for (cur = lib_list; cur; cur=cur->next) {
671                         got_em_all=1;
672                         printf("\t%s => %s (0x00000000)\n", cur->name, cur->path);
673                 }
674                 if (interp && interpreter_already_found==1)
675                         printf("\t%s => %s (0x00000000)\n", interp, interp);
676                 else
677                         printf("\tnot a dynamic executable\n");
678
679                 for (cur = lib_list; cur; cur=cur->next) {
680                         free(cur->name);
681                         cur->name=NULL;
682                         if (cur->path && cur->path != not_found) {
683                                 free(cur->path);
684                                 cur->path=NULL;
685                         }
686                 }
687                 lib_list=NULL;
688         }
689
690         return 0;
691 }
692