navid/haze / 4aab20aa1d3fcd84f6c3892dfa837c7a9acf3b4f132cf92ec13930df341ac679 / runtime/xyzrt.cpp

xyzrt.cpp

← runtime · 26683 bytes · raw · download

#include "xyzrt.h"

#include <cstdarg>
#include <cstddef>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <new>

#if defined(_WIN32)
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#include <windows.h>
#else
#include <sys/mman.h>
#include <unistd.h>
#if !defined(MAP_ANONYMOUS) && defined(MAP_ANON)
#define MAP_ANONYMOUS MAP_ANON
#endif
#endif

namespace {

constexpr uint32_t GRANULE = 16;
constexpr uint32_t HEADER_SIZE = 8;
constexpr uint32_t LINE_SIZE = 128;
constexpr uint32_t BLOCK_SHIFT = 15;
constexpr uint32_t BLOCK_SIZE = 1u << BLOCK_SHIFT;
constexpr uint32_t LINES_PER_BLOCK = BLOCK_SIZE / LINE_SIZE;
constexpr uint32_t LARGE_THRESHOLD = 8192;
constexpr uint32_t NO_BLOCK = 0xffffffffu;
constexpr uint32_t MAX_TYPES = 1024;
constexpr uint32_t MAX_GLOBAL_ROOTS = 8192;
constexpr uint32_t MAX_PINNED = 8192;
constexpr uint32_t MAX_LARGE = 65536;
constexpr uint32_t MARK_STACK = 1u << 20;
constexpr uint64_t DEFAULT_HEAP = 64ull << 30;
constexpr uint64_t MIN_HEAP = 16ull << 20;

struct alignas(8) Header {
  uint32_t type_id;
  uint8_t mark;
  uint8_t flags;
  uint16_t aux;
};
static_assert(sizeof(Header) == 8, "Header must be 8 bytes");

enum HeaderFlags : uint8_t {
  PINNED = 1u << 0,
  REMEMBERED = 1u << 1,
  LARGE = 1u << 2,
};

enum class BlockState : uint8_t {
  FREE = 0,
  ALLOCATING,
  RECYCLABLE,
  FULL,
  EVAC_SOURCE,
  EVAC_TARGET,
  LOS_RESERVED,
};

struct BlockMeta {
  uint32_t next;
  uint16_t holes;
  uint16_t marked_lines;
  uint8_t state;
  uint8_t generation;
  uint8_t flags;
  uint8_t age;
  uint32_t owner;
};
static_assert(sizeof(BlockMeta) == 16, "BlockMeta must be 16 bytes");

struct TypeDesc {
  uint32_t size;
  uint16_t pointer_count;
  uint16_t flags;
  const uint32_t *pointer_offsets;
};

struct RootMap {
  uint32_t count;
  uint32_t frame_size;
  const uint32_t *offsets;
};

struct alignas(64) Mutator {
  void *cursor;
  void *limit;
  void *ocursor;
  void *olimit;
  void *nursery_cursor;
  void *nursery_limit;
  XyzRootFrame *root_frame;
  uint32_t thread_id;
  uint32_t flags;
  uint8_t poll;
  uint8_t reserved[7];
  uint32_t current_block;
  uint32_t overflow_block;
};

struct LargeObj {
  void *base;
  size_t size;
};

inline uint32_t align_up(uint32_t n, uint32_t a) {
  return (n + a - 1) & ~(a - 1);
}

inline uint64_t align_down64(uint64_t n, uint64_t a) {
  return n & ~(a - 1);
}

inline bool env_on(const char *name) {
  const char *v = std::getenv(name);
  return v && *v && std::strcmp(v, "0") != 0;
}

uint64_t env_u64(const char *name, uint64_t fallback) {
  const char *v = std::getenv(name);
  if (!v || !*v)
    return fallback;
  char *end = nullptr;
  unsigned long long n = std::strtoull(v, &end, 0);
  if (end == v)
    return fallback;
  if (*end == 'k' || *end == 'K')
    n <<= 10;
  else if (*end == 'm' || *end == 'M')
    n <<= 20;
  else if (*end == 'g' || *end == 'G')
    n <<= 30;
  return n;
}

#if defined(_WIN32)
void *os_reserve(size_t n) {
  return VirtualAlloc(nullptr, n, MEM_RESERVE, PAGE_NOACCESS);
}
bool os_commit(void *p, size_t n) {
  return VirtualAlloc(p, n, MEM_COMMIT, PAGE_READWRITE) != nullptr;
}
void *os_alloc_zeroed(size_t n) {
  return VirtualAlloc(nullptr, n, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
}
void os_free(void *p, size_t) {
  if (p)
    VirtualFree(p, 0, MEM_RELEASE);
}
#else
void *os_reserve(size_t n) {
  int flags = MAP_PRIVATE | MAP_ANONYMOUS;
#ifdef MAP_NORESERVE
  flags |= MAP_NORESERVE;
#endif
  void *p = mmap(nullptr, n, PROT_NONE, flags, -1, 0);
  return p == MAP_FAILED ? nullptr : p;
}
bool os_commit(void *p, size_t n) {
  return mprotect(p, n, PROT_READ | PROT_WRITE) == 0;
}
void *os_alloc_zeroed(size_t n) {
  int flags = MAP_PRIVATE | MAP_ANONYMOUS;
#ifdef MAP_NORESERVE
  flags |= MAP_NORESERVE;
#endif
  void *p = mmap(nullptr, n, PROT_READ | PROT_WRITE, flags, -1, 0);
  return p == MAP_FAILED ? nullptr : p;
}
void os_free(void *p, size_t n) {
  if (p)
    munmap(p, n);
}
#endif

struct Heap {
  uint8_t *base = nullptr;
  size_t size = 0;
  uint32_t nblocks = 0;
  BlockMeta *meta = nullptr;
  uint8_t *line_marks = nullptr;
  uint32_t free_head = NO_BLOCK;
  uint32_t recyclable_head = NO_BLOCK;

  TypeDesc types[MAX_TYPES] = {};
  uint32_t ntypes = 1;

  uint8_t epoch = 1;
  bool initialized = false;
  bool log = false;
  bool verify_mode = false;
  bool poison = false;
  uint32_t stress_n = 0;
  uint32_t stress_counter = 0;
  uint64_t collections = 0;
  uint64_t allocations = 0;
  uint64_t live_lines_last = 0;

  Mutator main_mutator = {};
  Mutator *mutator = nullptr;

  LargeObj large[MAX_LARGE] = {};
  uint32_t nlarge = 0;

  void **global_roots[MAX_GLOBAL_ROOTS] = {};
  uint32_t nroots = 0;

  void *pinned[MAX_PINNED] = {};
  uint32_t npinned = 0;

  bool gc_requested = false;

  bool init();
  bool reserve_heap(size_t wanted);
  bool init_metadata();

  Mutator *current();
  uint32_t block_index(const void *p) const {
    return static_cast<uint32_t>(
        (static_cast<const uint8_t *>(p) - base) >> BLOCK_SHIFT);
  }
  bool in_heap(const void *p) const {
    uintptr_t a = reinterpret_cast<uintptr_t>(p);
    uintptr_t b = reinterpret_cast<uintptr_t>(base);
    return p && a >= b && a < b + size;
  }
  bool is_large_object(const void *p) const {
    for (uint32_t i = 0; i < nlarge; i++)
      if (large[i].base == p)
        return true;
    return false;
  }

  uint32_t type_for_size(uint32_t total);
  uint32_t register_type(uint32_t total, uint32_t ptr_count,
                         const uint32_t *offsets);

  void *allocate(uint32_t payload, uint32_t type_id);
  void *allocate_ordinary(uint32_t total, uint32_t type_id);
  void *allocate_large(uint32_t total, uint32_t type_id);
  uint32_t acquire_block();
  void push_free(uint32_t b);
  void push_recyclable(uint32_t b);
  bool try_alloc(Mutator *m, uint32_t total, uint32_t type_id, void **out);
  bool find_hole(Mutator *m, uint32_t total);

  void collect();
  void mark_roots();
  void mark_object(void *obj);
  void sweep();
  void reset_mutator(Mutator *m);
  void verify(bool after);

  void report(const char *fmt, ...);
};

Heap g_heap;
thread_local Mutator *tls_mutator = nullptr;

bool Heap::reserve_heap(size_t wanted) {
  size_t n = wanted;
  for (;;) {
    base = static_cast<uint8_t *>(os_reserve(n));
    if (base) {
      size = n;
      nblocks = static_cast<uint32_t>(n / BLOCK_SIZE);
      return true;
    }
    if (n <= MIN_HEAP)
      return false;
    n /= 2;
  }
}

bool Heap::init_metadata() {
  size_t line_bytes = static_cast<size_t>(nblocks) * LINES_PER_BLOCK;
  line_marks = static_cast<uint8_t *>(os_alloc_zeroed(line_bytes));
  meta = static_cast<BlockMeta *>(
      os_alloc_zeroed(static_cast<size_t>(nblocks) * sizeof(BlockMeta)));
  if (!line_marks || !meta)
    return false;

  for (uint32_t i = 0; i < nblocks; i++) {
    meta[i].next = (i + 1 < nblocks) ? i + 1 : NO_BLOCK;
    meta[i].state = static_cast<uint8_t>(BlockState::FREE);
    meta[i].owner = 0xffffffffu;
  }
  free_head = nblocks ? 0 : NO_BLOCK;
  recyclable_head = NO_BLOCK;

  types[0].size = 0;
  types[0].pointer_count = 0;
  types[0].flags = 0;
  types[0].pointer_offsets = nullptr;
  ntypes = 1;
  return true;
}

bool Heap::init() {
  if (initialized)
    return true;

  log = env_on("XYZ_GC_LOG");
  verify_mode = env_on("XYZ_GC_VERIFY");
  poison = env_on("XYZ_GC_POISON");
  stress_n = static_cast<uint32_t>(env_u64("XYZ_GC_STRESS", 0));

  uint64_t wanted = env_u64("XYZ_HEAP_SIZE", DEFAULT_HEAP);
  if (wanted < MIN_HEAP)
    wanted = MIN_HEAP;
  wanted = align_down64(wanted, BLOCK_SIZE);

  for (;;) {
    if (!reserve_heap(static_cast<size_t>(wanted))) {
      report("could not reserve a %llu-byte heap",
             static_cast<unsigned long long>(wanted));
      return false;
    }
    if (init_metadata())
      break;
    os_free(line_marks, static_cast<size_t>(nblocks) * LINES_PER_BLOCK);
    os_free(meta, static_cast<size_t>(nblocks) * sizeof(BlockMeta));
    line_marks = nullptr;
    meta = nullptr;
    os_free(base, size);
    base = nullptr;
    if (wanted <= MIN_HEAP) {
      report("could not allocate collector side metadata");
      return false;
    }
    wanted /= 2;
    wanted = align_down64(wanted, BLOCK_SIZE);
  }

  std::memset(&main_mutator, 0, sizeof(main_mutator));
  main_mutator.current_block = NO_BLOCK;
  main_mutator.overflow_block = NO_BLOCK;
  mutator = &main_mutator;
  tls_mutator = &main_mutator;
  initialized = true;

  if (log)
    report("heap: %llu bytes, %u blocks, %u lines/block",
           static_cast<unsigned long long>(size), nblocks, LINES_PER_BLOCK);
  return true;
}

Mutator *Heap::current() {
  if (!initialized)
    init();
  if (!tls_mutator) {
    tls_mutator = &main_mutator;
    mutator = &main_mutator;
  }
  return tls_mutator;
}

uint32_t Heap::type_for_size(uint32_t total) {
  total = align_up(total, GRANULE);
  for (uint32_t i = 1; i < ntypes; i++)
    if (types[i].size == total && types[i].pointer_count == 0)
      return i;
  if (ntypes >= MAX_TYPES) {
    report("type table exhausted");
    std::abort();
  }
  uint32_t id = ntypes++;
  types[id].size = total;
  types[id].pointer_count = 0;
  types[id].flags = 0;
  types[id].pointer_offsets = nullptr;
  return id;
}

uint32_t Heap::register_type(uint32_t total, uint32_t ptr_count,
                             const uint32_t *offsets) {
  total = align_up(total, GRANULE);
  for (uint32_t i = 1; i < ntypes; i++)
    if (types[i].size == total && types[i].pointer_count == ptr_count &&
        types[i].pointer_offsets == offsets)
      return i;
  if (ntypes >= MAX_TYPES) {
    report("type table exhausted");
    std::abort();
  }
  uint32_t id = ntypes++;
  types[id].size = total;
  types[id].pointer_count = static_cast<uint16_t>(ptr_count);
  types[id].flags = 0;
  types[id].pointer_offsets = offsets;
  return id;
}

void Heap::push_free(uint32_t b) {
  meta[b].next = free_head;
  meta[b].state = static_cast<uint8_t>(BlockState::FREE);
  meta[b].holes = LINES_PER_BLOCK;
  meta[b].marked_lines = 0;
  free_head = b;
}

void Heap::push_recyclable(uint32_t b) {
  meta[b].next = recyclable_head;
  meta[b].state = static_cast<uint8_t>(BlockState::RECYCLABLE);
  recyclable_head = b;
}

uint32_t Heap::acquire_block() {
  Mutator *m = current();
  for (;;) {
    uint32_t b = NO_BLOCK;
    if (recyclable_head != NO_BLOCK) {
      b = recyclable_head;
      recyclable_head = meta[b].next;
      meta[b].next = NO_BLOCK;
    } else if (free_head != NO_BLOCK) {
      b = free_head;
      free_head = meta[b].next;
      meta[b].next = NO_BLOCK;

      uint8_t *block = base + static_cast<size_t>(b) * BLOCK_SIZE;
      if (!os_commit(block, BLOCK_SIZE)) {
        report("could not commit block %u", b);
        std::abort();
      }
      std::memset(block, 0, BLOCK_SIZE);
      std::memset(line_marks + static_cast<size_t>(b) * LINES_PER_BLOCK, 0,
                  LINES_PER_BLOCK);
      meta[b].holes = LINES_PER_BLOCK;
      meta[b].marked_lines = 0;
    } else {
      return NO_BLOCK;
    }

    meta[b].state = static_cast<uint8_t>(BlockState::ALLOCATING);
    meta[b].owner =
        static_cast<uint32_t>(reinterpret_cast<uintptr_t>(m) & 0xffffffffu);
    meta[b].age = 0;

    uint8_t *block = base + static_cast<size_t>(b) * BLOCK_SIZE;
    m->current_block = b;
    m->cursor = block;
    m->limit = block + BLOCK_SIZE;

    if (meta[b].marked_lines == 0) {
      std::memset(line_marks + static_cast<size_t>(b) * LINES_PER_BLOCK, 0,
                  LINES_PER_BLOCK);
      return b;
    }

    /* A recyclable block: find a hole.  mark_hole() will fail and we move on
     * when every line is live. */
    return b;
  }
}

bool Heap::find_hole(Mutator *m, uint32_t total) {
  uint32_t b = m->current_block;
  if (b == NO_BLOCK)
    return false;
  uint8_t *block = base + static_cast<size_t>(b) * BLOCK_SIZE;
  size_t off = static_cast<uint8_t *>(m->cursor) - block;
  if (off >= BLOCK_SIZE)
    return false;
  uint32_t line = static_cast<uint32_t>(off) / LINE_SIZE;
  uint32_t base_line = b * LINES_PER_BLOCK;

  while (line < LINES_PER_BLOCK) {
    if (line_marks[base_line + line] == epoch) {
      line++;
      continue;
    }
    uint32_t end = line;
    while (end < LINES_PER_BLOCK && line_marks[base_line + end] != epoch)
      end++;
    uint32_t bytes = (end - line) * LINE_SIZE;
    if (bytes >= total) {
      m->cursor = block + static_cast<size_t>(line) * LINE_SIZE;
      m->limit = block + static_cast<size_t>(end) * LINE_SIZE;
      return true;
    }
    line = end;
  }
  return false;
}

bool Heap::try_alloc(Mutator *m, uint32_t total, uint32_t type_id,
                     void **out) {
  uint8_t *p = static_cast<uint8_t *>(m->cursor);
  if (!p || p + total > static_cast<uint8_t *>(m->limit))
    return false;

  uint32_t b = m->current_block;
  if (b == NO_BLOCK)
    return false;

  uint8_t *block = base + static_cast<size_t>(b) * BLOCK_SIZE;
  uint32_t first_line = static_cast<uint32_t>(p - block) / LINE_SIZE;
  uint32_t last_line =
      static_cast<uint32_t>((p + total - 1) - block) / LINE_SIZE;
  uint32_t base_line = b * LINES_PER_BLOCK;

  m->cursor = p + total;

  Header *h = reinterpret_cast<Header *>(p);
  h->type_id = type_id;
  h->mark = 0;
  h->flags = 0;
  h->aux = 0;
  std::memset(p + HEADER_SIZE, 0, total - HEADER_SIZE);

  for (uint32_t line = first_line; line <= last_line; line++)
    line_marks[base_line + line] = epoch;

  meta[b].state = static_cast<uint8_t>(BlockState::ALLOCATING);
  allocations++;
  *out = p;
  return true;
}

void *Heap::allocate_large(uint32_t total, uint32_t type_id) {
  if (nlarge >= MAX_LARGE) {
    report("large object table exhausted");
    std::abort();
  }
  void *p = os_alloc_zeroed(total);
  if (!p)
    return nullptr;
  Header *h = static_cast<Header *>(p);
  h->type_id = type_id;
  h->mark = 0;
  h->flags = LARGE;
  h->aux = 0;
  large[nlarge].base = p;
  large[nlarge].size = total;
  nlarge++;
  allocations++;
  return p;
}

void *Heap::allocate_ordinary(uint32_t total, uint32_t type_id) {
  Mutator *m = current();

  for (uint32_t attempt = 0; attempt < 2; attempt++) {
    for (;;) {
      if (m->current_block != NO_BLOCK) {
        void *p = nullptr;
        if (try_alloc(m, total, type_id, &p))
          return p;
        if (find_hole(m, total) && try_alloc(m, total, type_id, &p))
          return p;
        meta[m->current_block].state = static_cast<uint8_t>(BlockState::FULL);
        m->current_block = NO_BLOCK;
        m->cursor = m->limit = nullptr;
      }

      uint32_t b = acquire_block();
      if (b == NO_BLOCK)
        break;
      m->current_block = b;
      uint8_t *block = base + static_cast<size_t>(b) * BLOCK_SIZE;
      m->cursor = block;
      m->limit = block + BLOCK_SIZE;

      if (meta[b].marked_lines != 0) {
        void *p = nullptr;
        if (find_hole(m, total) && try_alloc(m, total, type_id, &p))
          return p;
        meta[b].state = static_cast<uint8_t>(BlockState::FULL);
        m->current_block = NO_BLOCK;
        m->cursor = m->limit = nullptr;
        continue;
      }

      void *p = nullptr;
      if (try_alloc(m, total, type_id, &p))
        return p;
      meta[b].state = static_cast<uint8_t>(BlockState::FULL);
      m->current_block = NO_BLOCK;
      m->cursor = m->limit = nullptr;
    }
    collect();
  }
  return nullptr;
}

void *Heap::allocate(uint32_t payload, uint32_t type_id) {
  init();

  if (stress_n) {
    if (++stress_counter >= stress_n) {
      stress_counter = 0;
      collect();
    }
  }

  uint32_t total;
  if (type_id == 0) {
    total = align_up(HEADER_SIZE + payload, GRANULE);
    type_id = type_for_size(total);
  } else {
    total = types[type_id].size;
    if (total < align_up(HEADER_SIZE + payload, GRANULE))
      total = align_up(HEADER_SIZE + payload, GRANULE);
  }

  if (total > LARGE_THRESHOLD) {
    void *p = allocate_large(total, type_id);
    if (!p) {
      collect();
      p = allocate_large(total, type_id);
    }
    return p;
  }

  void *p = allocate_ordinary(total, type_id);
  if (!p) {
    collect();
    p = allocate_ordinary(total, type_id);
  }
  if (!p) {
    report("out of heap after collection");
    std::abort();
  }
  return p;
}

void Heap::mark_object(void *obj) {
  static void *stack[MARK_STACK];
  size_t sp = 0;

  if (!obj)
    return;
  stack[sp++] = obj;

  while (sp) {
    void *p = stack[--sp];
    bool large_object = is_large_object(p);
    if (!in_heap(p) && !large_object)
      continue;
    if (reinterpret_cast<uintptr_t>(p) & (GRANULE - 1))
      continue;

    Header *h = reinterpret_cast<Header *>(p);
    if (h->mark == epoch)
      continue;
    h->mark = epoch;

    if (!(h->flags & LARGE) && !large_object) {
      uint32_t b = block_index(p);
      uint8_t *block = base + static_cast<size_t>(b) * BLOCK_SIZE;
      uint32_t first = static_cast<uint32_t>(static_cast<uint8_t *>(p) - block) /
                       LINE_SIZE;
      uint32_t total = types[h->type_id].size;
      if (total == 0)
        continue;
      uint32_t last =
          static_cast<uint32_t>((static_cast<uint8_t *>(p) + total - 1) - block) /
          LINE_SIZE;
      uint32_t base_line = b * LINES_PER_BLOCK;
      for (uint32_t line = first; line <= last; line++)
        line_marks[base_line + line] = epoch;
    }

    const TypeDesc &td = types[h->type_id];
    if (td.pointer_count && td.pointer_offsets) {
      for (uint32_t i = 0; i < td.pointer_count; i++) {
        uint32_t off = td.pointer_offsets[i];
        void *child = nullptr;
        std::memcpy(&child, static_cast<uint8_t *>(p) + off, sizeof(child));
        if (child && sp < MARK_STACK)
          stack[sp++] = child;
      }
    }
  }
}

void Heap::mark_roots() {
  Mutator *m = current();

  for (XyzRootFrame *f = m->root_frame; f; f = f->previous) {
    if (!f->descriptor || !f->slots)
      continue;
    const RootMap *map = reinterpret_cast<const RootMap *>(f->descriptor);
    for (uint32_t i = 0; i < map->count; i++)
      mark_object(f->slots[i]);
  }

  for (uint32_t i = 0; i < nroots; i++) {
    if (global_roots[i])
      mark_object(*global_roots[i]);
  }

  for (uint32_t i = 0; i < npinned; i++)
    mark_object(pinned[i]);
}

void Heap::sweep() {
  uint64_t live_total = 0;

  for (uint32_t b = 0; b < nblocks; b++) {
    uint8_t state = meta[b].state;
    if (state == static_cast<uint8_t>(BlockState::FREE) ||
        state == static_cast<uint8_t>(BlockState::LOS_RESERVED))
      continue;

    uint32_t base_line = b * LINES_PER_BLOCK;
    uint32_t live = 0;
    for (uint32_t i = 0; i < LINES_PER_BLOCK; i++)
      if (line_marks[base_line + i] == epoch)
        live++;

    live_total += live;

    if (live == 0) {
      if (poison) {
        uint8_t *block = base + static_cast<size_t>(b) * BLOCK_SIZE;
        std::memset(block, 0xDD, BLOCK_SIZE);
      }
      push_free(b);
    } else if (live == LINES_PER_BLOCK) {
      meta[b].state = static_cast<uint8_t>(BlockState::FULL);
      meta[b].marked_lines = LINES_PER_BLOCK;
      meta[b].holes = 0;
    } else {
      uint32_t holes = 0;
      bool in_hole = false;
      for (uint32_t i = 0; i < LINES_PER_BLOCK; i++) {
        bool dead = line_marks[base_line + i] != epoch;
        if (dead && !in_hole) {
          holes++;
          in_hole = true;
        } else if (!dead) {
          in_hole = false;
        }
      }
      meta[b].marked_lines = static_cast<uint16_t>(live);
      meta[b].holes = static_cast<uint16_t>(holes);
      push_recyclable(b);
    }
  }

  for (uint32_t i = 0; i < nlarge;) {
    Header *h = static_cast<Header *>(large[i].base);
    if (h->mark != epoch) {
      os_free(large[i].base, large[i].size);
      large[i] = large[--nlarge];
    } else {
      i++;
    }
  }

  live_lines_last = live_total;
}

void Heap::reset_mutator(Mutator *m) {
  m->cursor = nullptr;
  m->limit = nullptr;
  m->ocursor = nullptr;
  m->olimit = nullptr;
  m->current_block = NO_BLOCK;
  m->overflow_block = NO_BLOCK;
}

void Heap::collect() {
  if (!init())
    return;

  if (verify_mode)
    verify(false);

  collections++;

  if (epoch == 255) {
    std::memset(line_marks, 0,
                static_cast<size_t>(nblocks) * LINES_PER_BLOCK);
    epoch = 1;
  } else {
    epoch++;
  }

  for (uint32_t i = 0; i < nlarge; i++) {
    Header *h = static_cast<Header *>(large[i].base);
    h->mark = 0;
  }

  /* Invalidating mutator cursors first is what makes the collection
   * stop-the-world even in the single-threaded M0 implementation. */
  reset_mutator(current());
  recyclable_head = NO_BLOCK;

  mark_roots();
  sweep();

  gc_requested = false;

  if (verify_mode)
    verify(true);

  if (log)
    report("gc #%llu epoch=%u live_lines=%llu large=%u free_head=%u",
           static_cast<unsigned long long>(collections), epoch,
           static_cast<unsigned long long>(live_lines_last), nlarge,
           free_head);
}

void Heap::verify(bool after) {
  if (!initialized)
    return;

  auto fail = [](const char *what) {
    std::fprintf(stderr, "xyzrt: heap verification failed: %s\n", what);
    std::abort();
  };

  Mutator *m = current();

  for (XyzRootFrame *f = m->root_frame; f; f = f->previous) {
    if (!f->descriptor || !f->slots)
      fail("root frame has no descriptor or slots");
    const RootMap *map = reinterpret_cast<const RootMap *>(f->descriptor);
    for (uint32_t i = 0; i < map->count; i++) {
      void *p = f->slots[i];
      if (!p)
        continue;
      if (!in_heap(p) && !is_large_object(p))
        fail("root slot points outside the heap");
      if (reinterpret_cast<uintptr_t>(p) & (GRANULE - 1))
        fail("root slot is not granule aligned");
      Header *h = static_cast<Header *>(p);
      if (h->type_id == 0)
        fail("root slot has no type descriptor");
      if (after && h->mark != epoch)
        fail("live root was not marked");
    }
  }

  for (uint32_t i = 0; i < nroots; i++)
    if (global_roots[i] && *global_roots[i] && !in_heap(*global_roots[i]))
      fail("global root points outside the heap");

  for (uint32_t i = 0; i < nlarge; i++)
    if (reinterpret_cast<uintptr_t>(large[i].base) & (GRANULE - 1))
      fail("large object is not granule aligned");

  for (uint32_t b = 0; b < nblocks; b++) {
    uint8_t state = meta[b].state;
    if (state > static_cast<uint8_t>(BlockState::LOS_RESERVED))
      fail("invalid block state");
    if (state != static_cast<uint8_t>(BlockState::FREE) &&
        state != static_cast<uint8_t>(BlockState::LOS_RESERVED) &&
        after && meta[b].marked_lines == 0 && meta[b].holes == LINES_PER_BLOCK)
      fail("allocated block has no marked lines");
  }
}

void Heap::report(const char *fmt, ...) {
  va_list ap;
  va_start(ap, fmt);
  std::vfprintf(stderr, fmt, ap);
  va_end(ap);
  std::fputc('\n', stderr);
}

} // namespace

extern "C" {

void xyz_runtime_init(void) { g_heap.init(); }

void *xyz_alloc_slow(uint32_t payload_size, uint32_t type_id) {
  return g_heap.allocate(payload_size, type_id);
}

void *xyz_alloc_large(uint32_t payload_size, uint32_t type_id) {
  g_heap.init();
  uint32_t total = align_up(HEADER_SIZE + payload_size, GRANULE);
  if (type_id == 0)
    type_id = g_heap.type_for_size(total);
  return g_heap.allocate_large(total, type_id);
}

uint32_t xyz_type_for_size(uint32_t total_size) {
  g_heap.init();
  return g_heap.type_for_size(total_size);
}

uint32_t xyz_register_type(uint32_t total_size, uint32_t pointer_count,
                           const uint32_t *pointer_offsets) {
  g_heap.init();
  return g_heap.register_type(total_size, pointer_count, pointer_offsets);
}

void xyz_gc_request(void) { g_heap.gc_requested = true; }

void xyz_gc_poll(void) {
  if (g_heap.gc_requested)
    g_heap.collect();
}

void xyz_gc_collect(void) { g_heap.collect(); }

void xyz_gc_verify(void) { g_heap.verify(true); }

int xyz_gc_object_alive(void *object) {
  if (!g_heap.initialized || !object)
    return 0;
  if (!g_heap.in_heap(object) && !g_heap.is_large_object(object))
    return 0;
  Header *h = static_cast<Header *>(object);
  return h->mark == g_heap.epoch;
}

void xyz_thread_attach(void) {
  g_heap.init();
  if (!tls_mutator) {
    Mutator *m = static_cast<Mutator *>(os_alloc_zeroed(sizeof(Mutator)));
    if (!m) {
      xyz_panic("could not allocate mutator");
      return;
    }
    m->current_block = NO_BLOCK;
    m->overflow_block = NO_BLOCK;
    tls_mutator = m;
  }
}

void xyz_thread_detach(void) { tls_mutator = nullptr; }

void xyz_root_enter(XyzRootFrame *frame) {
  if (!frame)
    return;
  Mutator *m = g_heap.current();
  frame->previous = m->root_frame;
  m->root_frame = frame;
}

void xyz_root_leave(XyzRootFrame *frame) {
  if (!frame)
    return;
  Mutator *m = g_heap.current();
  if (m->root_frame == frame) {
    m->root_frame = frame->previous;
    return;
  }
  for (XyzRootFrame *f = m->root_frame; f; f = f->previous) {
    if (f->previous == frame) {
      f->previous = frame->previous;
      return;
    }
  }
}

void xyz_root_add(void **slot) {
  g_heap.init();
  if (g_heap.nroots < MAX_GLOBAL_ROOTS)
    g_heap.global_roots[g_heap.nroots++] = slot;
}

void xyz_root_remove(void **slot) {
  for (uint32_t i = 0; i < g_heap.nroots; i++) {
    if (g_heap.global_roots[i] == slot) {
      g_heap.global_roots[i] = g_heap.global_roots[--g_heap.nroots];
      return;
    }
  }
}

void xyz_native_enter(void) {}
void xyz_native_exit(void) {}

void xyz_pin(void *object) {
  if (!object || !g_heap.in_heap(object))
    return;
  Header *h = static_cast<Header *>(object);
  h->flags |= PINNED;
  if (g_heap.npinned < MAX_PINNED)
    g_heap.pinned[g_heap.npinned++] = object;
}

void xyz_unpin(void *object) {
  if (!object)
    return;
  Header *h = static_cast<Header *>(object);
  h->flags &= ~PINNED;
  for (uint32_t i = 0; i < g_heap.npinned; i++) {
    if (g_heap.pinned[i] == object) {
      g_heap.pinned[i] = g_heap.pinned[--g_heap.npinned];
      return;
    }
  }
}

void xyz_wb(void *object, void **slot, void *value) {
  if (!object || !slot)
    return;
  *slot = value;
  Header *h = static_cast<Header *>(object);
  h->flags |= REMEMBERED;
}

void xyz_print_i32(int32_t value) { std::printf("%d\n", value); }

void xyz_print_i64(int64_t value) {
  std::printf("%lld\n", static_cast<long long>(value));
}

void xyz_print_bool(int32_t value) {
  std::fputs(value ? "true\n" : "false\n", stdout);
}

void xyz_print_str(const char *value) {
  std::fputs(value ? value : "", stdout);
  std::fputc('\n', stdout);
}

void xyz_panic(const char *message) {
  std::fprintf(stderr, "xyz: %s\n", message ? message : "panic");
  std::fflush(stderr);
  std::exit(1);
}

} // extern "C"