Skip to content
pi-c Artifact [b6a9410020]
Login

Artifact [b6a9410020]

Artifact b6a94100204d892e3a213ce30f347a3facf105633ddcdc004c0bac3e63fa63a2:


/* The host executor's file operations: stat, read, write, mkdir, list,
 * remove, with the errno values the tools report. */
#include <assert.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>

#include "pic.h"

static int count(void *cb_state, const char *entry) {
    assert(strcmp(entry, ".") != 0 && strcmp(entry, "..") != 0);
    ++*(int *)cb_state;
    return 0;
}

static int stop(void *cb_state, const char *entry) {
    (void)cb_state;
    (void)entry;
    return 42;
}

int main(void) {
    const pic_executor *ex = pic_executor_get();
    const char *tmp = getenv("TMPDIR");
    char dir[512], sub[600], file[600];
    char *buf = NULL;
    size_t len = 0;
    pic_file_stat st;
    int n = 0;
    assert(ex == pic_executor_host());
    (void)snprintf(dir, sizeof dir, "%s/pic-files-XXXXXX", tmp && *tmp ? tmp : "/tmp");
    assert(mkdtemp(dir));
    (void)snprintf(sub, sizeof sub, "%s/sub", dir);
    (void)snprintf(file, sizeof file, "%s/sub/f.txt", dir);

    /* Files are created as POSIX does: the process umask applies. */
    mode_t um = umask(0);
    (void)umask(um);
    assert(ex->mkdir(ex->state, sub) == 0);
    assert(ex->mkdir(ex->state, sub) == EEXIST);
    assert(ex->stat(ex->state, file, &st) == ENOENT);
    assert(ex->write(ex->state, file, "hello", 5, 0600) == 0);
    assert(ex->stat(ex->state, file, &st) == 0 && !st.is_dir && st.size == 5 && st.mode == (0600 & ~(unsigned)um));
    assert(ex->stat(ex->state, sub, &st) == 0 && st.is_dir);
    assert(ex->write(ex->state, file, "bye", 3, 0644) == 0); /* replaced, with the new mode */
    assert(ex->stat(ex->state, file, &st) == 0 && st.size == 3 && st.mode == (0644 & ~(unsigned)um));

    assert(ex->read(ex->state, file, 1024, PIC_FILE_WRITABLE, &buf, &len) == 0);
    assert(len == 3 && strcmp(buf, "bye") == 0);
    free(buf);
    assert(ex->read(ex->state, file, 2, 0, &buf, &len) == EFBIG);
    assert(ex->read(ex->state, sub, 1024, 0, &buf, &len) == EISDIR);

    assert(ex->list(ex->state, sub, count, &n) == 0 && n == 1);
    assert(ex->list(ex->state, sub, stop, NULL) == 42);
    assert(ex->list(ex->state, file, count, &n) == ENOTDIR);

    assert(ex->remove(ex->state, file) == 0);
    assert(ex->remove(ex->state, file) == ENOENT);
    assert(ex->read(ex->state, file, 1024, 0, &buf, &len) == ENOENT);
    n = 0;
    assert(ex->list(ex->state, sub, count, &n) == 0 && n == 0);
    assert(rmdir(sub) == 0 && rmdir(dir) == 0);
    puts("PASS: host executor files");
    return 0;
}