cpp

Coverage Report

Created: 2025-05-10 05:26

/home/uke/oil/mycpp/mark_sweep_heap.cc
Line
Count
Source (jump to first uncovered line)
1
#include "mycpp/mark_sweep_heap.h"
2
3
#include <inttypes.h>  // PRId64
4
#include <stdlib.h>    // getenv()
5
#include <string.h>    // strlen()
6
#include <sys/time.h>  // gettimeofday()
7
#include <time.h>      // clock_gettime(), CLOCK_PROCESS_CPUTIME_ID
8
#include <unistd.h>    // STDERR_FILENO
9
10
#include "_build/detected-cpp-config.h"  // for GC_TIMING
11
#include "mycpp/gc_builtins.h"           // StringToInt()
12
#include "mycpp/gc_slab.h"
13
14
// TODO: Remove this guard when we have separate binaries
15
#if MARK_SWEEP
16
17
77
void MarkSweepHeap::Init() {
18
77
  Init(1000);  // collect at 1000 objects in tests
19
77
}
20
21
79
void MarkSweepHeap::Init(int gc_threshold) {
22
79
  gc_threshold_ = gc_threshold;
23
24
79
  char* e;
25
79
  e = getenv("OILS_GC_THRESHOLD");
26
79
  if (e) {
27
0
    int result;
28
0
    if (StringToInt(e, strlen(e), 10, &result)) {
29
      // Override collection threshold
30
0
      gc_threshold_ = result;
31
0
    }
32
0
  }
33
34
  // only for developers
35
79
  e = getenv("_OILS_GC_VERBOSE");
36
79
  if (e && strcmp(e, "1") == 0) {
37
0
    gc_verbose_ = true;
38
0
  }
39
40
79
  live_objs_.reserve(KiB(10));
41
79
  roots_.reserve(KiB(1));  // prevent resizing in common case
42
79
}
43
44
1.07k
int MarkSweepHeap::MaybeCollect() {
45
  // Maybe collect BEFORE allocation, because the new object won't be rooted
46
  #if GC_ALWAYS
47
  int result = Collect();
48
  #else
49
1.07k
  int result = -1;
50
1.07k
  if (num_live() > gc_threshold_) {
51
9
    result = Collect();
52
9
  }
53
1.07k
  #endif
54
55
1.07k
  num_gc_points_++;  // this is a manual collection point
56
1.07k
  return result;
57
1.07k
}
58
59
  #if defined(BUMP_SMALL)
60
    #include "mycpp/bump_leak_heap.h"
61
62
BumpLeakHeap gBumpLeak;
63
  #endif
64
65
// Allocate and update stats
66
// TODO: Make this interface nicer.
67
16.9k
void* MarkSweepHeap::Allocate(size_t num_bytes, int* obj_id, int* pool_id) {
68
  // log("Allocate %d", num_bytes);
69
16.9k
  #ifndef NO_POOL_ALLOC
70
16.9k
  if (num_bytes <= pool1_.kMaxObjSize) {
71
10.7k
    *pool_id = 1;
72
10.7k
    return pool1_.Allocate(obj_id);
73
10.7k
  }
74
6.24k
  if (num_bytes <= pool2_.kMaxObjSize) {
75
4.79k
    *pool_id = 2;
76
4.79k
    return pool2_.Allocate(obj_id);
77
4.79k
  }
78
1.44k
  *pool_id = 0;  // malloc(), not a pool
79
1.44k
  #endif
80
81
  // Does the pool allocator approximate a bump allocator?  Use pool2_
82
  // threshold of 48 bytes.
83
  // These only work with GC off -- OILS_GC_THRESHOLD=[big]
84
  #ifdef BUMP_SMALL
85
  if (num_bytes <= 48) {
86
    return gBumpLeak.Allocate(num_bytes);
87
  }
88
  #endif
89
90
1.44k
  if (to_free_.empty()) {
91
    // Use higher object IDs
92
1.28k
    *obj_id = greatest_obj_id_;
93
1.28k
    greatest_obj_id_++;
94
95
    // This check is ON in release mode
96
1.28k
    CHECK(greatest_obj_id_ <= kMaxObjId);
97
1.28k
  } else {
98
164
    ObjHeader* dead = to_free_.back();
99
164
    to_free_.pop_back();
100
101
164
    *obj_id = dead->obj_id;  // reuse the dead object's ID
102
103
164
    free(dead);
104
164
  }
105
106
0
  void* result = malloc(num_bytes);
107
1.44k
  DCHECK(result != nullptr);
108
109
0
  live_objs_.push_back(static_cast<ObjHeader*>(result));
110
111
1.44k
  num_live_++;
112
1.44k
  num_allocated_++;
113
1.44k
  bytes_allocated_ += num_bytes;
114
115
1.44k
  return result;
116
6.24k
}
117
118
  #if 0
