From 832c6c7bf9a2be2c5eaede8882bdd3e27af1f89c Mon Sep 17 00:00:00 2001 From: Maxwell Jeffress Date: Tue, 17 Mar 2026 18:35:37 +1100 Subject: [PATCH] Fix use segfault --- src/interpreter.c | 45 ++++++++++++++++++++------------------------- 1 file changed, 20 insertions(+), 25 deletions(-) diff --git a/src/interpreter.c b/src/interpreter.c index e9428c0..10497b1 100644 --- a/src/interpreter.c +++ b/src/interpreter.c @@ -15,6 +15,8 @@ int currentInstruction = 0; bool isMainScopeGlobal = true; +char* getFileContents(const char* filename); + [[noreturn]] void customError(GroundArg type, GroundArg what, GroundInstruction* where, int whereLine, int exitCode) { printf("Ground runtime error:\n ErrorType: "); printGroundArg(&type); @@ -1886,17 +1888,17 @@ GroundValue interpretGroundInstruction(GroundInstruction inst, GroundScope* scop char* envPath = getenv("GROUND_LIBS"); if (envPath) { - snprintf(path, sizeof(path), "%s/%s", envPath, libName); + snprintf(path, sizeof(path), "%s/%s.grnd", envPath, libName); if (access(path, F_OK) == 0) found = 1; } if (!found) { - snprintf(path, sizeof(path), "/usr/lib/ground/%s", libName); + snprintf(path, sizeof(path), "/usr/lib/ground/%s.grnd", libName); if (access(path, F_OK) == 0) found = 1; } if (!found) { - snprintf(path, sizeof(path), "%s", libName); + snprintf(path, sizeof(path), "%s.grnd", libName); if (access(path, F_OK) == 0) found = 1; } @@ -1905,29 +1907,22 @@ GroundValue interpretGroundInstruction(GroundInstruction inst, GroundScope* scop snprintf(errorMsg, sizeof(errorMsg), "Could not find library: %s", libName); runtimeError(FIXME, errorMsg, in, currentInstruction); } + + char* fileContents = getFileContents(path); + + GroundProgram program = parseFile(fileContents); + free(fileContents); + + GroundScope newScope = { + .variables = scope->variables, + .labels = malloc(sizeof(GroundLabel*)), + .isMainScope = false + }; + + *newScope.labels = NULL; - FILE* f = fopen(path, "r"); - if (!f) { - runtimeError(FIXME, "Failed to open file", in, currentInstruction); - } - fseek(f, 0, SEEK_END); - long fsize = ftell(f); - fseek(f, 0, SEEK_SET); - - char* content = malloc(fsize + 1); - if (!content) { - fclose(f); - runtimeError(FIXME, "Failed to allocate memory for file content", in, currentInstruction); - } - fread(content, 1, fsize, f); - fclose(f); - content[fsize] = 0; - - GroundProgram program = parseFile(content); - free(content); - - interpretGroundProgram(&program, scope); - freeGroundProgram(&program); + interpretGroundProgram(&program, &newScope); + break; }