+
+/* Slurp the executable portion of the runtime into a malloced buffer
+ * and return it. Places the size in bytes of the runtime into
+ * 'size_out'. Returns NULL if the runtime cannot be loaded from
+ * 'runtime_path'. */
+void *
+load_runtime(char *runtime_path, size_t *size_out)
+{
+ void *buf = NULL;
+ FILE *input = NULL;
+ size_t size, count;
+ os_vm_offset_t core_offset;
+
+ core_offset = search_for_embedded_core (runtime_path);
+ if ((input = fopen(runtime_path, "rb")) == NULL) {
+ fprintf(stderr, "Unable to open runtime: %s\n", runtime_path);
+ goto lose;
+ }
+
+ fseek(input, 0, SEEK_END);
+ size = (size_t) ftell(input);
+ fseek(input, 0, SEEK_SET);
+
+ if (core_offset != -1 && size > core_offset)
+ size = core_offset;
+
+ buf = successful_malloc(size);
+ if ((count = fread(buf, 1, size, input)) != size) {
+ fprintf(stderr, "Premature EOF while reading runtime.\n");
+ goto lose;
+ }
+
+ fclose(input);
+ *size_out = size;
+ return buf;
+
+lose:
+ if (input != NULL)
+ fclose(input);
+ if (buf != NULL)
+ free(buf);
+ return NULL;
+}
+
+boolean
+save_runtime_to_filehandle(FILE *output, void *runtime, size_t runtime_size)
+{
+ size_t padding;
+ void *padbytes;
+
+ fwrite(runtime, 1, runtime_size, output);
+
+ padding = (os_vm_page_size - (runtime_size % os_vm_page_size)) & ~os_vm_page_size;
+ if (padding > 0) {
+ padbytes = successful_malloc(padding);
+ memset(padbytes, 0, padding);
+ fwrite(padbytes, 1, padding, output);
+ free(padbytes);
+ }
+
+ return 1;
+}
+
+FILE *
+prepare_to_save(char *filename, boolean prepend_runtime, void **runtime_bytes,
+ size_t *runtime_size)
+{
+ FILE *file;
+ char *runtime_path;
+
+ if (prepend_runtime) {
+ runtime_path = os_get_runtime_executable_path();
+
+ if (runtime_path == NULL) {
+ fprintf(stderr, "Unable to get default runtime path.\n");
+ return NULL;
+ }
+
+ *runtime_bytes = load_runtime(runtime_path, runtime_size);
+ free(runtime_path);
+
+ if (*runtime_bytes == NULL)
+ return 0;
+ }
+
+ file = open_core_for_saving(filename);
+ if (file == NULL) {
+ free(*runtime_bytes);
+ perror(filename);
+ return NULL;
+ }
+
+ return file;
+}
+
+boolean
+save(char *filename, lispobj init_function, boolean prepend_runtime,
+ boolean save_runtime_options)
+{
+ FILE *file;
+ void *runtime_bytes = NULL;
+ size_t runtime_size;
+
+ file = prepare_to_save(filename, prepend_runtime, &runtime_bytes, &runtime_size);
+ if (file == NULL)
+ return 1;
+
+ if (prepend_runtime)
+ save_runtime_to_filehandle(file, runtime_bytes, runtime_size);
+
+ return save_to_filehandle(file, filename, init_function, prepend_runtime,
+ save_runtime_options);
+}