forked from bminor/binutils-gdb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmmaptrace.c
1666 lines (1536 loc) · 53.5 KB
/
mmaptrace.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 (C) 2021-2025 Free Software Foundation, Inc.
Contributed by Oracle.
This file is part of GNU Binutils.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3, or (at your option)
any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, 51 Franklin Street - Fifth Floor, Boston,
MA 02110-1301, USA. */
/*
* memory map tracking
* incorporating former "loadobjects" into more general "map"
* (including code and data segments and dynamic functions)
*/
#include "config.h"
#include <alloca.h>
#include <dlfcn.h>
#include <errno.h>
#include <fcntl.h>
#include <elf.h>
#include <sys/mman.h>
#include <sys/param.h>
#include <stdint.h>
#include "gp-defs.h"
#include "collector.h"
#include "gp-experiment.h"
#include "memmgr.h"
/*
* These are obsolete and unreliable.
* They are included here only for historical compatibility.
*/
#define MA_SHARED 0x08 /* changes are shared by mapped object */
#define MA_ANON 0x40 /* anonymous memory (e.g. /dev/zero) */
#define MA_ISM 0x80 /* intimate shared mem (shared MMU resources) */
#define MA_BREAK 0x10 /* grown by brk(2) */
#define MA_STACK 0x20 /* grown automatically on stack faults */
typedef struct prmap_t
{
unsigned long pr_vaddr; /* virtual address of mapping */
unsigned long pr_size; /* size of mapping in bytes */
char *pr_mapname; /* name in /proc/<pid>/object */
int pr_mflags; /* protection and attribute flags (see below) */
unsigned long pr_offset; /* offset into mapped object, if any */
unsigned long pr_dev;
unsigned long pr_ino;
int pr_pagesize; /* pagesize (bytes) for this mapping */
} prmap_t;
typedef struct MapInfo
{
struct MapInfo *next;
unsigned long vaddr;
unsigned long size;
char *mapname; /* name in /proc/<pid>/object */
char *filename;
unsigned long offset;
int mflags;
int pagesize;
} MapInfo;
typedef struct NameInfo
{
struct NameInfo *next;
char *mapname;
char filename[1]; /* dynamic length file name */
} NameInfo;
static NameInfo *namemaps = NULL;
static MapInfo mmaps; /* current memory maps */
static struct DataHandle *map_hndl = NULL;
static char dyntext_fname[MAXPATHLEN];
static void *mapcache = NULL;
static char *maptext = NULL;
static size_t maptext_sz = 4096; /* initial buffer size */
static int mmap_mode = 0;
static int mmap_initted = 0;
static collector_mutex_t map_lock = COLLECTOR_MUTEX_INITIALIZER;
static collector_mutex_t dyntext_lock = COLLECTOR_MUTEX_INITIALIZER;
/* a reentrance guard for the interposition functions ensures that updates to
the map cache/file are sequential, with the first doing the final update */
static int reentrance = 0;
#define CHCK_REENTRANCE (reentrance || mmap_mode <= 0)
#define CURR_REENTRANCE reentrance
#define PUSH_REENTRANCE reentrance++
#define POP_REENTRANCE reentrance--
/* interposition function handles */
static void *(*__real_mmap)(void* start, size_t length, int prot, int flags,
int fd, off_t offset) = NULL;
static void *(*__real_mmap64)(void* start, size_t length, int prot, int flags,
int fd, off64_t offset) = NULL;
static int (*__real_munmap)(void* start, size_t length) = NULL;
static void *(*__real_dlopen)(const char* pathname, int mode) = NULL;
static void *(*__real_dlopen_2_34)(const char* pathname, int mode) = NULL;
static void *(*__real_dlopen_2_17)(const char* pathname, int mode) = NULL;
static void *(*__real_dlopen_2_2_5)(const char* pathname, int mode) = NULL;
static void *(*__real_dlopen_2_1)(const char* pathname, int mode) = NULL;
static void *(*__real_dlopen_2_0)(const char* pathname, int mode) = NULL;
static int (*__real_dlclose)(void* handle) = NULL;
static int (*__real_dlclose_2_34)(void* handle) = NULL;
static int (*__real_dlclose_2_17)(void* handle) = NULL;
static int (*__real_dlclose_2_2_5)(void* handle) = NULL;
static int (*__real_dlclose_2_0)(void* handle) = NULL;
static void (*collector_heap_record)(int, size_t, void*) = NULL;
/* internal function prototypes */
static int init_mmap_intf ();
static int init_mmap_files ();
static void append_segment_record (char *format, ...);
static void update_map_segments (hrtime_t hrt, int resolve);
static void resolve_mapname (MapInfo *map, char *name);
static void record_segment_map (hrtime_t timestamp, uint64_t loadaddr,
unsigned long msize, int pagesize, int modeflags,
long long offset, unsigned check, char *name);
static void record_segment_unmap (hrtime_t timestamp, uint64_t loadaddr);
/* Linux needs handling of the vsyscall page to get its data into the map.xml file */
static void process_vsyscall_page ();
#define MAXVSYSFUNCS 10
static int nvsysfuncs = 0;
static char *sysfuncname[MAXVSYSFUNCS];
static uint64_t sysfuncvaddr[MAXVSYSFUNCS];
static unsigned long sysfuncsize[MAXVSYSFUNCS];
#define MAXDYN 20
static int ndyn = 0;
static char *dynname [MAXDYN];
static void *dynvaddr [MAXDYN];
static unsigned dynsize [MAXDYN];
static char *dynfuncname[MAXDYN];
/*===================================================================*/
/*
* void __collector_mmap_init_mutex_locks()
* Iinitialize mmap mutex locks.
*/
void
__collector_mmap_init_mutex_locks ()
{
__collector_mutex_init (&map_lock);
__collector_mutex_init (&dyntext_lock);
}
/* __collector_ext_update_map_segments called by the audit agent
* Is is also called by dbx/collector when a (possible) map update
* is intimated, such as after dlopen/dlclose.
* Required when libcollector.so is not preloaded and interpositions inactive.
*/
int
__collector_ext_update_map_segments (void)
{
if (!mmap_initted)
return 0;
TprintfT (0, "__collector_ext_update_map_segments(%d)\n", CURR_REENTRANCE);
if (CHCK_REENTRANCE)
return 0;
PUSH_REENTRANCE;
update_map_segments (GETRELTIME (), 1);
POP_REENTRANCE;
return 0;
}
/*
* int __collector_ext_mmap_install()
* Install and initialise mmap tracing.
*/
int
__collector_ext_mmap_install (int record)
{
TprintfT (0, "__collector_ext_mmap_install(mmap_mode=%d)\n", mmap_mode);
if (NULL_PTR (mmap))
{
if (init_mmap_intf ())
{
TprintfT (0, "ERROR: collector mmap tracing initialization failed.\n");
return COL_ERROR_EXPOPEN;
}
}
else
TprintfT (DBG_LT2, "collector mmap tracing: mmap pointer not null\n");
/* Initialize side door interface with the heap tracing module */
collector_heap_record = (void(*)(int, size_t, void*))dlsym (RTLD_DEFAULT, "__collector_heap_record");
if (record)
{
map_hndl = __collector_create_handle (SP_MAP_FILE);
if (map_hndl == NULL)
return COL_ERROR_MAPOPEN;
if (init_mmap_files ())
{
TprintfT (0, "ERROR: collector init_mmap_files() failed.\n");
return COL_ERROR_EXPOPEN;
}
}
mmaps.next = NULL;
mapcache = NULL;
PUSH_REENTRANCE;
update_map_segments (GETRELTIME (), 1); // initial map
POP_REENTRANCE;
mmap_mode = 1;
mmap_initted = 1;
process_vsyscall_page ();
return COL_ERROR_NONE;
}
/*
* int __collector_ext_mmap_deinstall()
* Optionally update final map and stop tracing mmap events.
*/
int
__collector_ext_mmap_deinstall (int update)
{
if (!mmap_initted)
return COL_ERROR_NONE;
mmap_mode = 0;
if (update)
{
/* Final map */
PUSH_REENTRANCE;
update_map_segments (GETRELTIME (), 1);
POP_REENTRANCE;
}
TprintfT (0, "__collector_ext_mmap_deinstall(%d)\n", update);
if (map_hndl != NULL)
{
__collector_delete_handle (map_hndl);
map_hndl = NULL;
}
__collector_mutex_lock (&map_lock); // get lock before resetting
/* Free all memory maps */
MapInfo *mp;
for (mp = mmaps.next; mp;)
{
MapInfo *next = mp->next;
__collector_freeCSize (__collector_heap, mp, sizeof (*mp));
mp = next;
}
mmaps.next = NULL;
/* Free all name maps */
NameInfo *np;
for (np = namemaps; np;)
{
NameInfo *next = np->next;
__collector_freeCSize (__collector_heap, np, sizeof (*np) + __collector_strlen (np->filename));
np = next;
}
namemaps = NULL;
mapcache = __collector_reallocVSize (__collector_heap, mapcache, 0);
mmaps.next = NULL;
mapcache = NULL;
__collector_mutex_unlock (&map_lock);
TprintfT (0, "__collector_ext_mmap_deinstall done\n");
return 0;
}
/*
* void __collector_mmap_fork_child_cleanup()
* Perform all necessary cleanup steps in child process after fork().
*/
void
__collector_mmap_fork_child_cleanup ()
{
/* Initialize all mmap "mutex" locks */
__collector_mmap_init_mutex_locks ();
if (!mmap_initted)
return;
mmap_mode = 0;
__collector_delete_handle (map_hndl);
__collector_mutex_lock (&map_lock); // get lock before resetting
/* Free all memory maps */
MapInfo *mp;
for (mp = mmaps.next; mp;)
{
MapInfo *next = mp->next;
__collector_freeCSize (__collector_heap, mp, sizeof (*mp));
mp = next;
}
mmaps.next = NULL;
/* Free all name maps */
NameInfo *np;
for (np = namemaps; np;)
{
NameInfo *next = np->next;
__collector_freeCSize (__collector_heap, np, sizeof (*np) + __collector_strlen (np->filename));
np = next;
}
namemaps = NULL;
mapcache = __collector_reallocVSize (__collector_heap, mapcache, 0);
mmap_initted = 0;
reentrance = 0;
__collector_mutex_unlock (&map_lock);
}
static int
init_mmap_files ()
{
TprintfT (DBG_LT2, "init_mmap_files\n");
/* also create the headerless dyntext file (if required) */
CALL_UTIL (snprintf)(dyntext_fname, sizeof (dyntext_fname), "%s/%s",
__collector_exp_dir_name, SP_DYNTEXT_FILE);
if (CALL_UTIL (access)(dyntext_fname, F_OK) != 0)
{
int fd = CALL_UTIL (open)(dyntext_fname, O_RDWR | O_CREAT | O_TRUNC,
S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
if (fd == -1)
{
char errmsg[256];
TprintfT (0, "ERROR: init_mmap_files: open(%s) failed\n",
dyntext_fname);
__collector_log_write ("<event kind=\"%s\" id=\"%d\" ec=\"%d\">%s: %s</event>\n",
SP_JCMD_CERROR, COL_ERROR_DYNOPEN, errno,
dyntext_fname, errmsg);
return COL_ERROR_DYNOPEN;
}
else
CALL_UTIL (close)(fd);
}
return COL_ERROR_NONE;
}
static void
append_segment_record (char *format, ...)
{
char buf[1024];
char *bufptr = buf;
va_list va;
va_start (va, format);
int sz = __collector_xml_vsnprintf (bufptr, sizeof (buf), format, va);
va_end (va);
if (__collector_expstate != EXP_OPEN && __collector_expstate != EXP_PAUSED)
{
TprintfT (0, "append_segment_record: expt neither open nor paused (%d); "
"not writing to map.xml\n\t%s", __collector_expstate, buf);
return;
}
if (sz >= sizeof (buf))
{
/* Allocate a new buffer */
sz += 1; /* add the terminating null byte */
bufptr = (char*) alloca (sz);
va_start (va, format);
sz = __collector_xml_vsnprintf (bufptr, sz, format, va);
va_end (va);
}
int rc = __collector_write_string (map_hndl, bufptr, sz);
if (rc != 0)
(void) __collector_log_write ("<event kind=\"%s\" id=\"%d\"></event>\n",
SP_JCMD_CERROR, COL_ERROR_MAPWRITE);
}
static void
record_segment_map (hrtime_t timestamp, uint64_t loadaddr, unsigned long msize,
int pagesize, int modeflags, long long offset,
unsigned check, char *name)
{
TprintfT (DBG_LT2, "record_segment_map(%s @ 0x%llx)\n", name, (long long) loadaddr);
append_segment_record ("<event kind=\"map\" object=\"segment\" tstamp=\"%u.%09u\" "
"vaddr=\"0x%016llX\" size=\"%lu\" pagesz=\"%d\" foffset=\"%c0x%08llX\" "
"modes=\"0x%03X\" chksum=\"0x%0X\" name=\"%s\"/>\n",
(unsigned) (timestamp / NANOSEC),
(unsigned) (timestamp % NANOSEC),
loadaddr, msize, pagesize,
offset < 0 ? '-' : '+', offset < 0 ? -offset : offset,
modeflags, check, name);
}
static void
record_segment_unmap (hrtime_t timestamp, uint64_t loadaddr)
{
TprintfT (DBG_LT2, "record_segment_unmap(@ 0x%llx)\n", (long long) loadaddr);
append_segment_record ("<event kind=\"unmap\" tstamp=\"%u.%09u\" vaddr=\"0x%016llX\"/>\n",
(unsigned) (timestamp / NANOSEC),
(unsigned) (timestamp % NANOSEC), loadaddr);
}
#if WSIZE(64)
#define ELF_EHDR Elf64_Ehdr
#define ELF_PHDR Elf64_Phdr
#define ELF_SHDR Elf64_Shdr
#define ELF_DYN Elf64_Dyn
#define ELF_AUX Elf64_auxv_t
#define ELF_SYM Elf64_Sym
#define ELF_ST_BIND ELF64_ST_BIND
#define ELF_ST_TYPE ELF64_ST_TYPE
#elif WSIZE(32)
#define ELF_EHDR Elf32_Ehdr
#define ELF_PHDR Elf32_Phdr
#define ELF_SHDR Elf32_Shdr
#define ELF_DYN Elf32_Dyn
#define ELF_AUX Elf32_auxv_t
#define ELF_SYM Elf32_Sym
#define ELF_ST_BIND ELF32_ST_BIND
#define ELF_ST_TYPE ELF32_ST_TYPE
#endif
static unsigned
checksum_mapname (MapInfo* map)
{
unsigned checksum = 0;
/* only checksum code segments */
if ((map->mflags & (PROT_EXEC | PROT_READ)) == 0 ||
(map->mflags & PROT_WRITE) != 0)
return 0;
checksum = (unsigned) - 1;
TprintfT (DBG_LT2, "checksum_mapname checksum = 0x%0X\n", checksum);
return checksum;
}
static void*
dlopen_searchpath (void*(real_dlopen) (const char *, int),
void *caller_addr, const char *basename, int mode)
{
TprintfT (DBG_LT2, "dlopen_searchpath(%p, %s, %d)\n", caller_addr, basename, mode);
Dl_info dl_info;
if (dladdr (caller_addr, &dl_info) == 0)
{
TprintfT (0, "ERROR: dladdr(%p): %s\n", caller_addr, dlerror ());
return 0;
}
TprintfT (DBG_LT2, "dladdr(%p): %p fname=%s\n",
caller_addr, dl_info.dli_fbase, dl_info.dli_fname);
int noload = RTLD_LAZY | RTLD_NOW | RTLD_NOLOAD;
void *caller_hndl = NULL;
#define WORKAROUND_RTLD_BUG 1
#ifdef WORKAROUND_RTLD_BUG
// A dynamic linker dlopen bug can result in corruption/closure of open streams
// XXXX workaround should be removed once linker patches are all available
#if WSIZE(64)
#define MAINBASE 0x400000
#elif WSIZE(32)
#define MAINBASE 0x08048000
#endif
const char* tmp_path =
(dl_info.dli_fbase == (void*) MAINBASE) ? NULL : dl_info.dli_fname;
caller_hndl = real_dlopen (tmp_path, noload);
#else //XXXX workaround should be removed once linker patches are all available
caller_hndl = real_dlopen (dl_info.dli_fname, noload);
#endif //XXXX workaround should be removed once linker patches are all available
if (!caller_hndl)
{
TprintfT (0, "ERROR: dlopen(%s,NOLOAD): %s\n", dl_info.dli_fname, dlerror ());
return NULL;
}
#if !defined(__MUSL_LIBC)
Dl_serinfo _info, *info = &_info;
Dl_serpath *path;
/* determine search path count and required buffer size */
dlinfo (caller_hndl, RTLD_DI_SERINFOSIZE, (void *) info);
/* allocate new buffer and initialize */
/*
CR# 7191331
There is a bug in Linux that causes the first call
to dlinfo() to return a small value for the dls_size.
The first call to dlinfo() determines the search path
count and the required buffer size. The second call to
dlinfo() tries to obtain the search path information.
However, the size of the buffer that is returned by
the first call to the dlinfo() is incorrect (too small).
The second call to dlinfo() uses the incorrect size to
allocate memory on the stack and internally uses the memcpy()
function to copy the search paths to the allocated memory space.
The length of the search path is much larger than the buffer
that is allocated on the stack. The memcpy() overwrites some
of the information that are saved on the stack, specifically,
it overwrites the "basename" parameter.
collect crashes right after the second call to dlinfo().
The search paths are used to locate the shared libraries.
dlinfo() creates the search paths based on the paths
that are assigned to LD_LIBRARY_PATH environment variable
and the standard library paths. The standard library paths
consists of the /lib and the /usr/lib paths. The
standard library paths are always included to the search
paths by dlinfo() even if the LD_LIBRARY_PATH environment
variable is not defined. Therefore, at the very least the
dls_cnt is assigned to 2 (/lib and /usr/lib) and dlinfo()
will never assign dls_cnt to zero. The dls_cnt is the count
of the potential paths for searching the shared libraries.
So we need to increase the buffer size before the second
call to dlinfo(). There are number of ways to increase
the buffer size. However, none of them can calculate the
buffer size precisely. Some users on the web have suggested
to multiply the MAXPATHLEN by dls_cnt for the buffer size.
The MAXPATHLEN is assigned to 1024 bytes. In my opinion
this is too much. So I have decided to multiply dls_size
by dls_cnt for the buffer size since the dls_size is much
smaller than 1024 bytes.
I have already confirmed with our user that the workaround
is working with his real application. Additionally,
the dlopen_searchpath() function is called only by the
libcollector init() function when the experiment is started.
Therefore, allocating some extra bytes on the stack which
is local to this routine is harmless.
*/
info = alloca (_info.dls_size * _info.dls_cnt);
info->dls_size = _info.dls_size;
info->dls_cnt = _info.dls_cnt;
/* obtain search path information */
dlinfo (caller_hndl, RTLD_DI_SERINFO, (void *) info);
path = &info->dls_serpath[0];
char pathname[MAXPATHLEN];
for (unsigned int cnt = 1; cnt <= info->dls_cnt; cnt++, path++)
{
__collector_strlcpy (pathname, path->dls_name, sizeof (pathname));
__collector_strlcat (pathname, "/", sizeof (pathname));
__collector_strlcat (pathname, basename, sizeof (pathname));
void* ret = NULL;
#if (ARCH(Intel) && WSIZE(32)) || ARCH(SPARC)
ret = (real_dlopen) (pathname, mode);
#else
ret = CALL_REAL (dlopen)(pathname, mode);
#endif
TprintfT (DBG_LT2, "try %d/%d: %s = %p\n", cnt, info->dls_cnt, pathname, ret);
if (ret)
return ret; // success!
}
#endif
return NULL;
}
static void
resolve_mapname (MapInfo *map, char *name)
{
map->filename = "";
map->mapname = "";
if (name == NULL || *name == '\0')
{
if (map->mflags & MA_STACK)
map->filename = "<" SP_MAP_STACK ">";
else if (map->mflags & MA_BREAK)
map->filename = "<" SP_MAP_HEAP ">";
else if (map->mflags & MA_ISM)
map->filename = "<" SP_MAP_SHMEM ">";
return;
}
NameInfo *np;
for (np = namemaps; np; np = np->next)
if (__collector_strcmp (np->mapname, name) == 0)
break;
if (np == NULL)
{
const char *fname;
fname = name;
/* Create and link a new name map */
size_t fnamelen = __collector_strlen (fname) + 1;
np = (NameInfo*) __collector_allocCSize (__collector_heap, sizeof (NameInfo) + fnamelen, 1);
if (np == NULL) // We could not get memory
return;
np->mapname = np->filename;
__collector_strlcpy (np->filename, fname, fnamelen);
np->next = namemaps;
namemaps = np;
}
map->mapname = np->mapname;
map->filename = np->filename;
if (map->filename[0] == (char) 0)
map->filename = map->mapname;
TprintfT (DBG_LT2, "resolve_mapname: %s resolved to %s\n", map->mapname, map->filename);
}
static unsigned long
str2ulong (char **ss)
{
char *s = *ss;
unsigned long val = 0UL;
const int base = 16;
for (;;)
{
char c = *s++;
if (c >= '0' && c <= '9')
val = val * base + (c - '0');
else if (c >= 'a' && c <= 'f')
val = val * base + (c - 'a') + 10;
else if (c >= 'A' && c <= 'F')
val = val * base + (c - 'A') + 10;
else
break;
}
*ss = s - 1;
return val;
}
static void
update_map_segments (hrtime_t hrt, int resolve)
{
size_t filesz;
if (__collector_mutex_trylock (&map_lock))
{
TprintfT (0, "WARNING: update_map_segments(resolve=%d) BUSY\n", resolve);
return;
}
TprintfT (DBG_LT2, "\n");
TprintfT (DBG_LT2, "begin update_map_segments(hrt, %d)\n", resolve);
// Note: there is similar code to read /proc/$PID/map[s] in
// perfan/er_kernel/src/KSubExp.cc KSubExp::write_subexpt_map()
const char* proc_map = "/proc/self/maps";
size_t bufsz = maptext_sz;
int done = 0;
filesz = 0;
int map_fd = CALL_UTIL (open)(proc_map, O_RDONLY);
while (!done)
{
bufsz *= 2;
maptext = __collector_reallocVSize (__collector_heap, maptext, bufsz);
TprintfT (DBG_LT2, " update_map_segments: Loop for bufsize=%ld\n",
(long) bufsz);
for (;;)
{
int n = CALL_UTIL (read)(map_fd, maptext + filesz, bufsz - filesz);
TprintfT (DBG_LT2, " update_map_segments: __collector_read(bufp=%p nbyte=%ld)=%d\n",
maptext + filesz, (long) ( bufsz - filesz), n);
if (n < 0)
{
TprintfT (0, "ERROR: update_map_segments: read(maps): errno=%d\n", errno);
(void) __collector_log_write ("<event kind=\"%s\" id=\"%d\" ec=\"%d\">%s</event>\n",
SP_JCMD_CERROR, COL_ERROR_MAPREAD, errno, proc_map);
CALL_UTIL (close)(map_fd);
__collector_mutex_unlock (&map_lock);
return;
}
else if (n == 0)
{
done = 1;
break;
}
filesz += n;
if (filesz >= bufsz) /* Buffer too small */
break;
}
}
CALL_UTIL (close)(map_fd);
maptext_sz = filesz;
int mapcache_entries = 0;
char *str, *str1;
for (str = maptext;; str = str1)
{
for (str1 = str; str1 - maptext < filesz; str1++)
{
if (*str1 == '\n')
{
*str1 = (char) 0;
break;
}
}
if (str1 - maptext >= filesz)
break;
str1++;
mapcache_entries++;
mapcache = __collector_reallocVSize (__collector_heap, mapcache,
sizeof (prmap_t) * mapcache_entries);
prmap_t *map = ((prmap_t *) mapcache) + (mapcache_entries - 1);
map->pr_vaddr = str2ulong (&str);
str++;
unsigned long eaddr = str2ulong (&str);
str++;
map->pr_size = eaddr - map->pr_vaddr;
map->pr_mflags = 0;
map->pr_mflags += (*str++ == 'r' ? PROT_READ : 0);
map->pr_mflags += (*str++ == 'w' ? PROT_WRITE : 0);
map->pr_mflags += (*str++ == 'x' ? PROT_EXEC : 0);
map->pr_mflags += (*str++ == 's' ? MA_SHARED : 0);
str++;
map->pr_offset = str2ulong (&str);
str++;
map->pr_dev = str2ulong (&str) * 0x100;
str++;
map->pr_dev += str2ulong (&str);
str++;
map->pr_ino = str2ulong (&str);
if (map->pr_dev == 0)
map->pr_mflags |= MA_ANON;
while (*str == ' ')
str++;
map->pr_mapname = str;
map->pr_pagesize = 4096;
}
/* Compare two maps and record all differences */
unsigned nidx = 0;
MapInfo *prev = &mmaps;
MapInfo *oldp = mmaps.next;
for (;;)
{
prmap_t *newp = nidx < mapcache_entries ?
(prmap_t*) mapcache + nidx : NULL;
if (oldp == NULL && newp == NULL)
break;
/* If two maps are equal proceed to the next pair */
if (oldp && newp &&
oldp->vaddr == newp->pr_vaddr &&
oldp->size == newp->pr_size &&
__collector_strcmp (oldp->mapname, newp->pr_mapname) == 0)
{
prev = oldp;
oldp = oldp->next;
nidx++;
continue;
}
/* Check if we need to unload the old map first */
if (newp == NULL || (oldp && oldp->vaddr <= newp->pr_vaddr))
{
if (oldp != NULL)
{
/* Don't record MA_ANON maps except MA_STACK and MA_BREAK */
if ((!(oldp->mflags & MA_ANON) || (oldp->mflags & (MA_STACK | MA_BREAK))))
record_segment_unmap (hrt, oldp->vaddr);
/* Remove and free map */
prev->next = oldp->next;
MapInfo *tmp = oldp;
oldp = oldp->next;
__collector_freeCSize (__collector_heap, tmp, sizeof (*tmp));
}
}
else
{
MapInfo *map = (MapInfo*) __collector_allocCSize (__collector_heap, sizeof (MapInfo), 1);
if (map == NULL)
{
__collector_mutex_unlock (&map_lock);
return;
}
map->vaddr = newp->pr_vaddr;
map->size = newp->pr_size;
map->offset = newp->pr_offset;
map->mflags = newp->pr_mflags;
map->pagesize = newp->pr_pagesize;
resolve_mapname (map, newp->pr_mapname);
/* Insert new map */
map->next = prev->next;
prev->next = map;
prev = map;
/* Don't record MA_ANON maps except MA_STACK and MA_BREAK */
if (!(newp->pr_mflags & MA_ANON) || (newp->pr_mflags & (MA_STACK | MA_BREAK)))
{
unsigned checksum = checksum_mapname (map);
record_segment_map (hrt, map->vaddr, map->size,
map->pagesize, map->mflags,
map->offset, checksum, map->filename);
}
nidx++;
}
}
TprintfT (DBG_LT2, "update_map_segments: done\n\n");
__collector_mutex_unlock (&map_lock);
} /* update_map_segments */
/*
* Map addr to a segment. Cope with split segments.
*/
int
__collector_check_segment_internal (unsigned long addr, unsigned long *base,
unsigned long *end, int maxnretries, int MA_FLAGS)
{
int number_of_tries = 0;
retry:
;
unsigned long curbase = 0;
unsigned long curfoff = 0;
unsigned long cursize = 0;
MapInfo *mp;
for (mp = mmaps.next; mp; mp = mp->next)
{
if (curbase + cursize == mp->vaddr &&
curfoff + cursize == mp->offset &&
((mp->mflags & MA_FLAGS) == MA_FLAGS
|| __collector_strncmp (mp->mapname, "[vdso]", 6) == 0
|| __collector_strncmp (mp->mapname, "[vsyscall]", 10) == 0
))
cursize = mp->vaddr + mp->size - curbase;
else if (addr < mp->vaddr)
break;
else if ((mp->mflags & MA_FLAGS) != MA_FLAGS
&& __collector_strncmp (mp->mapname, "[vdso]", 6)
&& __collector_strncmp (mp->mapname, "[vsyscall]", 10))
{
curbase = 0;
curfoff = 0;
cursize = 0;
}
else
{
curbase = mp->vaddr;
curfoff = mp->offset;
cursize = mp->size;
}
}
if (addr >= curbase && addr < curbase + cursize)
{
*base = curbase;
*end = curbase + cursize;
return 1;
}
/*
* 21275311 Unwind failure in native stack for java application running on jdk8 on x86
*
* On JDK8, we've observed cases where Java-compiled methods end up
* in virtual address segments that were "dead zones" (mflags&PROT_READ==0) at
* the time of the last update_map_segments() but are now "live". So if we
* fail to find a segment, let's call update_map_segments and then retry
* before giving up.
*/
if (number_of_tries < maxnretries)
{
number_of_tries++;
__collector_ext_update_map_segments ();
goto retry;
}
*base = 0;
*end = 0;
return 0;
}
/**
* Check if address belongs to a readable and executable segment
* @param addr
* @param base
* @param end
* @param maxnretries
* @return 1 - yes, 0 - no
*/
int
__collector_check_segment (unsigned long addr, unsigned long *base,
unsigned long *end, int maxnretries)
{
int MA_FLAGS = PROT_READ | PROT_EXEC;
int res = __collector_check_segment_internal (addr, base, end, maxnretries, MA_FLAGS);
return res;
}
/**
* Check if address belongs to a readable segment
* @param addr
* @param base
* @param end
* @param maxnretries
* @return 1 - yes, 0 - no
*/
int
__collector_check_readable_segment( unsigned long addr, unsigned long *base, unsigned long *end, int maxnretries )
{
int MA_FLAGS = PROT_READ;
int res = __collector_check_segment_internal(addr, base, end, maxnretries, MA_FLAGS);
return res;
}
static ELF_AUX *auxv = NULL;
static void
process_vsyscall_page ()
{
TprintfT (DBG_LT2, "process_vsyscall_page()\n");
if (ndyn != 0)
{
/* We've done this one in this process, and cached the results */
/* use the cached results */
for (int i = 0; i < ndyn; i++)
{
append_segment_record ("<event kind=\"map\" object=\"dynfunc\" name=\"%s\" "
"vaddr=\"0x%016lX\" size=\"%u\" funcname=\"%s\" />\n",
dynname[i], dynvaddr[i], dynsize[i], dynfuncname[i]);
TprintfT (DBG_LT2, "process_vsyscall_page: append_segment_record map dynfunc='%s' vaddr=0x%016lX size=%ld funcname='%s' -- from cache\n",
dynname[i], (unsigned long) dynvaddr[i],
(long) dynsize[i], dynfuncname[i]);
}
}
if (nvsysfuncs != 0)
{
/* We've done this one in this process, and cached the results */
/* use the cached results */
hrtime_t hrt = GETRELTIME ();
for (int i = 0; i < nvsysfuncs; i++)
{
append_segment_record ("<event kind=\"map\" object=\"function\" tstamp=\"%u.%09u\" "
"vaddr=\"0x%016lX\" size=\"%u\" name=\"%s\" />\n",
(unsigned) (hrt / NANOSEC), (unsigned) (hrt % NANOSEC),
(unsigned long) sysfuncvaddr[i], (unsigned) sysfuncsize[i], sysfuncname[i]);
TprintfT (DBG_LT2, "process_vsyscall_page: append_segment_record map function='%s' vaddr=0x%016lX size=%ld -- from cache\n",
sysfuncname[i], (unsigned long) sysfuncvaddr[i], (long) sysfuncsize[i]);
}
}
if (ndyn + nvsysfuncs != 0)
return;
/* After fork we can't rely on environ as it might have
* been moved by putenv(). Use the pointer saved by the parent.
*/
if (auxv == NULL)
{
char **envp = (char**) environ;
if (envp == NULL)
return;
while (*envp++ != NULL);
auxv = (ELF_AUX*) envp;
}
TprintfT (DBG_LT2, "process_vsyscall_page, auxv = ox%p\n", auxv);
ELF_AUX *ap;
#ifdef DEBUG
for (ap = auxv; ap->a_type != AT_NULL; ap++)
TprintfT (DBG_LT2, "process_vsyscall_page: ELF_AUX: "
" a_type = 0x%016llx %10lld "
" a_un.a_val = 0x%016llx %10lld\n",
(long long) ap->a_type, (long long) ap->a_type,
(long long) ap->a_un.a_val, (long long) ap->a_un.a_val);
#endif
// find the first ELF_AUX of type AT_SYSINFO_EHDR
ELF_EHDR *ehdr = NULL;
for (ap = auxv; ap->a_type != AT_NULL; ap++)
{
if (ap->a_type == AT_SYSINFO_EHDR)
{
// newer Linuxes do not have a_ptr field, they just have a_val
ehdr = (ELF_EHDR*)(intptr_t) ap->a_un.a_val;
if (ehdr != NULL)
break;
}
}
// If one is found
if (ehdr != NULL)
{
char *mapName = "SYSINFO_EHDR";
MapInfo *mp;
for (mp = mmaps.next; mp; mp = mp->next)
{
if ((unsigned long) ehdr == mp->vaddr)
{
mp->mflags |= PROT_EXEC;
if (mp->mapname && mp->mapname[0])
mapName = mp->mapname;
break;
}
}
// Find the dynsym section and record all symbols
char *base = (char*) ehdr;
ELF_SHDR *shdr = (ELF_SHDR*) (base + ehdr->e_shoff);
int i;
#if 0
TprintfT (DBG_LT2, "process_vsyscall_page: ehdr: EI_CLASS=%lld EI_DATA=%lld EI_OSABI=%lld e_type=%lld e_machine=%lld e_version=%lld\n"
" e_entry =0x%016llx %10lld e_phoff =0x%016llx %10lld\n"
" e_shoff =0x%016llx %10lld e_flags =0x%016llx %10lld\n"
" e_ehsize =0x%016llx %10lld e_phentsize =0x%016llx %10lld\n"
" e_phnum =0x%016llx %10lld e_shentsize =0x%016llx %10lld\n"
" e_shnum =0x%016llx %10lld e_shstrndx =0x%016llx %10lld\n",
(long long) ehdr->e_ident[EI_CLASS], (long long) ehdr->e_ident[EI_DATA], (long long) ehdr->e_ident[EI_OSABI],
(long long) ehdr->e_type, (long long) ehdr->e_machine, (long long) ehdr->e_version,
(long long) ehdr->e_entry, (long long) ehdr->e_entry,