119
void* MarkSweepHeap::Reallocate(void* p, size_t num_bytes) {
120
  FAIL(kNotImplemented);
121
  // This causes a double-free in the GC!
122
  // return realloc(p, num_bytes);
123
}
124
  #endif
125
126
// "Leaf" for marking / TraceChildren
127
//
128
// - Abort if nullptr
129
// - Find the header (get rid of this when remove ObjHeader member)
130
// - Tag::{Opaque,FixedSized,Scanned} have their mark bits set
131
// - Tag::{FixedSize,Scanned} are also pushed on the gray stack
132
133
2.23k
void MarkSweepHeap::MaybeMarkAndPush(RawObject* obj) {
134
2.23k
  ObjHeader* header = ObjHeader::FromObject(obj);
135
2.23k
  if (header->heap_tag == HeapTag::Global) {  // don't mark or push
136
322
    return;
137
322
  }
138
139
1.91k
  int obj_id = header->obj_id;
140
1.91k
  #ifndef NO_POOL_ALLOC
141
1.91k
  if (header->pool_id == 1) {
142
1.61k
    if (pool1_.IsMarked(obj_id)) {
143
145
      return;
144
145
    }
145
1.47k
    pool1_.Mark(obj_id);
146
1.47k
  } else if (header->pool_id == 2) {
147
276
    if (pool2_.IsMarked(obj_id)) {
148
56
      return;
149
56
    }
150
220
    pool2_.Mark(obj_id);
151
220
  } else
152
19
  #endif
153
19
  {
154
19
    if (mark_set_.IsMarked(obj_id)) {
155
0
      return;
156
0
    }
157
19
    mark_set_.Mark(obj_id);
158
19
  }
159
160
1.71k
  switch (header->heap_tag) {
161
235
  case HeapTag::Opaque:  // e.g. strings have no children
162
235
    break;
163
164
1.30k
  case HeapTag::Scanned:  // these 2 types have children
165
1.47k
  case HeapTag::FixedSize:
166
1.47k
    gray_stack_.push_back(header);  // Push the header, not the object!
167
1.47k
    break;
168
169
0
  default:
170
0
    FAIL(kShouldNotGetHere);
171
1.71k
  }
172
1.71k
}
173
174
128
void MarkSweepHeap::TraceChildren() {
175
1.60k
  while (!gray_stack_.empty()) {
176
1.47k
    ObjHeader* header = gray_stack_.back();
177
1.47k
    gray_stack_.pop_back();
178
179
1.47k
    switch (header->heap_tag) {
180
171
    case HeapTag::FixedSize: {
181
171
      auto fixed = reinterpret_cast<LayoutFixed*>(header->ObjectAddress());
182
171
      int mask = FIELD_MASK(*header);
183
184
4.27k
      for (int i = 0; i < kFieldMaskBits; ++i) {
185
4.10k
        if (mask & (1 << i)) {
186
181
          RawObject* child = fixed->children_[i];
187
181
          if (child) {
188
153
            MaybeMarkAndPush(child);
189
153
          }
190
181
        }
191
4.10k
      }
192
171
      break;
193
0
    }
194
195
1.30k
    case HeapTag::Scanned: {
196
1.30k
      auto slab = reinterpret_cast<Slab<RawObject*>*>(header->ObjectAddress());
197
198
1.30k
      int n = NUM_POINTERS(*header);
199
3.43k
      for (int i = 0; i < n; ++i) {
200
2.13k
        RawObject* child = slab->items_[i];
201
2.13k
        if (child) {
202
1.88k
          MaybeMarkAndPush(child);
203
1.88k
        }
204
2.13k
      }
205
1.30k
      break;
206
0
    }
207
0
    default:
208
      // Only FixedSize and Scanned are pushed
209
0
      FAIL(kShouldNotGetHere);
210
1.47k
    }
211
1.47k
  }
212
128
}
213
214
128
void MarkSweepHeap::Sweep() {
215
128
  #ifndef NO_POOL_ALLOC
216
128
  pool1_.Sweep();
217
128
  pool2_.Sweep();
218
128
  #endif
219
220
128
  int last_live_index = 0;
221
128
  int num_objs = live_objs_.size();
222
1.59k
  for (int i = 0; i < num_objs; ++i) {
223
1.46k
    ObjHeader* obj = live_objs_[i];
224
1.46k
    DCHECK(obj);  // malloc() shouldn't have returned nullptr
225
226
0
    bool is_live = mark_set_.IsMarked(obj->obj_id);
227
228
    // Compact live_objs_ and populate to_free_.  Note: doing the reverse could
229
    // be more efficient when many objects are dead.
230
1.46k
    if (is_live) {
231
19
      live_objs_[last_live_index++] = obj;
232
1.44k
    } else {
233
1.44k
      to_free_.push_back(obj);
234
      // free(obj);
235
1.44k
      num_live_--;
236
1.44k
    }
237
1.46k
  }
238
128
  live_objs_.resize(last_live_index);  // remove dangling objects
239
240
128
  num_collections_++;
241
128
  max_survived_ = std::max(max_survived_, num_live());
242
128
}
243
244
128
int MarkSweepHeap::Collect() {
245
128
  #ifdef GC_TIMING
246
128
  struct timespec start, end;
247
128
  if (clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &start) < 0) {
248
0
    FAIL("clock_gettime failed");
249
0
  }
