-
Notifications
You must be signed in to change notification settings - Fork 117
/
rtld.c
5072 lines (4474 loc) · 135 KB
/
rtld.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*-
* Copyright 1996, 1997, 1998, 1999, 2000 John D. Polstra.
* Copyright 2003 Alexander Kabaev <kan@FreeBSD.ORG>.
* Copyright 2009-2012 Konstantin Belousov <kib@FreeBSD.ORG>.
* Copyright 2012 John Marino <draco@marino.st>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* $FreeBSD$
*/
/*
* Dynamic linker for ELF.
*
* John Polstra <jdp@polstra.com>.
*/
#ifndef __GNUC__
#error "GCC is needed to compile this file"
#endif
#include <sys/param.h>
#include <sys/mount.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <sys/sysctl.h>
#include <sys/utsname.h>
#include <sys/ktrace.h>
#include <sys/resident.h>
#include <sys/tls.h>
#include <machine/tls.h>
#include <dlfcn.h>
#include <err.h>
#include <errno.h>
#include <fcntl.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "debug.h"
#include "rtld.h"
#include "libmap.h"
#include "rtld_printf.h"
#include "notes.h"
#define PATH_RTLD "/usr/libexec/ld-elf.so.2"
#define LD_ARY_CACHE 16
/* Types. */
typedef void (*func_ptr_type)();
typedef void * (*path_enum_proc) (const char *path, size_t len, void *arg);
/*
* Function declarations.
*/
static int __getstatictlsextra(void);
static const char *_getenv_ld(const char *id);
static void die(void) __dead2;
static void digest_dynamic1(Obj_Entry *, int, const Elf_Dyn **,
const Elf_Dyn **, const Elf_Dyn **);
static void digest_dynamic2(Obj_Entry *, const Elf_Dyn *, const Elf_Dyn *,
const Elf_Dyn *);
static void digest_dynamic(Obj_Entry *, int);
static Obj_Entry *digest_phdr(const Elf_Phdr *, int, caddr_t, const char *);
static void distribute_static_tls(Objlist *, RtldLockState *);
static Obj_Entry *dlcheck(void *);
static Obj_Entry *dlopen_object(const char *name, int fd, Obj_Entry *refobj,
int lo_flags, int mode, RtldLockState *lockstate);
static Obj_Entry *do_load_object(int, const char *, char *, struct stat *, int);
static int do_search_info(const Obj_Entry *obj, int, struct dl_serinfo *);
static bool donelist_check(DoneList *, const Obj_Entry *);
static void errmsg_restore(char *);
static char *errmsg_save(void);
static void *fill_search_info(const char *, size_t, void *);
static char *find_library(const char *, const Obj_Entry *, int *);
static const char *gethints(bool);
static void init_dag(Obj_Entry *);
static void init_rtld(caddr_t, Elf_Auxinfo **);
static void initlist_add_neededs(Needed_Entry *, Objlist *);
static void initlist_add_objects(Obj_Entry *, Obj_Entry **, Objlist *);
static void linkmap_add(Obj_Entry *);
static void linkmap_delete(Obj_Entry *);
static void load_filtees(Obj_Entry *, int flags, RtldLockState *);
static void unload_filtees(Obj_Entry *);
static int load_needed_objects(Obj_Entry *, int);
static int load_preload_objects(void);
static Obj_Entry *load_object(const char *, int fd, const Obj_Entry *, int);
static void map_stacks_exec(RtldLockState *);
static Obj_Entry *obj_from_addr(const void *);
static void objlist_call_fini(Objlist *, Obj_Entry *, RtldLockState *);
static void objlist_call_init(Objlist *, RtldLockState *);
static void objlist_clear(Objlist *);
static Objlist_Entry *objlist_find(Objlist *, const Obj_Entry *);
static void objlist_init(Objlist *);
static void objlist_push_head(Objlist *, Obj_Entry *);
static void objlist_push_tail(Objlist *, Obj_Entry *);
static void objlist_put_after(Objlist *, Obj_Entry *, Obj_Entry *);
static void objlist_remove(Objlist *, Obj_Entry *);
static int parse_libdir(const char *);
static void *path_enumerate(const char *, path_enum_proc, void *);
static int relocate_object_dag(Obj_Entry *root, bool bind_now,
Obj_Entry *rtldobj, int flags, RtldLockState *lockstate);
static int relocate_object(Obj_Entry *obj, bool bind_now, Obj_Entry *rtldobj,
int flags, RtldLockState *lockstate);
static int relocate_objects(Obj_Entry *, bool, Obj_Entry *, int,
RtldLockState *);
static int resolve_objects_ifunc(Obj_Entry *first, bool bind_now,
int flags, RtldLockState *lockstate);
static int rtld_dirname(const char *, char *);
static int rtld_dirname_abs(const char *, char *);
static void *rtld_dlopen(const char *name, int fd, int mode);
static void rtld_exit(void);
static char *search_library_path(const char *, const char *);
static char *search_library_pathfds(const char *, const char *, int *);
static const void **get_program_var_addr(const char *, RtldLockState *);
static void set_program_var(const char *, const void *);
static int symlook_default(SymLook *, const Obj_Entry *refobj);
static int symlook_global(SymLook *, DoneList *);
static void symlook_init_from_req(SymLook *, const SymLook *);
static int symlook_list(SymLook *, const Objlist *, DoneList *);
static int symlook_needed(SymLook *, const Needed_Entry *, DoneList *);
static int symlook_obj1_sysv(SymLook *, const Obj_Entry *);
static int symlook_obj1_gnu(SymLook *, const Obj_Entry *);
static void trace_loaded_objects(Obj_Entry *);
static void unlink_object(Obj_Entry *);
static void unload_object(Obj_Entry *);
static void unref_dag(Obj_Entry *);
static void ref_dag(Obj_Entry *);
static char *origin_subst_one(char *, const char *, const char *, bool);
static char *origin_subst(char *, const char *);
static void preinit_main(void);
static int rtld_verify_versions(const Objlist *);
static int rtld_verify_object_versions(Obj_Entry *);
static void object_add_name(Obj_Entry *, const char *);
static int object_match_name(const Obj_Entry *, const char *);
static void ld_utrace_log(int, void *, void *, size_t, int, const char *);
static void rtld_fill_dl_phdr_info(const Obj_Entry *obj,
struct dl_phdr_info *phdr_info);
static uint_fast32_t gnu_hash (const char *);
static bool matched_symbol(SymLook *, const Obj_Entry *, Sym_Match_Result *,
const unsigned long);
void r_debug_state(struct r_debug *, struct link_map *) __noinline;
void _r_debug_postinit(struct link_map *) __noinline;
/*
* Data declarations.
*/
static char *error_message; /* Message for dlerror(), or NULL */
struct r_debug r_debug; /* for GDB; */
static bool libmap_disable; /* Disable libmap */
static bool ld_loadfltr; /* Immediate filters processing */
static char *libmap_override; /* Maps to use in addition to libmap.conf */
static bool trust; /* False for setuid and setgid programs */
static bool dangerous_ld_env; /* True if environment variables have been
used to affect the libraries loaded */
static const char *ld_bind_now; /* Environment variable for immediate binding */
static const char *ld_debug; /* Environment variable for debugging */
static const char *ld_library_path; /* Environment variable for search path */
static const char *ld_library_dirs; /* Env variable for library descriptors */
static char *ld_preload; /* Environment variable for libraries to
load first */
static const char *ld_elf_hints_path; /* Env var. for alternative hints path */
static const char *ld_tracing; /* Called from ldd to print libs */
static const char *ld_utrace; /* Use utrace() to log events. */
static int (*rtld_functrace)( /* Optional function call tracing hook */
const char *caller_obj,
const char *callee_obj,
const char *callee_func,
void *stack);
static const Obj_Entry *rtld_functrace_obj; /* Object thereof */
static Obj_Entry *obj_list; /* Head of linked list of shared objects */
static Obj_Entry **obj_tail; /* Link field of last object in list */
static Obj_Entry **preload_tail;
static Obj_Entry *obj_main; /* The main program shared object */
static Obj_Entry obj_rtld; /* The dynamic linker shared object */
static unsigned int obj_count; /* Number of objects in obj_list */
static unsigned int obj_loads; /* Number of objects in obj_list */
static int ld_resident; /* Non-zero if resident */
static const char *ld_ary[LD_ARY_CACHE];
static int ld_index;
static Objlist initlist;
static Objlist list_global = /* Objects dlopened with RTLD_GLOBAL */
STAILQ_HEAD_INITIALIZER(list_global);
static Objlist list_main = /* Objects loaded at program startup */
STAILQ_HEAD_INITIALIZER(list_main);
static Objlist list_fini = /* Objects needing fini() calls */
STAILQ_HEAD_INITIALIZER(list_fini);
static Elf_Sym sym_zero; /* For resolving undefined weak refs. */
const char *__ld_sharedlib_base;
#define GDB_STATE(s,m) r_debug.r_state = s; r_debug_state(&r_debug,m);
extern Elf_Dyn _DYNAMIC;
#pragma weak _DYNAMIC
#ifndef RTLD_IS_DYNAMIC
#define RTLD_IS_DYNAMIC() (&_DYNAMIC != NULL)
#endif
#ifdef ENABLE_OSRELDATE
int osreldate;
#endif
static int stack_prot = PROT_READ | PROT_WRITE | RTLD_DEFAULT_STACK_EXEC;
#if 0
static int max_stack_flags;
#endif
/*
* Global declarations normally provided by crt1. The dynamic linker is
* not built with crt1, so we have to provide them ourselves.
*/
char *__progname;
char **environ;
/*
* Used to pass argc, argv to init functions.
*/
int main_argc;
char **main_argv;
/*
* Globals to control TLS allocation.
*/
size_t tls_last_offset; /* Static TLS offset of last module */
size_t tls_last_size; /* Static TLS size of last module */
size_t tls_static_space; /* Static TLS space allocated */
int tls_dtv_generation = 1; /* Used to detect when dtv size changes */
int tls_max_index = 1; /* Largest module index allocated */
/*
* Fill in a DoneList with an allocation large enough to hold all of
* the currently-loaded objects. Keep this as a macro since it calls
* alloca and we want that to occur within the scope of the caller.
*/
#define donelist_init(dlp) \
((dlp)->objs = alloca(obj_count * sizeof (dlp)->objs[0]), \
assert((dlp)->objs != NULL), \
(dlp)->num_alloc = obj_count, \
(dlp)->num_used = 0)
#define UTRACE_DLOPEN_START 1
#define UTRACE_DLOPEN_STOP 2
#define UTRACE_DLCLOSE_START 3
#define UTRACE_DLCLOSE_STOP 4
#define UTRACE_LOAD_OBJECT 5
#define UTRACE_UNLOAD_OBJECT 6
#define UTRACE_ADD_RUNDEP 7
#define UTRACE_PRELOAD_FINISHED 8
#define UTRACE_INIT_CALL 9
#define UTRACE_FINI_CALL 10
struct utrace_rtld {
char sig[4]; /* 'RTLD' */
int event;
void *handle;
void *mapbase; /* Used for 'parent' and 'init/fini' */
size_t mapsize;
int refcnt; /* Used for 'mode' */
char name[MAXPATHLEN];
};
#define LD_UTRACE(e, h, mb, ms, r, n) do { \
if (ld_utrace != NULL) \
ld_utrace_log(e, h, mb, ms, r, n); \
} while (0)
static void
ld_utrace_log(int event, void *handle, void *mapbase, size_t mapsize,
int refcnt, const char *name)
{
struct utrace_rtld ut;
ut.sig[0] = 'R';
ut.sig[1] = 'T';
ut.sig[2] = 'L';
ut.sig[3] = 'D';
ut.event = event;
ut.handle = handle;
ut.mapbase = mapbase;
ut.mapsize = mapsize;
ut.refcnt = refcnt;
bzero(ut.name, sizeof(ut.name));
if (name)
strlcpy(ut.name, name, sizeof(ut.name));
utrace(&ut, sizeof(ut));
}
/*
* Main entry point for dynamic linking. The first argument is the
* stack pointer. The stack is expected to be laid out as described
* in the SVR4 ABI specification, Intel 386 Processor Supplement.
* Specifically, the stack pointer points to a word containing
* ARGC. Following that in the stack is a null-terminated sequence
* of pointers to argument strings. Then comes a null-terminated
* sequence of pointers to environment strings. Finally, there is a
* sequence of "auxiliary vector" entries.
*
* The second argument points to a place to store the dynamic linker's
* exit procedure pointer and the third to a place to store the main
* program's object.
*
* The return value is the main program's entry point.
*/
func_ptr_type
_rtld(Elf_Addr *sp, func_ptr_type *exit_proc, Obj_Entry **objp)
{
Elf_Auxinfo *aux_info[AT_COUNT];
int i;
int argc;
char **argv;
char **env;
Elf_Auxinfo *aux;
Elf_Auxinfo *auxp;
const char *argv0;
Objlist_Entry *entry;
Obj_Entry *obj;
Obj_Entry *last_interposer;
/* marino: DO NOT MOVE THESE VARIABLES TO _rtld
Obj_Entry **preload_tail;
Objlist initlist;
from global to here. It will break the DWARF2 unwind scheme.
*/
/*
* On entry, the dynamic linker itself has not been relocated yet.
* Be very careful not to reference any global data until after
* init_rtld has returned. It is OK to reference file-scope statics
* and string constants, and to call static and global functions.
*/
/* Find the auxiliary vector on the stack. */
argc = *sp++;
argv = (char **) sp;
sp += argc + 1; /* Skip over arguments and NULL terminator */
env = (char **) sp;
/*
* If we aren't already resident we have to dig out some more info.
* Note that auxinfo does not exist when we are resident.
*
* I'm not sure about the ld_resident check. It seems to read zero
* prior to relocation, which is what we want. When running from a
* resident copy everything will be relocated so we are definitely
* good there.
*/
if (ld_resident == 0) {
while (*sp++ != 0) /* Skip over environment, and NULL terminator */
;
aux = (Elf_Auxinfo *) sp;
/* Digest the auxiliary vector. */
for (i = 0; i < AT_COUNT; i++)
aux_info[i] = NULL;
for (auxp = aux; auxp->a_type != AT_NULL; auxp++) {
if (auxp->a_type < AT_COUNT)
aux_info[auxp->a_type] = auxp;
}
/* Initialize and relocate ourselves. */
assert(aux_info[AT_BASE] != NULL);
init_rtld((caddr_t) aux_info[AT_BASE]->a_un.a_ptr, aux_info);
}
ld_index = 0; /* don't use old env cache in case we are resident */
__progname = obj_rtld.path;
argv0 = argv[0] != NULL ? argv[0] : "(null)";
environ = env;
main_argc = argc;
main_argv = argv;
trust = !issetugid();
ld_bind_now = _getenv_ld("LD_BIND_NOW");
/*
* If the process is tainted, then we un-set the dangerous environment
* variables. The process will be marked as tainted until setuid(2)
* is called. If any child process calls setuid(2) we do not want any
* future processes to honor the potentially un-safe variables.
*/
if (!trust) {
if ( unsetenv("LD_DEBUG")
|| unsetenv("LD_PRELOAD")
|| unsetenv("LD_LIBRARY_PATH")
|| unsetenv("LD_LIBRARY_PATH_FDS")
|| unsetenv("LD_ELF_HINTS_PATH")
|| unsetenv("LD_LIBMAP")
|| unsetenv("LD_LIBMAP_DISABLE")
|| unsetenv("LD_LOADFLTR")
|| unsetenv("LD_SHAREDLIB_BASE")
) {
_rtld_error("environment corrupt; aborting");
die();
}
}
__ld_sharedlib_base = _getenv_ld("LD_SHAREDLIB_BASE");
ld_debug = _getenv_ld("LD_DEBUG");
libmap_disable = _getenv_ld("LD_LIBMAP_DISABLE") != NULL;
libmap_override = (char *)_getenv_ld("LD_LIBMAP");
ld_library_path = _getenv_ld("LD_LIBRARY_PATH");
ld_library_dirs = _getenv_ld("LD_LIBRARY_PATH_FDS");
ld_preload = (char *)_getenv_ld("LD_PRELOAD");
ld_elf_hints_path = _getenv_ld("LD_ELF_HINTS_PATH");
ld_loadfltr = _getenv_ld("LD_LOADFLTR") != NULL;
dangerous_ld_env = (ld_library_path != NULL)
|| (ld_preload != NULL)
|| (ld_elf_hints_path != NULL)
|| ld_loadfltr
|| (libmap_override != NULL)
|| libmap_disable
;
ld_tracing = _getenv_ld("LD_TRACE_LOADED_OBJECTS");
ld_utrace = _getenv_ld("LD_UTRACE");
if ((ld_elf_hints_path == NULL) || strlen(ld_elf_hints_path) == 0)
ld_elf_hints_path = _PATH_ELF_HINTS;
if (ld_debug != NULL && *ld_debug != '\0')
debug = 1;
dbg("%s is initialized, base address = %p", __progname,
(caddr_t) aux_info[AT_BASE]->a_un.a_ptr);
dbg("RTLD dynamic = %p", obj_rtld.dynamic);
dbg("RTLD pltgot = %p", obj_rtld.pltgot);
dbg("initializing thread locks");
lockdflt_init();
/*
* If we are resident we can skip work that we have already done.
* Note that the stack is reset and there is no Elf_Auxinfo
* when running from a resident image, and the static globals setup
* between here and resident_skip will have already been setup.
*/
if (ld_resident)
goto resident_skip1;
/*
* Load the main program, or process its program header if it is
* already loaded.
*/
if (aux_info[AT_EXECFD] != NULL) { /* Load the main program. */
int fd = aux_info[AT_EXECFD]->a_un.a_val;
dbg("loading main program");
obj_main = map_object(fd, argv0, NULL);
close(fd);
if (obj_main == NULL)
die();
#if 0
max_stack_flags = obj_main->stack_flags;
#endif
} else { /* Main program already loaded. */
const Elf_Phdr *phdr;
int phnum;
caddr_t entry;
dbg("processing main program's program header");
assert(aux_info[AT_PHDR] != NULL);
phdr = (const Elf_Phdr *) aux_info[AT_PHDR]->a_un.a_ptr;
assert(aux_info[AT_PHNUM] != NULL);
phnum = aux_info[AT_PHNUM]->a_un.a_val;
assert(aux_info[AT_PHENT] != NULL);
assert(aux_info[AT_PHENT]->a_un.a_val == sizeof(Elf_Phdr));
assert(aux_info[AT_ENTRY] != NULL);
entry = (caddr_t) aux_info[AT_ENTRY]->a_un.a_ptr;
if ((obj_main = digest_phdr(phdr, phnum, entry, argv0)) == NULL)
die();
}
char buf[MAXPATHLEN];
if (aux_info[AT_EXECPATH] != NULL) {
char *kexecpath;
kexecpath = aux_info[AT_EXECPATH]->a_un.a_ptr;
dbg("AT_EXECPATH %p %s", kexecpath, kexecpath);
if (kexecpath[0] == '/')
obj_main->path = kexecpath;
else if (getcwd(buf, sizeof(buf)) == NULL ||
strlcat(buf, "/", sizeof(buf)) >= sizeof(buf) ||
strlcat(buf, kexecpath, sizeof(buf)) >= sizeof(buf))
obj_main->path = xstrdup(argv0);
else
obj_main->path = xstrdup(buf);
} else {
char resolved[MAXPATHLEN];
dbg("No AT_EXECPATH");
if (argv0[0] == '/') {
if (realpath(argv0, resolved) != NULL)
obj_main->path = xstrdup(resolved);
else
obj_main->path = xstrdup(argv0);
} else {
if (getcwd(buf, sizeof(buf)) != NULL
&& strlcat(buf, "/", sizeof(buf)) < sizeof(buf)
&& strlcat(buf, argv0, sizeof (buf)) < sizeof(buf)
&& access(buf, R_OK) == 0
&& realpath(buf, resolved) != NULL)
obj_main->path = xstrdup(resolved);
else
obj_main->path = xstrdup(argv0);
}
}
dbg("obj_main path %s", obj_main->path);
obj_main->mainprog = true;
if (aux_info[AT_STACKPROT] != NULL &&
aux_info[AT_STACKPROT]->a_un.a_val != 0)
stack_prot = aux_info[AT_STACKPROT]->a_un.a_val;
/*
* Get the actual dynamic linker pathname from the executable if
* possible. (It should always be possible.) That ensures that
* gdb will find the right dynamic linker even if a non-standard
* one is being used.
*/
if (obj_main->interp != NULL &&
strcmp(obj_main->interp, obj_rtld.path) != 0) {
free(obj_rtld.path);
obj_rtld.path = xstrdup(obj_main->interp);
__progname = obj_rtld.path;
}
digest_dynamic(obj_main, 0);
dbg("%s valid_hash_sysv %d valid_hash_gnu %d dynsymcount %d",
obj_main->path, obj_main->valid_hash_sysv, obj_main->valid_hash_gnu,
obj_main->dynsymcount);
linkmap_add(obj_main);
linkmap_add(&obj_rtld);
/* Link the main program into the list of objects. */
*obj_tail = obj_main;
obj_tail = &obj_main->next;
obj_count++;
obj_loads++;
/* Initialize a fake symbol for resolving undefined weak references. */
sym_zero.st_info = ELF_ST_INFO(STB_GLOBAL, STT_NOTYPE);
sym_zero.st_shndx = SHN_UNDEF;
sym_zero.st_value = -(uintptr_t)obj_main->relocbase;
if (!libmap_disable)
libmap_disable = (bool)lm_init(libmap_override);
dbg("loading LD_PRELOAD libraries");
if (load_preload_objects() == -1)
die();
preload_tail = obj_tail;
dbg("loading needed objects");
if (load_needed_objects(obj_main, 0) == -1)
die();
/* Make a list of all objects loaded at startup. */
last_interposer = obj_main;
for (obj = obj_list; obj != NULL; obj = obj->next) {
if (obj->z_interpose && obj != obj_main) {
objlist_put_after(&list_main, last_interposer, obj);
last_interposer = obj;
} else {
objlist_push_tail(&list_main, obj);
}
obj->refcount++;
}
dbg("checking for required versions");
if (rtld_verify_versions(&list_main) == -1 && !ld_tracing)
die();
resident_skip1:
if (ld_tracing) { /* We're done */
trace_loaded_objects(obj_main);
exit(0);
}
if (ld_resident) /* XXX clean this up! */
goto resident_skip2;
if (_getenv_ld("LD_DUMP_REL_PRE") != NULL) {
dump_relocations(obj_main);
exit (0);
}
/* setup TLS for main thread */
dbg("initializing initial thread local storage");
STAILQ_FOREACH(entry, &list_main, link) {
/*
* Allocate all the initial objects out of the static TLS
* block even if they didn't ask for it.
*/
allocate_tls_offset(entry->obj);
}
/*
* Calculate the size of the TLS static segment. This is allocated
* for every thread. Generally make it page-aligned for efficiency,
* but take into account the fact that the actual allocation also
* includes room for the struct tls_tcb header.
*/
{
ssize_t space;
ssize_t extra;
extra = __getstatictlsextra();
space = tls_last_offset + extra + sizeof(struct tls_tcb);
space = (space + PAGE_SIZE - 1) & ~((ssize_t)PAGE_SIZE - 1);
tls_static_space = (size_t)space - sizeof(struct tls_tcb);
}
/*
* Do not try to allocate the TLS here, let libc do it itself.
* (crt1 for the program will call _init_tls())
*/
if (relocate_objects(obj_main,
ld_bind_now != NULL && *ld_bind_now != '\0',
&obj_rtld, SYMLOOK_EARLY, NULL) == -1)
die();
dbg("doing copy relocations");
if (do_copy_relocations(obj_main) == -1)
die();
resident_skip2:
if (_getenv_ld("LD_RESIDENT_UNREGISTER_NOW")) {
if (exec_sys_unregister(-1) < 0) {
dbg("exec_sys_unregister failed %d\n", errno);
exit(errno);
}
dbg("exec_sys_unregister success\n");
exit(0);
}
if (_getenv_ld("LD_DUMP_REL_POST") != NULL) {
dump_relocations(obj_main);
exit (0);
}
dbg("initializing key program variables");
set_program_var("__progname", argv[0] != NULL ? basename(argv[0]) : "");
set_program_var("environ", env);
set_program_var("__elf_aux_vector", aux);
if (_getenv_ld("LD_RESIDENT_REGISTER_NOW")) {
extern void resident_start(void);
ld_resident = 1;
if (exec_sys_register(resident_start) < 0) {
dbg("exec_sys_register failed %d\n", errno);
exit(errno);
}
dbg("exec_sys_register success\n");
exit(0);
}
/* Make a list of init functions to call. */
objlist_init(&initlist);
initlist_add_objects(obj_list, preload_tail, &initlist);
r_debug_state(NULL, &obj_main->linkmap); /* say hello to gdb! */
map_stacks_exec(NULL);
dbg("resolving ifuncs");
{
RtldLockState lockstate;
wlock_acquire(rtld_bind_lock, &lockstate);
if (resolve_objects_ifunc(
obj_main,
(ld_bind_now != NULL && *ld_bind_now != '\0'),
SYMLOOK_EARLY,
&lockstate) == -1) {
die();
}
lock_release(rtld_bind_lock, &lockstate);
}
/*
* Do NOT call the initlist here, give libc a chance to set up
* the initial TLS segment. crt1 will then call _rtld_call_init().
*/
dbg("transferring control to program entry point = %p", obj_main->entry);
/* Return the exit procedure and the program entry point. */
*exit_proc = rtld_exit;
*objp = obj_main;
return (func_ptr_type) obj_main->entry;
}
/*
* Call the initialization list for dynamically loaded libraries.
* (called from crt1.c).
*/
void
_rtld_call_init(void)
{
RtldLockState lockstate;
Obj_Entry *obj;
if (!obj_main->note_present && obj_main->valid_hash_gnu) {
/*
* The use of a linker script with a PHDRS directive that does not include
* PT_NOTE will block the crt_no_init note. In this case we'll look for the
* recently added GNU hash dynamic tag which gets built by default. It is
* extremely unlikely to find a pre-3.1 binary without a PT_NOTE header and
* a gnu hash tag. If gnu hash found, consider binary to use new crt code.
*/
obj_main->crt_no_init = true;
dbg("Setting crt_no_init without presence of PT_NOTE header");
}
wlock_acquire(rtld_bind_lock, &lockstate);
if (obj_main->crt_no_init)
preinit_main();
else {
/*
* Make sure we don't call the main program's init and fini functions
* for binaries linked with old crt1 which calls _init itself.
*/
obj_main->init = obj_main->fini = (Elf_Addr)NULL;
obj_main->init_array = obj_main->fini_array = (Elf_Addr)NULL;
}
objlist_call_init(&initlist, &lockstate);
_r_debug_postinit(&obj_main->linkmap);
objlist_clear(&initlist);
dbg("loading filtees");
for (obj = obj_list->next; obj != NULL; obj = obj->next) {
if (ld_loadfltr || obj->z_loadfltr)
load_filtees(obj, 0, &lockstate);
}
lock_release(rtld_bind_lock, &lockstate);
}
void *
rtld_resolve_ifunc(const Obj_Entry *obj, const Elf_Sym *def)
{
void *ptr;
Elf_Addr target;
ptr = (void *)make_function_pointer(def, obj);
target = ((Elf_Addr (*)(void))ptr)();
return ((void *)target);
}
Elf_Addr
_rtld_bind(Obj_Entry *obj, Elf_Size reloff, void *stack)
{
const Elf_Rel *rel;
const Elf_Sym *def;
const Obj_Entry *defobj;
Elf_Addr *where;
Elf_Addr target;
RtldLockState lockstate;
rlock_acquire(rtld_bind_lock, &lockstate);
if (sigsetjmp(lockstate.env, 0) != 0)
lock_upgrade(rtld_bind_lock, &lockstate);
if (obj->pltrel)
rel = (const Elf_Rel *) ((caddr_t) obj->pltrel + reloff);
else
rel = (const Elf_Rel *) ((caddr_t) obj->pltrela + reloff);
where = (Elf_Addr *) (obj->relocbase + rel->r_offset);
def = find_symdef(ELF_R_SYM(rel->r_info), obj, &defobj, true, NULL,
&lockstate);
if (def == NULL)
die();
if (ELF_ST_TYPE(def->st_info) == STT_GNU_IFUNC)
target = (Elf_Addr)rtld_resolve_ifunc(defobj, def);
else
target = (Elf_Addr)(defobj->relocbase + def->st_value);
dbg("\"%s\" in \"%s\" ==> %p in \"%s\"",
defobj->strtab + def->st_name, basename(obj->path),
(void *)target, basename(defobj->path));
/*
* If we have a function call tracing hook, and the
* hook would like to keep tracing this one function,
* prevent the relocation so we will wind up here
* the next time again.
*
* We don't want to functrace calls from the functracer
* to avoid recursive loops.
*/
if (rtld_functrace != NULL && obj != rtld_functrace_obj) {
if (rtld_functrace(obj->path,
defobj->path,
defobj->strtab + def->st_name,
stack)) {
lock_release(rtld_bind_lock, &lockstate);
return target;
}
}
/*
* Write the new contents for the jmpslot. Note that depending on
* architecture, the value which we need to return back to the
* lazy binding trampoline may or may not be the target
* address. The value returned from reloc_jmpslot() is the value
* that the trampoline needs.
*/
target = reloc_jmpslot(where, target, defobj, obj, rel);
lock_release(rtld_bind_lock, &lockstate);
return target;
}
/*
* Error reporting function. Use it like printf. If formats the message
* into a buffer, and sets things up so that the next call to dlerror()
* will return the message.
*/
void
_rtld_error(const char *fmt, ...)
{
static char buf[512];
va_list ap;
va_start(ap, fmt);
rtld_vsnprintf(buf, sizeof buf, fmt, ap);
error_message = buf;
va_end(ap);
}
/*
* Return a dynamically-allocated copy of the current error message, if any.
*/
static char *
errmsg_save(void)
{
return error_message == NULL ? NULL : xstrdup(error_message);
}
/*
* Restore the current error message from a copy which was previously saved
* by errmsg_save(). The copy is freed.
*/
static void
errmsg_restore(char *saved_msg)
{
if (saved_msg == NULL)
error_message = NULL;
else {
_rtld_error("%s", saved_msg);
free(saved_msg);
}
}
const char *
basename(const char *name)
{
const char *p = strrchr(name, '/');
return p != NULL ? p + 1 : name;
}
static struct utsname uts;
static char *
origin_subst_one(char *real, const char *kw, const char *subst,
bool may_free)
{
char *p, *p1, *res, *resp;
int subst_len, kw_len, subst_count, old_len, new_len;
kw_len = strlen(kw);
/*
* First, count the number of the keyword occurrences, to
* preallocate the final string.
*/
for (p = real, subst_count = 0;; p = p1 + kw_len, subst_count++) {
p1 = strstr(p, kw);
if (p1 == NULL)
break;
}
/*
* If the keyword is not found, just return.
*/
if (subst_count == 0)
return (may_free ? real : xstrdup(real));
/*
* There is indeed something to substitute. Calculate the
* length of the resulting string, and allocate it.
*/
subst_len = strlen(subst);
old_len = strlen(real);
new_len = old_len + (subst_len - kw_len) * subst_count;
res = xmalloc(new_len + 1);
/*
* Now, execute the substitution loop.
*/
for (p = real, resp = res, *resp = '\0';;) {
p1 = strstr(p, kw);
if (p1 != NULL) {
/* Copy the prefix before keyword. */
memcpy(resp, p, p1 - p);
resp += p1 - p;
/* Keyword replacement. */
memcpy(resp, subst, subst_len);
resp += subst_len;
*resp = '\0';
p = p1 + kw_len;
} else
break;
}
/* Copy to the end of string and finish. */
strcat(resp, p);
if (may_free)
free(real);
return (res);
}
static char *
origin_subst(char *real, const char *origin_path)
{
char *res1, *res2, *res3, *res4;
if (uts.sysname[0] == '\0') {
if (uname(&uts) != 0) {
_rtld_error("utsname failed: %d", errno);
return (NULL);
}
}
res1 = origin_subst_one(real, "$ORIGIN", origin_path, false);
res2 = origin_subst_one(res1, "$OSNAME", uts.sysname, true);
res3 = origin_subst_one(res2, "$OSREL", uts.release, true);
res4 = origin_subst_one(res3, "$PLATFORM", uts.machine, true);
return (res4);
}
static void
die(void)
{
const char *msg = dlerror();
if (msg == NULL)
msg = "Fatal error";
rtld_fdputstr(STDERR_FILENO, msg);
rtld_fdputchar(STDERR_FILENO, '\n');
_exit(1);
}
/*
* Process a shared object's DYNAMIC section, and save the important
* information in its Obj_Entry structure.
*/
static void
digest_dynamic1(Obj_Entry *obj, int early, const Elf_Dyn **dyn_rpath,
const Elf_Dyn **dyn_soname, const Elf_Dyn **dyn_runpath)
{
const Elf_Dyn *dynp;
Needed_Entry **needed_tail = &obj->needed;
Needed_Entry **needed_filtees_tail = &obj->needed_filtees;
Needed_Entry **needed_aux_filtees_tail = &obj->needed_aux_filtees;
const Elf_Hashelt *hashtab;
const Elf32_Word *hashval;
Elf32_Word bkt, nmaskwords;
int bloom_size32;
bool nmw_power2;
int plttype = DT_REL;
*dyn_rpath = NULL;
*dyn_soname = NULL;
*dyn_runpath = NULL;
obj->bind_now = false;