-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathheap_explorer.c
More file actions
899 lines (806 loc) · 26 KB
/
heap_explorer.c
File metadata and controls
899 lines (806 loc) · 26 KB
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
/*
* This is a glibc heap exploration program.
* It allows you to allocate and free chunks,
* and observe how various heap data structures
* change.
*/
#define _GNU_SOURCE
#include <asm/prctl.h>
#include <fcntl.h>
#include <signal.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <sys/syscall.h>
#include <unistd.h>
#include "heap_explorer.h"
static char const GREEN[] = "\x1b[0;32m";
static char const YELLOW[] = "\x1b[0;33m";
static char const BLUE[] = "\x1b[0;34m";
static char const PURPLE[] = "\x1b[0;35m";
static char const CLEAR_COLOR[] = "\x1b[0m";
// Takes a pointer to chunk's data,
// returns a pointer to its size
static void *data2chunk(void const *const data) {
return (uint8_t *)data - sizeof(size_t);
}
// Takes a pointer to a chunk's size,
// returns a pointer to its data
static void *chunk2data(void const *const chunk) {
return (uint8_t *)chunk + sizeof(size_t);
}
// Takes a pointer to a chunk's prev_size,
// returns a pointer to its size.
static void *glibc_chunk2chunk(void const *const glibc_chunk) {
return (uint8_t *)glibc_chunk + sizeof(size_t);
}
// Takes a pointer to a chunk's size,
// returns a pointer to its prev_size.
static void *chunk2glibc_chunk(void const *const chunk) {
return (uint8_t *)chunk - sizeof(size_t);
}
// Takes a pointer to a chunk's size,
// returns a pointer to its data.
static void *glibc_chunk2data(void const *const glibc_chunk) {
return (uint8_t *)glibc_chunk + 2 * sizeof(size_t);
}
static bool is_in_skip_list(void const *const chunk) {
return ((void const* const *)chunk)[3] != NULL || ((void const* const *)chunk)[4] != NULL;
}
// Converts an int to a hex string.
// Returns a pointer to static memory.
static char *itoa_hex(uint64_t n) {
static char const UINT64_MAX_STR_HEX[] = "0xffffffffffffffff";
static char result_data[sizeof(UINT64_MAX_STR_HEX)];
char *result = result_data;
memset(result, 0, sizeof(result_data));
static char PREFIX[] = "0x";
strcpy(result, PREFIX);
for (size_t i = 0; i < strlen(PREFIX); i++) {
result++;
}
if (n == 0) {
result[0] = '0';
return result;
}
char const HEXDIGS[] = "0123456789abcdef";
for (int i = 0; n > 0; i++) {
result[i] = *(HEXDIGS + n % 16);
n /= 16;
}
for (uint64_t i = 0; i < strlen(result) / 2; i++) {
char tmp = result[i];
result[i] = result[strlen(result) - i - 1];
result[strlen(result) - i - 1] = tmp;
}
return result - strlen(PREFIX);
}
static char *ptoa(void const *const p) {
return itoa_hex((intptr_t)p);
}
static char const UINT64_MAX_STR_DEC[] = "18446744073709551615";
// Converts an int to a decimal string
// Returns a pointer to static memory.
static char *itoa(uint64_t n) {
static char result[sizeof(UINT64_MAX_STR_DEC)];
memset(result, 0, sizeof(result));
if (n == 0) {
result[0] = '0';
return result;
}
for (int i = 0; n > 0; i++) {
result[i] = '0' + n % 10;
n /= 10;
}
for (uint64_t i = 0; i < strlen(result) / 2; i++) {
char tmp = result[i];
result[i] = result[strlen(result) - i - 1];
result[strlen(result) - i - 1] = tmp;
}
return result;
}
static int32_t atoi32(uint8_t const *s) {
int32_t result = 0;
while ('0' <= *s && *s <= '9') {
result *= 10;
result += *s - '0';
s++;
}
if (*s != '\0') {
_exit(EXIT_FAILURE);
}
return result;
}
// Writes a null-terminated string to stdout
static void print(char const *const s) {
write(STDOUT_FILENO, s, strlen(s));
}
// Writes a null-terminated string to stdout,
// followed by a newline
static void println(char const *const s) {
static char const NL[] = "\n";
print(s);
print(NL);
}
// The glibc malloc_state struct, from glibc's malloc/malloc.c,
// with some slight simplifications. Should still be binary-compatible.
struct malloc_state {
uint32_t mutex;
uint32_t flags;
uint32_t have_fastchunks;
void *fastbinsY[10];
void *top;
void *last_remainder;
void *bins[254];
uint32_t binmap[4];
void *next;
void *next_free;
uint64_t attached_threads;
uint64_t system_mem;
uint64_t max_system_mem;
};
#define ARRAY_LEN(A) (sizeof(A) / sizeof(A[0]))
// The offset of malloc within the glibc mapping
static intptr_t const MALLOC_OFFSET = 0xa9190;
// The base address of glibc.
// Note that this is not the base of the first entry from `info proc mappings`
// that came from libc.so.6. Instead, this is the base of the entry before that,
// because that mapping (which I believe is the libc .bss) is randomized
// contiguously with glibc.
static intptr_t const LIBC_BASE = (intptr_t)malloc - MALLOC_OFFSET;
// The offset of main_arena within glibc.
static intptr_t const MAIN_ARENA_OFFSET = 0x1ebac0;
// A pointer to main_arena in glibc. This is the
// struct that stores most of the heap state.
static struct malloc_state const *const the_main_arena =
(struct malloc_state *)(LIBC_BASE + MAIN_ARENA_OFFSET);
#define NFASTBINS (ARRAY_LEN(the_main_arena->fastbinsY))
// Gets a chunk's data size.
// Note that this is 8 less than its size field,
// because the size itself is 8 bytes wide.
static uint64_t get_chunk_data_size(void const *const chunk) {
// We mask off the low 3 bits because they store metadata.
return (*(uint64_t const *)chunk & ~7ull) - sizeof(size_t);
}
// Prints a chunk's data size.
static void print_chunk_data_size(void const *const chunk) {
uint64_t const size = get_chunk_data_size(chunk);
print(", ");
print(PURPLE);
print("data size: ");
print(CLEAR_COLOR);
print(itoa_hex(size));
}
// Takes a pointer to a chunk's size (not prev_size),
// and dumps information about that chunk.
static void print_chunk(void const *const chunk, char const *const msg,
int64_t const arena_index, int64_t const bin_index,
char const *const color) {
print(ptoa(chunk));
print_chunk_data_size(chunk);
print(" ");
if (color != NULL) {
print(color);
}
if (msg != NULL) {
print("\t(");
if (arena_index != -1) {
print("arena ");
print(itoa(arena_index));
print(", ");
}
print(msg);
}
if (bin_index != -1) {
print(" ");
print(itoa(bin_index));
}
if (msg != NULL) {
print(")");
}
if (color != NULL) {
print(CLEAR_COLOR);
}
println("");
}
#define TCACHE_SIZE (64)
struct tcache_perthread_struct {
uint16_t counts[TCACHE_SIZE];
void *entries[TCACHE_SIZE];
};
// Takes a pointer to chunk's size, and returns a pointer
// to the next chunk's size.
static void *get_next_chunk(void const *const chunk) {
return (uint8_t *)chunk2data(chunk) + get_chunk_data_size(chunk);
}
// Gets the address of the given arena's tcache struct.
static struct tcache_perthread_struct *
get_the_tcache(struct malloc_state const *const arena) {
if (arena == the_main_arena) {
// Just get the first chunk on this heap
return (struct tcache_perthread_struct *)glibc_chunk2data(
((uint8_t *)chunk2glibc_chunk(
get_next_chunk(glibc_chunk2chunk(arena->top))) -
arena->system_mem));
} else {
// Get the chunk after the chunk containing the arena
return (struct tcache_perthread_struct *)((uint64_t *)(arena + 1) + 3);
}
}
// Gets the first chunk on the heap.
// If the heap is uninitialized, this will likely segfault.
static void *get_first_chunk(struct malloc_state const *const arena) {
return data2chunk(get_the_tcache(arena));
}
// Gets the last chunk on the heap.
// If the heap is uninitialized, this will likely segfault.
static void *get_last_chunk(struct malloc_state const *const arena) {
return glibc_chunk2chunk(arena->top);
}
// Returns whether chunk is in use (according to the following chunk's
// PREV_INUSE bit).
static bool is_in_use(void const *const chunk) {
return (*(uint64_t *)get_next_chunk(chunk)) & 1;
}
// Takes the address of a list link from tcache or fastbin,
// and deobfuscates it. Equivalent to REVEAL_PTR from glibc.
static void *deobfuscate_next_link(void const *const p) {
return (void *)((((intptr_t)p) >> 12) ^ *(intptr_t const *)p);
}
struct lookup_result {
int64_t idx;
int64_t arena;
};
static struct lookup_result const LOOKUP_FAILED = {.idx = -1, .arena = -1};
static bool lookup_failed(struct lookup_result lookup) {
return memcmp(&lookup, &LOOKUP_FAILED, sizeof(struct lookup_result)) == 0;
}
static bool lookup_succeeded(struct lookup_result lookup) {
return !lookup_failed(lookup);
}
// If `chunk` is in a fastbin, returns which one.
// Otherwise, returns -1
static int64_t arena_fastbin_lookup(struct malloc_state const *const arena,
void const *const chunk) {
for (int64_t i = 0; i < (int64_t)NFASTBINS; i++) {
if (arena->fastbinsY[i] != NULL) {
void const *curr = arena->fastbinsY[i];
while (curr != NULL) {
if (glibc_chunk2chunk(curr) == chunk) {
return i;
}
curr = deobfuscate_next_link(glibc_chunk2data(curr));
}
}
}
return -1;
}
// If `chunk` is in a tcache bin, returns which one.
// Otherwise, returns -1
static int64_t arena_tcache_lookup(struct malloc_state const *const arena,
void const *const chunk) {
struct tcache_perthread_struct const *const tcache = get_the_tcache(arena);
for (int64_t i = 0; i < TCACHE_SIZE; i++) {
if (tcache->entries[i] != NULL) {
void const *curr = tcache->entries[i];
while (curr != NULL) {
if (chunk == data2chunk(curr)) {
return i;
}
curr = deobfuscate_next_link(curr);
}
}
}
return -1;
}
static struct lookup_result tcache_lookup(void const *const chunk) {
struct malloc_state const *arena = the_main_arena;
int64_t arena_idx = 0;
do {
int64_t i = arena_tcache_lookup(arena, chunk);
if (i != -1) {
return (struct lookup_result){.idx = i, .arena = arena_idx};
}
arena = arena->next;
arena_idx++;
} while (arena != the_main_arena);
return LOOKUP_FAILED;
}
// If `chunk` is in a normal (small/large/unsorted) bin, returns which one.
// Otherwise, returns -1
static int64_t const NBINS = ARRAY_LEN(the_main_arena->bins) / 2;
static int64_t arena_bin_lookup(struct malloc_state const *const arena,
void const *const chunk) {
for (int64_t i = 0; i < NBINS; i++) {
void const *const head = data2chunk(arena->bins + i * 2);
void const *const head_link = *(void **)chunk2data(head);
if (head_link == NULL) {
continue;
}
void const *curr = glibc_chunk2chunk(head_link);
while (curr != head) {
if (curr == chunk) {
return i;
}
curr = glibc_chunk2chunk(*(void **)chunk2data(curr));
}
}
return -1;
}
// Prints all the chunks in the heap.
static void print_arena(struct malloc_state const *const arena) {
if (arena->top == NULL) {
println("This arena is empty.");
return;
}
void const *const last_chunk = get_last_chunk(arena);
void const *curr_chunk = get_first_chunk(arena);
uint64_t i = 0;
while (curr_chunk < last_chunk) {
print(YELLOW);
print("[");
print(itoa(i));
print("]:\t");
print(CLEAR_COLOR);
char const *msg = NULL;
char const *color = NULL;
int64_t bin_idx = -1;
int64_t arena_idx = -1;
struct lookup_result const tcache_lookup_result =
tcache_lookup(curr_chunk);
int64_t fastbin_idx = arena_fastbin_lookup(arena, curr_chunk);
if (!is_in_use(curr_chunk)) {
msg = "free";
color = GREEN;
bin_idx = arena_bin_lookup(arena, curr_chunk);
if (bin_idx == 0) {
msg = "unsorted bin";
bin_idx = -1;
} else if (bin_idx < 63) {
msg = "smallbin";
} else {
msg = "largebin";
}
} else if (lookup_succeeded(tcache_lookup_result)) {
msg = "tcache";
color = GREEN;
bin_idx = tcache_lookup_result.idx;
arena_idx = tcache_lookup_result.arena;
} else if (fastbin_idx != -1) {
msg = "fastbin";
color = GREEN;
bin_idx = fastbin_idx;
}
print_chunk(curr_chunk, msg, arena_idx, bin_idx, color);
void const *const next_chunk = get_next_chunk(curr_chunk);
curr_chunk = next_chunk;
i++;
}
if (curr_chunk == last_chunk) {
print(YELLOW);
print("[");
print(itoa(i));
print("]:\t");
print(CLEAR_COLOR);
print_chunk(last_chunk, "top chunk", -1, -1, BLUE);
} else {
print("Heap corrupted!");
}
}
static void *get_chunk_by_index(struct malloc_state const *const arena,
uint64_t const n) {
if (arena->top == NULL) {
println("The heap is empty.");
return NULL;
}
void const *const last_chunk = get_last_chunk(arena);
void *curr_chunk = get_first_chunk(arena);
uint64_t i = 0;
while (curr_chunk != last_chunk && i < n) {
curr_chunk = get_next_chunk(curr_chunk);
i++;
}
if (i != n) {
print("Couldn't find chunk ");
print(itoa(n));
println(".");
return NULL;
} else {
return curr_chunk;
}
}
// Frees the `n`th chunk on the heap.
static void free_chunk(void *const chunk) {
free(chunk2data(chunk));
}
// Returns the index of `chunk` in the heap.
// i.e., if `chunk` is the first thing allocated, returns 1
// (because of the bottom chunk), and if `chunk` is the top chunk,
// returns (num_chunks-1).
static int64_t arena_chunk_lookup(struct malloc_state const *const arena,
void const *const target_chunk) {
void const *const last_chunk = get_last_chunk(arena);
void *curr_chunk = get_first_chunk(arena);
int64_t i = 0;
while (curr_chunk != last_chunk && curr_chunk != target_chunk) {
curr_chunk = get_next_chunk(curr_chunk);
i++;
}
if (curr_chunk == target_chunk) {
return i;
} else {
return -1;
}
}
static struct lookup_result chunk_lookup(void const *const chunk) {
struct malloc_state const *arena = the_main_arena;
int64_t arena_idx = 0;
do {
int64_t i = arena_chunk_lookup(arena, chunk);
if (i != -1) {
return (struct lookup_result){.idx = i, .arena = arena_idx};
}
arena = arena->next;
arena_idx++;
} while (arena != the_main_arena);
return LOOKUP_FAILED;
}
static void print_bin_list(struct malloc_state const *const arena,
int64_t const bin_idx) {
if (bin_idx >= NBINS) {
println("Index out of bounds.");
return;
}
void const *const head = data2chunk(arena->bins + bin_idx * 2);
void const *const head_link = *(void **)chunk2data(head);
if (head_link == NULL) {
println("The bins are uninitialized.");
return;
}
void const *curr = glibc_chunk2chunk(head_link);
uint64_t i = 0;
print("{ ");
while (curr != head) {
if (i != 0) {
print(" -> ");
}
if (is_in_skip_list(curr)) {
print(GREEN);
}
print(ptoa(curr));
if (is_in_skip_list(curr)) {
print(CLEAR_COLOR);
}
curr = glibc_chunk2chunk(*(void **)chunk2data(curr));
i++;
}
println(" }");
}
static void print_fastbin_list(struct malloc_state const *const arena,
uint64_t const fastbin_idx) {
if (fastbin_idx >= NFASTBINS) {
println("Index out of bounds.");
return;
}
void const *const head = arena->fastbinsY[fastbin_idx];
void const *curr = head;
uint64_t i = 0;
print("{ ");
while (curr != NULL) {
if (i != 0) {
print(" -> ");
}
print(ptoa(glibc_chunk2chunk(curr)));
curr = deobfuscate_next_link(glibc_chunk2data(curr));
i++;
}
println(" }");
}
static void print_tcache_list(struct malloc_state const *const arena,
uint64_t const tcache_idx) {
if (tcache_idx >= TCACHE_SIZE) {
println("Index out of bounds.");
return;
}
struct tcache_perthread_struct const *const the_tcache =
get_the_tcache(arena);
void const *const head = the_tcache->entries[tcache_idx];
void const *curr = head;
uint64_t i = 0;
print("{ ");
while (curr != NULL) {
if (i != 0) {
print(" -> ");
}
print(ptoa(data2chunk(curr)));
curr = deobfuscate_next_link(curr);
i++;
}
println(" }");
}
// Parses a decimal int
static uint64_t parse_base10(char const *s) {
uint64_t result = 0;
while ('0' <= *s && *s <= '9') {
result *= 10;
result += *s - '0';
s++;
}
return result;
}
// Parses a hex int
static uint64_t parse_base16(char const *s) {
uint64_t result = 0;
while (('0' <= *s && *s <= '9') || ('a' <= *s && *s <= 'f') ||
('A' <= *s && *s <= 'F')) {
result *= 16;
if ('0' <= *s && *s <= '9') {
result += *s - '0';
} else if ('a' <= *s && *s <= 'f') {
result += *s - 'a' + 10;
} else if ('A' <= *s && *s <= 'F') {
result += *s - 'A' + 10;
}
s++;
}
return result;
}
// Reads a decimal or hex int from stdin
static uint64_t get_number(void) {
char num[sizeof(UINT64_MAX_STR_DEC)] =
{}; // we use UINT64_MAX_STR_DEC because it's longer than
// UINT64_MAX_STR_HEX
for (uint64_t i = 0; i < sizeof(num) - 1; i++) {
int const rc = read(STDIN_FILENO, num + i, 1);
if (rc <= 0) {
_exit(rc);
}
if (num[i] == '\n') {
num[i] = '\0';
break;
}
}
return num[0] == '0' && (num[1] == 'x' || num[1] == 'X')
? parse_base16(num + 2)
: parse_base10(num);
}
static bool is_mmapped(void const *const chunk) {
return (*(uint64_t *)chunk) & 2;
}
static uint64_t arena_lookup(struct malloc_state const *const arena) {
struct malloc_state const *curr = the_main_arena;
int64_t arena_idx = 0;
do {
if (curr == arena) {
return arena_idx;
}
curr = curr->next;
arena_idx++;
} while (curr != the_main_arena);
_exit(EXIT_FAILURE);
}
static pid_t get_next_tid(void) {
pid_t const my_tid = syscall(SYS_gettid);
uint8_t dirents[4096];
int const procfs_fd = open("/proc/self/task", O_DIRECTORY);
uint64_t const bytes_read =
syscall(SYS_getdents64, procfs_fd, dirents, sizeof(dirents));
if (bytes_read == 0) {
_exit(EXIT_FAILURE);
}
uint64_t offset = 0;
bool found_a_thread = false;
uint64_t first_valid_offset = 0;
while (offset < bytes_read) {
uint16_t const d_reclen = *(
uint16_t *)(dirents + offset + sizeof(uint64_t) + sizeof(uint64_t));
uint8_t *const filename = dirents + offset + sizeof(uint64_t) +
sizeof(uint64_t) + sizeof(uint16_t) +
sizeof(uint8_t);
int32_t received_tid = 0;
if (strcmp((char *)filename, ".") != 0 &&
strcmp((char *)filename, "..") != 0) {
received_tid = atoi32(filename);
if (!found_a_thread) {
first_valid_offset = offset;
found_a_thread = true;
}
}
offset += d_reclen;
if (received_tid == my_tid) {
break;
}
}
if (offset > bytes_read) {
_exit(EXIT_FAILURE);
}
if (offset == bytes_read) { // Wrap back around to the beginning
offset = first_valid_offset;
}
offset += sizeof(uint64_t) + sizeof(uint64_t) + sizeof(uint16_t) +
sizeof(uint8_t);
pid_t result = atoi32(dirents + offset);
close(procfs_fd);
return result;
}
static void *get_fs_base(void) {
void *const fs_base;
syscall(SYS_arch_prctl, ARCH_GET_FS, &fs_base);
return fs_base;
}
static int const TRIGGER_SIGNAL = SIGINT;
void explore_heap(void) {
static char const PS1[] = "> ";
static char const PS2[] = ">> ";
println("\nWelcome to Heap Explorer!");
// This was determined by experiment in GDB.
// No idea about how portable this is.
struct malloc_state const *const my_arena =
*(struct malloc_state const **)((uint8_t *)get_fs_base() - 0x30);
struct malloc_state const *arena = my_arena;
if (arena == NULL) {
arena = the_main_arena;
}
while (true) {
print("You are TID ");
print(itoa(syscall(SYS_gettid)));
print(", viewing arena ");
uint64_t arena_idx = arena_lookup(arena);
print(itoa(arena_idx));
if (arena_idx == 0) {
print(" (main_arena)");
}
if (arena == my_arena) {
print(" (this thread's arena)");
}
println("");
static char const *OPTIONS[] = {
"Allocate chunk(s).",
"Free a chunk.",
"Reallocate a chunk.",
"Print this arena.",
"Print a tcache list.",
"Print a fastbin list.",
"Print a bin list.",
"Switch to next arena.",
"Switch to next thread.",
"Exit Heap Explorer."
};
for (size_t i = 0; i < ARRAY_LEN(OPTIONS); i++) {
print(BLUE);
print(itoa(i + 1));
print(". ");
print(CLEAR_COLOR);
println(OPTIONS[i]);
}
print(PS1);
switch (get_number()) {
case 0: {
println("Command not recognized.");
break;
}
case 1: {
println("How many?");
print(PS2);
uint64_t count = get_number();
println("How big?");
print(PS2);
uint64_t size = get_number();
for (uint64_t i = 0; i < count; i++) {
void const *const chunk = data2chunk(malloc(size));
if (is_mmapped(chunk)) {
print("-> (mmapped)");
} else {
struct lookup_result const lookup_result =
chunk_lookup(chunk);
if (lookup_failed(lookup_result)) {
println("Couldn't find the chunk we requested. "
"Possibly, the allocation failed.");
_exit(EXIT_FAILURE);
}
print("-> [arena ");
print(itoa(lookup_result.arena));
print(", chunk ");
print(itoa(lookup_result.idx));
println("]");
}
}
break;
}
case 2: {
println("Free which chunk?");
print(PS2);
uint64_t const chunk_idx = get_number();
void *const chunk = get_chunk_by_index(arena, chunk_idx);
if (chunk != NULL) {
free_chunk(chunk);
}
break;
}
case 3: {
println("Reallocate which chunk?");
print(PS2);
uint64_t const chunk_idx = get_number();
void *const chunk = get_chunk_by_index(arena, chunk_idx);
if (chunk == NULL) {
break;
}
println("How big?");
print(PS2);
uint64_t size = get_number();
void *const result = realloc(chunk2data(chunk), size);
void const *const result_chunk = data2chunk(result);
if (is_mmapped(result_chunk)) {
print("-> (mmapped)");
} else {
struct lookup_result const lookup_result = chunk_lookup(result_chunk);
if (lookup_failed(lookup_result)) {
println("Couldn't find the chunk we requested. "
"Possibly, the reallocation failed.");
_exit(EXIT_FAILURE);
}
print("-> [arena ");
print(itoa(lookup_result.arena));
print(", chunk ");
print(itoa(lookup_result.idx));
println("]");
}
break;
}
case 4: {
print_arena(arena);
break;
}
case 5: {
println("Print which tcache list?");
print(PS2);
print_tcache_list(arena, get_number());
break;
}
case 6: {
println("Print which fastbin list?");
print(PS2);
print_fastbin_list(arena, get_number());
break;
}
case 7: {
println("Print which bin list?");
print(PS2);
print_bin_list(arena, get_number());
break;
}
case 8: {
arena = arena->next;
break;
}
case 9: {
pid_t const next_tid = get_next_tid();
syscall(SYS_tkill, next_tid, TRIGGER_SIGNAL);
return;
}
case 10: {
println("Bye!");
return;
}
default: {
println("Unrecognized command.");
break;
}
}
println("");
}
}
static void explore_heap_sighandler(int) {
explore_heap();
}
static void __attribute__((constructor)) install_signal_handler(void) {
struct sigaction sa;
sa.sa_handler = explore_heap_sighandler;
sigemptyset(&sa.sa_mask);
sa.sa_flags = SA_RESTART;
if (sigaction(TRIGGER_SIGNAL, &sa, NULL) == -1) {
println("libheap_explorer: Couldn't install signal handler!");
_exit(EXIT_FAILURE);
}
}