Initial import from FreeBSD RELENG_4:
[dragonfly.git] / libexec / rtld-aout / rtld.c
1 /*
2  * Copyright (c) 1993 Paul Kranenburg
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. All advertising materials mentioning features or use of this software
14  *    must display the following acknowledgement:
15  *      This product includes software developed by Paul Kranenburg.
16  * 4. The name of the author may not be used to endorse or promote products
17  *    derived from this software without specific prior written permission
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
20  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
21  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
22  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
23  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
24  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
28  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29  *
30  * $FreeBSD: src/libexec/rtld-aout/rtld.c,v 1.58.2.2 2002/03/04 12:00:31 dwmalone Exp $
31  */
32
33 #include <sys/param.h>
34 #include <sys/types.h>
35 #include <sys/stat.h>
36 #include <sys/file.h>
37 #include <sys/time.h>
38 #include <sys/resource.h>
39 #include <sys/errno.h>
40 #include <sys/mman.h>
41 #ifndef MAP_COPY
42 #define MAP_COPY        MAP_PRIVATE
43 #endif
44 #include <dlfcn.h>
45 #include <err.h>
46 #include <fcntl.h>
47 #include <a.out.h>
48 #include <paths.h>
49 #include <stab.h>
50 #include <stdio.h>
51 #include <stdlib.h>
52 #include <string.h>
53 #include <unistd.h>
54 #if __STDC__
55 #include <stdarg.h>
56 #else
57 #include <varargs.h>
58 #endif
59
60 #include <link.h>
61
62 #include "md.h"
63 #include "shlib.h"
64 #include "support.h"
65 #include "dynamic.h"
66
67 #ifndef MAP_ANON
68 #define MAP_ANON        0
69 #define anon_open() do {                                        \
70         if ((anon_fd = open(_PATH_DEVZERO, O_RDWR, 0)) == -1)   \
71                 err("open: %s", _PATH_DEVZERO);                 \
72 } while (0)
73 #define anon_close() do {       \
74         (void)close(anon_fd);   \
75         anon_fd = -1;           \
76 } while (0)
77 #else
78 #define anon_open()
79 #define anon_close()
80 #endif
81
82 /*
83  * Structure for building a list of shared objects.
84  */
85 struct so_list {
86         struct so_map   *sol_map;       /* Link map for shared object */
87         struct so_list  *sol_next;      /* Next entry in the list */
88 };
89
90 /*
91  * Loader private data, hung off <so_map>->som_spd
92  */
93 struct somap_private {
94         int             spd_version;
95         struct so_map   *spd_parent;
96         struct so_list  *spd_children;
97         struct so_map   *spd_prev;
98         dev_t           spd_dev;
99         ino_t           spd_ino;
100         int             spd_refcount;
101         int             spd_flags;
102 #define RTLD_MAIN       0x01
103 #define RTLD_RTLD       0x02
104 #define RTLD_DL         0x04
105 #define RTLD_INIT       0x08
106         unsigned long   a_text;    /* text size, if known     */
107         unsigned long   a_data;    /* initialized data size   */
108         unsigned long   a_bss;     /* uninitialized data size */
109
110 #ifdef SUN_COMPAT
111         long            spd_offset;     /* Correction for Sun main programs */
112 #endif
113 };
114
115 #define LM_PRIVATE(smp) ((struct somap_private *)(smp)->som_spd)
116
117 #ifdef SUN_COMPAT
118 #define LM_OFFSET(smp)  (LM_PRIVATE(smp)->spd_offset)
119 #else
120 #define LM_OFFSET(smp)  (0)
121 #endif
122
123 /* Base address for section_dispatch_table entries */
124 #define LM_LDBASE(smp)  (smp->som_addr + LM_OFFSET(smp))
125
126 /* Start of text segment */
127 #define LM_TXTADDR(smp) (smp->som_addr == (caddr_t)0 ? PAGSIZ : 0)
128
129 /* Start of run-time relocation_info */
130 #define LM_REL(smp)     ((struct relocation_info *) \
131         (smp->som_addr + LM_OFFSET(smp) + LD_REL((smp)->som_dynamic)))
132
133 /* Start of symbols */
134 #define LM_SYMBOL(smp, i)       ((struct nzlist *) \
135         (smp->som_addr + LM_OFFSET(smp) + LD_SYMBOL((smp)->som_dynamic) + \
136                 i * (LD_VERSION_NZLIST_P(smp->som_dynamic->d_version) ? \
137                         sizeof(struct nzlist) : sizeof(struct nlist))))
138
139 /* Start of hash table */
140 #define LM_HASH(smp)    ((struct rrs_hash *) \
141         ((smp)->som_addr + LM_OFFSET(smp) + LD_HASH((smp)->som_dynamic)))
142
143 /* Start of strings */
144 #define LM_STRINGS(smp) ((char *) \
145         ((smp)->som_addr + LM_OFFSET(smp) + LD_STRINGS((smp)->som_dynamic)))
146
147 /* Start of search paths */
148 #define LM_PATHS(smp)   ((char *) \
149         ((smp)->som_addr + LM_OFFSET(smp) + LD_PATHS((smp)->som_dynamic)))
150
151 /* End of text */
152 #define LM_ETEXT(smp)   ((char *) \
153         ((smp)->som_addr + LM_TXTADDR(smp) + LD_TEXTSZ((smp)->som_dynamic)))
154
155 /* Needed shared objects */
156 #define LM_NEED(smp)    ((struct sod *) \
157         ((smp)->som_addr + LM_TXTADDR(smp) + LD_NEED((smp)->som_dynamic)))
158
159 /* PLT is in data segment, so don't use LM_OFFSET here */
160 #define LM_PLT(smp)     ((jmpslot_t *) \
161         ((smp)->som_addr + LD_PLT((smp)->som_dynamic)))
162
163 /* Parent of link map */
164 #define LM_PARENT(smp)  (LM_PRIVATE(smp)->spd_parent)
165
166 #ifndef RELOC_EXTERN_P
167 #define RELOC_EXTERN_P(s) ((s)->r_extern)
168 #endif
169
170 #ifndef RELOC_SYMBOL
171 #define RELOC_SYMBOL(s) ((s)->r_symbolnum)
172 #endif
173
174 #ifndef RELOC_PCREL_P
175 #define RELOC_PCREL_P(s) ((s)->r_pcrel)
176 #endif
177
178 #define END_SYM         "_end"
179
180 static char             __main_progname[] = "main";
181 static char             *main_progname = __main_progname;
182 static char             us[] = "/usr/libexec/ld.so";
183
184 char                    **environ;
185 char                    *__progname;
186 int                     errno;
187
188 static uid_t            uid, euid;
189 static gid_t            gid, egid;
190 static int              careful;
191 static int              anon_fd = -1;
192
193 static char             *ld_bind_now;
194 static char             *ld_ignore_missing_objects;
195 static char             *ld_library_path;
196 static char             *ld_preload;
197 static char             *ld_tracing;
198 static char             *ld_suppress_warnings;
199 static char             *ld_warn_non_pure_code;
200
201 struct so_map           *link_map_head;
202 struct so_map           *link_map_tail;
203 struct rt_symbol        *rt_symbol_head;
204
205 static void             *__dlopen __P((const char *, int));
206 static int              __dlclose __P((void *));
207 static void             *__dlsym __P((void *, const char *));
208 static const char       *__dlerror __P((void));
209 static void             __dlexit __P((void));
210 static void             *__dlsym3 __P((void *, const char *, void *));
211 static int              __dladdr __P((const void *, Dl_info *));
212
213 static struct ld_entry  ld_entry = {
214         __dlopen, __dlclose, __dlsym, __dlerror, __dlexit, __dlsym3, __dladdr
215 };
216
217        void             xprintf __P((char *, ...));
218 static struct so_map    *map_object __P((       const char *,
219                                                 struct sod *,
220                                                 struct so_map *));
221 static int              map_preload __P((void));
222 static int              map_sods __P((struct so_map *));
223 static int              reloc_dag __P((struct so_map *, int));
224 static void             unmap_object __P((struct so_map *, int));
225 static struct so_map    *alloc_link_map __P((   const char *, struct sod *,
226                                                 struct so_map *, caddr_t,
227                                                 struct _dynamic *));
228 static void             init_link_map __P((     struct so_map *,
229                                                 struct somap_private *,
230                                                 const char *, struct sod *,
231                                                 struct so_map *, caddr_t,
232                                                 struct _dynamic *));
233 static void             free_link_map __P((struct so_map *));
234 static inline int       check_text_reloc __P((  struct relocation_info *,
235                                                 struct so_map *,
236                                                 caddr_t));
237 static int              reloc_map __P((struct so_map *, int));
238 static void             reloc_copy __P((struct so_map *));
239 static void             init_dag __P((struct so_map *));
240 static void             init_sods __P((struct so_list *));
241 static void             init_internal_malloc __P((void));
242 static void             init_external_malloc __P((void));
243 static int              call_map __P((struct so_map *, char *));
244 static char             *findhint __P((char *, int, int *));
245 static char             *rtfindlib __P((char *, int, int, int));
246 static char             *rtfindfile __P((const char *));
247 void                    binder_entry __P((void));
248 long                    binder __P((jmpslot_t *));
249 static struct nzlist    *lookup __P((char *, struct so_map **, int));
250 static inline struct rt_symbol  *lookup_rts __P((char *, unsigned long));
251 static struct nzlist    *lookup_in_obj __P((char *, unsigned long,
252     struct so_map *, int));
253 static struct rt_symbol *enter_rts __P((char *, unsigned long, long, int,
254     caddr_t, long, struct so_map *));
255 static void             *sym_addr __P((char *));
256 static struct nzlist *  lookup_errno_hack(char *, struct so_map **, int);
257 static void             die __P((void));
258 static void             generror __P((char *, ...));
259 static int              maphints __P((void));
260 static void             unmaphints __P((void));
261 static void             ld_trace __P((struct so_map *));
262 static void             rt_readenv __P((void));
263 static int              hinthash __P((char *, int));
264 int                     rtld __P((int, struct crt_ldso *, struct _dynamic *));
265
266 /*
267  * Compute a hash value for symbol tables.  Don't change this -- the
268  * algorithm is dictated by the way the linker builds the symbol
269  * tables in the shared objects.
270  */
271 static inline unsigned long
272 sym_hash(s)
273         const char      *s;
274 {
275         unsigned long    h;
276
277         h = 0;
278         while (*s != '\0')
279                 h = (h << 1) + *s++;
280         return h & 0x7fffffffUL;
281 }
282
283 static inline int
284 strcmp (register const char *s1, register const char *s2)
285 {
286         while (*s1 == *s2++)
287                 if (*s1++ == 0)
288                         return (0);
289         return (*(unsigned char *)s1 - *(unsigned char *)--s2);
290 }
291
292 #include "md-static-funcs.c"
293
294 /*
295  * Called from assembler stub that has set up crtp (passed from crt0)
296  * and dp (our __DYNAMIC).
297  */
298 int
299 rtld(version, crtp, dp)
300 int                     version;
301 struct crt_ldso         *crtp;
302 struct _dynamic         *dp;
303 {
304         struct relocation_info  *reloc;
305         struct relocation_info  *reloc_limit;   /* End+1 of relocation */
306         struct so_debug         *ddp;
307         struct so_map           *main_map;
308         struct so_map           *smp;
309         char                    *add_paths;
310         char                    *main_path;
311
312         /* Check version */
313         if (version != CRT_VERSION_BSD_2 &&
314             version != CRT_VERSION_BSD_3 &&
315             version != CRT_VERSION_BSD_4 &&
316             version != CRT_VERSION_BSD_5 &&
317             version != CRT_VERSION_SUN)
318                 return -1;
319
320         /* Fixup __DYNAMIC structure */
321         (long)dp->d_un.d_sdt += crtp->crt_ba;
322
323         /* Relocate ourselves */
324         reloc = (struct relocation_info *) (LD_REL(dp) + crtp->crt_ba);
325         reloc_limit =
326                 (struct relocation_info *) ((char *) reloc + LD_RELSZ(dp));
327         while(reloc < reloc_limit) {
328                 /*
329                  * Objects linked with "-Bsymbolic" (in particular, ld.so
330                  * itself) can end up having unused relocation entries at
331                  * the end.  These can be detected by the fact that they
332                  * have an address of 0.
333                  */
334                 if(reloc->r_address == 0)       /* We're done */
335                     break;
336                 md_relocate_simple(reloc, crtp->crt_ba,
337                         reloc->r_address + crtp->crt_ba);
338                 ++reloc;
339         }
340
341         if (version >= CRT_VERSION_BSD_4)
342                 __progname = crtp->crt_ldso;
343         if (version >= CRT_VERSION_BSD_3)
344                 main_progname = crtp->crt_prog;
345         main_path = version >= CRT_VERSION_BSD_5 ? crtp->crt_argv[0] :
346             main_progname;
347
348         /* Some buggy versions of crt0.o have crt_ldso filled in as NULL. */
349         if (__progname == NULL)
350                 __progname = us;
351
352         /* Fill in some fields in _DYNAMIC or crt structure */
353         if (version >= CRT_VERSION_BSD_4)
354                 crtp->crt_ldentry = &ld_entry;          /* crt */
355         else
356                 crtp->crt_dp->d_entry = &ld_entry;      /* _DYNAMIC */
357
358         /* Initialize our internal malloc package. */
359         init_internal_malloc();
360
361         /* Setup out (private) environ variable */
362         environ = crtp->crt_ep;
363
364         /* Get user and group identifiers */
365         uid = getuid(); euid = geteuid();
366         gid = getgid(); egid = getegid();
367
368         careful = (uid != euid) || (gid != egid);
369
370         rt_readenv();
371
372         anon_open();
373
374         /* Make a link map entry for the main program */
375         main_map = alloc_link_map(main_path,
376                              (struct sod *) NULL, (struct so_map *) NULL,
377                              (caddr_t) 0, crtp->crt_dp);
378         LM_PRIVATE(main_map)->spd_refcount++;
379         LM_PRIVATE(main_map)->spd_flags |= RTLD_MAIN;
380
381         /* Make a link map entry for ourselves */
382         smp = alloc_link_map(us,
383                              (struct sod *) NULL, (struct so_map *) NULL,
384                              (caddr_t) crtp->crt_ba, dp);
385         LM_PRIVATE(smp)->spd_refcount++;
386         LM_PRIVATE(smp)->spd_flags |= RTLD_RTLD;
387
388         /*
389          * Setup the executable's run path
390          */
391         if (version >= CRT_VERSION_BSD_4) {
392                 add_paths = LM_PATHS(main_map);
393                 if (add_paths)
394                         add_search_path(add_paths);
395         }
396
397         /*
398          * Setup the directory search list for findshlib.  We use only
399          * the standard search path.  Any extra directories from
400          * LD_LIBRARY_PATH are searched explicitly, in rtfindlib.
401          */
402         std_search_path();
403
404         /* Map in LD_PRELOADs before the main program's shared objects so we
405            can intercept those calls */
406         if (ld_preload != NULL) {
407                 if(map_preload() == -1)                 /* Failed */
408                         die();
409         }
410
411         /* Map all the shared objects that the main program depends upon */
412         if(map_sods(main_map) == -1)
413                 die();
414
415         if(ld_tracing) {        /* We're done */
416                 ld_trace(link_map_head);
417                 exit(0);
418         }
419
420         crtp->crt_dp->d_un.d_sdt->sdt_loaded = link_map_head->som_next;
421
422         /* Relocate all mapped objects. */
423         if(reloc_dag(main_map, ld_bind_now != NULL) == -1)      /* Failed */
424                 die();
425
426         /*
427          * Switch to the same malloc that the program uses.  We do
428          * this before initializing the loaded objects, because their
429          * initialization functions may well call malloc, and it won't
430          * work right until we have set it up.
431          */
432         init_external_malloc();
433
434         /* Initialize all mapped objects. */
435         init_dag(main_map);
436
437         ddp = crtp->crt_dp->d_debug;
438         ddp->dd_cc = rt_symbol_head;
439         if (ddp->dd_in_debugger) {
440                 caddr_t addr = (caddr_t)((long)crtp->crt_bp & (~(PAGSIZ - 1)));
441
442                 /* Set breakpoint for the benefit of debuggers */
443                 if (mprotect(addr, PAGSIZ,
444                                 PROT_READ|PROT_WRITE|PROT_EXEC) == -1) {
445                         err(1, "Cannot set breakpoint (%s)", main_progname);
446                 }
447                 md_set_breakpoint((long)crtp->crt_bp, (long *)&ddp->dd_bpt_shadow);
448                 if (mprotect(addr, PAGSIZ, PROT_READ|PROT_EXEC) == -1) {
449                         err(1, "Cannot re-protect breakpoint (%s)",
450                                 main_progname);
451                 }
452
453                 ddp->dd_bpt_addr = crtp->crt_bp;
454                 if (link_map_head)
455                         ddp->dd_sym_loaded = 1;
456         }
457
458         /* Close the hints file */
459         unmaphints();
460
461         /* Close our file descriptor */
462         (void)close(crtp->crt_ldfd);
463         anon_close();
464
465         return LDSO_VERSION_HAS_DLADDR;
466 }
467
468 void
469 ld_trace(smp)
470         struct so_map *smp;
471 {
472         char    *fmt1, *fmt2, *fmt, *main_local;
473         int     c;
474
475         if ((main_local = getenv("LD_TRACE_LOADED_OBJECTS_PROGNAME")) == NULL)
476                 main_local = "";
477
478         if ((fmt1 = getenv("LD_TRACE_LOADED_OBJECTS_FMT1")) == NULL)
479                 fmt1 = "\t-l%o.%m => %p (%x)\n";
480
481         if ((fmt2 = getenv("LD_TRACE_LOADED_OBJECTS_FMT2")) == NULL)
482                 fmt2 = "\t%o (%x)\n";
483
484         for (; smp; smp = smp->som_next) {
485                 struct sod      *sodp;
486                 char            *name, *path;
487
488                 if ((sodp = smp->som_sod) == NULL)
489                         continue;
490
491                 name = (char *)sodp->sod_name;
492                 if (LM_PARENT(smp))
493                         name += (long)LM_LDBASE(LM_PARENT(smp));
494
495                 if ((path = smp->som_path) == NULL)
496                         path = "not found";
497
498                 fmt = sodp->sod_library ? fmt1 : fmt2;
499                 while ((c = *fmt++) != '\0') {
500                         switch (c) {
501                         default:
502                                 putchar(c);
503                                 continue;
504                         case '\\':
505                                 switch (c = *fmt) {
506                                 case '\0':
507                                         continue;
508                                 case 'n':
509                                         putchar('\n');
510                                         break;
511                                 case 't':
512                                         putchar('\t');
513                                         break;
514                                 }
515                                 break;
516                         case '%':
517                                 switch (c = *fmt) {
518                                 case '\0':
519                                         continue;
520                                 case '%':
521                                 default:
522                                         putchar(c);
523                                         break;
524                                 case 'A':
525                                         printf("%s", main_local);
526                                         break;
527                                 case 'a':
528                                         printf("%s", main_progname);
529                                         break;
530                                 case 'o':
531                                         printf("%s", name);
532                                         break;
533                                 case 'm':
534                                         printf("%d", sodp->sod_major);
535                                         break;
536                                 case 'n':
537                                         printf("%d", sodp->sod_minor);
538                                         break;
539                                 case 'p':
540                                         printf("%s", path);
541                                         break;
542                                 case 'x':
543                                         printf("%p", smp->som_addr);
544                                         break;
545                                 }
546                                 break;
547                         }
548                         ++fmt;
549                 }
550         }
551 }
552
553 /*
554  * Allocate a new link map and return a pointer to it.
555  *
556  * PATH is the pathname of the shared object.
557  *
558  * SODP is a pointer to the shared object dependency structure responsible
559  * for causing the new object to be loaded.  PARENT is the shared object
560  * into which SODP points.  Both can be NULL if the new object is not
561  * being loaded as a result of a shared object dependency.
562  *
563  * ADDR is the address at which the object has been mapped.  DP is a pointer
564  * to its _dynamic structure.
565  */
566 static struct so_map *
567 alloc_link_map(path, sodp, parent, addr, dp)
568         const char      *path;
569         struct sod      *sodp;
570         struct so_map   *parent;
571         caddr_t         addr;
572         struct _dynamic *dp;
573 {
574         struct so_map           *smp;
575         struct somap_private    *smpp;
576
577 #ifdef DEBUG /* { */
578         xprintf("alloc_link_map: \"%s\" at %p\n", path, addr);
579 #endif /* } */
580
581         smp = (struct so_map *)xmalloc(sizeof(struct so_map));
582         smpp = (struct somap_private *)xmalloc(sizeof(struct somap_private));
583         init_link_map(smp, smpp, path, sodp, parent, addr, dp);
584
585         /* Link the new entry into the list of link maps */
586         smpp->spd_prev = link_map_tail;
587         if(link_map_tail == NULL)       /* First link map entered into list */
588                 link_map_head = link_map_tail = smp;
589         else {                          /* Append to end of list */
590                 link_map_tail->som_next = smp;
591                 link_map_tail = smp;
592         }
593
594         return smp;
595 }
596
597 /*
598  * Initialize a link map entry that has already been allocated.
599  */
600 static void
601 init_link_map(smp, smpp, path, sodp, parent, addr, dp)
602         struct so_map           *smp;
603         struct somap_private    *smpp;
604         const char              *path;
605         struct sod              *sodp;
606         struct so_map           *parent;
607         caddr_t                  addr;
608         struct _dynamic         *dp;
609 {
610         memset(smp, 0, sizeof *smp);
611         memset(smpp, 0, sizeof *smpp);
612         smp->som_spd = (caddr_t)smpp;
613         smp->som_addr = addr;
614         smp->som_path = path ? strdup(path) : NULL;
615         smp->som_sod = sodp;
616         smp->som_dynamic = dp;
617         smpp->spd_parent = parent;
618 #ifdef SUN_COMPAT
619         smpp->spd_offset =
620                 (addr==0 && dp && dp->d_version==LD_VERSION_SUN) ? PAGSIZ : 0;
621 #endif
622 }
623
624 /*
625  * Remove the specified link map entry from the list of link maps, and free
626  * the associated storage.
627  */
628 static void
629 free_link_map(smp)
630         struct so_map   *smp;
631 {
632         struct somap_private    *smpp = LM_PRIVATE(smp);
633
634 #ifdef DEBUG /* { */
635         xprintf("free_link_map: \"%s\"\n", smp->som_path);
636 #endif /* } */
637
638         if(smpp->spd_prev == NULL)      /* Removing first entry in list */
639                 link_map_head = smp->som_next;
640         else                            /* Update link of previous entry */
641                 smpp->spd_prev->som_next = smp->som_next;
642
643         if(smp->som_next == NULL)       /* Removing last entry in list */
644                 link_map_tail = smpp->spd_prev;
645         else                            /* Update back link of next entry */
646                 LM_PRIVATE(smp->som_next)->spd_prev = smpp->spd_prev;
647
648         if (smp->som_path != NULL)
649                 free(smp->som_path);
650         free(smpp);
651         free(smp);
652 }
653
654 /*
655  * Map the shared object specified by PATH into memory, if it is not
656  * already mapped.  Increment the object's reference count, and return a
657  * pointer to its link map.
658  *
659  * As a special case, if PATH is NULL, it is taken to refer to the main
660  * program.
661  *
662  * SODP is a pointer to the shared object dependency structure that caused
663  * this object to be requested.  PARENT is a pointer to the link map of
664  * the shared object containing that structure.  For a shared object not
665  * being mapped as a result of a shared object dependency, these pointers
666  * should be NULL.  An example of this is a shared object that is explicitly
667  * loaded via dlopen().
668  *
669  * The return value is a pointer to the link map for the requested object.
670  * If the operation failed, the return value is NULL.  In that case, an
671  * error message can be retrieved by calling dlerror().
672  */
673 static struct so_map *
674 map_object(path, sodp, parent)
675         const char      *path;
676         struct sod      *sodp;
677         struct so_map   *parent;
678 {
679         struct so_map   *smp;
680         struct stat     statbuf;
681
682         if(path == NULL)        /* Special case for the main program itself */
683                 smp = link_map_head;
684         else {
685                 /*
686                  * Check whether the shared object is already mapped.
687                  * We check first for an exact match by pathname.  That
688                  * will detect the usual case.  If no match is found by
689                  * pathname, then stat the file, and check for a match by
690                  * device and inode.  That will detect the less common case
691                  * involving multiple links to the same library.
692                  */
693                 for(smp = link_map_head;  smp != NULL;  smp = smp->som_next) {
694                         if(!(LM_PRIVATE(smp)->spd_flags & (RTLD_MAIN|RTLD_RTLD))
695                         && smp->som_path != NULL
696                         && strcmp(smp->som_path, path) == 0)
697                                 break;
698                 }
699                 if(smp == NULL) {  /* Check for a match by device and inode */
700                         if (stat(path, &statbuf) == -1) {
701                                 generror ("cannot stat \"%s\" : %s",
702                                         path, strerror(errno));
703                                 return NULL;
704                         }
705                         for (smp = link_map_head;  smp != NULL;
706                              smp = smp->som_next) {
707                                 struct somap_private *smpp = LM_PRIVATE(smp);
708
709                                 if (!(smpp->spd_flags & (RTLD_MAIN | RTLD_RTLD))
710                                 && smpp->spd_ino == statbuf.st_ino
711                                 && smpp->spd_dev == statbuf.st_dev)
712                                         break;
713                         }
714                 }
715         }
716
717         if (smp == NULL) {      /* We must map the object */
718                 struct _dynamic *dp;
719                 int             fd;
720                 caddr_t         addr;
721                 struct exec     hdr;
722                 struct somap_private *smpp;
723
724                 if ((fd = open(path, O_RDONLY, 0)) == -1) {
725                         generror ("open failed for \"%s\" : %s",
726                                   path, strerror (errno));
727                         return NULL;
728                 }
729
730                 if (read(fd, &hdr, sizeof(hdr)) != sizeof(hdr)) {
731                         generror ("header read failed for \"%s\"", path);
732                         (void)close(fd);
733                         return NULL;
734                 }
735
736                 if (N_BADMAG(hdr)) {
737                         generror ("bad magic number in \"%s\"", path);
738                         (void)close(fd);
739                         return NULL;
740                 }
741
742                 /*
743                  * Map the entire address space of the object.  It is
744                  * tempting to map just the text segment at first, in
745                  * order to avoid having to use mprotect to change the
746                  * protections of the data segment.  But that would not
747                  * be correct.  Mmap might find a group of free pages
748                  * large enough to hold the text segment, but not large
749                  * enough for the entire object.  When we then mapped
750                  * in the data and BSS segments, they would either be
751                  * non-contiguous with the text segment (if we didn't
752                  * specify MAP_FIXED), or they would map over some
753                  * previously mapped region (if we did use MAP_FIXED).
754                  * The only way we can be sure of getting a contigous
755                  * region that is large enough is to map the entire
756                  * region at once.
757                  */
758                 if ((addr = mmap(0, hdr.a_text + hdr.a_data + hdr.a_bss,
759                          PROT_READ|PROT_EXEC,
760                          MAP_COPY, fd, 0)) == (caddr_t)-1) {
761                         generror ("mmap failed for \"%s\" : %s",
762                                   path, strerror (errno));
763                         (void)close(fd);
764                         return NULL;
765                 }
766
767                 (void)close(fd);
768
769                 /* Change the data segment to writable */
770                 if (mprotect(addr + hdr.a_text, hdr.a_data,
771                     PROT_READ|PROT_WRITE|PROT_EXEC) != 0) {
772                         generror ("mprotect failed for \"%s\" : %s",
773                                   path, strerror (errno));
774                         (void)munmap(addr, hdr.a_text + hdr.a_data + hdr.a_bss);
775                         return NULL;
776                 }
777
778                 /* Map in pages of zeros for the BSS segment */
779                 if (mmap(addr + hdr.a_text + hdr.a_data, hdr.a_bss,
780                          PROT_READ|PROT_WRITE|PROT_EXEC,
781                          MAP_ANON|MAP_COPY|MAP_FIXED,
782                          anon_fd, 0) == (caddr_t)-1) {
783                         generror ("mmap failed for \"%s\" : %s",
784                                   path, strerror (errno));
785                         (void)munmap(addr, hdr.a_text + hdr.a_data + hdr.a_bss);
786                         return NULL;
787                 }
788
789                 /* Assume _DYNAMIC is the first data item */
790                 dp = (struct _dynamic *)(addr+hdr.a_text);
791
792                 /* Fixup __DYNAMIC structure */
793                 (long)dp->d_un.d_sdt += (long)addr;
794
795                 smp = alloc_link_map(path, sodp, parent, addr, dp);
796
797                 /* save segment sizes for unmap. */
798                 smpp = LM_PRIVATE(smp);
799                 smpp->a_text = hdr.a_text;
800                 smpp->a_data = hdr.a_data;
801                 smpp->a_bss = hdr.a_bss;
802
803                 /*
804                  * Save the device and inode, so we can detect multiple links
805                  * to the same library.  Note, if we reach this point, then
806                  * statbuf is guaranteed to have been filled in.
807                  */
808                 smpp->spd_dev = statbuf.st_dev;
809                 smpp->spd_ino = statbuf.st_ino;
810         }
811
812         LM_PRIVATE(smp)->spd_refcount++;
813         if(LM_PRIVATE(smp)->spd_refcount == 1) {  /* First use of object */
814                 /*
815                  * Recursively map all of the shared objects that this
816                  * one depends upon.
817                  */
818                 if(map_sods(smp) == -1) {               /* Failed */
819                         unmap_object(smp, 0);           /* Clean up */
820                         return NULL;
821                 }
822         }
823
824         return smp;
825 }
826
827 /*
828  * Map all the shared libraries named in the LD_PRELOAD environment
829  * variable.
830  *
831  * Returns 0 on success, -1 on failure.  On failure, an error message can
832  * be gotten via dlerror().
833  */
834         static int
835 map_preload __P((void)) {
836         char    *ld_name = ld_preload;
837         char    *name;
838
839         while ((name = strsep(&ld_name, ":")) != NULL) {
840                 char            *path = NULL;
841                 struct so_map   *smp = NULL;
842
843                 if (*name != '\0') {
844                         path = (strchr(name, '/') != NULL) ?  strdup(name) :
845                                 rtfindfile(name);
846                 }
847                 if (path == NULL) {
848                         generror("Can't find LD_PRELOAD shared"
849                                 " library \"%s\"", name);
850                 } else {
851                         smp = map_object(path, (struct sod *) NULL,
852                                 (struct so_map *) NULL);
853                         free(path);
854                 }
855                 if (ld_name != NULL)
856                         *(ld_name - 1) = ':';
857                 if (smp == NULL) {
858                         /*
859                          * We don't bother to unmap already-loaded libraries
860                          * on failure, because in that case the program is
861                          * about to die anyway.
862                          */
863                         return -1;
864                 }
865         }
866         return 0;
867 }
868
869 /*
870  * Map all of the shared objects that a given object depends upon.  PARENT is
871  * a pointer to the link map for the shared object whose dependencies are
872  * to be mapped.
873  *
874  * Returns 0 on success.  Returns -1 on failure.  In that case, an error
875  * message can be retrieved by calling dlerror().
876  */
877 static int
878 map_sods(parent)
879         struct so_map   *parent;
880 {
881         struct somap_private    *parpp = LM_PRIVATE(parent);
882         struct so_list          **soltail = &parpp->spd_children;
883         long                    next = LD_NEED(parent->som_dynamic);
884
885         while(next != 0) {
886                 struct sod      *sodp =
887                         (struct sod *) (LM_LDBASE(parent) + next);
888                 char            *name =
889                         (char *) (LM_LDBASE(parent) + sodp->sod_name);
890                 char            *path = NULL;
891                 struct so_map   *smp = NULL;
892
893                 if(sodp->sod_library) {
894                         /*
895                          * First try for a match with an adequate minor
896                          * number.
897                          */
898                         path = rtfindlib(name, sodp->sod_major,
899                                          sodp->sod_minor, 1);
900                         /*
901                          * If none was found, try for just a major version
902                          * match.  A warning is issued by rtfindlib in
903                          * this case, since the minor version number isn't
904                          * really high enough.
905                          */
906                         if (path == NULL)
907                                 path = rtfindlib(name, sodp->sod_major,
908                                                  sodp->sod_minor, 0);
909                         if(path == NULL && !ld_tracing) {
910                                 generror ("Can't find shared library"
911                                           " \"lib%s.so.%d.%d\"", name,
912                                           sodp->sod_major, sodp->sod_minor);
913                         }
914                 } else {
915                         if(careful && name[0] != '/') {
916                                 generror("Shared library path must start"
917                                          " with \"/\" for \"%s\"", name);
918                         } else
919                                 path = strdup(name);
920                 }
921
922                 if(path != NULL) {
923                         smp = map_object(path, sodp, parent);
924                         free(path);
925                 }
926
927                 if(smp != NULL) {
928                         struct so_list  *solp = (struct so_list *)
929                                 xmalloc(sizeof(struct so_list));
930                         solp->sol_map = smp;
931                         solp->sol_next = NULL;
932                         *soltail = solp;
933                         soltail = &solp->sol_next;
934                 } else if(ld_tracing) {
935                         /*
936                          * Allocate a dummy map entry so that we will get the
937                          * "not found" message.
938                          */
939                         (void)alloc_link_map(NULL, sodp, parent, 0, 0);
940                 } else if (ld_ignore_missing_objects) {
941                         const char *msg;
942                         /*
943                          * Call __dlerror() even it we're not going to use
944                          * the message, in order to clear the saved message.
945                          */
946                         msg = __dlerror();  /* Should never be NULL */
947                         if (!ld_suppress_warnings)
948                                 warnx("warning: %s", msg);
949                 } else  /* Give up */
950                         break;
951
952                 next = sodp->sod_next;
953         }
954
955         if(next != 0) {
956                 /*
957                  * Oh drat, we have to clean up a mess.
958                  *
959                  * We failed to load a shared object that we depend upon.
960                  * So now we have to unload any dependencies that we had
961                  * already successfully loaded prior to the error.
962                  *
963                  * Cleaning up doesn't matter so much for the initial
964                  * loading of the program, since any failure is going to
965                  * terminate the program anyway.  But it is very important
966                  * to clean up properly when something is being loaded
967                  * via dlopen().
968                  */
969                 struct so_list          *solp;
970
971                 while((solp = parpp->spd_children) != NULL) {
972                         unmap_object(solp->sol_map, 0);
973                         parpp->spd_children = solp->sol_next;
974                         free(solp);
975                 }
976
977                 return -1;
978         }
979
980         return 0;
981 }
982
983 /*
984  * Relocate the DAG of shared objects rooted at the given link map
985  * entry.  Returns 0 on success, or -1 on failure.  On failure, an
986  * error message can be retrieved via dlerror().
987  */
988 static int
989 reloc_dag(root, bind_now)
990         struct so_map   *root;
991         int             bind_now;
992 {
993         struct so_map   *smp;
994
995         /*
996          * Relocate all newly-loaded objects.  We avoid recursion for this
997          * step by taking advantage of a few facts.  This function is called
998          * only when there are in fact some newly-loaded objects to process.
999          * Furthermore, all newly-loaded objects will have their link map
1000          * entries at the end of the link map list.  And, the root of the
1001          * tree of objects just loaded will have been the first to be loaded
1002          * and therefore the first new object in the link map list.  Finally,
1003          * we take advantage of the fact that we can relocate the newly-loaded
1004          * objects in any order.
1005          *
1006          * All these facts conspire to let us simply loop over the tail
1007          * portion of the link map list, relocating each object so
1008          * encountered.
1009          */
1010         for(smp = root;  smp != NULL;  smp = smp->som_next) {
1011                 if(!(LM_PRIVATE(smp)->spd_flags & RTLD_RTLD)) {
1012                         if(reloc_map(smp, bind_now) < 0)
1013                                 return -1;
1014                 }
1015         }
1016
1017         /*
1018          * Copy any relocated initialized data.  Again, we can just loop
1019          * over the appropriate portion of the link map list.
1020          */
1021         for(smp = root;  smp != NULL;  smp = smp->som_next) {
1022                 if(!(LM_PRIVATE(smp)->spd_flags & RTLD_RTLD))
1023                         reloc_copy(smp);
1024         }
1025
1026         return 0;
1027 }
1028
1029 /*
1030  * Remove a reference to the shared object specified by SMP.  If no
1031  * references remain, unmap the object and, recursively, its descendents.
1032  * This function also takes care of calling the finalization routines for
1033  * objects that are removed.
1034  *
1035  * If KEEP is true, then the actual calls to munmap() are skipped,
1036  * and the object is kept in memory.  That is used only for finalization,
1037  * from dlexit(), when the program is exiting.  There are two reasons
1038  * for it.  First, the program is exiting and there is no point in
1039  * spending the time to explicitly unmap its shared objects.  Second,
1040  * even after dlexit() has been called, there are still a couple of
1041  * calls that are made to functions in libc.  (This is really a bug
1042  * in crt0.)  So libc and the main program, at least, must remain
1043  * mapped in that situation.
1044  *
1045  * Under no reasonable circumstances should this function fail.  If
1046  * anything goes wrong, we consider it an internal error, and report
1047  * it with err().
1048  */
1049 static void
1050 unmap_object(smp, keep)
1051         struct so_map   *smp;
1052         int             keep;
1053 {
1054         struct somap_private    *smpp = LM_PRIVATE(smp);
1055
1056         smpp->spd_refcount--;
1057         if(smpp->spd_refcount == 0) {           /* Finished with this object */
1058                 struct so_list  *solp;
1059
1060                 if(smpp->spd_flags & RTLD_INIT) {       /* Was initialized */
1061                         /*
1062                          * Call the object's finalization routine.  For
1063                          * backward compatibility, we first try to call
1064                          * ".fini".  If that does not exist, we call
1065                          * "__fini".
1066                          */
1067                         if(call_map(smp, ".fini") == -1)
1068                                 call_map(smp, "__fini");
1069                 }
1070
1071                 /* Recursively unreference the object's descendents */
1072                 while((solp = smpp->spd_children) != NULL) {
1073                         unmap_object(solp->sol_map, keep);
1074                         smpp->spd_children = solp->sol_next;
1075                         free(solp);
1076                 }
1077
1078                 if(!keep) {     /* Unmap the object from memory */
1079                         if(munmap(smp->som_addr,
1080                         smpp->a_text + smpp->a_data + smpp->a_bss) < 0)
1081                                 err(1, "internal error 1: munmap failed");
1082
1083                         /* Unlink and free the object's link map entry */
1084                         free_link_map(smp);
1085                 }
1086         }
1087 }
1088
1089 static inline int
1090 check_text_reloc(r, smp, addr)
1091 struct relocation_info  *r;
1092 struct so_map           *smp;
1093 caddr_t                 addr;
1094 {
1095         char    *sym;
1096
1097         if (addr >= LM_ETEXT(smp))
1098                 return 0;
1099
1100         if (RELOC_EXTERN_P(r))
1101                 sym = LM_STRINGS(smp) +
1102                                 LM_SYMBOL(smp, RELOC_SYMBOL(r))->nz_strx;
1103         else
1104                 sym = "";
1105
1106         if (!ld_suppress_warnings && ld_warn_non_pure_code)
1107                 warnx("warning: non pure code in %s at %x (%s)",
1108                                 smp->som_path, r->r_address, sym);
1109
1110         if (smp->som_write == 0 &&
1111                 mprotect(smp->som_addr + LM_TXTADDR(smp),
1112                                 LD_TEXTSZ(smp->som_dynamic),
1113                                 PROT_READ|PROT_WRITE|PROT_EXEC) == -1) {
1114                 generror ("mprotect failed for \"%s\" : %s",
1115                           smp->som_path, strerror (errno));
1116                 return -1;
1117         }
1118
1119         smp->som_write = 1;
1120         return 0;
1121 }
1122
1123 static int
1124 reloc_map(smp, bind_now)
1125         struct so_map           *smp;
1126         int                     bind_now;
1127 {
1128         /*
1129          * Caching structure for reducing the number of calls to
1130          * lookup() during relocation.
1131          *
1132          * While relocating a given shared object, the dynamic linker
1133          * maintains a caching vector that is directly indexed by
1134          * the symbol number in the relocation entry.  The first time
1135          * a given symbol is looked up, the caching vector is
1136          * filled in with a pointer to the symbol table entry, and
1137          * a pointer to the so_map of the shared object in which the
1138          * symbol was defined.  On subsequent uses of the same symbol,
1139          * that information is retrieved directly from the caching
1140          * vector, without calling lookup() again.
1141          *
1142          * A symbol that is referenced in a relocation entry is
1143          * typically referenced in many relocation entries, so this
1144          * caching reduces the number of calls to lookup()
1145          * dramatically.  The overall improvement in the speed of
1146          * dynamic linking is also dramatic -- as much as a factor
1147          * of three for programs that use many shared libaries.
1148          */
1149         struct cacheent {
1150                 struct nzlist *np;      /* Pointer to symbol entry */
1151                 struct so_map *src_map; /* Shared object that defined symbol */
1152         };
1153
1154         struct _dynamic         *dp = smp->som_dynamic;
1155         struct relocation_info  *r = LM_REL(smp);
1156         struct relocation_info  *rend = r + LD_RELSZ(dp)/sizeof(*r);
1157         long                    symbolbase = (long)LM_SYMBOL(smp, 0);
1158         char                    *stringbase = LM_STRINGS(smp);
1159         int symsize             = LD_VERSION_NZLIST_P(dp->d_version) ?
1160                                         sizeof(struct nzlist) :
1161                                         sizeof(struct nlist);
1162         long                    numsyms = LD_STABSZ(dp) / symsize;
1163         size_t                  cachebytes = numsyms * sizeof(struct cacheent);
1164         struct cacheent         *symcache =
1165                                         (struct cacheent *) alloca(cachebytes);
1166
1167         if(symcache == NULL) {
1168                 generror("Cannot allocate symbol caching vector for %s",
1169                         smp->som_path);
1170                 return -1;
1171         }
1172         bzero(symcache, cachebytes);
1173
1174         if (LD_PLTSZ(dp))
1175                 md_fix_jmpslot(LM_PLT(smp),
1176                                 (long)LM_PLT(smp), (long)binder_entry);
1177
1178         for (; r < rend; r++) {
1179                 char    *sym;
1180                 caddr_t addr;
1181
1182                 /*
1183                  * Objects linked with "-Bsymbolic" can end up having unused
1184                  * relocation entries at the end.  These can be detected by
1185                  * the fact that they have an address of 0.
1186                  */
1187                 if(r->r_address == 0)   /* Finished relocating this object */
1188                         break;
1189
1190                 addr = smp->som_addr + r->r_address;
1191                 if (check_text_reloc(r, smp, addr) < 0)
1192                         return -1;
1193
1194                 if (RELOC_EXTERN_P(r)) {
1195                         struct so_map   *src_map = NULL;
1196                         struct nzlist   *p, *np;
1197                         long    relocation;
1198
1199                         if (RELOC_JMPTAB_P(r) && !bind_now)
1200                                 continue;
1201
1202                         p = (struct nzlist *)
1203                                 (symbolbase + symsize * RELOC_SYMBOL(r));
1204
1205                         if (p->nz_type == (N_SETV + N_EXT))
1206                                 src_map = smp;
1207
1208                         sym = stringbase + p->nz_strx;
1209
1210                         /*
1211                          * Look up the symbol, checking the caching
1212                          * vector first.
1213                          */
1214                         np = symcache[RELOC_SYMBOL(r)].np;
1215                         if(np != NULL)  /* Symbol already cached */
1216                                 src_map = symcache[RELOC_SYMBOL(r)].src_map;
1217                         else {  /* Symbol not cached yet */
1218                                 np = lookup(sym, &src_map, RELOC_JMPTAB_P(r));
1219                                 /*
1220                                  * Record the needed information about
1221                                  * the symbol in the caching vector,
1222                                  * so that we won't have to call
1223                                  * lookup the next time we encounter
1224                                  * the symbol.
1225                                  */
1226                                 symcache[RELOC_SYMBOL(r)].np = np;
1227                                 symcache[RELOC_SYMBOL(r)].src_map = src_map;
1228                         }
1229
1230                         if (np == NULL) {
1231                                 generror ("Undefined symbol \"%s\" in %s:%s",
1232                                         sym, main_progname, smp->som_path);
1233                                 return -1;
1234                         }
1235
1236                         /*
1237                          * Found symbol definition.
1238                          * If it's in a link map, adjust value
1239                          * according to the load address of that map.
1240                          * Otherwise it's a run-time allocated common
1241                          * whose value is already up-to-date.
1242                          */
1243                         relocation = np->nz_value;
1244                         if (src_map)
1245                                 relocation += (long)src_map->som_addr;
1246
1247                         if (RELOC_JMPTAB_P(r)) {
1248                                 md_bind_jmpslot(relocation, addr);
1249                                 continue;
1250                         }
1251
1252                         relocation += md_get_addend(r, addr);
1253
1254                         if (RELOC_PCREL_P(r))
1255                                 relocation -= (long)smp->som_addr;
1256
1257                         if (RELOC_COPY_P(r) && src_map) {
1258                                 (void)enter_rts(sym, sym_hash(sym),
1259                                         (long)addr,
1260                                         N_DATA + N_EXT,
1261                                         src_map->som_addr + np->nz_value,
1262                                         np->nz_size, src_map);
1263                                 continue;
1264                         }
1265
1266                         md_relocate(r, relocation, addr, 0);
1267                 } else {
1268                         md_relocate(r,
1269 #ifdef SUN_COMPAT
1270                                 md_get_rt_segment_addend(r, addr)
1271 #else
1272                                 md_get_addend(r, addr)
1273 #endif
1274                                         + (long)smp->som_addr, addr, 0);
1275                 }
1276
1277         }
1278
1279         if (smp->som_write) {
1280                 if (mprotect(smp->som_addr + LM_TXTADDR(smp),
1281                                 LD_TEXTSZ(smp->som_dynamic),
1282                                 PROT_READ|PROT_EXEC) == -1) {
1283                         generror ("mprotect failed for \"%s\" : %s",
1284                                   smp->som_path, strerror (errno));
1285                         return -1;
1286                 }
1287                 smp->som_write = 0;
1288         }
1289         return 0;
1290 }
1291
1292 static void
1293 reloc_copy(smp)
1294         struct so_map           *smp;
1295 {
1296         struct rt_symbol        *rtsp;
1297
1298         for (rtsp = rt_symbol_head; rtsp; rtsp = rtsp->rt_next)
1299                 if ((rtsp->rt_smp == NULL || rtsp->rt_smp == smp) &&
1300                                 rtsp->rt_sp->nz_type == N_DATA + N_EXT) {
1301                         bcopy(rtsp->rt_srcaddr, (caddr_t)rtsp->rt_sp->nz_value,
1302                                                         rtsp->rt_sp->nz_size);
1303                 }
1304 }
1305
1306 /*
1307  * Initialize the DAG of shared objects rooted at the given object.
1308  */
1309 static void
1310 init_dag(smp)
1311         struct so_map           *smp;
1312 {
1313         struct somap_private    *smpp = LM_PRIVATE(smp);
1314
1315         if(!(smpp->spd_flags & RTLD_INIT)) {    /* Not initialized yet */
1316                 smpp->spd_flags |= RTLD_INIT;
1317
1318                 /* Make sure all the children are initialized */
1319                 if(smpp->spd_children != NULL)
1320                         init_sods(smpp->spd_children);
1321
1322                 if(call_map(smp, ".init") == -1)
1323                         call_map(smp, "__init");
1324         }
1325 }
1326
1327 static void
1328 init_sods(solp)
1329         struct so_list  *solp;
1330 {
1331         /* Recursively initialize the rest of the list */
1332         if(solp->sol_next != NULL)
1333                 init_sods(solp->sol_next);
1334
1335         /* Initialize the first element of the list */
1336         init_dag(solp->sol_map);
1337 }
1338
1339
1340 /*
1341  * Call a function in a given shared object.  SMP is the shared object, and
1342  * SYM is the name of the function.
1343  *
1344  * Returns 0 on success, or -1 if the symbol was not found.  Failure is not
1345  * necessarily an error condition, so no error message is generated.
1346  */
1347 static int
1348 call_map(smp, sym)
1349         struct so_map           *smp;
1350         char                    *sym;
1351 {
1352         struct so_map           *src_map = smp;
1353         struct nzlist           *np;
1354
1355         np = lookup(sym, &src_map, 1);
1356         if (np) {
1357                 (*(void (*)())(src_map->som_addr + np->nz_value))();
1358                 return 0;
1359         }
1360
1361         return -1;
1362 }
1363
1364 /*
1365  * Run-time common symbol table.
1366  */
1367
1368 #define RTC_TABSIZE             57
1369 static struct rt_symbol         *rt_symtab[RTC_TABSIZE];
1370
1371 /*
1372  * Look up a symbol in the run-time common symbol table.  For efficiency,
1373  * the symbol's hash value must be passed in too.
1374  */
1375 static inline struct rt_symbol *
1376 lookup_rts(name, hash)
1377         char            *name;
1378         unsigned long    hash;
1379 {
1380         register struct rt_symbol       *rtsp;
1381
1382         for (rtsp = rt_symtab[hash % RTC_TABSIZE]; rtsp; rtsp = rtsp->rt_link)
1383                 if (strcmp(name, rtsp->rt_sp->nz_name) == 0)
1384                         return rtsp;
1385
1386         return NULL;
1387 }
1388
1389 /*
1390  * Enter a symbol into the run-time common symbol table.  For efficiency,
1391  * the symbol's hash value must be passed in too.
1392  */
1393 static struct rt_symbol *
1394 enter_rts(name, hash, value, type, srcaddr, size, smp)
1395         char            *name;
1396         unsigned long    hash;
1397         long             value;
1398         int              type;
1399         caddr_t          srcaddr;
1400         long             size;
1401         struct so_map   *smp;
1402 {
1403         register struct rt_symbol       *rtsp, **rpp;
1404
1405         /* Find end of bucket */
1406         for (rpp = &rt_symtab[hash % RTC_TABSIZE]; *rpp; rpp = &(*rpp)->rt_link)
1407                 continue;
1408
1409         /* Allocate new common symbol */
1410         rtsp = (struct rt_symbol *)xmalloc(sizeof(struct rt_symbol));
1411         rtsp->rt_sp = (struct nzlist *)xmalloc(sizeof(struct nzlist));
1412         rtsp->rt_sp->nz_name = strdup(name);
1413         rtsp->rt_sp->nz_value = value;
1414         rtsp->rt_sp->nz_type = type;
1415         rtsp->rt_sp->nz_size = size;
1416         rtsp->rt_srcaddr = srcaddr;
1417         rtsp->rt_smp = smp;
1418         rtsp->rt_link = NULL;
1419
1420         /* Link onto linear list as well */
1421         rtsp->rt_next = rt_symbol_head;
1422         rt_symbol_head = rtsp;
1423
1424         *rpp = rtsp;
1425
1426         return rtsp;
1427 }
1428
1429
1430 /*
1431  * Lookup NAME in the link maps. The link map producing a definition
1432  * is returned in SRC_MAP. If SRC_MAP is not NULL on entry the search
1433  * is confined to that map.
1434  *
1435  * REAL_DEF_ONLY is a boolean which specifies whether certain special
1436  * symbols for functions should satisfy the lookup or not.  The
1437  * reasons behind it are somewhat complicated.  They are motivated
1438  * by the scenario in which the address of a single function is
1439  * taken from several shared objects.  The address should come out
1440  * the same in all cases, because the application code might decide
1441  * to use it in comparisons.  To make this work, the linker creates
1442  * a symbol entry for the function in the main executable, with a
1443  * type of N_UNDF+N_EXT, an N_AUX of AUX_FUNC, and a value that
1444  * refers to the PLT entry for the function in the main executable.
1445  * If REAL_DEF_ONLY is false, then this kind of special symbol is
1446  * considered a "definition" when lookup up the symbol.  Since the
1447  * main executable is at the beginning of the shared object search
1448  * list, the result is that references from all shared objects will
1449  * resolve to the main program's PLT entry, and thus the function
1450  * addresses will compare equal as they should.
1451  *
1452  * When relocating the PLT entry itself, we obviously must match
1453  * only the true defining symbol for the function.  In that case, we
1454  * set REAL_DEF_ONLY to true, which disables matching the special
1455  * N_UNDF+N_EXT entries.
1456  *
1457  * It is not so clear how to set this flag for a lookup done from
1458  * dlsym.  If the lookup specifies a particular shared object other
1459  * than the main executable, the flag makes no difference -- only the
1460  * true definition will be matched.  (That is because the special
1461  * symbols are only present in the main executable, which will not
1462  * be searched.)  But when the lookup is over all the shared objects
1463  * (i.e., dlsym's "fd" parameter is NULL), then the flag does have an
1464  * effect.  We elect to match only the true definition even in that
1465  * case.
1466  *
1467  * The upshot of all this is the following rule of thumb: Set
1468  * REAL_DEF_ONLY in all cases except when processing a non-PLT
1469  * relocation.
1470  */
1471 static struct nzlist *
1472 lookup(name, src_map, real_def_only)
1473         char            *name;
1474         struct so_map   **src_map;      /* IN/OUT */
1475         int             real_def_only;
1476 {
1477         unsigned long            hash;
1478
1479         hash = sym_hash(name);
1480
1481         if (*src_map != NULL)   /* Look in just one specific object */
1482                 return lookup_in_obj(name, hash, *src_map, real_def_only);
1483         else {  /* Search runtime symbols and all loaded objects */
1484                 unsigned long            common_size;
1485                 struct so_map           *smp;
1486                 struct rt_symbol        *rtsp;
1487                 struct nzlist           *np;
1488
1489                 if ((rtsp = lookup_rts(name, hash)) != NULL)
1490                         return rtsp->rt_sp;
1491
1492                 common_size = 0;
1493                 for (smp = link_map_head; smp; smp = smp->som_next) {
1494                         if (LM_PRIVATE(smp)->spd_flags & RTLD_RTLD)
1495                                 continue;
1496                         np = lookup_in_obj(name, hash, smp, real_def_only);
1497                         if (np == NULL)
1498                                 continue;
1499                         /* We know that np->nz_value > 0 at this point. */
1500                         if (np->nz_type == N_UNDF+N_EXT &&
1501                             N_AUX(&np->nlist) != AUX_FUNC) {    /* Common */
1502                                 if (common_size < np->nz_value)
1503                                         common_size = np->nz_value;
1504                                 continue;
1505                         }
1506
1507                         /* We found the symbol definition. */
1508                         *src_map = smp;
1509                         return np;
1510                 }
1511                 if (common_size > 0) {  /* It is a common symbol. */
1512                         void    *mem;
1513
1514                         mem = memset(xmalloc(common_size), 0, common_size);
1515                         rtsp = enter_rts(name, hash, (long)mem, N_UNDF + N_EXT,
1516                             0, common_size, NULL);
1517                         return rtsp->rt_sp;
1518                 }
1519
1520                 /*
1521                  * Just before giving up, check for the __error() hack.
1522                  */
1523                 np = lookup_errno_hack(name, src_map, real_def_only);
1524                 if (np != NULL)
1525                         return np;
1526
1527                 /* No definition was found for the symbol. */
1528                 return NULL;
1529         }
1530 }
1531
1532 /*
1533  * Lookup a symbol in one specific shared object.  The hash
1534  * value is passed in for efficiency.  For an explanation of the
1535  * "real_def_only" flag, see the comment preceding the "lookup"
1536  * function.
1537  */
1538 static struct nzlist *
1539 lookup_in_obj(name, hash, smp, real_def_only)
1540         char            *name;
1541         unsigned long    hash;
1542         struct so_map   *smp;
1543         int              real_def_only;
1544 {
1545         unsigned long    buckets;
1546         struct rrs_hash *hp;
1547         char            *cp;
1548         struct nzlist   *np;
1549         char            *symbolbase;
1550         struct rrs_hash *hashbase;
1551         char            *stringbase;
1552         size_t          symsize;
1553
1554         if ((buckets = LD_BUCKETS(smp->som_dynamic)) == 0)
1555                 return NULL;
1556
1557         hashbase = LM_HASH(smp);
1558
1559 restart:
1560         hp = &hashbase[hash % buckets];
1561         if (hp->rh_symbolnum == -1)
1562                 return NULL;
1563
1564         symbolbase = (char *)LM_SYMBOL(smp, 0);
1565         stringbase = LM_STRINGS(smp);
1566         symsize = LD_VERSION_NZLIST_P(smp->som_dynamic->d_version)?
1567             sizeof(struct nzlist) : sizeof(struct nlist);
1568         for ( ; ; ) {
1569                 np = (struct nzlist *)(symbolbase + hp->rh_symbolnum*symsize);
1570                 cp = stringbase + np->nz_strx;
1571                 if (strcmp(cp, name) == 0)
1572                         break;
1573                 if (hp->rh_next == 0)   /* End of hash chain */
1574                         return NULL;
1575                 hp = hashbase + hp->rh_next;
1576         }
1577
1578         /*
1579          * We have a symbol with the name we're looking for.
1580          */
1581         if (np->nz_type == N_INDR+N_EXT) {
1582                 /*
1583                  * Next symbol gives the aliased name. Restart
1584                  * search with new name.
1585                  */
1586                 name = stringbase + (++np)->nz_strx;
1587                 hash = sym_hash(name);
1588                 goto restart;
1589         }
1590
1591         if (np->nz_value == 0)  /* It's not a definition */
1592                 return NULL;
1593
1594         if (real_def_only)      /* Don't match special function symbols. */
1595                 if (np->nz_type == N_UNDF+N_EXT &&
1596                     N_AUX(&np->nlist) == AUX_FUNC)
1597                         return NULL;
1598
1599         return np;
1600 }
1601
1602 /*
1603  * Return the value of a symbol in the user's program.  This is used
1604  * internally for a few symbols which must exist.  If the requested
1605  * symbol is not found, this simply exits with a fatal error.
1606  */
1607 static void *
1608 sym_addr(name)
1609         char            *name;
1610 {
1611         struct so_map   *smp;
1612         struct nzlist   *np;
1613
1614         smp = NULL;
1615         np = lookup(name, &smp, 1);
1616         if (np == NULL)
1617                 errx(1, "Program has no symbol \"%s\"", name);
1618         return ((smp == NULL) ? NULL : smp->som_addr) + np->nz_value;
1619 }
1620
1621
1622 static int *p_errno;    /* Pointer to errno variable in main program. */
1623
1624 /*
1625  * Help old a.out binaries that are broken by the new errno macro.  They
1626  * can be missing __error() through no fault of their own.  In particular,
1627  * old a.out binaries can link against an old libc that does not contain
1628  * __error(), yet still require __error() because of other libraries that
1629  * have been recompiled since the errno change.  This locates the backward
1630  * compatible work-alike we have hidden here in ld.so.
1631  */
1632 static struct nzlist *
1633 lookup_errno_hack(sym, src_map, real_def_only)
1634         char            *sym;
1635         struct so_map   **src_map;
1636         int              real_def_only;
1637 {
1638         struct so_map   *smp;
1639         struct nzlist   *np;
1640
1641         if (strcmp(sym, "___error") != 0)
1642                 return NULL;
1643
1644         /*
1645          * Locate errno in the main program.  If it's not there, NULL
1646          * will be returned by our __error() substitute, and a core dump
1647          * will follow.  That's impossible, of course, since crt0.o always
1648          * supplies errno.
1649          */
1650         smp = NULL;
1651         np = lookup("_errno", &smp, 1);
1652         if (np != NULL && smp != NULL) {
1653                 p_errno = (int *)(smp->som_addr + np->nz_value);
1654 #ifdef DEBUG
1655                 xprintf(" HACK: _errno at %p in %s\n", p_errno, smp->som_path);
1656 #endif
1657         }
1658
1659         /*
1660          * Specifically find the ld.so link map because most routines
1661          * skip over it during normal operation.
1662          */
1663         for (smp = link_map_head; ; smp = smp->som_next)
1664                 if (LM_PRIVATE(smp)->spd_flags & RTLD_RTLD)
1665                         break;
1666
1667         /*
1668          * Find our __error() substitute stashed here in ld.so.
1669          */
1670         np = lookup("___error_unthreaded_hack", &smp, real_def_only);
1671         if (np != NULL)
1672                 *src_map = smp;
1673
1674 #ifdef DEBUG
1675         if (np == NULL)
1676                 xprintf(" HACK: %s fudge not found, oops\n", sym);
1677         else
1678                 xprintf(" HACK: %s fudge in %s\n", sym, smp->som_path);
1679 #endif
1680
1681         return np;
1682 }
1683
1684
1685 /*
1686  * Just like __error_unthreaded(), but for those poor orphaned a.out
1687  * binaries from way back that are bamboozled by the new errno macro.
1688  */
1689 int *
1690 __error_unthreaded_hack()
1691 {
1692         return p_errno;
1693 }
1694
1695
1696 /*
1697  * This routine is called from the jumptable to resolve
1698  * procedure calls to shared objects.
1699  */
1700 long
1701 binder(jsp)
1702         jmpslot_t       *jsp;
1703 {
1704         struct so_map   *smp, *src_map = NULL;
1705         long            addr;
1706         char            *sym;
1707         struct nzlist   *np;
1708         int             index;
1709
1710         /*
1711          * Find the PLT map that contains JSP.
1712          */
1713         for (smp = link_map_head; smp; smp = smp->som_next) {
1714                 if (LM_PLT(smp) < jsp &&
1715                         jsp < LM_PLT(smp) + LD_PLTSZ(smp->som_dynamic)/sizeof(*jsp))
1716                         break;
1717         }
1718
1719         if (smp == NULL)
1720                 errx(1, "Call to binder from unknown location: %p\n", jsp);
1721
1722         index = jsp->reloc_index & JMPSLOT_RELOC_MASK;
1723
1724         /* Get the local symbol this jmpslot refers to */
1725         sym = LM_STRINGS(smp) +
1726                 LM_SYMBOL(smp,RELOC_SYMBOL(&LM_REL(smp)[index]))->nz_strx;
1727
1728         np = lookup(sym, &src_map, 1);
1729         if (np == NULL)
1730                 errx(1, "Undefined symbol \"%s\" called from %s:%s at %p",
1731                                 sym, main_progname, smp->som_path, jsp);
1732
1733         /* Fixup jmpslot so future calls transfer directly to target */
1734         addr = np->nz_value;
1735         if (src_map)
1736                 addr += (long)src_map->som_addr;
1737
1738         md_fix_jmpslot(jsp, (long)jsp, addr);
1739
1740 #if DEBUG
1741         xprintf(" BINDER: %s located at = %#x in %s\n", sym, addr,
1742                 src_map->som_path);
1743 #endif
1744         return addr;
1745 }
1746
1747 static struct hints_header      *hheader;       /* NULL means not mapped */
1748 static struct hints_bucket      *hbuckets;
1749 static char                     *hstrtab;
1750
1751 /*
1752  * Map the hints file into memory, if it is not already mapped.  Returns
1753  * 0 on success, or -1 on failure.
1754  */
1755 static int
1756 maphints __P((void))
1757 {
1758         static int              hints_bad;      /* TRUE if hints are unusable */
1759         static int              paths_added;
1760         int                     hfd;
1761         struct hints_header     hdr;
1762         caddr_t                 addr;
1763
1764         if (hheader != NULL)    /* Already mapped */
1765                 return 0;
1766
1767         if (hints_bad)          /* Known to be corrupt or unavailable */
1768                 return -1;
1769
1770         if ((hfd = open(_PATH_LD_HINTS, O_RDONLY, 0)) == -1) {
1771                 hints_bad = 1;
1772                 return -1;
1773         }
1774
1775         /* Read the header and check it */
1776
1777         if (read(hfd, &hdr, sizeof hdr) != sizeof hdr ||
1778             HH_BADMAG(hdr) ||
1779             (hdr.hh_version != LD_HINTS_VERSION_1 &&
1780              hdr.hh_version != LD_HINTS_VERSION_2)) {
1781                 close(hfd);
1782                 hints_bad = 1;
1783                 return -1;
1784         }
1785
1786         /* Map the hints into memory */
1787
1788         addr = mmap(0, hdr.hh_ehints, PROT_READ, MAP_SHARED, hfd, 0);
1789         if (addr == (caddr_t)-1) {
1790                 close(hfd);
1791                 hints_bad = 1;
1792                 return -1;
1793         }
1794
1795         close(hfd);
1796
1797         hheader = (struct hints_header *)addr;
1798         hbuckets = (struct hints_bucket *)(addr + hheader->hh_hashtab);
1799         hstrtab = (char *)(addr + hheader->hh_strtab);
1800         /* pluck out the system ldconfig path */
1801         if (hheader->hh_version >= LD_HINTS_VERSION_2 && !paths_added) {
1802                 add_search_path(hstrtab + hheader->hh_dirlist);
1803                 paths_added = 1;
1804         }
1805
1806         return 0;
1807 }
1808
1809 /*
1810  * Unmap the hints file, if it is currently mapped.
1811  */
1812 static void
1813 unmaphints()
1814 {
1815         if (hheader != NULL) {
1816                 munmap((caddr_t)hheader, hheader->hh_ehints);
1817                 hheader = NULL;
1818         }
1819 }
1820
1821 int
1822 hinthash(cp, vmajor)
1823         char    *cp;
1824         int     vmajor;
1825 {
1826         int     k = 0;
1827
1828         while (*cp)
1829                 k = (((k << 1) + (k >> 14)) ^ (*cp++)) & 0x3fff;
1830
1831         k = (((k << 1) + (k >> 14)) ^ (vmajor*257)) & 0x3fff;
1832
1833         return k;
1834 }
1835
1836 #undef major
1837 #undef minor
1838
1839 /*
1840  * Search for a library in the hints generated by ldconfig.  On success,
1841  * returns the full pathname of the matching library.  This string is
1842  * always dynamically allocated on the heap.
1843  *
1844  * MINORP is an in/out parameter.  If the incoming value of *MINORP is
1845  * >= 0, then no library will be considered a match unless its minor
1846  * version number is at least that large.  Otherwise, only the major
1847  * version number is checked.  In any case, the minor number of the
1848  * matching library is stored into *MINORP.
1849  *
1850  * Returns NULL if the library cannot be found.
1851  */
1852 static char *
1853 findhint(name, major, minorp)
1854         char    *name;
1855         int     major;
1856         int     *minorp;
1857 {
1858         struct hints_bucket     *bp =
1859                 hbuckets + (hinthash(name, major) % hheader->hh_nbucket);
1860
1861         while (1) {
1862                 /* Sanity check */
1863                 if (bp->hi_namex >= hheader->hh_strtab_sz) {
1864                         warnx("Bad name index: %#x\n", bp->hi_namex);
1865                         break;
1866                 }
1867                 if (bp->hi_pathx >= hheader->hh_strtab_sz) {
1868                         warnx("Bad path index: %#x\n", bp->hi_pathx);
1869                         break;
1870                 }
1871                 /*
1872                  * For a given major number, the hints file has only one
1873                  * entry -- namely, the one with the highest minor number.
1874                  * If we find an entry with a matching major number, we
1875                  * know it is the best one.
1876                  */
1877                 if (strcmp(name, hstrtab + bp->hi_namex) == 0 &&
1878                     bp->hi_major == major) {
1879                         struct stat s;
1880                         int realminor;
1881
1882                         realminor = bp->hi_ndewey >= 2 ? bp->hi_minor : 0;
1883                         if (realminor < *minorp)        /* Not good enough */
1884                                 return NULL;
1885                         if (stat(hstrtab + bp->hi_pathx, &s) == -1)
1886                                 return NULL;  /* Doesn't actually exist */
1887                         *minorp = realminor;
1888                         return strdup(hstrtab + bp->hi_pathx);
1889                 }
1890
1891                 if (bp->hi_next == -1)
1892                         break;
1893
1894                 /* Move on to next in bucket */
1895                 bp = &hbuckets[bp->hi_next];
1896         }
1897
1898         /* No hints available for name */
1899         return NULL;
1900 }
1901
1902 /*
1903  * Search for the given shared library.  On success, returns a string
1904  * containing the full pathname for the library.  This string is always
1905  * dynamically allocated on the heap.
1906  *
1907  * Returns NULL if the library cannot be found.
1908  */
1909 static char *
1910 rtfindlib(name, major, minor, strictminor)
1911         char    *name;
1912         int     major, minor;
1913         int     strictminor;
1914 {
1915         char    *ld_path = ld_library_path;
1916         char    *path = NULL;
1917         int     realminor;
1918
1919         realminor = strictminor ? minor : -1;
1920         if (ld_path != NULL) {  /* First, search the directories in ld_path */
1921                 /*
1922                  * There is no point in trying to use the hints file for this.
1923                  */
1924                 char    *dir;
1925
1926                 while (path == NULL && (dir = strsep(&ld_path, ":")) != NULL) {
1927                         path = search_lib_dir(dir, name, &major, &realminor, 0);
1928                         if (ld_path != NULL)
1929                                 *(ld_path - 1) = ':';
1930                 }
1931         }
1932
1933         if (path == NULL && maphints() == 0)    /* Search the hints file */
1934                 path = findhint(name, major, &realminor);
1935
1936         if (path == NULL)       /* Search the standard directories */
1937                 path = findshlib(name, &major, &realminor, 0);
1938
1939         if (path != NULL && realminor < minor && !ld_suppress_warnings) {
1940                 warnx("warning: %s: minor version %d"
1941                       " older than expected %d, using it anyway",
1942                       path, realminor, minor);
1943         }
1944
1945         return path;
1946 }
1947
1948 /*
1949  * Search for the given shared library file.  This is similar to rtfindlib,
1950  * except that the argument is the actual name of the desired library file.
1951  * Thus there is no need to worry about version numbers.  The return value
1952  * is a string containing the full pathname for the library.  This string
1953  * is always dynamically allocated on the heap.
1954  *
1955  * Returns NULL if the library cannot be found.
1956  */
1957 static char *
1958 rtfindfile(name)
1959         const char      *name;
1960 {
1961         char    *ld_path = ld_library_path;
1962         char    *path = NULL;
1963
1964         if (ld_path != NULL) {  /* First, search the directories in ld_path */
1965                 char    *dir;
1966
1967                 while (path == NULL && (dir = strsep(&ld_path, ":")) != NULL) {
1968                         struct stat     sb;
1969
1970                         path = concat(dir, "/", name);
1971                         if (lstat(path, &sb) == -1) {   /* Does not exist */
1972                                 free(path);
1973                                 path = NULL;
1974                         }
1975                         if (ld_path != NULL)
1976                                 *(ld_path - 1) = ':';
1977                 }
1978         }
1979
1980         /*
1981          * We don't search the hints file.  It is organized around major
1982          * and minor version numbers, so it is not suitable for finding
1983          * a specific file name.
1984          */
1985
1986         if (path == NULL)       /* Search the standard directories */
1987                 path = find_lib_file(name);
1988
1989         return path;
1990 }
1991
1992 /*
1993  * Buffer for error messages and a pointer that is set to point to the buffer
1994  * when a error occurs.  It acts as a last error flag, being set to NULL
1995  * after an error is returned.
1996  */
1997 #define DLERROR_BUF_SIZE 512
1998 static char  dlerror_buf [DLERROR_BUF_SIZE];
1999 static char *dlerror_msg = NULL;
2000
2001
2002 static void *
2003 __dlopen(path, mode)
2004         const char      *path;
2005         int              mode;
2006 {
2007         struct so_map   *old_tail = link_map_tail;
2008         struct so_map   *smp;
2009         int             bind_now = mode == RTLD_NOW;
2010         char            *name;
2011
2012         /*
2013          * path == NULL is handled by map_object()
2014          */
2015
2016         anon_open();
2017
2018         name = (path && strchr(path, '/') == NULL) ? rtfindfile(path) : (char *)path;
2019
2020         /* Map the object, and the objects on which it depends */
2021         smp = map_object(name, (struct sod *) NULL, (struct so_map *) NULL);
2022         if (name != path)
2023                 free(name);
2024         if(smp == NULL)         /* Failed */
2025                 return NULL;
2026         LM_PRIVATE(smp)->spd_flags |= RTLD_DL;
2027
2028         /* Relocate and initialize all newly-mapped objects */
2029         if(link_map_tail != old_tail) {  /* We have mapped some new objects */
2030                 if(reloc_dag(smp, bind_now) == -1)      /* Failed */
2031                         return NULL;
2032                 init_dag(smp);
2033         }
2034
2035         unmaphints();
2036         anon_close();
2037
2038         return smp;
2039 }
2040
2041 static int
2042 __dlclose(fd)
2043         void    *fd;
2044 {
2045         struct so_map   *smp = (struct so_map *)fd;
2046         struct so_map   *scanp;
2047
2048 #ifdef DEBUG
2049         xprintf("dlclose(%s): refcount = %d\n", smp->som_path,
2050                 LM_PRIVATE(smp)->spd_refcount);
2051 #endif
2052         /* Check the argument for validity */
2053         for(scanp = link_map_head;  scanp != NULL;  scanp = scanp->som_next)
2054                 if(scanp == smp)        /* We found the map in the list */
2055                         break;
2056         if(scanp == NULL || !(LM_PRIVATE(smp)->spd_flags & RTLD_DL)) {
2057                 generror("Invalid argument to dlclose");
2058                 return -1;
2059         }
2060
2061         unmap_object(smp, 0);
2062
2063         return 0;
2064 }
2065
2066 /*
2067  * This form of dlsym is obsolete.  Current versions of crt0 don't call
2068  * it.  It can still be called by old executables that were linked with
2069  * old versions of crt0.
2070  */
2071 static void *
2072 __dlsym(fd, sym)
2073         void            *fd;
2074         const char      *sym;
2075 {
2076         if (fd == RTLD_NEXT) {
2077                 generror("RTLD_NEXT not supported by this version of"
2078                     " crt0.o");
2079                 return NULL;
2080         }
2081         return __dlsym3(fd, sym, NULL);
2082 }
2083
2084 static void *
2085 resolvesym(fd, sym, retaddr)
2086         void    *fd;
2087         char    *sym;
2088         void    *retaddr;
2089 {
2090         struct so_map   *smp;
2091         struct so_map   *src_map;
2092         struct nzlist   *np;
2093         long            addr;
2094
2095         if (fd == RTLD_NEXT) {
2096                 /* Find the shared object that contains the caller. */
2097                 for (smp = link_map_head;  smp != NULL;  smp = smp->som_next) {
2098                         void *textbase = smp->som_addr + LM_TXTADDR(smp);
2099                         void *textlimit = LM_ETEXT(smp);
2100
2101                         if (textbase <= retaddr && retaddr < textlimit)
2102                                 break;
2103                 }
2104                 if (smp == NULL) {
2105                         generror("Cannot determine caller's shared object");
2106                         return NULL;
2107                 }
2108                 smp = smp->som_next;
2109                 if (smp != NULL && LM_PRIVATE(smp)->spd_flags & RTLD_RTLD)
2110                         smp = smp->som_next;
2111                 if (smp == NULL) {
2112                         generror("No next shared object for RTLD_NEXT");
2113                         return NULL;
2114                 }
2115                 do {
2116                         src_map = smp;
2117                         np = lookup(sym, &src_map, 1);
2118                 } while (np == NULL && (smp = smp->som_next) != NULL);
2119         } else {
2120                 smp = (struct so_map *)fd;
2121                 src_map = NULL;
2122
2123                 /*
2124                  * Restrict search to passed map if dlopen()ed.
2125                  */
2126                 if (smp != NULL && LM_PRIVATE(smp)->spd_flags & RTLD_DL)
2127                         src_map = smp;
2128
2129                 np = lookup(sym, &src_map, 1);
2130         }
2131
2132         if (np == NULL) {
2133                 generror("Undefined symbol");
2134                 return NULL;
2135         }
2136
2137         addr = np->nz_value;
2138         if (src_map)
2139                 addr += (long)src_map->som_addr;
2140
2141         return (void *)addr;
2142 }
2143
2144 static int
2145 __dladdr(addr, dlip)
2146         const void      *addr;
2147         Dl_info         *dlip;
2148 {
2149         struct _dynamic *dp;
2150         struct so_map   *smp;
2151         char            *stringbase;
2152         long             numsyms;
2153         int              symsize;
2154         int              i;
2155
2156         /* Find the shared object that contains the address. */
2157         for (smp = link_map_head;  smp != NULL;  smp = smp->som_next) {
2158                 struct so_map           *src_map;
2159                 struct somap_private    *smpp;
2160                 struct nzlist           *np;
2161
2162                 smpp = LM_PRIVATE(smp);
2163                 if (smpp->spd_flags & RTLD_RTLD)
2164                         continue;
2165
2166                 if ((void *)smp->som_addr > addr)
2167                         continue;
2168
2169                 src_map = smp;
2170                 if ((np = lookup(END_SYM, &src_map, 1)) == NULL)
2171                         continue;       /* No "_end" symbol?! */
2172                 if (addr < (void *)(smp->som_addr + np->nz_value))
2173                         break;
2174         }
2175         if (smp == NULL) {
2176                 generror("No shared object contains address");
2177                 return 0;
2178         }
2179         dlip->dli_fname = smp->som_path;
2180         dlip->dli_fbase = smp->som_addr;
2181         dlip->dli_saddr = (void *) 0;
2182         dlip->dli_sname = NULL;
2183
2184         dp = smp->som_dynamic;
2185         symsize = LD_VERSION_NZLIST_P(dp->d_version) ?
2186             sizeof(struct nzlist) : sizeof(struct nlist);
2187         numsyms = LD_STABSZ(dp) / symsize;
2188         stringbase = LM_STRINGS(smp);
2189
2190         for (i = 0;  i < numsyms;  i++) {
2191                 struct nzlist   *symp = LM_SYMBOL(smp, i);
2192                 unsigned long    value;
2193
2194                 /* Reject all except definitions. */
2195                 if (symp->nz_type != N_EXT + N_ABS &&
2196                     symp->nz_type != N_EXT + N_TEXT &&
2197                     symp->nz_type != N_EXT + N_DATA &&
2198                     symp->nz_type != N_EXT + N_BSS)
2199                         continue;
2200
2201                 /*
2202                  * If the symbol is greater than the specified address, or
2203                  * if it is further away from addr than the current nearest
2204                  * symbol, then reject it.
2205                  */
2206                 value = (unsigned long) (smp->som_addr + symp->nz_value);
2207                 if (value > (unsigned long) addr ||
2208                     value < (unsigned long) dlip->dli_saddr)
2209                         continue;
2210
2211                 /* Update our idea of the nearest symbol. */
2212                 dlip->dli_sname = stringbase + symp->nz_strx;
2213                 dlip->dli_saddr = (void *) value;
2214
2215                 if (dlip->dli_saddr == addr)    /* Can't get any closer. */
2216                     break;
2217         }
2218         /*
2219          * Remove any leading underscore from the symbol name, to hide
2220          * our a.out-ness.
2221          */
2222         if (dlip->dli_sname != NULL && dlip->dli_sname[0] == '_')
2223                 dlip->dli_sname++;
2224         return 1;
2225 }
2226
2227 static void *
2228 __dlsym3(fd, sym, retaddr)
2229         void            *fd;
2230         const char      *sym;
2231         void            *retaddr;
2232 {
2233         void *result;
2234
2235         result = resolvesym(fd, sym, retaddr);
2236         /*
2237          * XXX - Ugly, but it makes the least impact on the run-time loader
2238          * sources.  We assume that most of the time the error is a
2239          * undefined symbol error from above, so we try again.  If it's
2240          * not an undefined symbol we end up getting the same error twice,
2241          * but that's acceptable.
2242          */
2243         if (result == NULL) {
2244                 /* Prepend an underscore and try again */
2245                 char *newsym = xmalloc(strlen(sym) + 2);
2246
2247                 newsym[0] = '_';
2248                 strcpy(&newsym[1], sym);
2249                 result = resolvesym(fd, newsym, retaddr);
2250                 free(newsym);
2251         }
2252         return result;
2253 }
2254
2255 static const char *
2256 __dlerror __P((void))
2257 {
2258         const char      *err;
2259
2260         err = dlerror_msg;
2261         dlerror_msg = NULL;  /* Next call will return NULL */
2262
2263         return err;
2264 }
2265
2266 static void
2267 __dlexit __P((void))
2268 {
2269 #ifdef DEBUG
2270 xprintf("__dlexit called\n");
2271 #endif
2272
2273         unmap_object(link_map_head, 1);
2274 }
2275
2276 /*
2277  * Print the current error message and exit with failure status.
2278  */
2279 static void
2280 die __P((void))
2281 {
2282         const char      *msg;
2283
2284         fprintf(stderr, "ld.so failed");
2285         if ((msg = __dlerror()) != NULL)
2286                 fprintf(stderr, ": %s", msg);
2287         putc('\n', stderr);
2288         _exit(1);
2289 }
2290
2291
2292 /*
2293  * Generate an error message that can be later be retrieved via dlerror.
2294  */
2295 static void
2296 #if __STDC__
2297 generror(char *fmt, ...)
2298 #else
2299 generror(fmt, va_alist)
2300 char    *fmt;
2301 #endif
2302 {
2303         va_list ap;
2304 #if __STDC__
2305         va_start(ap, fmt);
2306 #else
2307         va_start(ap);
2308 #endif
2309         vsnprintf (dlerror_buf, DLERROR_BUF_SIZE, fmt, ap);
2310         dlerror_msg = dlerror_buf;
2311
2312         va_end(ap);
2313 }
2314
2315 void
2316 #if __STDC__
2317 xprintf(char *fmt, ...)
2318 #else
2319 xprintf(fmt, va_alist)
2320 char    *fmt;
2321 #endif
2322 {
2323         char buf[256];
2324         va_list ap;
2325 #if __STDC__
2326         va_start(ap, fmt);
2327 #else
2328         va_start(ap);
2329 #endif
2330
2331         vsnprintf(buf, sizeof(buf), fmt, ap);
2332         (void)write(1, buf, strlen(buf));
2333         va_end(ap);
2334 }
2335
2336 /*
2337  * rt_readenv() etc.
2338  *
2339  * Do a sweep over the environment once only, pick up what
2340  * looks interesting.
2341  *
2342  * This is pretty obscure, but is relatively simple.  Simply
2343  * look at each environment variable, if it starts with "LD_" then
2344  * look closer at it.  If it's in our table, set the variable
2345  * listed.  effectively, this is like:
2346  *    ld_preload = careful ? NULL : getenv("LD_PRELOAD");
2347  * except that the environment is scanned once only to pick up all
2348  * known variables, rather than scanned multiple times for each
2349  * variable.
2350  *
2351  * If an environment variable of interest is set to the empty string, we
2352  * treat it as if it were unset.
2353  */
2354
2355 #define L(n, u, v) { n, sizeof(n) - 1, u, v },
2356 struct env_scan_tab {
2357         char    *name;
2358         int     len;
2359         int     unsafe;
2360         char    **value;
2361 } scan_tab[] = {
2362         L("LD_LIBRARY_PATH=",           1, &ld_library_path)
2363         L("LD_PRELOAD=",                1, &ld_preload)
2364         L("LD_IGNORE_MISSING_OBJECTS=", 1, &ld_ignore_missing_objects)
2365         L("LD_TRACE_LOADED_OBJECTS=",   0, &ld_tracing)
2366         L("LD_BIND_NOW=",               0, &ld_bind_now)
2367         L("LD_SUPPRESS_WARNINGS=",      0, &ld_suppress_warnings)
2368         L("LD_WARN_NON_PURE_CODE=",     0, &ld_warn_non_pure_code)
2369         { NULL, 0, 0, NULL }
2370 };
2371 #undef L
2372
2373 static void
2374 rt_readenv()
2375 {
2376         char **p = environ;
2377         char *v;
2378         struct env_scan_tab *t;
2379
2380         /* for each string in the environment... */
2381         while ((v = *p++)) {
2382
2383                 /* check for LD_xxx */
2384                 if (v[0] != 'L' || v[1] != 'D' || v[2] != '_')
2385                         continue;
2386
2387                 for (t = scan_tab; t->name; t++) {
2388                         if (careful && t->unsafe)
2389                                 continue;       /* skip for set[ug]id */
2390                         if (strncmp(t->name, v, t->len) == 0) {
2391                                 if (*(v + t->len) != '\0')      /* Not empty */
2392                                         *t->value = v + t->len;
2393                                 break;
2394                         }
2395                 }
2396         }
2397 }
2398
2399 /*
2400  * Malloc implementation for use within the dynamic linker.  At first
2401  * we do a simple allocation using sbrk.  After the user's program
2402  * has been loaded, we switch to using whatever malloc functions are
2403  * defined there.
2404  */
2405
2406 /* Symbols related to the sbrk and brk implementations. */
2407 #define CURBRK_SYM      "curbrk"
2408 #define MINBRK_SYM      "minbrk"
2409 #define END_SYM         "_end"
2410
2411 /* Symbols related to malloc. */
2412 #define FREE_SYM        "_free"
2413 #define MALLOC_SYM      "_malloc"
2414 #define REALLOC_SYM     "_realloc"
2415
2416 /* Hooks into the implementation of sbrk and brk. */
2417 extern char *curbrk __asm__(CURBRK_SYM);
2418 extern char *minbrk __asm__(MINBRK_SYM);
2419
2420 /* Pointers to the user program's malloc functions. */
2421 static void     *(*p_malloc) __P((size_t));
2422 static void     *(*p_realloc) __P((void *, size_t));
2423 static void      (*p_free) __P((void *));
2424
2425 /* Upper limit of the memory allocated by our internal malloc. */
2426 static char     *rtld_alloc_lev;
2427
2428 /*
2429  * Set up the internal malloc so that it will take its memory from the
2430  * main program's sbrk arena.
2431  */
2432 static void
2433 init_internal_malloc __P((void))
2434 {
2435         const struct exec *hdr;
2436
2437         /*
2438          * Before anything calls sbrk or brk, we have to initialize
2439          * its idea of the current break level to just beyond the main
2440          * program's address space.  Strictly speaking, the right
2441          * way to do that is to look up the value of "_end" in the
2442          * application's run time symbol table.
2443          *
2444          * That is what we used to do, and it works correctly for
2445          * every valid program.  Unfortunately, it doesn't work right
2446          * for "unexec"ed versions of emacs.  They are incorrectly
2447          * generated with a wrong value for "_end".  (xemacs gets it
2448          * right.)
2449          *
2450          * To work around this, we peek at the exec header to get the
2451          * sizes of the text, data, and bss segments.  Luckily, the
2452          * header is in memory at the start of the first mapped page.
2453          * From the segment sizes, we can calculate a proper initial
2454          * value for the break level.
2455          */
2456         hdr = (const struct exec *)PAGSIZ;
2457         if (N_BADMAG(*hdr))     /* Sanity check */
2458                 errx(1, "Cannot find program's a.out header");
2459         rtld_alloc_lev = curbrk = minbrk =
2460                 (char *)hdr + hdr->a_text + hdr->a_data + hdr->a_bss;
2461 }
2462
2463 /*
2464  * Set things up so that the dynamic linker can use the program's
2465  * malloc functions.
2466  */
2467 static void
2468 init_external_malloc __P((void))
2469 {
2470         /*
2471          * Patch the program's idea of the current break address to
2472          * what it really is as a result of the allocations we have
2473          * already done.
2474          */
2475         *(char **)(sym_addr(CURBRK_SYM)) = curbrk;
2476
2477         /*
2478          * Set the minimum break level too.  Otherwise, "unexec"ed
2479          * emacs sets the break too low and wipes out our tables of
2480          * shared objects.
2481          */
2482         *(char **)(sym_addr(MINBRK_SYM)) = curbrk;
2483
2484         /*
2485          * Set up pointers to the program's allocation functions, so
2486          * that we can use them from now on.
2487          */
2488         p_malloc = (void *(*)(size_t))(sym_addr(MALLOC_SYM));
2489         p_free = (void (*)(void *))(sym_addr(FREE_SYM));
2490         p_realloc = (void *(*)(void *, size_t))(sym_addr(REALLOC_SYM));
2491 }
2492
2493 void *
2494 malloc(size)
2495         size_t   size;
2496 {
2497         char            *p;
2498
2499         /* If we are far enough along, we can use the system malloc. */
2500         if (p_malloc != NULL)
2501                 return (*p_malloc)(size);
2502
2503         /*
2504          * Otherwise we use our simple built-in malloc.  We get the
2505          * memory from brk() in increments of one page.  We store the
2506          * allocated size in the first word, so that realloc can be
2507          * made to work.
2508          */
2509         if (rtld_alloc_lev == NULL)
2510                 errx(1, "Internal error: internal malloc called before"
2511                     " being initialized");
2512
2513         p = (char *)ALIGN(rtld_alloc_lev);
2514         rtld_alloc_lev = p + sizeof(size_t) + size;
2515
2516         if (rtld_alloc_lev > curbrk) {  /* Get memory from system */
2517                 char    *newbrk;
2518
2519                 newbrk = (char *)
2520                     roundup2((unsigned long)rtld_alloc_lev, PAGSIZ);
2521                 if (brk(newbrk) == -1)
2522                         return NULL;
2523         }
2524
2525         *(size_t *)p = size;
2526         return p + sizeof(size_t);
2527 }
2528
2529 void *
2530 realloc(ptr, size)
2531         void    *ptr;
2532         size_t   size;
2533 {
2534         size_t   old_size;
2535         void    *new_ptr;
2536
2537         if (ptr == NULL)
2538                 return malloc(size);
2539
2540         /*
2541          * If we are far enough along, and if the memory originally came
2542          * from the system malloc, we can use the system realloc.
2543          */
2544         if (p_realloc != NULL && (char *)ptr >= rtld_alloc_lev)
2545                 return (*p_realloc)(ptr, size);
2546
2547         old_size = *((size_t *)ptr - 1);
2548         if (old_size >= size)   /* Not expanding the region */
2549                 return ptr;
2550
2551         new_ptr = malloc(size);
2552         if (new_ptr != NULL)
2553                 memcpy(new_ptr, ptr, old_size);
2554         return new_ptr;
2555 }
2556
2557 void
2558 free(ptr)
2559         void    *ptr;
2560 {
2561         if (ptr == NULL)
2562                 return;
2563
2564         /*
2565          * If we are far enough along, and if the memory originally came
2566          * from the system malloc, we can use the system free.  Otherwise
2567          * we can't free the memory and we just let it go to waste.
2568          */
2569         if (p_free != NULL && (char *)ptr >= rtld_alloc_lev)
2570                 (*p_free)(ptr);
2571 }