Skip to content
suit Artifact [acd67ca31b]
Login

Artifact [acd67ca31b]

Artifact acd67ca31bfe850e1206cfe1ba9e924ebad5bce94c1ef676cc223aa9e1239dfb:


#include "join.h"

#include "platform.h"

#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>

// The sources, for each but the last the newline that ends it and the blank line,
// and one byte more to tell that a file is too long.
constexpr size_t BUF_SIZE = JOIN_SOURCES_MAX * JOIN_SOURCE_MAX + 2 * (JOIN_SOURCES_MAX - 1) + 1;

static char built[BUF_SIZE];
static char current[BUF_SIZE];

// Read up to CAP bytes of PATH into BUF. Returns 0 or an errno value.
static int read_into(const char *path, char *buf, size_t cap, size_t *len)
{
    *len = 0;
    int fd = sys_open(path, O_RDONLY, 0);
    if (fd < 0) return errno;
    ssize_t n = 1;
    while (*len < cap && n > 0) {
        n = sys_read(fd, buf + *len, cap - *len);
        if (n < 0 && errno == EINTR) {
            n = 1;
            continue;
        }
        *len += n > 0 ? (size_t)n : 0;
    }
    int err = n < 0 ? errno : 0;
    (void)sys_close(fd);
    return err;
}

// Append the source at PATH to BUILT, which holds *LEN bytes.
static int add_source(const char *path, size_t *len)
{
    size_t n;
    int err = read_into(path, built + *len, JOIN_SOURCE_MAX + 1, &n);
    if (err == 0 && n > JOIN_SOURCE_MAX) err = EFBIG;
    if (err != 0) {
        say(STDERR_FILENO, "suit: cannot read %s: %s\n", path,
            err == EFBIG ? "over 512 KiB, too long to join" : strerror(err));
        return 1;
    }
    *len += n;
    return 0;
}

// The sources in order, a blank line between each and the next.
static int build(const Join *j, size_t *len)
{
    *len = 0;
    for (uint32_t i = 0; i < j->n; i++) {
        if (i > 0) {
            // The blank line: end the last source's last line if it has no newline.
            bool ends_line = *len > 0 && built[*len - 1] == '\n';
            if (!ends_line) built[(*len)++] = '\n';
            built[(*len)++] = '\n';
        }
        if (add_source(j->src[i], len) != 0) return 1;
    }
    return 0;
}

int join_current(const Join *j)
{
    size_t want;
    if (build(j, &want) != 0) return -1;
    size_t have;
    int err = read_into(j->path, current, sizeof current, &have);
    // A file that cannot be read is not the joined content: it gets rewritten.
    return err == 0 && have == want && memcmp(current, built, want) == 0;
}

int join_write(const Join *j)
{
    size_t len;
    if (build(j, &len) != 0) return 1;
    int err = sys_write_atomic(j->path, built, len);
    if (err != 0) say(STDERR_FILENO, "suit: cannot write %s: %s\n", j->path, strerror(err));
    return err == 0 ? 0 : 1;
}