Skip to content

A 2.78-trillion-parameter Kimi K3 running inference on a single CPU in 8.24 GB of RAM. Portable C99: no BLAS, no framework, no GPU.

fix(json): refuse truncated and malformed documents

Fareed Khan6680ec7eb98c
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index fc2ea87..0b52ca7 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -175,7 +175,7 @@ jobs:
run: |
make CC=clang CFLAGS="-O1 -g -std=gnu99 -Wall -Wextra -fsanitize=address,undefined -fno-omit-frame-pointer" \
LDFLAGS="-lm -fsanitize=address,undefined -lpsapi -lwinpthread" ARCH= \
- bin/test_ops bin/test_cfg bin/test_cache bin/test_st bin/test_st_faults bin/k3_model
+ bin/test_ops bin/test_cfg bin/test_cache bin/test_st bin/test_st_faults bin/test_json bin/k3_model
cp /clang64/bin/libclang_rt.asan_dynamic-x86_64.dll /clang64/bin/libwinpthread-1.dll /clang64/bin/libc++.dll bin/
- name: Run under sanitizers
env:
@@ -191,6 +191,7 @@ jobs:
./bin/test_st.exe tests/fixtures/st /tmp/idx.json \
plain.f32.2d plain.bf16.1d tricky.f16.1d packed.u8.2d scalar.f32 second.shard.f32
./bin/test_st_faults.exe tests/fixtures/st /tmp/stfault
+ ./bin/test_json.exe
./bin/k3_model.exe tests/fixtures
# CMakeLists.txt documents itself as staying interchangeable with the Make build, but
@@ -246,7 +247,7 @@ jobs:
run: |
make CFLAGS="-O1 -g -std=gnu99 -Wall -Wextra -fsanitize=address,undefined -fno-omit-frame-pointer" \
LDFLAGS="-lm -fsanitize=address,undefined" ARCH= \
- bin/test_ops bin/test_cfg bin/test_cache bin/test_st bin/test_st_faults \
+ bin/test_ops bin/test_cfg bin/test_cache bin/test_st bin/test_st_faults bin/test_json \
bin/test_model_stream bin/k3_model \
bin/bench_kernels \
-j"$(nproc)"
@@ -264,6 +265,7 @@ jobs:
./bin/test_st tests/fixtures/st "$RUNNER_TEMP/idx.json" \
plain.f32.2d plain.bf16.1d tricky.f16.1d packed.u8.2d scalar.f32 second.shard.f32
./bin/test_st_faults tests/fixtures/st "$RUNNER_TEMP/stfault"
+ ./bin/test_json
./bin/test_model_stream tests/fixtures/st
./bin/k3_model tests/fixtures
# The ms and GFLOP/s it prints are meaningless under -O1 with ASan interceptors
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 3a63e69..26e4565 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -151,6 +151,7 @@ k3_add_test(test_cfg tests/unit/test_cfg.c)
k3_add_test(test_tok tests/unit/test_tok.c)
k3_add_test(test_chat tests/unit/test_chat.c)
k3_add_test(test_st_faults tests/unit/test_st_faults.c)
+k3_add_test(test_json tests/unit/test_json.c)
target_link_libraries(test_chat PRIVATE k3_chat)
k3_add_test(scale_test tests/unit/scale_test.c)
k3_add_test(test_trunk tests/unit/test_trunk.c)
@@ -188,6 +189,7 @@ add_test(NAME config_reject_bad_topk
add_test(NAME safetensors COMMAND test_st ${FIX}/st ${CMAKE_CURRENT_BINARY_DIR}/idx.json
plain.f32.2d plain.bf16.1d tricky.f16.1d packed.u8.2d scalar.f32 second.shard.f32)
add_test(NAME shard_faults COMMAND test_st_faults ${FIX}/st ${CMAKE_CURRENT_BINARY_DIR}/stfault)
+add_test(NAME json_refusals COMMAND test_json)
add_test(NAME model_stream COMMAND test_model_stream ${FIX}/st)
add_test(NAME ultra_cli_contract
COMMAND ${CMAKE_COMMAND} -DCLI=$<TARGET_FILE:k3_cli>
diff --git a/Makefile b/Makefile
index ac0dc33..0a738d6 100644
--- a/Makefile
+++ b/Makefile
@@ -156,7 +156,7 @@ CHAT_SRC := src/chat/k3_chat.c src/chat/k3_sampler.c
CLI_BIN := $(BIN)/k3
# Tests that need no checkpoint. These run in CI on every push.
-UNIT_TESTS := test_ops test_cache test_st test_model_stream test_cfg test_tok test_chat scale_test k3_model test_trunk test_st_faults
+UNIT_TESTS := test_ops test_cache test_st test_model_stream test_cfg test_tok test_chat scale_test k3_model test_trunk test_st_faults test_json
# Tests that need real shards. Built and run by `make test-all` with SHARD_DIR set;
# see the weights-test target below.
WEIGHT_TESTS := test_expert test_real_layer
@@ -213,6 +213,9 @@ $(BIN)/test_tok: tests/unit/test_tok.c | $(BIN)
$(BIN)/test_chat: tests/unit/test_chat.c src/chat/k3_chat.c src/chat/k3_sampler.c | $(BIN)
$(CC) $(CFLAGS) -Wno-unused-function $(INCLUDES) $^ -o $@ $(LDFLAGS)
+$(BIN)/test_json: tests/unit/test_json.c | $(BIN)
+ $(CC) -O2 -std=c99 $(WARN) -Wno-unused-function $(INCLUDES) $< -o $@ -lm
+
$(BIN)/test_cfg: tests/unit/test_cfg.c src/core/k3_ops.c | $(BIN)
$(CC) -O2 -std=c99 $(WARN) -Wno-unused-function $(INCLUDES) $^ -o $@ -lm
@@ -259,6 +262,7 @@ test: $(CLI_BIN) $(TEST_BINS)
plain.f32.2d plain.bf16.1d tricky.f16.1d packed.u8.2d scalar.f32 second.shard.f32
@echo "== model streaming =="; ./$(BIN)/test_model_stream $(FIXTURES)/st
@echo "== shard faults =="; ./$(BIN)/test_st_faults $(FIXTURES)/st $(BUILD)/stfault
+ @echo "== json refusals =="; ./$(BIN)/test_json
@echo "== config reader =="; ./$(BIN)/test_cfg fixture $(FIXTURES)/ref_k3.json
@echo "== config refusals =="; \
for f in no_layermap bad_layer_index bad_topk; do \
diff --git a/tests/unit/test_json.c b/tests/unit/test_json.c
new file mode 100644
index 0000000..a26d07c
--- /dev/null
+++ b/tests/unit/test_json.c
@@ -0,0 +1,184 @@
+/* test_json.c - truncated and malformed JSON must be refused loudly.
+ *
+ * WHY THIS FILE EXISTS
+ * third_party/json.h reads bytes the engine did not write itself
+ * (safetensors headers, configs, trunk manifests). A truncated file that
+ * parses as if it were complete is a silent-wrong-model case, and a read
+ * past the input terminator is a memory-safety bug. Each case below feeds
+ * the parser an exact-size copy so an overread is visible to sanitizers.
+ *
+ * usage: test_json
+ * needs no weights, no tokenizer files, no fixtures.
+ */
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+static int allocations, fail_at, live;
+
+static void *test_malloc(size_t n)
+{
+ if (++allocations == fail_at) return NULL;
+ void *p = malloc(n);
+ if (p) live++;
+ return p;
+}
+
+static void *test_calloc(size_t n, size_t size)
+{
+ if (++allocations == fail_at) return NULL;
+ void *p = calloc(n, size);
+ if (p) live++;
+ return p;
+}
+
+static void *test_realloc(void *p, size_t n)
+{
+ if (++allocations == fail_at) return NULL;
+ const int was_null = p == NULL;
+ void *q = realloc(p, n);
+ if (q && was_null) live++;
+ return q;
+}
+
+static void test_free(void *p)
+{
+ if (p) live--;
+ free(p);
+}
+
+#define malloc test_malloc
+#define calloc test_calloc
+#define realloc test_realloc
+#define free test_free
+#include "json.h"
+#undef malloc
+#undef calloc
+#undef realloc
+#undef free
+
+static int fails;
+static void check(int ok, const char *what)
+{
+ if (!ok) { fprintf(stderr, "FAIL: %s\n", what); fails++; }
+}
+
+static void reject(const char *text, size_t n)
+{
+ /* Exact allocation: a read past the terminator must be visible to ASan. */
+ char *copy = malloc(n + 1);
+ if (!copy) exit(2);
+ memcpy(copy, text, n);
+ copy[n] = '\0';
+ jval *v = json_parse(copy, NULL);
+ if (v != NULL) fprintf(stderr, "FAIL: accepted %s\n", copy);
+ else if (live != 0) fprintf(stderr, "FAIL: leak after refusing %s\n", copy);
+ if (v != NULL || live != 0) fails++;
+ json_free_tree(v);
+ if (live != 0) fails++;
+ free(copy);
+}
+
+int main(void)
+{
+ static const char *bad[] = {
+ "", " ", "{", "{\"a\"", "{\"a\":", "{\"a\":1", "{\"a\":1,}",
+ "{a:1}", "{\"a\" 1}", "{\"a\":1 \"b\":2}", "[", "[1", "[1,]",
+ "[1 2]", "{\"a\":1} garbage", "true false", "nul", "truth", "NaN",
+ "Infinity", "+1", "01", "-01", "-", ".1", "1.", "1e", "1e+",
+ "1e9999", "\"unterminated", "\"\\", "\"\\q\"", "\"\\u\"",
+ "\"\\u123\"", "\"\\u12xz\"", "\"\\uD800\"", "\"\\uDC00\"",
+ "\"\\uD800\\u0041\"", "\"\\u0000\"", "\vnull"
+ };
+ /* Raw control bytes inside a string are refused (built at runtime so the
+ * C source stays readable). */
+ char raw_nl[] = { '"', 'l', 'i', 'n', 'e', '\n', 'b', 'r', 'e', 'a', 'k', '"', '\0' };
+ char raw_tab[] = { '"', 'a', '\x01', 'b', '"', '\0' };
+
+ size_t i;
+ for (i = 0; i < sizeof bad / sizeof bad[0]; i++)
+ reject(bad[i], strlen(bad[i]));
+ reject(raw_nl, strlen(raw_nl));
+ reject(raw_tab, strlen(raw_tab));
+
+ static const char doc[] =
+ "{\"a\":[0,1,2,3,4,5,6,7,8,9],\"b\":\""
+ "abcdefghijklmnopqrstuvwxyz0123456789"
+ "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
+ "abcdefghijklmnopqrstuvwxyz0123456789\","
+ "\"c\":{\"k0\":null,\"k1\":true,\"k2\":false,\"k3\":-1.25e+2,"
+ "\"k4\":[],\"k5\":{},\"k6\":0,\"k7\":1,\"k8\":2},"
+ "\"unicode\":\"\\u0041\\u00e9\\u20ac\\ud83d\\ude80\"}";
+ for (i = 0; i < strlen(doc); i++) reject(doc, i);
+
+ allocations = 0;
+ fail_at = 0;
+ jval *v = json_parse(doc, NULL);
+ check(v != NULL, "complete document parses");
+ const int count = allocations;
+ if (v) {
+ jval *a = json_get(v, "a"), *u = json_get(v, "unicode");
+ jval *c = json_get(v, "c");
+ jval *number = c ? json_get(c, "k3") : NULL;
+ check(a && a->t == J_ARR && a->len == 10 && a->kids[9]->num == 9,
+ "array values survive growth");
+ check(number && number->t == J_NUM && number->num == -125,
+ "signed fraction with exponent");
+ check(u && u->t == J_STR &&
+ !strcmp(u->str, "A\xc3\xa9\xe2\x82\xac\xf0\x9f\x9a\x80"),
+ "unicode and surrogate pairs decode to UTF-8");
+ }
+ json_free_tree(v);
+ check(live == 0, "successful tree can be freed");
+
+ /* Every allocation failure must propagate as a clean refusal. */
+ for (i = 1; i <= (size_t)count; i++) {
+ allocations = 0;
+ fail_at = (int)i;
+ v = json_parse(doc, NULL);
+ if (v != NULL) {
+ fprintf(stderr, "FAIL: allocation %u did not propagate\n", (unsigned)i);
+ fails++;
+ }
+ json_free_tree(v);
+ if (live != 0) {
+ fprintf(stderr, "FAIL: leak after allocation %u failed\n", (unsigned)i);
+ fails++;
+ }
+ }
+ fail_at = 0;
+
+ /* Valid escapes still work. */
+ v = json_parse("{\"e\":\"X\\\"Y\\\\Z\\/W\\b\\f\\n\\r\\t\"}", NULL);
+ check(v != NULL, "valid escapes parse");
+ if (v) {
+ jval *e = json_get(v, "e");
+ check(e && e->t == J_STR && !strcmp(e->str, "X\"Y\\Z/W\b\f\n\r\t"),
+ "escape values decode");
+ }
+ json_free_tree(v);
+
+ /* Nesting past the ceiling is refused instead of substituted. */
+ {
+ char deep[2 * (J_MAX_DEPTH + 1) + 2];
+ memset(deep, '[', J_MAX_DEPTH + 1);
+ deep[J_MAX_DEPTH + 1] = '0';
+ memset(deep + J_MAX_DEPTH + 2, ']', J_MAX_DEPTH + 1);
+ deep[sizeof deep - 1] = '\0';
+ reject(deep, strlen(deep));
+ }
+ static const char *good[] = {"null", "true", "false", "0", "-0", "1e-3",
+ "[]", "{}", "\"\"", " \t\r\n[1,2]\n"};
+ for (i = 0; i < sizeof good / sizeof good[0]; i++) {
+ v = json_parse(good[i], NULL);
+ if (!v) {
+ fprintf(stderr, "FAIL: refused valid %s\n", good[i]);
+ fails++;
+ }
+ json_free_tree(v);
+ }
+ check(live == 0, "no parser allocations remain");
+ printf("JSON: %d allocation failures exercised; %s\n", count,
+ fails ? "FAILED" : "PASSED");
+ return fails ? 1 : 0;
+}
diff --git a/third_party/json.h b/third_party/json.h
index b19dbfd..c6d1f4f 100644
--- a/third_party/json.h
+++ b/third_party/json.h
@@ -3,11 +3,13 @@
* Sized for exactly what this project reads and no more:
* - safetensors headers (the tensor index at the front of each shard)
* - config.json and tokenizer_config.json
+ * - trunk.json manifests
* - the reference fixtures under tests/fixtures/ (prompt_ids / full_ids)
*
- * It is deliberately incomplete: no \uXXXX escapes, no exotic number syntax. Those do
- * not occur in the inputs above, and supporting them would add parsing surface to code
- * that runs against files fetched from the network.
+ * It is strict on purpose: a truncated or malformed document is refused with
+ * NULL rather than parsed as if it were complete. Every input here can be
+ * corrupt or hostile, and a wrong answer that looks right is the worst
+ * failure mode of this engine. Callers already handle NULL.
*/
#ifndef JSON_H
#define JSON_H
@@ -15,6 +17,7 @@
#include <string.h>
#include <stdio.h>
#include <ctype.h>
+#include <math.h>
typedef enum { J_NULL, J_BOOL, J_NUM, J_STR, J_ARR, J_OBJ } jtype;
@@ -22,7 +25,7 @@ typedef struct jval {
jtype t;
double num; /* J_NUM */
int boolean; /* J_BOOL */
- char *str; /* J_STR (NUL-terminated, inside the arena) */
+ char *str; /* J_STR (NUL-terminated, individually owned) */
/* array: children in [0..len). object: keys[] and kids[] run in parallel */
struct jval **kids;
char **keys; /* J_OBJ only */
@@ -31,7 +34,7 @@ typedef struct jval {
typedef struct {
const char *s;
- char *arena; /* backing buffer for the parsed strings */
+ char *arena; /* unused, kept for the json_parse(text, &arena) shape */
size_t acap, aoff;
int depth; /* current nesting depth: the bound that stops a hostile
* JSON like [[[[...]]]] from overflowing this recursive-descent
@@ -44,7 +47,7 @@ typedef struct {
/* Nesting ceiling. Safetensors headers and config files are shallow (depth ~3), so
* 1024 is far above anything legitimate while staying well below the stack limit.
* The cap exists so that a hostile or corrupt file cannot recurse the parser into a
- * stack overflow. */
+ * stack overflow. Past the ceiling the document is refused outright. */
#define J_MAX_DEPTH 1024
static char *j_dup(jparser *p, const char *b, int n) {
@@ -56,7 +59,11 @@ static char *j_dup(jparser *p, const char *b, int n) {
return d;
}
-static void j_ws(jparser *p) { while (*p->s && isspace((unsigned char)*p->s)) p->s++; }
+/* JSON whitespace only: space, tab, LF, CR. isspace() also accepts \v and \f,
+ * which JSON does not, so a document starting with \v must not parse. */
+static void j_ws(jparser *p) {
+ while (*p->s == ' ' || *p->s == '\t' || *p->s == '\n' || *p->s == '\r') p->s++;
+}
static jval *j_new(jparser *p, jtype t) {
jval *v = (jval *)calloc(1, sizeof(jval));
@@ -66,8 +73,25 @@ static jval *j_new(jparser *p, jtype t) {
static jval *j_parse_val(jparser *p);
+static int j_hex(const char *s, unsigned *out) {
+ unsigned v = 0;
+ int i;
+ for (i = 0; i < 4; i++) {
+ char c = s[i];
+ unsigned d;
+ if (c >= '0' && c <= '9') d = (unsigned)(c - '0');
+ else if (c >= 'a' && c <= 'f') d = (unsigned)(c - 'a' + 10);
+ else if (c >= 'A' && c <= 'F') d = (unsigned)(c - 'A' + 10);
+ else return 0;
+ v = (v << 4) | d;
+ }
+ *out = v;
+ return 1;
+}
+
static char *j_parse_str_raw(jparser *p) {
- /* assume *p->s == '"' */
+ /* The caller guarantees the opening quote; a NUL here means truncation. */
+ if (*p->s != '"') return NULL;
p->s++;
/* A GROWING heap buffer, deliberately not a fixed stack array. A fixed 64 KB
* buffer silently truncates the long strings that appear in tokenizer and config
@@ -77,39 +101,64 @@ static char *j_parse_str_raw(jparser *p) {
if (!tmp) { p->oom = 1; return NULL; }
/* A library must not exit(1) on OOM: the CLI distinguishes misuse (2)
* from failure, and every json_parse caller already handles NULL. */
- #define J_PUT(ch) do{ if (n + 1 >= cap) { cap *= 2; char *nt = (char *)realloc(tmp, cap); \
- if (!nt) { free(tmp); p->oom = 1; return NULL; } tmp = nt; } tmp[n++] = (char)(ch); }while(0)
- while (*p->s && *p->s != '"') {
- char c = *p->s++;
- if (c == '\\' && *p->s) {
- char e = *p->s++;
- switch (e) {
- case 'n': c = '\n'; break; case 't': c = '\t'; break;
- case 'r': c = '\r'; break; case 'b': c = '\b'; break;
- case 'f': c = '\f'; break; case '/': c = '/'; break;
- case '\\': c = '\\'; break; case '"': c = '"'; break;
- case 'u': { /* \uXXXX -> codepoint UTF-8 (con coppie surrogate) */
- if (!p->s[0]||!p->s[1]||!p->s[2]||!p->s[3]) { c='?'; break; } /* truncated \u: do not read past the NUL */
- unsigned cp = (unsigned)strtoul((char[]){p->s[0],p->s[1],p->s[2],p->s[3],0}, NULL, 16);
- p->s += 4;
- if (cp >= 0xD800 && cp <= 0xDBFF && p->s[0]=='\\' && p->s[1]=='u'
- && p->s[2] && p->s[3] && p->s[4] && p->s[5]) {
- unsigned lo = (unsigned)strtoul((char[]){p->s[2],p->s[3],p->s[4],p->s[5],0}, NULL, 16);
- if (lo >= 0xDC00 && lo <= 0xDFFF) { cp = 0x10000 + ((cp-0xD800)<<10) + (lo-0xDC00); p->s += 6; }
+ #define J_PUT(ch) do{ if (n + 1 >= cap) { \
+ if (cap > (size_t)0x40000000) { free(tmp); p->oom = 1; return NULL; } \
+ cap *= 2; char *nt = (char *)realloc(tmp, cap); \
+ if (!nt) { free(tmp); p->oom = 1; return NULL; } tmp = nt; } \
+ tmp[n++] = (char)(ch); }while(0)
+ for (;;) {
+ char c = *p->s;
+ if (c == '\0') { free(tmp); return NULL; } /* unterminated */
+ if (c == '"') { p->s++; break; } /* closing quote */
+ if ((unsigned char)c < 0x20) { free(tmp); return NULL; } /* raw control */
+ if (c != '\\') { p->s++; J_PUT(c); continue; }
+ /* Escape. *p->s == '\\' and the next byte decides; NUL ends the input. */
+ p->s++;
+ c = *p->s;
+ if (c == '\0') { free(tmp); return NULL; }
+ switch (c) {
+ case '"': p->s++; J_PUT('"'); break;
+ case '\\': p->s++; J_PUT('\\'); break;
+ case '/': p->s++; J_PUT('/'); break;
+ case 'b': p->s++; J_PUT('\b'); break;
+ case 'f': p->s++; J_PUT('\f'); break;
+ case 'n': p->s++; J_PUT('\n'); break;
+ case 'r': p->s++; J_PUT('\r'); break;
+ case 't': p->s++; J_PUT('\t'); break;
+ case 'u': {
+ unsigned cp, lo;
+ /* Four hex digits must follow; the NUL check inside j_hex's
+ * caller matters because p->s[1..4] may run into the end. */
+ if (p->s[1] == '\0' || p->s[2] == '\0' ||
+ p->s[3] == '\0' || p->s[4] == '\0') { free(tmp); return NULL; }
+ if (!j_hex(p->s + 1, &cp)) { free(tmp); return NULL; }
+ p->s += 5;
+ if (cp >= 0xD800 && cp <= 0xDBFF) {
+ /* High surrogate: a low surrogate must follow, else the
+ * document is malformed rather than encodable. */
+ if (p->s[0] != '\\' || p->s[1] != 'u' ||
+ p->s[2] == '\0' || p->s[3] == '\0' ||
+ p->s[4] == '\0' || p->s[5] == '\0' ||
+ !j_hex(p->s + 2, &lo) || lo < 0xDC00 || lo > 0xDFFF) {
+ free(tmp); return NULL;
}
- if (cp < 0x80) { J_PUT(cp); }
- else if (cp < 0x800) { J_PUT(0xC0|(cp>>6)); J_PUT(0x80|(cp&0x3F)); }
- else if (cp < 0x10000) { J_PUT(0xE0|(cp>>12)); J_PUT(0x80|((cp>>6)&0x3F)); J_PUT(0x80|(cp&0x3F)); }
- else { J_PUT(0xF0|(cp>>18)); J_PUT(0x80|((cp>>12)&0x3F)); J_PUT(0x80|((cp>>6)&0x3F)); J_PUT(0x80|(cp&0x3F)); }
- continue;
+ cp = 0x10000 + ((cp - 0xD800) << 10) + (lo - 0xDC00);
+ p->s += 6;
+ } else if (cp >= 0xDC00 && cp <= 0xDFFF) {
+ free(tmp); return NULL; /* lone low surrogate */
+ } else if (cp == 0) {
+ free(tmp); return NULL; /* NUL cannot live in a C string */
}
- default: c = e; break;
+ if (cp < 0x80) { J_PUT(cp); }
+ else if (cp < 0x800) { J_PUT(0xC0|(cp>>6)); J_PUT(0x80|(cp&0x3F)); }
+ else if (cp < 0x10000) { J_PUT(0xE0|(cp>>12)); J_PUT(0x80|((cp>>6)&0x3F)); J_PUT(0x80|(cp&0x3F)); }
+ else { J_PUT(0xF0|(cp>>18)); J_PUT(0x80|((cp>>12)&0x3F)); J_PUT(0x80|((cp>>6)&0x3F)); J_PUT(0x80|(cp&0x3F)); }
+ break;
}
+ default: free(tmp); return NULL; /* no \q, \a, or friends */
}
- J_PUT(c);
}
#undef J_PUT
- if (*p->s == '"') p->s++;
char *out = j_dup(p, tmp, (int)n); free(tmp);
return out; /* NULL with oom latched on failure */
}
@@ -140,11 +189,50 @@ static int j_grow2(jparser *p, void **a, size_t ae, void **b, size_t be,
return 1;
}
+static jval *j_parse_num(jparser *p) {
+ /* Strict JSON numbers: -?(0|[1-9][0-9]*)(\.[0-9]+)?([eE][+-]?[0-9]+)?.
+ * strtod alone accepts "+1", "01", "NaN", "Infinity" and hex, none of
+ * which this parser's inputs may contain. NaN/Infinity would also turn
+ * into UB one cast later, where a double becomes an int64 offset. */
+ const char *s = p->s;
+ if (*s == '-') s++;
+ if (*s == '0') {
+ s++;
+ if (*s >= '0' && *s <= '9') return NULL; /* no leading zeros */
+ } else if (*s >= '1' && *s <= '9') {
+ do s++; while (*s >= '0' && *s <= '9');
+ } else {
+ return NULL;
+ }
+ if (*s == '.') {
+ s++;
+ if (*s < '0' || *s > '9') return NULL;
+ do s++; while (*s >= '0' && *s <= '9');
+ }
+ if (*s == 'e' || *s == 'E') {
+ s++;
+ if (*s == '+' || *s == '-') s++;
+ if (*s < '0' || *s > '9') return NULL;
+ do s++; while (*s >= '0' && *s <= '9');
+ }
+ {
+ char *end = NULL;
+ double d = strtod(p->s, &end);
+ if (end != s || !isfinite(d)) return NULL;
+ p->s = s;
+ jval *v = j_new(p, J_NUM);
+ if (!v) return NULL;
+ v->num = d;
+ return v;
+ }
+}
+
static jval *j_parse_val(jparser *p);
static void json_free_tree(jval *v);
static jval *j_parse_obj(jparser *p) {
- if (++p->depth > J_MAX_DEPTH) { p->depth--; return j_new(p, J_NULL); }
+ if (*p->s != '{') return NULL;
+ if (++p->depth > J_MAX_DEPTH) { p->depth--; return NULL; }
p->s++; jval *v = j_new(p, J_OBJ);
if (!v) { p->depth--; return NULL; }
int cap = 8;
@@ -156,15 +244,25 @@ static jval *j_parse_obj(jparser *p) {
}
j_ws(p);
if (*p->s == '}') { p->s++; p->depth--; return v; }
+ if (*p->s == '\0') { json_free_tree(v); p->depth--; return NULL; }
for (;;) {
j_ws(p);
+ /* Keys are always quoted strings. Anything else, including NUL for
+ * a truncated "{", is a refusal rather than a scan past the end. */
+ if (*p->s != '"') { json_free_tree(v); p->depth--; return NULL; }
char *key = j_parse_str_raw(p);
- j_ws(p); if (*p->s == ':') p->s++;
+ j_ws(p);
+ /* The colon is mandatory: {"a" 1} must not parse as {"a":1}. */
+ if (!key || p->oom || *p->s != ':') {
+ free(key); json_free_tree(v); p->depth--;
+ return NULL;
+ }
+ p->s++;
jval *val = j_parse_val(p);
/* Every allocated node is owned by exactly one frame's kids[], so
* freeing this frame's partial v closes the whole failed subtree;
* only the in-flight key/val need separate handling. */
- if (!key || !val || p->oom) {
+ if (!val || p->oom) {
free(key); json_free_tree(val); json_free_tree(v);
p->depth--;
return NULL;
@@ -180,14 +278,17 @@ static jval *j_parse_obj(jparser *p) {
j_ws(p);
if (*p->s == ',') { p->s++; continue; }
if (*p->s == '}') { p->s++; break; }
- break;
+ /* Missing comma or brace, or truncation: {"a":1 and {"a":1 "b":2}. Key and value are already owned by v. */
+ json_free_tree(v); p->depth--;
+ return NULL;
}
p->depth--;
return v;
}
static jval *j_parse_arr(jparser *p) {
- if (++p->depth > J_MAX_DEPTH) { p->depth--; return j_new(p, J_NULL); }
+ if (*p->s != '[') return NULL;
+ if (++p->depth > J_MAX_DEPTH) { p->depth--; return NULL; }
p->s++; jval *v = j_new(p, J_ARR);
if (!v) { p->depth--; return NULL; }
int cap = 8;
@@ -195,6 +296,7 @@ static jval *j_parse_arr(jparser *p) {
if (!v->kids) { free(v); p->oom = 1; p->depth--; return NULL; }
j_ws(p);
if (*p->s == ']') { p->s++; p->depth--; return v; }
+ if (*p->s == '\0') { json_free_tree(v); p->depth--; return NULL; }
for (;;) {
jval *val = j_parse_val(p);
if (!val || p->oom) { json_free_tree(val); json_free_tree(v); p->depth--; return NULL; }
@@ -209,7 +311,10 @@ static jval *j_parse_arr(jparser *p) {
j_ws(p);
if (*p->s == ',') { p->s++; continue; }
if (*p->s == ']') { p->s++; break; }
- break;
+ /* [1 2], [1, and [1 all end here. A trailing comma fails on the
+ * next value parse ([1,] -> ']' is not a value). */
+ json_free_tree(v); p->depth--;
+ return NULL;
}
p->depth--;
return v;
@@ -217,28 +322,48 @@ static jval *j_parse_arr(jparser *p) {
static jval *j_parse_val(jparser *p) {
j_ws(p);
- char c = *p->s;
- if (c == '"') {
- jval *v = j_new(p, J_STR);
- if (!v) return NULL;
- v->str = j_parse_str_raw(p);
- if (!v->str) { free(v); return NULL; }
- return v;
+ {
+ char c = *p->s;
+ jval *v;
+ if (c == '\0') return NULL;
+ if (c == '"') {
+ v = j_new(p, J_STR);
+ if (!v) return NULL;
+ v->str = j_parse_str_raw(p);
+ if (!v->str) { free(v); return NULL; }
+ return v;
+ }
+ if (c == '{') return j_parse_obj(p);
+ if (c == '[') return j_parse_arr(p);
+ /* Literals must end at a delimiter: "truth" is not "true". */
+ if (c == 't' && !strncmp(p->s, "true", 4) &&
+ !isalnum((unsigned char)p->s[4]) && p->s[4] != '_') {
+ p->s += 4; v = j_new(p, J_BOOL); if (!v) return NULL; v->boolean = 1; return v;
+ }
+ if (c == 'f' && !strncmp(p->s, "false", 5) &&
+ !isalnum((unsigned char)p->s[5]) && p->s[5] != '_') {
+ p->s += 5; v = j_new(p, J_BOOL); if (!v) return NULL; v->boolean = 0; return v;
+ }
+ if (c == 'n' && !strncmp(p->s, "null", 4) &&
+ !isalnum((unsigned char)p->s[4]) && p->s[4] != '_') {
+ p->s += 4; return j_new(p, J_NULL);
+ }
+ if (c == '-' || (c >= '0' && c <= '9')) return j_parse_num(p);
+ return NULL;
}
- if (c == '{') return j_parse_obj(p);
- if (c == '[') return j_parse_arr(p);
- if (c == 't' && !strncmp(p->s, "true", 4)) { p->s += 4; jval *v = j_new(p, J_BOOL); if (!v) return NULL; v->boolean = 1; return v; }
- if (c == 'f' && !strncmp(p->s, "false", 5)) { p->s += 5; jval *v = j_new(p, J_BOOL); if (!v) return NULL; v->boolean = 0; return v; }
- if (c == 'n' && !strncmp(p->s, "null", 4)) { p->s += 4; return j_new(p, J_NULL); }
- /* numero */
- { char *end; double d = strtod(p->s, &end); p->s = end; jval *v = j_new(p, J_NUM); if (!v) return NULL; v->num = d; return v; }
}
/* API */
static jval *json_parse(const char *text, char **arena_out) {
jparser p = { text, NULL, 0, 0, 0, 0 };
jval *v = j_parse_val(&p);
- if (p.oom) { json_free_tree(v); v = NULL; }
+ if (!v || p.oom) { json_free_tree(v); v = NULL; }
+ else {
+ /* One value and nothing else: trailing bytes mean truncation or
+ * concatenation, never a document. {"a":1} garbage is refused. */
+ j_ws(&p);
+ if (*p.s != '\0') { json_free_tree(v); v = NULL; }
+ }
if (arena_out) *arena_out = p.arena; else free(p.arena);
return v;
}
@@ -253,8 +378,8 @@ static jval *json_get(jval *o, const char *key) {
* the parser hands out is individually heap-owned (see j_dup), including
* object keys and J_STR values, so freeing after extraction leaks nothing.
* The one exception a caller must respect: anything it ALIASED out of the
- * tree (k3_trunk.c tensor names, k3_tok.h special-token strings) must be
- * strdup'd first (trunk) or deliberately process-lifetime (tokenizer). */
+ * tree (k3_tok.h special-token strings) must be strdup'd first (trunk) or
+ * deliberately process-lifetime (tokenizer). */
static void json_free_tree(jval *v) {
int i;
if (!v) return;