250
0
  #endif
251
252
0
  int num_roots = roots_.size();
253
128
  int num_globals = global_roots_.size();
254
255
128
  if (gc_verbose_) {
256
0
    log("");
257
0
    log("%2d. GC with %d roots (%d global) and %d live objects",
258
0
        num_collections_, num_roots + num_globals, num_globals, num_live());
259
0
  }
260
261
  // Resize it
262
128
  mark_set_.ReInit(greatest_obj_id_);
263
128
  #ifndef NO_POOL_ALLOC
264
128
  pool1_.PrepareForGc();
265
128
  pool2_.PrepareForGc();
266
128
  #endif
267
268
  // Mark roots.
269
  // Note: It might be nice to get rid of double pointers
270
390
  for (int i = 0; i < num_roots; ++i) {
271
262
    RawObject* root = *(roots_[i]);
272
262
    if (root) {
273
186
      MaybeMarkAndPush(root);
274
186
    }
275
262
  }
276
277
136
  for (int i = 0; i < num_globals; ++i) {
278
8
    RawObject* root = global_roots_[i];
279
8
    if (root) {
280
8
      MaybeMarkAndPush(root);
281
8
    }
282
8
  }
283
284
  // Traverse object graph.
285
128
  TraceChildren();
286
287
128
  Sweep();
288
289
128
  if (gc_verbose_) {
290
0
    log("    %d live after sweep", num_live());
291
0
  }
292
293
  // We know how many are live.  If the number of objects is close to the
294
  // threshold (above 75%), then set the threshold to 2 times the number of
295
  // live objects.  This is an ad hoc policy that removes observed "thrashing"
296
  // -- being at 99% of the threshold and doing FUTILE mark and sweep.
297
298
128
  int water_mark = (gc_threshold_ * 3) / 4;
299
128
  if (num_live() > water_mark) {
300
0
    gc_threshold_ = num_live() * 2;
301
0
    num_growths_++;
302
0
    if (gc_verbose_) {
303
0
      log("    exceeded %d live objects; gc_threshold set to %d", water_mark,
304
0
          gc_threshold_);
305
0
    }
306
0
  }
307
308
128
  #ifdef GC_TIMING
309
128
  if (clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &end) < 0) {
310
0
    FAIL("clock_gettime failed");
311
0
  }
312
313
0
  double start_secs = start.tv_sec + start.tv_nsec / 1e9;
314
128
  double end_secs = end.tv_sec + end.tv_nsec / 1e9;
315
128
  double gc_millis = (end_secs - start_secs) * 1000.0;
316
317
128
  if (gc_verbose_) {
318
0
    log("    %.1f ms GC", gc_millis);
319
0
  }
320
321
128
  total_gc_millis_ += gc_millis;
322
128
  if (gc_millis > max_gc_millis_) {
323
69
    max_gc_millis_ = gc_millis;
324
69
  }
325
128
  #endif
326
327
128
  return num_live();  // for unit tests only
