/home/andy/git/oilshell/oil/mycpp/bump_leak_heap.cc
Line | Count | Source |
1 | | // mycpp/bump_leak_heap.cc: Leaky Bump Allocator |
2 | | |
3 | | #include "mycpp/bump_leak_heap.h" |
4 | | |
5 | | #include <inttypes.h> // PRId64 |
6 | | #include <stddef.h> |
7 | | #include <stdio.h> |
8 | | #include <string.h> // memcpy |
9 | | #include <unistd.h> // STDERR_FILENO |
10 | | |
11 | | #include "mycpp/common.h" // aligned |
12 | | |
13 | | // We need this #ifdef because we don't want the global var in other binaries |
14 | | |
15 | | #ifdef BUMP_LEAK |
16 | | char gMemory[MiB(2000)]; // some benchmarks take more than 1 GiB |
17 | | |
18 | | // This type is for "layout"; it's not instantiated |
19 | | struct LayoutBlock { |
20 | | size_t num_bytes; |
21 | | char data[1]; // flexible array |
22 | | }; |
23 | | |
24 | | // offsetof() accounts for possible padding, but it should equal sizeof(size_t) |
25 | | const int kHeaderSize = offsetof(LayoutBlock, data); |
26 | | |
27 | | // Allocate() bumps a pointer |
28 | 4 | void* BumpLeakHeap::Allocate(size_t num_bytes) { |
29 | 4 | char* p = &(gMemory[mem_pos_]); |
30 | 4 | LayoutBlock* block = reinterpret_cast<LayoutBlock*>(p); |
31 | 4 | block->num_bytes = num_bytes; // record size for Reallocate() |
32 | | |
33 | 4 | mem_pos_ += aligned(kHeaderSize + num_bytes); |
34 | | |
35 | | // Update stats |
36 | 4 | num_allocated_++; |
37 | 4 | bytes_allocated_ += num_bytes; |
38 | | |
39 | | // log("Allocate() -> %p", block->data); |
40 | 4 | return block->data; // pointer user can write to |
41 | 4 | } |
42 | | |
43 | | // Reallocate() calls Allocate() and then copies the old data |
44 | 2 | void* BumpLeakHeap::Reallocate(void* old_data, size_t num_bytes) { |
45 | | // log(""); |
46 | | // log("Reallocate(%d) got %p", num_bytes, old_data); |
47 | 2 | char* new_data = reinterpret_cast<char*>(Allocate(num_bytes)); |
48 | | |
49 | 2 | char* p_old = reinterpret_cast<char*>(old_data) - kHeaderSize; |
50 | 2 | LayoutBlock* old_block = reinterpret_cast<LayoutBlock*>(p_old); |
51 | | |
52 | 2 | memcpy(new_data, old_block->data, old_block->num_bytes); |
53 | | |
54 | 2 | return new_data; |
55 | 2 | } |
56 | | |
57 | 4 | void BumpLeakHeap::PrintStats(int fd) { |
58 | 4 | dprintf(fd, "[BumpLeakHeap]"); |
59 | 4 | dprintf(fd, " num allocated = %10d\n", num_allocated_); |
60 | 4 | dprintf(fd, "bytes allocated = %10" PRId64 "\n", bytes_allocated_); |
61 | 4 | dprintf(fd, " mem pos = %10d\n", mem_pos_); |
62 | 4 | } |
63 | | |
64 | 2 | void BumpLeakHeap::CleanProcessExit() { |
65 | 2 | PrintStats(STDERR_FILENO); |
66 | 2 | } |
67 | | |
68 | 1 | void BumpLeakHeap::FastProcessExit() { |
69 | 1 | PrintStats(STDERR_FILENO); |
70 | 1 | } |
71 | | |
72 | | BumpLeakHeap gHeap; |
73 | | #endif |