Fix some warnings
[sbcl.git] / src / runtime / save.c
blob6d2f20a8bdb97340887f130365e50d68ce4260e3
1 /*
2 * This software is part of the SBCL system. See the README file for
3 * more information.
5 * This software is derived from the CMU CL system, which was
6 * written at Carnegie Mellon University and released into the
7 * public domain. The software is in the public domain and is
8 * provided with absolutely no warranty. See the COPYING and CREDITS
9 * files for more information.
12 #ifndef LISP_FEATURE_WIN32
13 #include <sys/types.h>
14 #include <sys/stat.h>
15 #endif
16 #include <stdlib.h>
17 #include <stdio.h>
18 #include <string.h>
19 #include <sys/file.h>
21 #include "sbcl.h"
22 #if defined(LISP_FEATURE_WIN32) && defined(LISP_FEATURE_SB_THREAD)
23 #include "pthreads_win32.h"
24 #else
25 #include <signal.h>
26 #endif
27 #include "runtime.h"
28 #include "os.h"
29 #include "core.h"
30 #include "globals.h"
31 #include "save.h"
32 #include "dynbind.h"
33 #include "lispregs.h"
34 #include "validate.h"
35 #include "gc-internal.h"
36 #include "thread.h"
37 #include "arch.h"
39 #include "genesis/static-symbols.h"
40 #include "genesis/symbol.h"
42 #ifdef LISP_FEATURE_SB_CORE_COMPRESSION
43 # include <zlib.h>
44 #endif
46 /* write_runtime_options uses a simple serialization scheme that
47 * consists of one word of magic, one word indicating whether options
48 * are actually saved, and one word per struct field. */
49 static void
50 write_runtime_options(FILE *file, struct runtime_options *options)
52 size_t optarray[RUNTIME_OPTIONS_WORDS];
54 memset(&optarray, 0, sizeof(optarray));
55 optarray[0] = RUNTIME_OPTIONS_MAGIC;
57 if (options != NULL) {
58 /* optarray[1] is a flag indicating that options are present */
59 optarray[1] = 1;
60 optarray[2] = options->dynamic_space_size;
61 optarray[3] = options->thread_control_stack_size;
64 if (RUNTIME_OPTIONS_WORDS !=
65 fwrite(optarray, sizeof(size_t), RUNTIME_OPTIONS_WORDS, file)) {
66 perror("Error writing runtime options to file");
70 static void
71 write_lispobj(lispobj obj, FILE *file)
73 if (1 != fwrite(&obj, sizeof(lispobj), 1, file)) {
74 perror("Error writing to file");
78 static void
79 write_bytes_to_file(FILE * file, char *addr, long bytes, int compression)
81 if (compression == COMPRESSION_LEVEL_NONE) {
82 while (bytes > 0) {
83 sword_t count = fwrite(addr, 1, bytes, file);
84 if (count > 0) {
85 bytes -= count;
86 addr += count;
88 else {
89 perror("error writing to core file");
90 lose("core file is incomplete or corrupt\n");
93 #ifdef LISP_FEATURE_SB_CORE_COMPRESSION
94 } else if ((compression >= -1) && (compression <= 9)) {
95 # define ZLIB_BUFFER_SIZE (1u<<16)
96 z_stream stream;
97 unsigned char buf[ZLIB_BUFFER_SIZE];
98 unsigned char * written, * end;
99 long total_written = 0;
100 int ret;
101 stream.zalloc = NULL;
102 stream.zfree = NULL;
103 stream.opaque = NULL;
104 stream.avail_in = bytes;
105 stream.next_in = (void*)addr;
106 ret = deflateInit(&stream, compression);
107 if (ret != Z_OK)
108 lose("deflateInit: %i\n", ret);
109 do {
110 stream.avail_out = sizeof(buf);
111 stream.next_out = buf;
112 ret = deflate(&stream, Z_FINISH);
113 if (ret < 0) lose("zlib deflate error: %i... exiting\n", ret);
114 written = buf;
115 end = buf+sizeof(buf)-stream.avail_out;
116 total_written += end - written;
117 while (written < end) {
118 long count = fwrite(written, 1, end-written, file);
119 if (count > 0) {
120 written += count;
121 } else {
122 perror("error writing to core file");
123 lose("core file is incomplete or corrupt\n");
126 } while (stream.avail_out == 0);
127 deflateEnd(&stream);
128 printf("compressed %lu bytes into %lu at level %i\n",
129 bytes, total_written, compression);
130 # undef ZLIB_BUFFER_SIZE
131 #endif
132 } else {
133 #ifdef LISP_FEATURE_SB_CORE_COMPRESSION
134 lose("Unknown core compression level %i, exiting\n", compression);
135 #else
136 lose("zlib-compressed core support not built in this runtime\n");
137 #endif
140 if (fflush(file) != 0) {
141 perror("error writing to core file");
142 lose("core file is incomplete or corrupt\n");
147 static long
148 write_and_compress_bytes(FILE *file, char *addr, long bytes, os_vm_offset_t file_offset,
149 int compression)
151 long here, data;
153 bytes = (bytes+os_vm_page_size-1)&~(os_vm_page_size-1);
155 #ifdef LISP_FEATURE_WIN32
156 long count;
157 /* touch every single page in the space to force it to be mapped. */
158 for (count = 0; count < bytes; count += 0x1000) {
159 volatile int temp = addr[count];
161 #endif
163 fflush(file);
164 here = ftell(file);
165 fseek(file, 0, SEEK_END);
166 data = (ftell(file)+os_vm_page_size-1)&~(os_vm_page_size-1);
167 fseek(file, data, SEEK_SET);
168 write_bytes_to_file(file, addr, bytes, compression);
169 fseek(file, here, SEEK_SET);
170 return ((data - file_offset) / os_vm_page_size) - 1;
173 static long __attribute__((__unused__))
174 write_bytes(FILE *file, char *addr, long bytes, os_vm_offset_t file_offset)
176 return write_and_compress_bytes(file, addr, bytes, file_offset,
177 COMPRESSION_LEVEL_NONE);
180 static void
181 output_space(FILE *file, int id, lispobj *addr, lispobj *end,
182 os_vm_offset_t file_offset,
183 int core_compression_level)
185 size_t words, bytes, data, compressed_flag;
186 static char *names[] = {NULL, "dynamic", "static", "read-only",
187 "immobile", "immobile"};
189 compressed_flag
190 = ((core_compression_level != COMPRESSION_LEVEL_NONE)
191 ? DEFLATED_CORE_SPACE_ID_FLAG : 0);
193 write_lispobj(id | compressed_flag, file);
194 words = end - addr;
195 write_lispobj(words, file);
197 bytes = words * sizeof(lispobj);
199 printf("writing %lu bytes from the %s space at %p\n",
200 (uword_t)bytes, names[id], addr);
202 data = write_and_compress_bytes(file, (char *)addr, bytes, file_offset,
203 core_compression_level);
205 write_lispobj(data, file);
206 write_lispobj((uword_t)addr / os_vm_page_size, file);
207 write_lispobj((bytes + os_vm_page_size - 1) / os_vm_page_size, file);
210 FILE *
211 open_core_for_saving(char *filename)
213 /* Open the output file. We don't actually need the file yet, but
214 * the fopen() might fail for some reason, and we want to detect
215 * that and back out before we do anything irreversible. */
216 unlink(filename);
217 return fopen(filename, "wb");
220 #ifdef LISP_FEATURE_IMMOBILE_SPACE
221 extern void prepare_immobile_space_for_save();
222 # define N_SPACES_TO_SAVE 5
223 # ifdef LISP_FEATURE_IMMOBILE_CODE
224 lispobj code_component_order;
225 extern void defrag_immobile_space(lispobj);
226 # endif
227 #else
228 # define N_SPACES_TO_SAVE 3
229 #endif
230 boolean
231 save_to_filehandle(FILE *file, char *filename, lispobj init_function,
232 boolean make_executable,
233 boolean save_runtime_options,
234 int core_compression_level)
236 struct thread *th;
237 os_vm_offset_t core_start_pos;
239 #ifdef LISP_FEATURE_X86_64
240 untune_asm_routines_for_microarch();
241 #endif
243 /* Smash the enclosing state. (Once we do this, there's no good
244 * way to go back, which is a sufficient reason that this ends up
245 * being SAVE-LISP-AND-DIE instead of SAVE-LISP-AND-GO-ON). */
246 printf("[undoing binding stack and other enclosing state... ");
247 fflush(stdout);
248 for_each_thread(th) { /* XXX really? */
249 unbind_to_here((lispobj *)th->binding_stack_start,th);
250 SetSymbolValue(CURRENT_CATCH_BLOCK, 0,th);
251 SetSymbolValue(CURRENT_UNWIND_PROTECT_BLOCK, 0,th);
253 printf("done]\n");
254 fflush(stdout);
255 #ifdef LISP_FEATURE_IMMOBILE_CODE
256 // It's better to wait to defrag until after the binding stack is undone,
257 // because we explicitly don't fixup code refs from stacks.
258 // i.e. if there *were* something on the binding stack that cared that code
259 // moved, it would be wrong. This way we can be sure we don't care.
260 if (code_component_order) {
261 // Assert that defrag will not move the init_function
262 gc_assert(!immobile_space_p(init_function));
263 printf("[defragmenting immobile space... ");
264 fflush(stdout);
265 defrag_immobile_space(code_component_order);
266 printf("done]\n");
268 #endif
270 /* (Now we can actually start copying ourselves into the output file.) */
272 printf("[saving current Lisp image into %s:\n", filename);
273 fflush(stdout);
275 core_start_pos = ftell(file);
276 write_lispobj(CORE_MAGIC, file);
278 write_lispobj(BUILD_ID_CORE_ENTRY_TYPE_CODE, file);
279 write_lispobj(/* (We're writing the word count of the entry here, and the 2
280 * term is one word for the leading BUILD_ID_CORE_ENTRY_TYPE_CODE
281 * word and one word where we store the count itself.) */
282 2 + strlen((const char *)build_id),
283 file);
285 unsigned char *p;
286 for (p = (unsigned char *)build_id; *p; ++p)
287 write_lispobj(*p, file);
290 write_lispobj(NEW_DIRECTORY_CORE_ENTRY_TYPE_CODE, file);
291 write_lispobj(/* (word count = N spaces described by 5 words each, plus the
292 * entry type code, plus this count itself) */
293 (5*N_SPACES_TO_SAVE)+2, file);
294 output_space(file,
295 READ_ONLY_CORE_SPACE_ID,
296 (lispobj *)READ_ONLY_SPACE_START,
297 (lispobj *)SymbolValue(READ_ONLY_SPACE_FREE_POINTER,0),
298 core_start_pos,
299 core_compression_level);
300 output_space(file,
301 STATIC_CORE_SPACE_ID,
302 (lispobj *)STATIC_SPACE_START,
303 (lispobj *)SymbolValue(STATIC_SPACE_FREE_POINTER,0),
304 core_start_pos,
305 core_compression_level);
306 #ifdef LISP_FEATURE_GENCGC
307 /* Flush the current_region, updating the tables. */
308 gc_alloc_update_all_page_tables(1);
309 update_dynamic_space_free_pointer();
310 #endif
311 #ifdef LISP_FEATURE_IMMOBILE_SPACE
312 prepare_immobile_space_for_save();
313 output_space(file,
314 IMMOBILE_FIXEDOBJ_CORE_SPACE_ID,
315 (lispobj *)IMMOBILE_SPACE_START,
316 (lispobj *)SymbolValue(IMMOBILE_FIXEDOBJ_FREE_POINTER,0),
317 core_start_pos,
318 core_compression_level);
319 output_space(file,
320 IMMOBILE_VARYOBJ_CORE_SPACE_ID,
321 (lispobj *)IMMOBILE_VARYOBJ_SUBSPACE_START,
322 (lispobj *)SymbolValue(IMMOBILE_SPACE_FREE_POINTER,0),
323 core_start_pos,
324 core_compression_level);
325 #endif
326 #ifdef reg_ALLOC
327 #ifdef LISP_FEATURE_GENCGC
328 output_space(file,
329 DYNAMIC_CORE_SPACE_ID,
330 (lispobj *)DYNAMIC_SPACE_START,
331 dynamic_space_free_pointer,
332 core_start_pos,
333 core_compression_level);
334 #else
335 output_space(file,
336 DYNAMIC_CORE_SPACE_ID,
337 (lispobj *)current_dynamic_space,
338 dynamic_space_free_pointer,
339 core_start_pos,
340 core_compression_level);
341 #endif
342 #else
343 output_space(file,
344 DYNAMIC_CORE_SPACE_ID,
345 (lispobj *)DYNAMIC_SPACE_START,
346 (lispobj *)SymbolValue(ALLOCATION_POINTER,0),
347 core_start_pos,
348 core_compression_level);
349 #endif
351 write_lispobj(INITIAL_FUN_CORE_ENTRY_TYPE_CODE, file);
352 write_lispobj(3, file);
353 write_lispobj(init_function, file);
355 #ifdef LISP_FEATURE_GENCGC
357 size_t size = (last_free_page*sizeof(sword_t)+os_vm_page_size-1)
358 &~(os_vm_page_size-1);
359 uword_t *data = calloc(size, 1);
360 if (data) {
361 uword_t word;
362 sword_t offset;
363 page_index_t i;
364 for (i = 0; i < last_free_page; i++) {
365 /* Thanks to alignment requirements, the two low bits
366 * are always zero, so we can use them to store the
367 * allocation type -- region is always closed, so only
368 * the two low bits of allocation flags matter. */
369 word = page_table[i].scan_start_offset;
370 gc_assert((word & 0x03) == 0);
371 data[i] = word | (0x03 & page_table[i].allocated);
373 write_lispobj(PAGE_TABLE_CORE_ENTRY_TYPE_CODE, file);
374 write_lispobj(4, file);
375 write_lispobj(size, file);
376 offset = write_bytes(file, (char *)data, size, core_start_pos);
377 write_lispobj(offset, file);
380 #endif
382 write_lispobj(END_CORE_ENTRY_TYPE_CODE, file);
384 /* Write a trailing header, ignored when parsing the core normally.
385 * This is used to locate the start of the core when the runtime is
386 * prepended to it. */
387 fseek(file, 0, SEEK_END);
389 /* If NULL runtime options are passed to write_runtime_options,
390 * command-line processing is performed as normal in the SBCL
391 * executable. Otherwise, the saved runtime options are used and
392 * all command-line arguments are available to Lisp in
393 * SB-EXT:*POSIX-ARGV*. */
394 write_runtime_options(file,
395 (save_runtime_options ? runtime_options : NULL));
397 if (1 != fwrite(&core_start_pos, sizeof(os_vm_offset_t), 1, file)) {
398 perror("Error writing core starting position to file");
399 fclose(file);
400 } else {
401 write_lispobj(CORE_MAGIC, file);
402 fclose(file);
405 #ifndef LISP_FEATURE_WIN32
406 if (make_executable)
407 chmod (filename, 0755);
408 #endif
410 printf("done]\n");
411 exit(0);
413 #undef N_SPACES_TO_SAVE
415 /* Check if the build_id for the current runtime is present in a
416 * buffer. */
418 check_runtime_build_id(void *buf, size_t size)
420 size_t idlen;
421 char *pos;
423 idlen = strlen((const char*)build_id) - 1;
424 while ((pos = memchr(buf, build_id[0], size)) != NULL) {
425 size -= (pos + 1) - (char *)buf;
426 buf = (pos + 1);
427 if (idlen <= size && memcmp(buf, build_id + 1, idlen) == 0)
428 return 1;
431 return 0;
434 /* Slurp the executable portion of the runtime into a malloced buffer
435 * and return it. Places the size in bytes of the runtime into
436 * 'size_out'. Returns NULL if the runtime cannot be loaded from
437 * 'runtime_path'. */
438 void *
439 load_runtime(char *runtime_path, size_t *size_out)
441 void *buf = NULL;
442 FILE *input = NULL;
443 size_t size, count;
444 os_vm_offset_t core_offset;
446 core_offset = search_for_embedded_core (runtime_path);
447 if ((input = fopen(runtime_path, "rb")) == NULL) {
448 fprintf(stderr, "Unable to open runtime: %s\n", runtime_path);
449 goto lose;
452 fseek(input, 0, SEEK_END);
453 size = (size_t) ftell(input);
454 fseek(input, 0, SEEK_SET);
456 if (core_offset != -1 && size > (size_t) core_offset)
457 size = core_offset;
459 buf = successful_malloc(size);
460 if ((count = fread(buf, 1, size, input)) != size) {
461 fprintf(stderr, "Premature EOF while reading runtime.\n");
462 goto lose;
465 if (!check_runtime_build_id(buf, size)) {
466 fprintf(stderr, "Failed to locate current build_id in runtime: %s\n",
467 runtime_path);
468 goto lose;
471 fclose(input);
472 *size_out = size;
473 return buf;
475 lose:
476 if (input != NULL)
477 fclose(input);
478 if (buf != NULL)
479 free(buf);
480 return NULL;
483 boolean
484 save_runtime_to_filehandle(FILE *output, void *runtime, size_t runtime_size,
485 int application_type)
487 size_t padding;
488 void *padbytes;
490 #ifdef LISP_FEATURE_WIN32
492 PIMAGE_DOS_HEADER dos_header = (PIMAGE_DOS_HEADER)runtime;
493 PIMAGE_NT_HEADERS nt_header = (PIMAGE_NT_HEADERS)((char *)dos_header +
494 dos_header->e_lfanew);
496 int sub_system;
497 switch (application_type) {
498 case 0:
499 sub_system = IMAGE_SUBSYSTEM_WINDOWS_CUI;
500 break;
501 case 1:
502 sub_system = IMAGE_SUBSYSTEM_WINDOWS_GUI;
503 break;
504 default:
505 fprintf(stderr, "Invalid application type %d\n", application_type);
506 return 0;
509 nt_header->OptionalHeader.Subsystem = sub_system;
511 #endif
513 if (runtime_size != fwrite(runtime, 1, runtime_size, output)) {
514 perror("Error saving runtime");
515 return 0;
518 padding = (os_vm_page_size - (runtime_size % os_vm_page_size)) & ~os_vm_page_size;
519 if (padding > 0) {
520 padbytes = successful_malloc(padding);
521 memset(padbytes, 0, padding);
522 if (padding != fwrite(padbytes, 1, padding, output)) {
523 perror("Error saving runtime");
524 free(padbytes);
525 return 0;
527 free(padbytes);
530 return 1;
533 FILE *
534 prepare_to_save(char *filename, boolean prepend_runtime, void **runtime_bytes,
535 size_t *runtime_size)
537 FILE *file;
538 char *runtime_path;
540 if (prepend_runtime) {
541 runtime_path = os_get_runtime_executable_path(0);
543 if (runtime_path == NULL && saved_runtime_path == NULL) {
544 fprintf(stderr, "Unable to get default runtime path.\n");
545 return NULL;
548 if (runtime_path == NULL)
549 *runtime_bytes = load_runtime(saved_runtime_path, runtime_size);
550 else {
551 *runtime_bytes = load_runtime(runtime_path, runtime_size);
552 free(runtime_path);
555 if (*runtime_bytes == NULL)
556 return 0;
559 file = open_core_for_saving(filename);
560 if (file == NULL) {
561 free(*runtime_bytes);
562 perror(filename);
563 return NULL;
566 return file;
569 boolean
570 save(char *filename, lispobj init_function, boolean prepend_runtime,
571 boolean save_runtime_options, boolean compressed, int compression_level,
572 int application_type)
574 FILE *file;
575 void *runtime_bytes = NULL;
576 size_t runtime_size;
578 file = prepare_to_save(filename, prepend_runtime, &runtime_bytes, &runtime_size);
579 if (file == NULL)
580 return 1;
582 if (prepend_runtime)
583 save_runtime_to_filehandle(file, runtime_bytes, runtime_size, application_type);
585 return save_to_filehandle(file, filename, init_function, prepend_runtime,
586 save_runtime_options,
587 compressed ? compressed : COMPRESSION_LEVEL_NONE);