navid/haze / 410cf353c8bebfa56a4099714ad9c7b96a5835655bb2a68a9416269d91a86ce7 / tests/runtime_test.cpp

runtime_test.cpp

← tests · 2833 bytes · raw · download

#include "hazert.h"

#include <cstdio>
#include <cstdlib>

namespace {

int failures = 0;

void check(bool ok, const char* what) {
    if (!ok) {
        std::fprintf(stderr, "FAIL: %s\n", what);
        failures++;
    }
}

} // namespace

int main() {
    haze_runtime_init();

    /* A descriptor with two managed pointer fields. */
    static const uint32_t offsets[] = {8, 16};
    uint32_t parent_type = haze_register_type(32, 2, offsets);

    void* child = haze_alloc_slow(16, 0);
    void* parent = haze_alloc_slow(16, parent_type);
    check(child && parent, "allocation");
    *reinterpret_cast<void**>(static_cast<unsigned char*>(parent) + 8) = child;

    void* root = parent;
    haze_root_add(&root);
    haze_gc_collect();
    haze_gc_verify();
    check(haze_gc_object_alive(parent), "parent kept by global root");
    check(haze_gc_object_alive(child), "child traced through descriptor");

    haze_root_remove(&root);
    parent = nullptr;
    child = nullptr;
    haze_gc_collect();
    haze_gc_verify();

    /* Medium object. */
    void* medium = haze_alloc_slow(4000, 0);
    check(medium != nullptr, "medium allocation");
    root = medium;
    haze_root_add(&root);
    haze_gc_collect();
    check(haze_gc_object_alive(medium), "medium object survives");
    haze_root_remove(&root);

    /* Large object space. */
    void* large = haze_alloc_large(10000, 0);
    check(large != nullptr, "large allocation");
    root = large;
    haze_root_add(&root);
    haze_gc_collect();
    check(haze_gc_object_alive(large), "large object survives");
    haze_root_remove(&root);
    haze_gc_collect();
    check(!haze_gc_object_alive(large), "large object reclaimed");

    /* Shadow-stack frame. */
    void* slot[1] = {nullptr};
    static const uint32_t root_offsets[] = {0};
    HazeRootMap map = {1, 24, root_offsets};
    HazeRootFrame frame = {nullptr, &map, slot};
    slot[0] = haze_alloc_slow(64, 0);
    haze_root_enter(&frame);
    haze_gc_collect();
    haze_gc_verify();
    check(haze_gc_object_alive(slot[0]), "object kept by root frame");
    haze_root_leave(&frame);
    haze_gc_collect();
    check(!haze_gc_object_alive(slot[0]), "object collected after root leave");

    /* Epoch wraparound smoke test. */
    void* stable = haze_alloc_slow(32, 0);
    root = stable;
    haze_root_add(&root);
    for (int i = 0; i < 300; i++) {
        haze_gc_collect();
        if (!haze_gc_object_alive(stable)) {
            check(false, "stable object survived epoch wrap");
            break;
        }
    }
    haze_root_remove(&root);
    haze_gc_collect();
    check(!haze_gc_object_alive(stable), "stable object reclaimed");

    if (failures) {
        std::fprintf(stderr, "%d runtime test(s) failed\n", failures);
        return 1;
    }
    std::puts("runtime tests passed");
    return 0;
}