328
128
}
329
330
0
void MarkSweepHeap::PrintShortStats() {
331
0
  #ifndef NO_POOL_ALLOC
332
0
  int fd = 2;
333
0
  dprintf(fd, "  num allocated    = %10d\n",
334
0
          num_allocated_ + pool1_.num_allocated() + pool2_.num_allocated());
335
0
  dprintf(
336
0
      fd, "bytes allocated    = %10" PRId64 "\n",
337
0
      bytes_allocated_ + pool1_.bytes_allocated() + pool2_.bytes_allocated());
338
0
  #endif
339
0
}
340
341
6
void MarkSweepHeap::PrintStats(int fd) {
342
6
  dprintf(fd, "  num live         = %10d\n", num_live());
343
  // max survived_ can be less than num_live(), because leave off the last GC
344
6
  dprintf(fd, "  max survived     = %10d\n", max_survived_);
345
6
  dprintf(fd, "\n");
346
347
6
  #ifndef NO_POOL_ALLOC
348
6
  dprintf(fd, "  num allocated    = %10d\n",
349
6
          num_allocated_ + pool1_.num_allocated() + pool2_.num_allocated());
350
6
  dprintf(fd, "  num in heap      = %10d\n", num_allocated_);
351
  #else
352
  dprintf(fd, "  num allocated    = %10d\n", num_allocated_);
353
  #endif
354
355
6
  #ifndef NO_POOL_ALLOC
356
6
  dprintf(fd, "  num in pool 1    = %10d\n", pool1_.num_allocated());
357
6
  dprintf(fd, "  num in pool 2    = %10d\n", pool2_.num_allocated());
358
6
  dprintf(
359
6
      fd, "bytes allocated    = %10" PRId64 "\n",
360
6
      bytes_allocated_ + pool1_.bytes_allocated() + pool2_.bytes_allocated());
361
  #else
362
  dprintf(fd, "bytes allocated    = %10" PRId64 "\n", bytes_allocated_);
363
  #endif
364
365
6
  dprintf(fd, "\n");
366
6
  dprintf(fd, "  num gc points    = %10d\n", num_gc_points_);
367
6
  dprintf(fd, "  num collections  = %10d\n", num_collections_);
368
6
  dprintf(fd, "\n");
369
6
  dprintf(fd, "   gc threshold    = %10d\n", gc_threshold_);
370
6
  dprintf(fd, "  num growths      = %10d\n", num_growths_);
371
6
  dprintf(fd, "\n");
372
6
  dprintf(fd, "  max gc millis    = %10.1f\n", max_gc_millis_);
373
6
  dprintf(fd, "total gc millis    = %10.1f\n", total_gc_millis_);
374
6
  dprintf(fd, "\n");
375
6
  dprintf(fd, "roots capacity     = %10d\n",
376
6
          static_cast<int>(roots_.capacity()));
377
6
  dprintf(fd, " objs capacity     = %10d\n",
378
6
          static_cast<int>(live_objs_.capacity()));
379
6
}
380
381
// Cleanup at the end of main() to remain ASAN-safe
382
65
void MarkSweepHeap::MaybePrintStats() {
383
65
  int stats_fd = -1;
384
65
  char* e = getenv("OILS_GC_STATS");
385
65
  if (e && strlen(e)) {  // env var set and non-empty
386
0
    stats_fd = STDERR_FILENO;
387
65
  } else {
388
    // A raw file descriptor lets benchmarks extract stats even if the script
389
    // writes to stdout and stderr.  Shells can't use open() without potential
390
    // conflicts.
391
392
65
    e = getenv("OILS_GC_STATS_FD");
393
65
    if (e && strlen(e)) {
394
      // Try setting 'stats_fd'.  If there's an error, it will be unchanged, and
395
      // we don't PrintStats();
396
0
      StringToInt(e, strlen(e), 10, &stats_fd);
397
0
    }
398
65
  }
399
400
65
  if (stats_fd != -1) {
401
0
    PrintStats(stats_fd);
402
0
  }
403
65
}
404
405
63
void MarkSweepHeap::FreeEverything() {
406
63
  roots_.clear();
407
63
  global_roots_.clear();
408
409
63
  Collect();
410
411
  // Collect() told us what to free()
412
1.28k
  for (auto obj : to_free_) {
413
1.28k
    free(obj);
414
1.28k
  }
415
63
  #ifndef NO_POOL_ALLOC
416
63
  pool1_.Free();
417
63
  pool2_.Free();
418
63
  #endif
419
63
}
420
421
63
void MarkSweepHeap::CleanProcessExit() {
422
63
  MaybePrintStats();
423
424
63
  char* e = getenv("OILS_GC_ON_EXIT");
425
  // collect by default; OILS_GC_ON_EXIT=0 overrides
426
63
  if (e && strcmp(e, "0") == 0) {
427
0
    ;
428
63
  } else {
429
63
    FreeEverything();
430
63
  }
431
63
}
432
433
// for the main binary
434
2
void MarkSweepHeap::ProcessExit() {
435
2
  MaybePrintStats();
436
437
  #ifdef CLEAN_PROCESS_EXIT
438
  FreeEverything();
439
  #else
440
2
  char* e = getenv("OILS_GC_ON_EXIT");
441
  // don't collect by default; OILS_GC_ON_EXIT=1 overrides
442
2
  if (e && strcmp(e, "1") == 0) {
443
0
    FreeEverything();
444
0
  }
445
2
  #endif
446
2
}
447
448
MarkSweepHeap gHeap;
449
450
#endif  // MARK_SWEEP