Added ability to directly embed NED programs in NEDsim binary for runtime execution.
[screensavers] / hacks / NEDsim / simulator.c
index 7f5f135..ec1db20 100644 (file)
@@ -364,7 +364,7 @@ parse_aout_file(FILE * input, struct exec * aout_exec, uint8_t * text_segment,
 }
 
 struct NEDstate *
 }
 
 struct NEDstate *
-init_simulator(char * input_file)
+init_simulator(char * input_file, const uint8_t * blob, const size_t * blob_size)
 {
     struct NEDstate * state = malloc(sizeof(struct NEDstate));
     state->hack = malloc(sizeof(struct NEDhack));
 {
     struct NEDstate * state = malloc(sizeof(struct NEDstate));
     state->hack = malloc(sizeof(struct NEDhack));
@@ -381,20 +381,39 @@ init_simulator(char * input_file)
     state->hack->resume_word = false;
 
     /* Load an initial image into memory. */
     state->hack->resume_word = false;
 
     /* Load an initial image into memory. */
-    struct exec aout_exec;
-    struct nlist * symbol_table;
-    uint32_t symbol_count;
-    FILE * input = NULL;
-    if ((input = fopen(input_file, "r")) == NULL) {
-        fprintf(stderr, "ERROR: %s: %s\n", input_file, strerror(errno));
+    if (input_file) {
+        struct exec aout_exec;
+        struct nlist * symbol_table;
+        uint32_t symbol_count;
+        FILE * input = NULL;
+        if ((input = fopen(input_file, "r")) == NULL) {
+            fprintf(stderr, "ERROR: %s: %s\n", input_file, strerror(errno));
+            state->halted = true;
+        }
+        parse_aout_file(input, &aout_exec, state->ram, &symbol_table, &symbol_count);
+        fclose(input);
+        for (size_t i=0; i < symbol_count; i++) {
+            free(symbol_table[i].n_un.n_name);
+        }
+        free(symbol_table);
+    } else if (blob && blob_size) {
+        if (*blob_size <= RAM_LENGTH) {
+            size_t index = *blob_size;
+            while (index) {
+                index--;
+                state->ram[index] = blob[index];
+            }
+        } else {
+            fprintf(stderr,
+                    "ERROR: Built-in NED1 program is larger than simulated RAM (%zu vs %d bytes)",
+                    *blob_size, RAM_LENGTH
+            );
+            state->halted = true;
+        }
+    } else {
+        fprintf(stderr, "ERROR: No suitable binary image passed when initializing simulator.\n");
         state->halted = true;
     }
         state->halted = true;
     }
-    parse_aout_file(input, &aout_exec, state->ram, &symbol_table, &symbol_count);
-    fclose(input);
-    for (size_t i=0; i < symbol_count; i++) {
-        free(symbol_table[i].n_un.n_name);
-    }
-    free(symbol_table);
 
     return state;
 }
 
     return state;
 }