From 7dc12ac44f3a03348230f563e8409a9e64adf7b5 Mon Sep 17 00:00:00 2001 From: David Given Date: Mon, 26 Feb 2024 21:46:34 +0100 Subject: [PATCH] Don't write garbage after strings when initialising arrays to a string which is shorter than the array itself. When writing garbage, make sure it's actually escaped properly. --- mach/proto/mcg/data.c | 11 ++++++++--- mach/proto/mcg/mcg.h | 2 +- mach/proto/mcg/parse_em.c | 2 +- 3 files changed, 10 insertions(+), 5 deletions(-) diff --git a/mach/proto/mcg/data.c b/mach/proto/mcg/data.c index dfd3651d4..a137196e9 100644 --- a/mach/proto/mcg/data.c +++ b/mach/proto/mcg/data.c @@ -81,10 +81,10 @@ static bool istext(char c) return isprint(c) && (c != '"'); } -void data_block(const uint8_t* data, size_t size, bool is_ro) +void data_block(const uint8_t* data, size_t datalen, size_t size, bool is_ro) { const uint8_t* start = data; - const uint8_t* end = data + size; + const uint8_t* end = data + datalen; const uint8_t* p = data; emit_header(is_ro ? SECTION_ROM : SECTION_DATA); @@ -100,7 +100,9 @@ void data_block(const uint8_t* data, size_t size, bool is_ro) fprintf(outputfile, "\t.ascii \""); while (start < p) { - fprintf(outputfile, "%c", *start); + if ((*start == '\\') || (*start == '"')) + fputc('\\', outputfile); + fputc(*start, outputfile); start++; } fprintf(outputfile, "\"\n"); @@ -125,6 +127,9 @@ void data_block(const uint8_t* data, size_t size, bool is_ro) fprintf(outputfile, "\n"); } } + + for (size_t zeroes = 0; zeroes < (size - datalen); zeroes++) + fprintf(outputfile, "\t.data1 0\n"); } void data_offset(const char* label, arith offset, bool is_ro) diff --git a/mach/proto/mcg/mcg.h b/mach/proto/mcg/mcg.h index 69f194e85..a0e5436c7 100644 --- a/mach/proto/mcg/mcg.h +++ b/mach/proto/mcg/mcg.h @@ -95,7 +95,7 @@ extern struct symbol* symbol_walk(symbol_walker_t* walker, void* user); extern void data_label(const char* name); extern void data_int(arith data, size_t size, bool is_ro); extern void data_float(const char* data, size_t size, bool is_ro); -extern void data_block(const uint8_t* data, size_t size, bool is_ro); +extern void data_block(const uint8_t* data, size_t datalen, size_t size, bool is_ro); extern void data_offset(const char* label, arith offset, bool is_ro); extern void data_bss(arith size, int init); diff --git a/mach/proto/mcg/parse_em.c b/mach/proto/mcg/parse_em.c index e8859d2fb..8411d13d5 100644 --- a/mach/proto/mcg/parse_em.c +++ b/mach/proto/mcg/parse_em.c @@ -281,7 +281,7 @@ static void parse_pseu(void) } case str_ptyp: - data_block((const uint8_t*) strdup(em.em_string), em.em_size, ro); + data_block((const uint8_t*) em.em_string, strlen(em.em_string), em.em_size, ro); break; case cst_ptyp: