Skip to content
pi-c Artifact [203a5fae4b]
Login

Artifact [203a5fae4b]

Artifact 203a5fae4be967672450d05d91688b1b776fc9584ca270bcee334e743c3a64a6:


/* The host platform (see platform.h). */
#include <errno.h>
#include <fcntl.h>
#include <sys/file.h>
#include <time.h>
#include <unistd.h>
#include <sys/random.h>

#include "platform.h"

static int64_t host_wall_ns(void) {
    struct timespec ts;
    if (clock_gettime(CLOCK_REALTIME, &ts) != 0) {
        return -1;
    }
    return (int64_t)ts.tv_sec * 1000000000 + ts.tv_nsec;
}

static uint64_t host_mono_ns(void) {
    struct timespec ts;
    (void)clock_gettime(CLOCK_MONOTONIC, &ts);
    return (uint64_t)ts.tv_sec * 1000000000u + (uint64_t)ts.tv_nsec;
}

static int host_entropy(void *buf, size_t n) { return getentropy(buf, n); }

static int host_lock(const char *path) {
    int fd = open(path, O_RDWR | O_CREAT | O_CLOEXEC, 0600);
    if (fd < 0) {
        return -1;
    }
    if (flock(fd, LOCK_EX | LOCK_NB) != 0) {
        int e = errno;
        close(fd);
        errno = e;
        return -2;
    }
    return fd;
}

static void host_unlock(int handle) { close(handle); }

static const pic_platform host = {
    host_wall_ns, host_mono_ns, host_entropy, host_lock, host_unlock, pic_input_read_host, NULL,
};

static const pic_platform *current = &host;

const pic_platform *pic_platform_host(void) { return &host; }
const pic_platform *pic_platform_get(void) { return current; }
void pic_platform_set(const pic_platform *p) { current = p ? p : &host; }