/
alloc_replace.c
5500 lines (5168 loc) · 215 KB
/
alloc_replace.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) 2012-2017 Google, Inc. All rights reserved.
* **********************************************************/
/* Dr. Memory: the memory debugger
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation;
* version 2.1 of the License, and no later version.
* This library 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
* Library General Public License for more details.
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
/***************************************************************************
* alloc_replace.c: application allocator replacement routines for both
* Dr. Memory and Dr. Heapstat
*/
/* Requirements beyond regular allocator:
* + add redzones (configurable)
* + delay frees (configurable): thus unlike most allocators we do
* not want to re-use a block immediately even with same-size
* repeated alloc-free in order to detect use-after-free
* + callbacks for custom actions like updating shadow memory
* or heap profiling
* + provide iterator over all chunks
* + given pointer, know whether the start of a live chunk,
* the start of a freed chunk, or neither
* + store both requested size and allocated size
* + store type: malloc, new or new[]
* + store custom flags per chunk (for use during leak scan)
* + store callstack
* + optional: given pointer, know whether *inside* a live chunk,
* a freed chunk, or neither. required during leak scan, but can
* build new data structure at that point.
* nice-to-have when reporting neighbors of unaddr, and can
* use shadow mem heuristics instead.
*
* Differences vs wrap-based implementation wrt client_ callouts:
* + redzones are built-in rather than added by the client, to
* facilitate both storing headers in them and sharing adjacent
* + delay free lists are built-in rather than maintained by client
*
* Design:
* + for !alloc_ops.external_headers, header sits inside redzone;
* for alloc_ops.external_headers, header is in a hashtable
* + redzones are shared among adjacent allocs and are centered to
* reduce the likelihood of corruption from over/underflow:
*
* | request sz| | redzone size | request size | | redzone size |
* | app chunk | pad | rz | header | rz | app chunk |pad| rz | header | rz |
* ^
* next_chunk _|
*
* + for !alloc_ops.shared_redzones, there are two redzones in between
* each chunk, with the header in between and separate from the redzones
* (geared toward modes that want to fill the redzones)
* + arena->next_chunk always has a redzone + header space (if co-located, i.e.,
* !alloc_ops.external_headers) to its left
* + free lists are kept in buckets by size. larger is preferred over
* searching. final bucket is var-sized and is always searched.
* frees are appended to make the lists FIFO for better delaying
* (though worse alloc re-use), and searches start at the front and
* take the first fit.
* we can add fancier algorithms in the future.
* + for alloc_ops.external_headers, free list entries use headers that
* are co-located with the chunk headers
* + for !alloc_ops.external_headers, free list entry headers begin where
* regular headers begin, in the middle of the redzone.
*/
#include "dr_api.h"
#include "drwrap.h"
#include "drmgr.h"
#include "utils.h"
#include "asm_utils.h"
#include "alloc.h"
#include "alloc_private.h"
#include "heap.h"
#include "drsymcache.h"
#include <string.h> /* memcpy */
#ifdef MACOS
# include <sys/syscall.h>
# include <sys/mman.h>
# include <malloc/malloc.h>
#elif defined(LINUX)
# include "sysnum_linux.h"
# define __USE_GNU /* for mremap */
# include <sys/mman.h>
#else
# include "../wininc/crtdbg.h"
#endif
#ifdef UNIX
# include <errno.h>
#endif
/***************************************************************************
* header and free list data structures
*/
/* 64-bit malloc impls generally align to 16, and in fact some Windows code
* assumes this (i#1219).
*/
#define CHUNK_ALIGNMENT IF_X64_ELSE(16, 8)
#define CHUNK_MIN_SIZE IF_X64_ELSE(16, 8)
#define CHUNK_MIN_MMAP 128*1024
/* initial commit on linux has to hold at least one non-mmap chunk */
#define ARENA_INITIAL_COMMIT CHUNK_MIN_MMAP
#define ARENA_INITIAL_SIZE 4*1024*1024
#define REQUEST_DIFF_MAX USHRT_MAX
/* we only support allocation sizes under 4GB */
typedef uint heapsz_t;
/* each free list bucket contains freed chunks of at least its bucket size
* XXX: add stats on searches to help in tuning these
*/
static const uint free_list_sizes[] = {
IF_NOT_X64_(8) 16, 24, 32, 40, 64, 96, 128, 192, 256, 384, 512, 1024, 2048,
4096, 8192, 16384, 32768,
};
#define NUM_FREE_LISTS (sizeof(free_list_sizes)/sizeof(free_list_sizes[0]))
/* Values stored in chunk header flags */
enum {
CHUNK_FREED = MALLOC_RESERVED_1, /* 0x0001 */
CHUNK_MMAP = MALLOC_RESERVED_2, /* 0x0002 */
/* MALLOC_RESERVED_{3,4} are used for types */ /* 0x000C */
CHUNK_PRE_US = MALLOC_RESERVED_5, /* 0x0100 */
CHUNK_PREV_FREE = MALLOC_RESERVED_6, /* 0x0200 */
CHUNK_DELAY_FREE = MALLOC_RESERVED_7, /* 0x0400 */
#ifdef WINDOWS
CHUNK_LAYER_RTL = MALLOC_RESERVED_8, /* 0x0800 */
#endif
/* i#1532: only check for non-static libc. This is Windows-only but it's
* cleaner to avoid all the ifdefs down below.
*/
CHUNK_LAYER_NOCHECK = 0x1000,
CHUNK_SKIP_ITER = 0x2000,
/* meta-flags */
#ifdef WINDOWS
ALLOCATOR_TYPE_FLAGS = (MALLOC_ALLOCATOR_FLAGS | CHUNK_LAYER_RTL |
CHUNK_LAYER_NOCHECK),
#else
ALLOCATOR_TYPE_FLAGS = (MALLOC_ALLOCATOR_FLAGS),
#endif
};
#define HEADER_MAGIC 0x5244 /* "DR" */
/* This header struct is used in both a traditional co-located header
* and as a hashtable payload (for alloc_ops.external_headers). Note
* that when using redzones there's no problem with a large header as
* it sits inside the redzone. But with the hashtable, and for
* pattern mode with co-located headers, and for Dr. Heapstat where we
* have no redzone, we want to make the header as compact as is
* reasonable.
*/
typedef struct _chunk_header_t {
void *user_data;
/* If we wanted to save space we could hand out sizes only equal to the buckets
* and shrink the alloc_size field. We'd use a separate header for the largest
* bucket that had the alloc_size.
*/
heapsz_t alloc_size;
/* Bitmask of CHUNK_ flags */
ushort flags;
/* Put magic last for a greater chance of surviving underflow, esp when our
* header has no redzone buffer (when redzone_size <= HEADER_SIZE, which
* unfortunately is true by default as both are 16 for 32-bit).
*/
ushort magic;
union {
/* A live or delay-free chunk does not need a prev pointer, while a truly
* free chunk does not need the request size nor the prev size (b/c
* we always coalesce, and we don't set prev size if prev is delay-free).
*/
struct {
/* Difference between alloc_size and requested size. We currently always
* split re-used large free chunks, so 64K as the max diff works out.
*/
ushort request_diff;
/* The size of the previous free chunk / CHUNK_ALIGNMENT (i.e., >>3). Only
* valid if CHUNK_PREV_FREE is set in flags. We get away with only a 512KB
* max because larger elements, which are always mmaps, are not put on the
* free list or coalesced. We assert on the various constants all lining up
* in our init routine. After coalescing we can reach a larger size than
* 512KB, in which case we place 0 here and store the size immediately
* prior to the redzone.
*
* If CHUNK_MMAP is set in flags, this holds the padding at the start
* of the mmap base put in place for alignment of the returned alloc,
* / CHUNK_ALIGNMENT (i.e., >> 3).
*/
ushort prev_size_shr;
#ifdef X64
/* Compiler will add anyway: just making explicit. we need the header
* size to be aligned to 8 so we can't pack. for alloc_ops.external_headers
* we eat this overhead to provide runtime flexibility w/ the same
* data struct as we don't need it there.
* Update: actually we need to align to 16.
*/
uint pad;
#endif
} unfree;
struct _free_header_t *prev;
} u;
} chunk_header_t;
/* Header at the top of an mmap used for large allocs. If we didn't need to
* support memalign() & co, we could get away without this.
*/
typedef struct _mmap_header_t {
chunk_header_t *head;
size_t map_size;
} mmap_header_t;
/* To support pattern mode, which wants to fill the redzone with its pattern,
* we don't want the next pointer in the redzone. For now we pay the cost
* of extra memory rather than complicate the interface to pattern mode
* to have it skip the next pointer (we'd need a call when we move from delay
* queueu to free lists, and we'd need to adjust real_base on several calls:
* and ensure client isn't storing things by real base!).
* Thus, we indirect the live header size through here.
*/
static heapsz_t header_size;
/* if redzone is too small, header sticks beyond it */
static heapsz_t header_beyond_redzone;
/* we place header in the middle */
static heapsz_t redzone_beyond_header;
/* Free list header for both regular and var-size chunk. Each chunk
* is at least 8 bytes so we can fit the next pointer here even for
* x64. We squish the prev pointer into fields of the chunk header we
* no longer need, for a true free; for a delay free we don't use a
* prev pointer.
*
* FIXME: for alloc_ops.external_headers do we need a chunk pointer
* here? or will it be in the head struct?
*/
typedef struct _free_header_t {
chunk_header_t head;
struct _free_header_t *next;
} free_header_t;
typedef struct _free_lists_t {
/* Delayed frees are kept here for more fair delaying across sizes
* than if we put them into the per-size lists.
*/
free_header_t *delay_front;
free_header_t *delay_last;
/* The delay threshold is per-arena */
uint delayed_chunks;
size_t delayed_bytes;
/* A normal free list can be LIFO, but for more effective delayed frees
* we want FIFO. FIFO-per-bucket-size is sufficient.
*/
free_header_t *front[NUM_FREE_LISTS];
free_header_t *last[NUM_FREE_LISTS];
} free_lists_t;
#ifdef LINUX
/* we assume we're the sole users of the brk (after pre-us allocs) */
static byte *pre_us_brk;
static byte *cur_brk;
#endif
#ifdef WINDOWS
/* For alloc_ops.global_lock (xref i#949). Each arena's dr_lock points
* at this lock when alloc_ops.global_lock is true.
*/
static void *global_lock;
#endif
/* header at the top of each arena (an "arena" for this code is a contiguous
* piece of memory parceled out into individual malloc "chunks")
*/
typedef struct _arena_header_t {
#ifdef MACOS
/* Placed at the start for easy conversion back and forth.
* We ignore the function pointers inside here.
* Xref i#1699.
*/
malloc_zone_t zone_inlined;
/* Some apps write to zone_inlined.zone_name and then mark the page read-only. */
char padding[PAGE_SIZE-sizeof(malloc_zone_t)];
/* For child arenas to point at the parent */
malloc_zone_t *zone;
#endif
byte *start_chunk;
byte *next_chunk;
byte *commit_end;
byte *reserve_end;
free_lists_t *free_list;
#ifdef WINDOWS
/* i#949: We need two locks. The lock field is the app lock, which can
* be acquired while in app code. This field is a pure DR lock, and
* it's used to synchronize free chunk splitting and coalescing with
* malloc iteration. (Regular mallocs and frees that do not split
* or coalesce do not need to synchronize with malloc iteration.)
* We always acquire the app lock first if we acquire both.
*/
void *dr_lock;
#endif
void *lock; /* app lock for Windows */
uint flags;
/* If we free the final chunk before the brk we need to know to mark the
* next carved-out chunk w/ the prev free size.
*/
heapsz_t prev_free_sz;
uint magic;
#ifdef WINDOWS
/* A member of the alloc set for which this arena is the default heap */
app_pc alloc_set_member;
/* Base of the module for which this is the default Heap */
app_pc modbase;
/* HANDLE of Heap, for pre-us Heap */
HANDLE handle;
#endif
/* we need to iterate arenas belonging to one (non-default) Heap */
struct _arena_header_t *next_arena;
/* for main arena of each Heap, we inline free_lists_t here */
} arena_header_t;
#ifdef WINDOWS
/* pick a flag that can't be passed on the Heap level to identify whether
* a Heap or a regular arena
*/
# define ARENA_MAIN HEAP_ZERO_MEMORY /* 0x8 */
# define ARENA_PRE_US_MAPPED 0x100 /* unused by Windows */
/* another non-Heap flag to identify libc-default Heaps (i#939) */
# define ARENA_LIBC_DEFAULT HEAP_REALLOC_IN_PLACE_ONLY /* 0x10 */
/* identify whether a static libc heap is the process heap (i#1223) */
# define ARENA_LIBC_SPECULATIVE 0x200 /* unused by Windows */
/* flags that we support being passed to HeapCreate:
* HEAP_CREATE_ENABLE_EXECUTE | HEAP_GENERATE_EXCEPTIONS | HEAP_NO_SERIALIZE |
* HEAP_GROWABLE
*/
# define HEAP_CREATE_POSSIBLE_FLAGS 0x40007
static HANDLE process_heap;
/* i#1754: for pre-us mapped memory, in particular the shared-memory CsrPortHeap,
* we do not attempt to detect uninitialized reads as it very difficult to
* track writes by csrss. The simplest way to accomplish this is to mark
* all allocs as defined by zeroing them.
*/
# define WINDOWS_ZERO_MEMORY(arena, alloc_flags) \
(TEST(ARENA_PRE_US_MAPPED, (arena)->flags) || TEST(HEAP_ZERO_MEMORY, (alloc_flags)))
#else
# define ARENA_MAIN 0x0001
#endif
/* Linux current arena, or Windows default Heap. We always use this main
* pointer as the arena, even though there can be extra sub-arena regions that
* belong to this Heap linked in the next_arena field.
*/
static arena_header_t *cur_arena;
/* For handling pre-us mallocs for non-earliest injection or delayed/attach
* instrumentation. Contains chunk_header_t entries.
* We assume this table is only added to at init and only removed from
* at exit time and thus needs no external lock.
*/
#define PRE_US_TABLE_HASH_BITS 8
static hashtable_t pre_us_table;
/* XXX i#879: for pattern mode we ideally don't want any co-located
* headers and instead want a hashtable of live allocs (free are in
* free lists and/or rbtree).
* Cleaner to have own table here and not try to use the alloc.c malloc-wrap table
* though we do want the same hash tuning.
* Currently we have a much simpler implementation for pattern mode
* that uses non-shared redzones and a header in between (so it looks
* like wrapping, and like wrapping won't detect a bug that clobbers
* the header prior to corruption and possible crash).
*/
#ifdef STATISTICS
static uint heap_capacity;
static uint peak_heap_capacity;
static uint num_arenas;
static uint peak_num_arenas;
static uint num_splits;
static uint num_coalesces;
static uint num_dealloc;
static uint dbgcrt_mismatch;
static uint allocs_left_native;
#endif
#ifdef DEBUG
/* used to allow use of app stack on abort */
static bool aborting;
#endif
/* Indicates whether process initialization is fully complete, including
* iteration of modules. Thus, we don't set this until we get the
* first bb event.
*/
static bool process_initialized;
#ifdef WINDOWS
static app_pc executable_base;
static arena_header_t *
check_libc_vs_process_heap(alloc_routine_entry_t *e, arena_header_t *arena);
#endif
#ifdef MACOS
static void
malloc_zone_init(arena_header_t *arena);
#endif
/* Flags controlling allocation behavior */
typedef enum {
ALLOC_SYNCHRONIZE = 0x0001, /* malloc, free, and realloc */
ALLOC_ZERO = 0x0002, /* malloc and realloc */
ALLOC_IS_REALLOC = 0x0004, /* malloc and free */
/* Routines that free the client_data (client_malloc_data_free(),
* client_handle_free_reuse()) and routines reporting on invalid
* heap args or OOM are called regardless of these flags' values.
*/
/* Whether to invoke client_{add,remove}_malloc_{pre,post} */
ALLOC_INVOKE_CLIENT_DATA = 0x0008, /* malloc and free */
/* Whether to invoke client_handle_{malloc,free} */
ALLOC_INVOKE_CLIENT_ACTION = 0x0010, /* malloc and free */
ALLOC_INVOKE_CLIENT = ALLOC_INVOKE_CLIENT_DATA | ALLOC_INVOKE_CLIENT_ACTION,
ALLOC_IN_PLACE_ONLY = 0x0020, /* realloc */
ALLOC_ALLOW_NULL = 0x0040, /* realloc: do not fail on NULL */
ALLOC_ALLOW_EMPTY = 0x0080, /* realloc: size==0 does re-allocate */
ALLOC_IGNORE_MISMATCH = 0x0100, /* free, realloc, size */
ALLOC_IS_QUERY = 0x0200, /* check_type_match */
} alloc_flags_t;
/***************************************************************************
* utility routines
*/
#define DR_STATE_TO_SWAP (DR_STATE_ALL & (~DR_STATE_STACK_BOUNDS))
#ifdef WINDOWS
static inline const char *
malloc_layer_name(uint flags)
{
if (TEST(CHUNK_LAYER_RTL, flags))
return "Windows API layer";
else
return "C library layer";
}
#endif
static inline void *
enter_client_code(void)
{
void *drcontext = dr_get_current_drcontext();
/* For our callstack walk we need the frame ptr of our replacement
* functions to be marked defined. By using our replace xbp we
* have the malloc frame in the callstack (i#639).
* Note that we do not want to, say, pass in the mcontext and
* mark defined through get_stack_registers()'s xsp, as that
* will mark a bunch of uninitialized slots on the stack.
*/
byte *final_app_xsp = (byte *)
dr_read_saved_reg(drcontext, DRWRAP_REPLACE_NATIVE_SP_SLOT);
client_stack_alloc((byte *)final_app_xsp - sizeof(void*), (byte *)final_app_xsp,
true/*defined*/);
/* while we are using the app's stack and registers, we need to
* switch to the private peb/teb to avoid asserts in symbol
* routines.
* XXX: is it safe to do away w/ this and relax the asserts?
* if perf becomes an issue we could do a lazy swap on symbol
* queries (and hope no other private lib calls occur).
*
* On Linux we don't need to swap b/c we (and our priv libs) won't
* examine the selectors or descriptors: -mangle_app_seg ensures
* we don't need to swap. Which is good b/c a swap involves a
* system call which kills performance: i#941.
*/
#ifdef WINDOWS
dr_switch_to_dr_state_ex(drcontext, DR_STATE_TO_SWAP);
#endif
return drcontext;
}
static void
exit_client_code(void *drcontext, bool in_app_mode)
{
byte *final_app_xsp = (byte *)
dr_read_saved_reg(drcontext, DRWRAP_REPLACE_NATIVE_SP_SLOT);
client_stack_dealloc((byte *)final_app_xsp - sizeof(void*), (byte *)final_app_xsp);
#if WINDOWS
if (!in_app_mode)
dr_switch_to_app_state_ex(drcontext, DR_STATE_TO_SWAP);
#endif
drwrap_replace_native_fini(drcontext);
/* i#1217: yet another point where we zero out data to avoid stale retaddrs
* on our callstacks. For 32-bit, dr_write_saved_reg() called by
* drwrap_replace_native_fini() has the app retaddr on the stack. We clear
* it here.
* For 32-bit, we assume it's safe to write beyond TOS.
* For 64-bit, this is not a leaf routine, so we similarly assume it's safe:
* but it's more fragile (xref i#1278).
* drwrap_replace_native_fini() currently uses 12 bytes of stack for 32-bit
* and 56 for 64-bit (and dr_write_saved_reg() uses 32, but we
* only care about its param slots).
*
* XXX: if we knew whether we had DrMem definedness info we could avoid
* this work for full mode.
*/
# define ZERO_APP_STACK_SZ IF_X64_ELSE(64, 32)
/* We can't call memset() or any regular function b/c it will clobber its
* own stack, nor can we have a loop here as we can clobber our own locals.
* Thus we must use an asm routine.
*/
zero_pointers_on_stack(ZERO_APP_STACK_SZ);
}
/* i#900: we need to mark an app lock acquisition as a safe spot.
* This is made possible by drwrap_replace_native() using a continuation
* strategy rather than returning to the code cache.
* N.B.: no DR lock can be held by the caller!
*/
static void
app_heap_lock(void *drcontext, void *recur_lock)
{
dr_mark_safe_to_suspend(drcontext, true/*enter safe region*/);
dr_recurlock_lock(recur_lock);
dr_mark_safe_to_suspend(drcontext, false/*exit safe region*/);
}
static void
app_heap_unlock(void *drcontext, void *recur_lock)
{
/* Nothing special, just for symmetry */
dr_recurlock_unlock(recur_lock);
}
/* Locking for any alloc or free operation */
static void
arena_lock(void *drcontext, arena_header_t *arena, bool app_synch)
{
/* XXX i#948: use per-thread free lists to avoid lock in common case,
* for Linux or Windows libc at least (where heap synch is not part
* of app API), and when !alloc_ops.global_lock.
*/
if (app_synch)
app_heap_lock(drcontext, arena->lock);
#ifdef WINDOWS
/* i#949: regardless of app synch, we need to synchronize our own
* operations. We must grab this after the app lock. We don't need
* this to be a safe spot as it's only grabbed in our own code.
*/
if (alloc_ops.global_lock)
dr_recurlock_lock(arena->dr_lock);
#else
/* We assume every top-level caller synchronizes (can't check here b/c
* this can be called via realloc calling free or malloc).
* If synch becomes optional on Linux, need to use dr_lock too.
*/
#endif
}
static void
arena_unlock(void *drcontext, arena_header_t *arena, bool app_synch)
{
#ifdef WINDOWS
if (alloc_ops.global_lock)
dr_recurlock_unlock(arena->dr_lock);
#else
/* We assume every top-level caller synchronizes (can't check here b/c
* this can be called via realloc calling free or malloc).
* If synch becomes optional on Linux, need to use dr_lock too.
*/
#endif
if (app_synch)
app_heap_unlock(drcontext, arena->lock);
}
/* i#949: locking for alloc or free operations that affect concurrent
* iteration: splitting or coalescing of free chunks. Changing header
* flags concurrently with iteration is ok. If the iterator wants to
* look for certain flags across multiple iterations, the user needs
* to set alloc_ops.global_lock.
*/
static void
iterator_lock(arena_header_t *arena, bool in_alloc)
{
/* We could blindly lock (it's a recursive lock) but more performant this way */
#ifdef WINDOWS
if (!in_alloc || !alloc_ops.global_lock)
dr_recurlock_lock(arena->dr_lock);
else
ASSERT(dr_recurlock_self_owns(arena->dr_lock), "lock error");
#else
if (!in_alloc)
dr_recurlock_lock(arena->lock);
else
ASSERT(dr_recurlock_self_owns(arena->lock), "lock error");
#endif
}
static void
iterator_unlock(arena_header_t *arena, bool in_alloc)
{
#ifdef WINDOWS
ASSERT(dr_recurlock_self_owns(arena->dr_lock), "lock error");
if (!in_alloc || !alloc_ops.global_lock)
dr_recurlock_unlock(arena->dr_lock);
#else
ASSERT(dr_recurlock_self_owns(arena->lock), "lock error");
if (!in_alloc)
dr_recurlock_unlock(arena->lock);
#endif
}
#if defined(WINDOWS) && defined(X64)
static app_pc
get_replace_native_caller(void *drcontext)
{
/* drwrap saved the retaddr slot for us */
byte *app_xsp = (byte *) dr_read_saved_reg(drcontext, DRWRAP_REPLACE_NATIVE_SP_SLOT);
return *(app_pc *)app_xsp;
}
#endif
/* This must be inlined to get an xsp that's in the call chain */
#define INITIALIZE_MCONTEXT_FOR_REPORT(mc) do { \
/* assumption: we only need xsp and xbp initialized */ \
(mc)->size = sizeof(*(mc)); \
(mc)->flags = DR_MC_CONTROL | DR_MC_INTEGER; \
get_stack_registers(&MC_SP_REG(mc), &MC_FP_REG(mc)); \
} while (0)
#ifdef WINDOWS
static inline uint
arena_page_prot(uint flags)
{
return DR_MEMPROT_READ | DR_MEMPROT_WRITE |
(TEST(HEAP_CREATE_ENABLE_EXECUTE, flags) ? DR_MEMPROT_EXEC : 0);
}
#endif
/* We used to call raw_syscall() and virtual_alloc(), but for DRi#199 we
* now have DR routines we can use, which avoids DR asserts (mainly on
* Linux allmem, but possible to have problems everywhere if the app
* puts code in the heap).
*/
static byte *
os_large_alloc(size_t commit_size _IF_WINDOWS(size_t reserve_size) _IF_WINDOWS(uint prot))
{
#ifdef UNIX
byte *map = (byte *)
dr_raw_mem_alloc(commit_size, DR_MEMPROT_READ | DR_MEMPROT_WRITE, NULL);
ASSERT(ALIGNED(commit_size, PAGE_SIZE), "must align to at least page size");
/* dr_raw_mem_alloc returns NULL on failure, but I'm keeping the range for
* raw syscall.
*/
if ((ptr_int_t)map <= 0 && (ptr_int_t)map > -PAGE_SIZE) {
LOG(2, "os_large_alloc FAILED with return value "PFX"\n", map);
return NULL;
}
LOG(3, "%s commit="PIFX" => "PFX"\n", __FUNCTION__, commit_size, map);
return map;
#else
byte *loc = NULL;
ASSERT(ALIGNED(commit_size, PAGE_SIZE), "must align to at least page size");
ASSERT(ALIGNED(reserve_size, PAGE_SIZE), "must align to at least page size");
ASSERT(reserve_size >= commit_size, "must reserve more than commit");
loc = dr_custom_alloc(NULL, DR_ALLOC_NON_HEAP | DR_ALLOC_NON_DR |
DR_ALLOC_RESERVE_ONLY, reserve_size,
DR_MEMPROT_NONE, NULL);
if (loc == NULL)
return NULL;
loc = dr_custom_alloc(NULL, DR_ALLOC_NON_HEAP | DR_ALLOC_NON_DR |
DR_ALLOC_COMMIT_ONLY | DR_ALLOC_FIXED_LOCATION, commit_size,
prot, loc);
if (loc == NULL) {
dr_custom_free(NULL, DR_ALLOC_NON_HEAP | DR_ALLOC_NON_DR, loc, reserve_size);
return NULL;
}
LOG(3, "%s commit="PIFX" reserve="PIFX" prot=0x%x => "PFX"\n",
__FUNCTION__, commit_size, reserve_size, prot, loc);
return loc;
#endif
}
/* For Windows, up to caller to ensure new_commit_size <= previously reserved size */
static bool
os_large_alloc_extend(byte *map, size_t cur_commit_size, size_t new_commit_size
_IF_WINDOWS(uint prot))
{
ASSERT(ALIGNED(cur_commit_size, PAGE_SIZE), "must align to at least page size");
ASSERT(ALIGNED(new_commit_size, PAGE_SIZE), "must align to at least page size");
ASSERT(new_commit_size > cur_commit_size, "this routine does not support shrinking");
#ifdef LINUX
byte *newmap = (byte *) dr_raw_mremap(map, cur_commit_size, new_commit_size,
0/*can't move*/, NULL/*ignored*/);
if ((ptr_int_t)newmap <= 0 && (ptr_int_t)newmap > -PAGE_SIZE)
return false;
return true;
#elif defined(MACOS)
/* There is no mremap on Mac so we try to do a new mmap at the right spot.
* We can still free both with one munmap.
* We don't dare do DR_ALLOC_FIXED_LOCATION as it may clobber something.
*/
byte *newmap = (byte *)
dr_raw_mem_alloc(new_commit_size - cur_commit_size,
DR_MEMPROT_READ | DR_MEMPROT_WRITE,
map + cur_commit_size);
if ((ptr_int_t)newmap <= 0 && (ptr_int_t)newmap > -PAGE_SIZE)
return false;
if (newmap != map + cur_commit_size) {
/* Didn't get the subsequent spot: bail. */
dr_raw_mem_free(newmap, new_commit_size - cur_commit_size);
return false;
}
return true;
#else /* WINDOWS */
/* i#1258: we have to tweak [map + cur_commit_size, map + new_commit_size)
* and not re-commit [map, map + new_commit_size) b/c the latter will
* modify the prot bits on existing pages, which the app might have
* changed from the arena default!
*/
return (dr_custom_alloc(NULL, DR_ALLOC_NON_HEAP | DR_ALLOC_NON_DR |
DR_ALLOC_COMMIT_ONLY | DR_ALLOC_FIXED_LOCATION,
new_commit_size - cur_commit_size, prot,
map + cur_commit_size) != NULL);
#endif
}
/* For Windows, map_size is ignored and the whole allocation is freed */
static bool
os_large_free(byte *map, size_t map_size)
{
#ifdef UNIX
bool success;
ASSERT(ALIGNED(map, PAGE_SIZE), "invalid mmap base");
ASSERT(ALIGNED(map_size, PAGE_SIZE), "invalid mmap size");
success = dr_raw_mem_free(map, map_size);
LOG(3, "%s "PFX" size="PIFX" => %d\n", __FUNCTION__, map, map_size, success);
return success;
#else
LOG(3, "%s "PFX" size="PIFX"\n", __FUNCTION__, map, map_size);
return dr_custom_free(NULL, DR_ALLOC_NON_HEAP | DR_ALLOC_NON_DR, map, map_size);
#endif
}
static inline heapsz_t
chunk_request_size(chunk_header_t *head)
{
return (head->alloc_size - head->u.unfree.request_diff);
}
static void
notify_client_alloc(void *drcontext, byte *ptr, chunk_header_t *head,
alloc_flags_t flags, dr_mcontext_t *mc, app_pc caller)
{
malloc_info_t info = { sizeof(info), ptr, chunk_request_size(head),
head->alloc_size, false/*!pre_us*/, true/*redzone*/,
TEST(ALLOC_ZERO, flags), TEST(ALLOC_IS_REALLOC, flags),
0, head->user_data };
if (TEST(ALLOC_INVOKE_CLIENT_DATA, flags)) {
head->user_data = client_add_malloc_pre(&info, mc, caller);
info.client_data = head->user_data;
client_add_malloc_post(&info);
}
if (TEST(ALLOC_INVOKE_CLIENT_ACTION, flags)) {
ASSERT(drcontext != NULL, "invalid arg");
client_handle_malloc(drcontext, &info, mc);
}
}
/***************************************************************************
* core allocation routines
*/
static inline chunk_header_t *
header_from_ptr(const void *ptr)
{
if (alloc_ops.external_headers) {
/* XXX i#879: hashtable lookup */
ASSERT(false, "NYI");
return NULL;
} else {
if ((ptr_uint_t)ptr < header_size)
return NULL;
else {
return (chunk_header_t *) ((byte *)ptr - redzone_beyond_header - header_size);
}
}
}
static inline byte *
ptr_from_header(chunk_header_t *head)
{
if (alloc_ops.external_headers) {
/* XXX i#879: hashtable lookup */
ASSERT(false, "NYI");
return NULL;
} else {
ASSERT(!TEST(CHUNK_PRE_US, head->flags), "caller must handle pre-us");
return (byte *)head + redzone_beyond_header + header_size;
}
}
static inline chunk_header_t *
header_from_mmap_base(void *map)
{
if (alloc_ops.external_headers) {
/* XXX i#879: hashtable lookup */
ASSERT(false, "NYI");
return NULL;
} else {
if ((ptr_uint_t)map < header_size)
return NULL;
else {
mmap_header_t *mhead = (mmap_header_t *) map;
return mhead->head;
}
}
}
/* Distance from the end of one chunk (its start pointer plus alloc_size) to
* the start of the user memory for the subsequent chunk
*/
static inline size_t
inter_chunk_space(void)
{
return alloc_ops.redzone_size + header_beyond_redzone +
(alloc_ops.shared_redzones ? 0 : alloc_ops.redzone_size);
}
/* Pass in result of header_from_ptr() as 2nd arg, but don't de-reference it!
* Returns true for both live mallocs and chunks in delay free lists
*/
static inline bool
is_valid_chunk(const void *ptr, chunk_header_t *head)
{
/* Note that we can't be sure w/o using a hashtable, but for performance
* it's worth it to risk not identifying an invalid free so we use
* heuristics.
* XXX improvements:
* + should we have an option of using a hashtable to be sure,
* even when !alloc_ops.external_headers?
* app corrupting our allocator would be bad.
* + check whether in heap memory region(s) if that's cheap: if
* need rbtree lookup then don't
* + could check that next header is a real header, or at end of arena
* + could have client_ callout that checks shadow memory
*/
if (alloc_ops.external_headers) {
/* XXX i#879: need to look in delay free rbtree too */
return head != NULL;
} else {
/* Unlike a regular malloc library, we cannot afford to crash on
* a bogus arg from the app b/c Dr. Memory is supposed to detect
* invalid args and crashes. We use DR's new, fast dr_safe_read()
* (via safe_read()) to have low overhead yet stability.
* An alternative might be a top-level crash handler
* that bails out w/ an error report about invalid args.
*/
ushort magic;
/* App heap corruption can touch our magic field (deliberately
* nearest the app alloc), causing us to report as an invalid
* heap arg (after reporting the unaddr access) and later as a
* leak, which doesn't seem ideal: but it's hard to do better.
* Xref i#950.
*/
return (ptr != NULL &&
ALIGNED(ptr, CHUNK_ALIGNMENT) &&
safe_read(&head->magic, sizeof(magic), &magic) &&
magic == HEADER_MAGIC);
}
}
/* This is called on every free, so keep it efficient.
* However, esp on Windows, we must pay the overhead to avoid crashes
* from callers causing us to mix our free lists across Heaps.
*
* Up to caller to check for large allocs, which are not inside arenas!
* (Yes, this means that on Windows the app can pass any Heap it likes: so
* far that hasn't been an issue but one could imagine a Heap flag that
* needs to apply to a large alloc free or size query.)
*/
static inline bool
ptr_is_in_arena(byte *ptr, arena_header_t *arena)
{
arena_header_t *a;
for (a = arena; a != NULL; a = a->next_arena) {
if (ptr >= a->start_chunk && ptr < a->commit_end)
return true;
}
LOG(2, "%s: "PFX" not found in arena "PFX"\n", __FUNCTION__, ptr, arena);
return false;
}
/* Returns true iff ptr is a live alloc inside arena. Thus, will return
* false for pre-us allocs from other arenas.
*/
static bool
is_live_alloc(void *ptr, arena_header_t *arena, chunk_header_t *head)
{
bool live = false;
if (alloc_ops.external_headers) {
live = (head != NULL);
} else {
live = (is_valid_chunk(ptr, head) &&
!TEST(CHUNK_FREED, head->flags));
}
return (live &&
/* large allocs are their own arenas */
(TEST(CHUNK_MMAP, head->flags) || ptr_is_in_arena(ptr, arena)));
}
/* returns NULL if an invalid ptr, but will return a freed chunk */
static inline chunk_header_t *
header_from_ptr_include_pre_us(void *ptr)
{
chunk_header_t *head = header_from_ptr(ptr);
if (!is_valid_chunk(ptr, head))
head = hashtable_lookup(&pre_us_table, (void *)ptr);
return head;
}
/* The base param must be non-NULL for pre-us; else, it can be NULL */
static inline void
header_to_info(chunk_header_t *head, malloc_info_t *info, byte *pre_us_base,
alloc_flags_t flags /* pass 0 if not a new alloc notification */)
{
info->struct_size = sizeof(*info);
info->pre_us = TEST(CHUNK_PRE_US, head->flags);
info->base = (info->pre_us ? pre_us_base : ptr_from_header(head));
ASSERT(!info->pre_us || pre_us_base != NULL, "need base for pre-us!");
info->request_size = chunk_request_size(head);
info->pad_size = head->alloc_size;
info->has_redzone = !info->pre_us;
info->zeroed = TEST(ALLOC_ZERO, flags);
info->realloc = TEST(ALLOC_IS_REALLOC, flags);
info->client_flags = head->flags & MALLOC_POSSIBLE_CLIENT_FLAGS;
info->client_data = head->user_data;
}
/* Assumes caller zeroed the full struct and initialized the commit_end and
* reserve_end fields.
*/
static void
arena_init(arena_header_t *arena, arena_header_t *parent)
{
size_t header_size = sizeof(*arena);
if (parent != NULL) {
/* XXX: maybe we should have two different headers for parents vs children */
arena->flags = (parent->flags & (~ARENA_MAIN));
arena->lock = parent->lock;
#ifdef WINDOWS
arena->dr_lock = parent->dr_lock;
#endif
arena->free_list = parent->free_list;
#ifdef WINDOWS
arena->alloc_set_member = parent->alloc_set_member;
arena->modbase = parent->modbase;
arena->handle = parent->handle;
#endif
#ifdef MACOS
arena->zone = parent->zone;
#endif
} else {
arena->flags = ARENA_MAIN;
arena->lock = dr_recurlock_create();
/* We only grab this DR lock as the app and we mark it with
* dr_recurlock_mark_as_app(), as well as using dr_mark_safe_to_suspend(),
* to ensure proper DR behavior
*/
dr_recurlock_mark_as_app(arena->lock);
#ifdef WINDOWS
if (alloc_ops.global_lock)
arena->dr_lock = global_lock;
else
arena->dr_lock = dr_recurlock_create();
#endif
/* to avoid complications of storing and freeing DR heap we inline these
* in the main arena's header
*/
arena->free_list = (free_lists_t *) ((byte *)arena + header_size);
header_size += sizeof(*arena->free_list);