// Fuzz target for the project files. The first byte picks the format: 'r' roots,
// 'p' projects, 's' projects.set, 'g' a git config, 'u' a remote address.
// Whatever parses must write back out and parse again to the same entries, a key
// must satisfy project_key_ok, and a git config's address must fit.
#include "project.h"
#include "platform.h"
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
static Roots roots_a;
static Roots roots_b;
static Projects proj_a;
static Projects proj_b;
static char path[4096 + 8];
static char text[PROJECT_FILE_MAX + 1];
int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size);
static void same_projects(const Projects *a, const Projects *b)
{
ensure(a->n == b->n);
for (uint32_t i = 0; i < a->n; i++) {
// written sorted by path, so look each one up
[[maybe_unused]] const ProjectEntry *e = projects_find(b, a->e[i].path);
ensure(e != nullptr && strcmp(e->key, a->e[i].key) == 0 && e->kind == a->e[i].kind);
}
}
static void address(char *s, size_t len)
{
char url[PROJECT_URL_MAX];
char key[PROJECT_KEY_MAX + 1];
if (project_git_remote(s, len, url, sizeof url)) s = url;
if (project_key_from_url(s, key, sizeof key)) ensure(project_key_ok(key));
else ensure(key[0] == '\0');
}
int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size)
{
if (size == 0) return 0;
if (path[0] == '\0') {
const char *tmp = getenv("TMPDIR");
char dir[4096];
snprintf(dir, sizeof dir, "%s/suit-fuzz-project.XXXXXX", tmp != nullptr ? tmp : "/tmp");
if (mkdtemp(dir) == nullptr) abort();
snprintf(path, sizeof path, "%s/file", dir);
}
char kind = (char)data[0];
const char *body = (const char *)data + 1;
size_t len = size - 1;
ProjectError e;
if (kind == 'r') {
if (!roots_parse(&roots_a, body, len, &e)) {
ensure(e.msg[0] != '\0' && roots_a.n == 0);
return 0;
}
[[maybe_unused]] int w = roots_write(&roots_a, path);
ensure(w == 0);
[[maybe_unused]] bool again = roots_load(&roots_b, path, &e);
ensure(again && roots_b.n == roots_a.n);
for (uint32_t i = 0; i < roots_a.n; i++) ensure(strcmp(roots_a.path[i], roots_b.path[i]) == 0);
} else if (kind == 'p' || kind == 's') {
bool with_kind = kind == 'p';
if (!projects_parse(&proj_a, body, len, with_kind, &e)) {
ensure(e.msg[0] != '\0' && proj_a.n == 0);
return 0;
}
[[maybe_unused]] int w = projects_write(&proj_a, path, with_kind);
ensure(w == 0);
[[maybe_unused]] bool again = projects_load(&proj_b, path, with_kind, &e);
ensure(again);
same_projects(&proj_a, &proj_b);
} else if (len <= PROJECT_FILE_MAX) {
memcpy(text, body, len);
text[len] = '\0';
address(text, len);
}
return 0;
}