Correctly treat progn contents as toplevel forms when byte compiling
[emacs.git] / src / unexw32.c
blobf70cdd794784db778a64b01b678b5c2c350d18d8
1 /* unexec for GNU Emacs on Windows NT.
2 Copyright (C) 1994, 2001-2014 Free Software Foundation, Inc.
4 This file is part of GNU Emacs.
6 GNU Emacs is free software: you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation, either version 3 of the License, or
9 (at your option) any later version.
11 GNU Emacs is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
20 Geoff Voelker (voelker@cs.washington.edu) 8-12-94
23 #include <config.h>
24 #include "unexec.h"
25 #include "lisp.h"
26 #include "w32common.h"
27 #include "w32.h"
29 #include <stdio.h>
30 #include <fcntl.h>
31 #include <time.h>
32 #include <windows.h>
34 /* Include relevant definitions from IMAGEHLP.H, which can be found
35 in \\win32sdk\mstools\samples\image\include\imagehlp.h. */
37 PIMAGE_NT_HEADERS
38 (__stdcall * pfnCheckSumMappedFile) (LPVOID BaseAddress,
39 DWORD FileLength,
40 LPDWORD HeaderSum,
41 LPDWORD CheckSum);
43 extern BOOL ctrl_c_handler (unsigned long type);
45 extern char my_begdata[];
46 extern char my_edata[];
47 extern char my_begbss[];
48 extern char my_endbss[];
49 extern char *my_begbss_static;
50 extern char *my_endbss_static;
52 #include "w32heap.h"
54 #undef min
55 #undef max
56 #define min(x, y) (((x) < (y)) ? (x) : (y))
57 #define max(x, y) (((x) > (y)) ? (x) : (y))
59 /* Basically, our "initialized" flag. */
60 BOOL using_dynamic_heap = FALSE;
62 int open_input_file (file_data *p_file, char *name);
63 int open_output_file (file_data *p_file, char *name, unsigned long size);
64 void close_file_data (file_data *p_file);
66 void get_section_info (file_data *p_file);
67 void copy_executable_and_dump_data (file_data *, file_data *);
68 void dump_bss_and_heap (file_data *p_infile, file_data *p_outfile);
70 /* Cached info about the .data section in the executable. */
71 PIMAGE_SECTION_HEADER data_section;
72 PCHAR data_start = 0;
73 DWORD_PTR data_size = 0;
75 /* Cached info about the .bss section in the executable. */
76 PIMAGE_SECTION_HEADER bss_section;
77 PCHAR bss_start = 0;
78 DWORD_PTR bss_size = 0;
79 DWORD_PTR extra_bss_size = 0;
80 /* bss data that is static might be discontiguous from non-static. */
81 PIMAGE_SECTION_HEADER bss_section_static;
82 PCHAR bss_start_static = 0;
83 DWORD_PTR bss_size_static = 0;
84 DWORD_PTR extra_bss_size_static = 0;
86 PIMAGE_SECTION_HEADER heap_section;
88 /* MinGW64 doesn't add a leading underscore to external symbols,
89 whereas configure.ac sets up LD_SWITCH_SYSTEM_TEMACS to force the
90 entry point at __start, with two underscores. */
91 #ifdef __MINGW64__
92 #define _start __start
93 #endif
95 /* Startup code for running on NT. When we are running as the dumped
96 version, we need to bootstrap our heap and .bss section into our
97 address space before we can actually hand off control to the startup
98 code supplied by NT (primarily because that code relies upon malloc ()). */
99 void
100 _start (void)
102 extern void mainCRTStartup (void);
104 #if 1
105 /* Give us a way to debug problems with crashes on startup when
106 running under the MSVC profiler. */
107 if (GetEnvironmentVariable ("EMACS_DEBUG", NULL, 0) > 0)
108 DebugBreak ();
109 #endif
111 /* Cache system info, e.g., the NT page size. */
112 cache_system_info ();
114 /* Grab our malloc arena space now, before CRT starts up. */
115 init_heap ();
117 /* This prevents ctrl-c's in shells running while we're suspended from
118 having us exit. */
119 SetConsoleCtrlHandler ((PHANDLER_ROUTINE) ctrl_c_handler, TRUE);
121 /* Prevent Emacs from being locked up (eg. in batch mode) when
122 accessing devices that aren't mounted (eg. removable media drives). */
123 SetErrorMode (SEM_FAILCRITICALERRORS);
124 mainCRTStartup ();
128 /* File handling. */
130 /* Implementation note: this and the next functions work with ANSI
131 codepage encoded file names! */
133 open_input_file (file_data *p_file, char *filename)
135 HANDLE file;
136 HANDLE file_mapping;
137 void *file_base;
138 unsigned long size, upper_size;
140 file = CreateFileA (filename, GENERIC_READ, FILE_SHARE_READ, NULL,
141 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
142 if (file == INVALID_HANDLE_VALUE)
143 return FALSE;
145 size = GetFileSize (file, &upper_size);
146 file_mapping = CreateFileMapping (file, NULL, PAGE_READONLY,
147 0, size, NULL);
148 if (!file_mapping)
149 return FALSE;
151 file_base = MapViewOfFile (file_mapping, FILE_MAP_READ, 0, 0, size);
152 if (file_base == 0)
153 return FALSE;
155 p_file->name = filename;
156 p_file->size = size;
157 p_file->file = file;
158 p_file->file_mapping = file_mapping;
159 p_file->file_base = file_base;
161 return TRUE;
165 open_output_file (file_data *p_file, char *filename, unsigned long size)
167 HANDLE file;
168 HANDLE file_mapping;
169 void *file_base;
171 /* We delete any existing FILENAME because loadup.el will create a
172 hard link to it under the name emacs-XX.YY.ZZ.nn.exe. Evidently,
173 overwriting a file on Unix breaks any hard links to it, but that
174 doesn't happen on Windows. If we don't delete the file before
175 creating it, all the emacs-XX.YY.ZZ.nn.exe end up being hard
176 links to the same file, which defeats the purpose of these hard
177 links: being able to run previous builds. */
178 DeleteFileA (filename);
179 file = CreateFileA (filename, GENERIC_READ | GENERIC_WRITE, 0, NULL,
180 CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
181 if (file == INVALID_HANDLE_VALUE)
182 return FALSE;
184 file_mapping = CreateFileMapping (file, NULL, PAGE_READWRITE,
185 0, size, NULL);
186 if (!file_mapping)
187 return FALSE;
189 file_base = MapViewOfFile (file_mapping, FILE_MAP_WRITE, 0, 0, size);
190 if (file_base == 0)
191 return FALSE;
193 p_file->name = filename;
194 p_file->size = size;
195 p_file->file = file;
196 p_file->file_mapping = file_mapping;
197 p_file->file_base = file_base;
199 return TRUE;
202 /* Close the system structures associated with the given file. */
203 void
204 close_file_data (file_data *p_file)
206 UnmapViewOfFile (p_file->file_base);
207 CloseHandle (p_file->file_mapping);
208 /* For the case of output files, set final size. */
209 SetFilePointer (p_file->file, p_file->size, NULL, FILE_BEGIN);
210 SetEndOfFile (p_file->file);
211 CloseHandle (p_file->file);
215 /* Routines to manipulate NT executable file sections. */
217 /* Return pointer to section header for named section. */
218 IMAGE_SECTION_HEADER *
219 find_section (char * name, IMAGE_NT_HEADERS * nt_header)
221 PIMAGE_SECTION_HEADER section;
222 int i;
224 section = IMAGE_FIRST_SECTION (nt_header);
226 for (i = 0; i < nt_header->FileHeader.NumberOfSections; i++)
228 if (strcmp (section->Name, name) == 0)
229 return section;
230 section++;
232 return NULL;
235 /* Return pointer to section header for section containing the given
236 relative virtual address. */
237 IMAGE_SECTION_HEADER *
238 rva_to_section (DWORD_PTR rva, IMAGE_NT_HEADERS * nt_header)
240 PIMAGE_SECTION_HEADER section;
241 int i;
243 section = IMAGE_FIRST_SECTION (nt_header);
245 for (i = 0; i < nt_header->FileHeader.NumberOfSections; i++)
247 /* Some linkers (eg. the NT SDK linker I believe) swapped the
248 meaning of these two values - or rather, they ignored
249 VirtualSize entirely and always set it to zero. This affects
250 some very old exes (eg. gzip dated Dec 1993). Since
251 w32_executable_type relies on this function to work reliably,
252 we need to cope with this. */
253 DWORD_PTR real_size = max (section->SizeOfRawData,
254 section->Misc.VirtualSize);
255 if (rva >= section->VirtualAddress
256 && rva < section->VirtualAddress + real_size)
257 return section;
258 section++;
260 return NULL;
263 /* Return pointer to section header for section containing the given
264 offset in its raw data area. */
265 IMAGE_SECTION_HEADER *
266 offset_to_section (DWORD_PTR offset, IMAGE_NT_HEADERS * nt_header)
268 PIMAGE_SECTION_HEADER section;
269 int i;
271 section = IMAGE_FIRST_SECTION (nt_header);
273 for (i = 0; i < nt_header->FileHeader.NumberOfSections; i++)
275 if (offset >= section->PointerToRawData
276 && offset < section->PointerToRawData + section->SizeOfRawData)
277 return section;
278 section++;
280 return NULL;
283 /* Return offset to an object in dst, given offset in src. We assume
284 there is at least one section in both src and dst images, and that
285 the some sections may have been added to dst (after sections in src). */
286 DWORD_PTR
287 relocate_offset (DWORD_PTR offset,
288 IMAGE_NT_HEADERS * src_nt_header,
289 IMAGE_NT_HEADERS * dst_nt_header)
291 PIMAGE_SECTION_HEADER src_section = IMAGE_FIRST_SECTION (src_nt_header);
292 PIMAGE_SECTION_HEADER dst_section = IMAGE_FIRST_SECTION (dst_nt_header);
293 int i = 0;
295 while (offset >= src_section->PointerToRawData)
297 if (offset < src_section->PointerToRawData + src_section->SizeOfRawData)
298 break;
299 i++;
300 if (i == src_nt_header->FileHeader.NumberOfSections)
302 /* Handle offsets after the last section. */
303 dst_section = IMAGE_FIRST_SECTION (dst_nt_header);
304 dst_section += dst_nt_header->FileHeader.NumberOfSections - 1;
305 while (dst_section->PointerToRawData == 0)
306 dst_section--;
307 while (src_section->PointerToRawData == 0)
308 src_section--;
309 return offset
310 + (dst_section->PointerToRawData + dst_section->SizeOfRawData)
311 - (src_section->PointerToRawData + src_section->SizeOfRawData);
313 src_section++;
314 dst_section++;
316 return offset +
317 (dst_section->PointerToRawData - src_section->PointerToRawData);
320 #define OFFSET_TO_RVA(offset, section) \
321 ((section)->VirtualAddress + ((DWORD_PTR)(offset) - (section)->PointerToRawData))
323 #define RVA_TO_OFFSET(rva, section) \
324 ((section)->PointerToRawData + ((DWORD_PTR)(rva) - (section)->VirtualAddress))
326 #define RVA_TO_SECTION_OFFSET(rva, section) \
327 ((DWORD_PTR)(rva) - (section)->VirtualAddress)
329 /* Convert address in executing image to RVA. */
330 #define PTR_TO_RVA(ptr) ((DWORD_PTR)(ptr) - (DWORD_PTR) GetModuleHandle (NULL))
332 #define RVA_TO_PTR(var,section,filedata) \
333 ((unsigned char *)(RVA_TO_OFFSET (var,section) + (filedata).file_base))
335 #define PTR_TO_OFFSET(ptr, pfile_data) \
336 ((unsigned char *)(ptr) - (pfile_data)->file_base)
338 #define OFFSET_TO_PTR(offset, pfile_data) \
339 ((pfile_data)->file_base + (DWORD_PTR)(offset))
342 /* Flip through the executable and cache the info necessary for dumping. */
343 void
344 get_section_info (file_data *p_infile)
346 PIMAGE_DOS_HEADER dos_header;
347 PIMAGE_NT_HEADERS nt_header;
348 int overlap;
350 dos_header = (PIMAGE_DOS_HEADER) p_infile->file_base;
351 if (dos_header->e_magic != IMAGE_DOS_SIGNATURE)
353 printf ("Unknown EXE header in %s...bailing.\n", p_infile->name);
354 exit (1);
356 nt_header = (PIMAGE_NT_HEADERS) (((DWORD_PTR) dos_header) +
357 dos_header->e_lfanew);
358 if (nt_header == NULL)
360 printf ("Failed to find IMAGE_NT_HEADER in %s...bailing.\n",
361 p_infile->name);
362 exit (1);
365 /* Check the NT header signature ... */
366 if (nt_header->Signature != IMAGE_NT_SIGNATURE)
368 printf ("Invalid IMAGE_NT_SIGNATURE 0x%x in %s...bailing.\n",
369 nt_header->Signature, p_infile->name);
370 exit (1);
373 /* Locate the ".data" and ".bss" sections for Emacs. (Note that the
374 actual section names are probably different from these, and might
375 actually be the same section.)
377 We do this as follows: first we determine the virtual address
378 ranges in this process for the data and bss variables that we wish
379 to preserve. Then we map these VAs to the section entries in the
380 source image. Finally, we determine the new size of the raw data
381 area for the bss section, so we can make the new image the correct
382 size. */
384 /* We arrange for the Emacs initialized data to be in a separate
385 section if possible, because we cannot rely on my_begdata and
386 my_edata marking out the full extent of the initialized data, at
387 least on the Alpha where the linker freely reorders variables
388 across libraries. If we can arrange for this, all we need to do is
389 find the start and size of the EMDATA section. */
390 data_section = find_section ("EMDATA", nt_header);
391 if (data_section)
393 data_start = (char *) nt_header->OptionalHeader.ImageBase +
394 data_section->VirtualAddress;
395 data_size = data_section->Misc.VirtualSize;
397 else
399 /* Fallback on the old method if compiler doesn't support the
400 data_set #pragma (or its equivalent). */
401 data_start = my_begdata;
402 data_size = my_edata - my_begdata;
403 data_section = rva_to_section (PTR_TO_RVA (my_begdata), nt_header);
404 if (data_section != rva_to_section (PTR_TO_RVA (my_edata), nt_header))
406 printf ("Initialized data is not in a single section...bailing\n");
407 exit (1);
411 /* As noted in lastfile.c, the Alpha (but not the Intel) MSVC linker
412 globally segregates all static and public bss data (ie. across all
413 linked modules, not just per module), so we must take both static
414 and public bss areas into account to determine the true extent of
415 the bss area used by Emacs.
417 To be strictly correct, we dump the static and public bss areas
418 used by Emacs separately if non-overlapping (since otherwise we are
419 dumping bss data belonging to system libraries, eg. the static bss
420 system data on the Alpha). */
422 bss_start = my_begbss;
423 bss_size = my_endbss - my_begbss;
424 bss_section = rva_to_section (PTR_TO_RVA (my_begbss), nt_header);
425 if (bss_section != rva_to_section (PTR_TO_RVA (my_endbss), nt_header))
427 printf ("Uninitialized data is not in a single section...bailing\n");
428 exit (1);
430 /* Compute how much the .bss section's raw data will grow. */
431 extra_bss_size =
432 ROUND_UP (RVA_TO_SECTION_OFFSET (PTR_TO_RVA (my_endbss), bss_section),
433 nt_header->OptionalHeader.FileAlignment)
434 - bss_section->SizeOfRawData;
436 bss_start_static = my_begbss_static;
437 bss_size_static = my_endbss_static - my_begbss_static;
438 bss_section_static = rva_to_section (PTR_TO_RVA (my_begbss_static), nt_header);
439 if (bss_section_static != rva_to_section (PTR_TO_RVA (my_endbss_static), nt_header))
441 printf ("Uninitialized static data is not in a single section...bailing\n");
442 exit (1);
444 /* Compute how much the static .bss section's raw data will grow. */
445 extra_bss_size_static =
446 ROUND_UP (RVA_TO_SECTION_OFFSET (PTR_TO_RVA (my_endbss_static), bss_section_static),
447 nt_header->OptionalHeader.FileAlignment)
448 - bss_section_static->SizeOfRawData;
450 /* Combine the bss sections into one if they overlap. */
451 #ifdef _ALPHA_
452 overlap = 1; /* force all bss data to be dumped */
453 #else
454 overlap = 0;
455 #endif
456 if (bss_start < bss_start_static)
458 if (bss_start_static < bss_start + bss_size)
459 overlap = 1;
461 else
463 if (bss_start < bss_start_static + bss_size_static)
464 overlap = 1;
466 if (overlap)
468 if (bss_section != bss_section_static)
470 printf ("BSS data not in a single section...bailing\n");
471 exit (1);
473 bss_start = min (bss_start, bss_start_static);
474 bss_size = max (my_endbss, my_endbss_static) - bss_start;
475 bss_section_static = 0;
476 extra_bss_size_static = 0;
479 heap_section = rva_to_section (PTR_TO_RVA (get_heap_start ()), nt_header);
483 /* The dump routines. */
485 void
486 copy_executable_and_dump_data (file_data *p_infile,
487 file_data *p_outfile)
489 unsigned char *dst, *dst_save;
490 PIMAGE_DOS_HEADER dos_header;
491 PIMAGE_NT_HEADERS nt_header;
492 PIMAGE_NT_HEADERS dst_nt_header;
493 PIMAGE_SECTION_HEADER section;
494 PIMAGE_SECTION_HEADER dst_section;
495 DWORD_PTR offset;
496 int i;
497 int be_verbose = GetEnvironmentVariable ("DEBUG_DUMP", NULL, 0) > 0;
499 #define COPY_CHUNK(message, src, size, verbose) \
500 do { \
501 unsigned char *s = (void *)(src); \
502 unsigned long count = (size); \
503 if (verbose) \
505 printf ("%s\n", (message)); \
506 printf ("\t0x%08x Offset in input file.\n", s - p_infile->file_base); \
507 printf ("\t0x%08x Offset in output file.\n", dst - p_outfile->file_base); \
508 printf ("\t0x%08x Size in bytes.\n", count); \
510 memcpy (dst, s, count); \
511 dst += count; \
512 } while (0)
514 #define COPY_PROC_CHUNK(message, src, size, verbose) \
515 do { \
516 unsigned char *s = (void *)(src); \
517 unsigned long count = (size); \
518 if (verbose) \
520 printf ("%s\n", (message)); \
521 printf ("\t0x%08x Address in process.\n", s); \
522 printf ("\t0x%08x Offset in output file.\n", dst - p_outfile->file_base); \
523 printf ("\t0x%08x Size in bytes.\n", count); \
525 memcpy (dst, s, count); \
526 dst += count; \
527 } while (0)
529 #define DST_TO_OFFSET() PTR_TO_OFFSET (dst, p_outfile)
530 #define ROUND_UP_DST(align) \
531 (dst = p_outfile->file_base + ROUND_UP (DST_TO_OFFSET (), (align)))
532 #define ROUND_UP_DST_AND_ZERO(align) \
533 do { \
534 unsigned char *newdst = p_outfile->file_base \
535 + ROUND_UP (DST_TO_OFFSET (), (align)); \
536 /* Zero the alignment slop; it may actually initialize real data. */ \
537 memset (dst, 0, newdst - dst); \
538 dst = newdst; \
539 } while (0)
541 /* Copy the source image sequentially, ie. section by section after
542 copying the headers and section table, to simplify the process of
543 dumping the raw data for the bss and heap sections.
545 Note that dst is updated implicitly by each COPY_CHUNK. */
547 dos_header = (PIMAGE_DOS_HEADER) p_infile->file_base;
548 nt_header = (PIMAGE_NT_HEADERS) (((DWORD_PTR) dos_header) +
549 dos_header->e_lfanew);
550 section = IMAGE_FIRST_SECTION (nt_header);
552 dst = (unsigned char *) p_outfile->file_base;
554 COPY_CHUNK ("Copying DOS header...", dos_header,
555 (DWORD_PTR) nt_header - (DWORD_PTR) dos_header, be_verbose);
556 dst_nt_header = (PIMAGE_NT_HEADERS) dst;
557 COPY_CHUNK ("Copying NT header...", nt_header,
558 (DWORD_PTR) section - (DWORD_PTR) nt_header, be_verbose);
559 dst_section = (PIMAGE_SECTION_HEADER) dst;
560 COPY_CHUNK ("Copying section table...", section,
561 nt_header->FileHeader.NumberOfSections * sizeof (*section),
562 be_verbose);
564 /* Align the first section's raw data area, and set the header size
565 field accordingly. */
566 ROUND_UP_DST_AND_ZERO (dst_nt_header->OptionalHeader.FileAlignment);
567 dst_nt_header->OptionalHeader.SizeOfHeaders = DST_TO_OFFSET ();
569 for (i = 0; i < nt_header->FileHeader.NumberOfSections; i++)
571 char msg[100];
572 /* Windows section names are fixed 8-char strings, only
573 zero-terminated if the name is shorter than 8 characters. */
574 sprintf (msg, "Copying raw data for %.8s...", section->Name);
576 dst_save = dst;
578 /* Update the file-relative offset for this section's raw data (if
579 it has any) in case things have been relocated; we will update
580 the other offsets below once we know where everything is. */
581 if (dst_section->PointerToRawData)
582 dst_section->PointerToRawData = DST_TO_OFFSET ();
584 /* Can always copy the original raw data. */
585 COPY_CHUNK
586 (msg, OFFSET_TO_PTR (section->PointerToRawData, p_infile),
587 section->SizeOfRawData, be_verbose);
588 /* Ensure alignment slop is zeroed. */
589 ROUND_UP_DST_AND_ZERO (dst_nt_header->OptionalHeader.FileAlignment);
591 /* Note that various sections below may be aliases. */
592 if (section == data_section)
594 dst = dst_save
595 + RVA_TO_SECTION_OFFSET (PTR_TO_RVA (data_start), dst_section);
596 COPY_PROC_CHUNK ("Dumping initialized data...",
597 data_start, data_size, be_verbose);
598 dst = dst_save + dst_section->SizeOfRawData;
600 if (section == bss_section)
602 /* Dump contents of bss variables, adjusting the section's raw
603 data size as necessary. */
604 dst = dst_save
605 + RVA_TO_SECTION_OFFSET (PTR_TO_RVA (bss_start), dst_section);
606 COPY_PROC_CHUNK ("Dumping bss data...", bss_start,
607 bss_size, be_verbose);
608 ROUND_UP_DST (dst_nt_header->OptionalHeader.FileAlignment);
609 dst_section->PointerToRawData = PTR_TO_OFFSET (dst_save, p_outfile);
610 /* Determine new size of raw data area. */
611 dst = max (dst, dst_save + dst_section->SizeOfRawData);
612 dst_section->SizeOfRawData = dst - dst_save;
613 dst_section->Characteristics &= ~IMAGE_SCN_CNT_UNINITIALIZED_DATA;
614 dst_section->Characteristics |= IMAGE_SCN_CNT_INITIALIZED_DATA;
616 if (section == bss_section_static)
618 /* Dump contents of static bss variables, adjusting the
619 section's raw data size as necessary. */
620 dst = dst_save
621 + RVA_TO_SECTION_OFFSET (PTR_TO_RVA (bss_start_static), dst_section);
622 COPY_PROC_CHUNK ("Dumping static bss data...", bss_start_static,
623 bss_size_static, be_verbose);
624 ROUND_UP_DST (dst_nt_header->OptionalHeader.FileAlignment);
625 dst_section->PointerToRawData = PTR_TO_OFFSET (dst_save, p_outfile);
626 /* Determine new size of raw data area. */
627 dst = max (dst, dst_save + dst_section->SizeOfRawData);
628 dst_section->SizeOfRawData = dst - dst_save;
629 dst_section->Characteristics &= ~IMAGE_SCN_CNT_UNINITIALIZED_DATA;
630 dst_section->Characteristics |= IMAGE_SCN_CNT_INITIALIZED_DATA;
632 if (section == heap_section)
634 DWORD_PTR heap_start = (DWORD_PTR) get_heap_start ();
635 DWORD_PTR heap_size = get_committed_heap_size ();
637 /* Dump the used portion of the predump heap, adjusting the
638 section's size to the appropriate size. */
639 dst = dst_save
640 + RVA_TO_SECTION_OFFSET (PTR_TO_RVA (heap_start), dst_section);
641 COPY_PROC_CHUNK ("Dumping heap...", heap_start, heap_size,
642 be_verbose);
643 ROUND_UP_DST (dst_nt_header->OptionalHeader.FileAlignment);
644 dst_section->PointerToRawData = PTR_TO_OFFSET (dst_save, p_outfile);
645 /* Determine new size of raw data area. */
646 dst = max (dst, dst_save + dst_section->SizeOfRawData);
647 dst_section->SizeOfRawData = dst - dst_save;
648 /* Reduce the size of the heap section to fit (must be last
649 section). */
650 dst_nt_header->OptionalHeader.SizeOfImage -=
651 dst_section->Misc.VirtualSize
652 - ROUND_UP (dst_section->SizeOfRawData,
653 dst_nt_header->OptionalHeader.SectionAlignment);
654 dst_section->Misc.VirtualSize =
655 ROUND_UP (dst_section->SizeOfRawData,
656 dst_nt_header->OptionalHeader.SectionAlignment);
657 dst_section->Characteristics &= ~IMAGE_SCN_CNT_UNINITIALIZED_DATA;
658 dst_section->Characteristics |= IMAGE_SCN_CNT_INITIALIZED_DATA;
661 /* Align the section's raw data area. */
662 ROUND_UP_DST (dst_nt_header->OptionalHeader.FileAlignment);
664 section++;
665 dst_section++;
668 /* Copy remainder of source image. */
670 section--;
671 while (section->PointerToRawData == 0);
672 offset = ROUND_UP (section->PointerToRawData + section->SizeOfRawData,
673 nt_header->OptionalHeader.FileAlignment);
674 COPY_CHUNK
675 ("Copying remainder of executable...",
676 OFFSET_TO_PTR (offset, p_infile),
677 p_infile->size - offset, be_verbose);
679 /* Final size for new image. */
680 p_outfile->size = DST_TO_OFFSET ();
682 /* Now patch up remaining file-relative offsets. */
683 section = IMAGE_FIRST_SECTION (nt_header);
684 dst_section = IMAGE_FIRST_SECTION (dst_nt_header);
686 #define ADJUST_OFFSET(var) \
687 do { \
688 if ((var) != 0) \
689 (var) = relocate_offset ((var), nt_header, dst_nt_header); \
690 } while (0)
692 dst_nt_header->OptionalHeader.SizeOfInitializedData = 0;
693 dst_nt_header->OptionalHeader.SizeOfUninitializedData = 0;
694 for (i = 0; i < dst_nt_header->FileHeader.NumberOfSections; i++)
696 /* Recompute data sizes for completeness. */
697 if (dst_section[i].Characteristics & IMAGE_SCN_CNT_INITIALIZED_DATA)
698 dst_nt_header->OptionalHeader.SizeOfInitializedData +=
699 ROUND_UP (dst_section[i].Misc.VirtualSize, dst_nt_header->OptionalHeader.FileAlignment);
700 else if (dst_section[i].Characteristics & IMAGE_SCN_CNT_UNINITIALIZED_DATA)
701 dst_nt_header->OptionalHeader.SizeOfUninitializedData +=
702 ROUND_UP (dst_section[i].Misc.VirtualSize, dst_nt_header->OptionalHeader.FileAlignment);
704 ADJUST_OFFSET (dst_section[i].PointerToLinenumbers);
707 ADJUST_OFFSET (dst_nt_header->FileHeader.PointerToSymbolTable);
709 /* Update offsets in debug directory entries. */
711 IMAGE_DATA_DIRECTORY debug_dir =
712 dst_nt_header->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_DEBUG];
713 PIMAGE_DEBUG_DIRECTORY debug_entry;
715 section = rva_to_section (debug_dir.VirtualAddress, dst_nt_header);
716 if (section)
718 debug_entry = (PIMAGE_DEBUG_DIRECTORY)
719 (RVA_TO_OFFSET (debug_dir.VirtualAddress, section) + p_outfile->file_base);
720 debug_dir.Size /= sizeof (IMAGE_DEBUG_DIRECTORY);
722 for (i = 0; i < debug_dir.Size; i++, debug_entry++)
723 ADJUST_OFFSET (debug_entry->PointerToRawData);
729 /* Dump out .data and .bss sections into a new executable. */
730 void
731 unexec (const char *new_name, const char *old_name)
733 file_data in_file, out_file;
734 char out_filename[MAX_PATH], in_filename[MAX_PATH], new_name_a[MAX_PATH];
735 unsigned long size;
736 char *p;
737 char *q;
739 /* Ignore old_name, and get our actual location from the OS. */
740 if (!GetModuleFileNameA (NULL, in_filename, MAX_PATH))
741 abort ();
743 /* Can't use dostounix_filename here, since that needs its file name
744 argument encoded in UTF-8. */
745 for (p = in_filename; *p; p = CharNextA (p))
746 if (*p == '\\')
747 *p = '/';
749 strcpy (out_filename, in_filename);
750 filename_to_ansi (new_name, new_name_a);
752 /* Change the base of the output filename to match the requested name. */
753 if ((p = strrchr (out_filename, '/')) == NULL)
754 abort ();
755 /* The filenames have already been expanded, and will be in Unix
756 format, so it is safe to expect an absolute name. */
757 if ((q = strrchr (new_name_a, '/')) == NULL)
758 abort ();
759 strcpy (p, q);
761 /* Make sure that the output filename has the ".exe" extension...patch
762 it up if not. */
763 p = out_filename + strlen (out_filename) - 4;
764 if (strcmp (p, ".exe"))
765 strcat (out_filename, ".exe");
767 printf ("Dumping from %s\n", in_filename);
768 printf (" to %s\n", out_filename);
770 /* We need to round off our heap to NT's page size. */
771 round_heap (get_page_size ());
773 /* Open the undumped executable file. */
774 if (!open_input_file (&in_file, in_filename))
776 printf ("Failed to open %s (%d)...bailing.\n",
777 in_filename, GetLastError ());
778 exit (1);
781 /* Get the interesting section info, like start and size of .bss... */
782 get_section_info (&in_file);
784 /* The size of the dumped executable is the size of the original
785 executable plus the size of the heap and the size of the .bss section. */
786 size = in_file.size +
787 get_committed_heap_size () +
788 extra_bss_size +
789 extra_bss_size_static;
790 if (!open_output_file (&out_file, out_filename, size))
792 printf ("Failed to open %s (%d)...bailing.\n",
793 out_filename, GetLastError ());
794 exit (1);
797 /* Set the flag (before dumping). */
798 using_dynamic_heap = TRUE;
800 copy_executable_and_dump_data (&in_file, &out_file);
802 /* Patch up header fields; profiler is picky about this. */
804 PIMAGE_DOS_HEADER dos_header;
805 PIMAGE_NT_HEADERS nt_header;
806 HANDLE hImagehelp = LoadLibrary ("imagehlp.dll");
807 DWORD headersum;
808 DWORD checksum;
810 dos_header = (PIMAGE_DOS_HEADER) out_file.file_base;
811 nt_header = (PIMAGE_NT_HEADERS) ((char *) dos_header + dos_header->e_lfanew);
813 nt_header->OptionalHeader.CheckSum = 0;
814 // nt_header->FileHeader.TimeDateStamp = time (NULL);
815 // dos_header->e_cp = size / 512;
816 // nt_header->OptionalHeader.SizeOfImage = size;
818 pfnCheckSumMappedFile = (void *) GetProcAddress (hImagehelp, "CheckSumMappedFile");
819 if (pfnCheckSumMappedFile)
821 // nt_header->FileHeader.TimeDateStamp = time (NULL);
822 pfnCheckSumMappedFile (out_file.file_base,
823 out_file.size,
824 &headersum,
825 &checksum);
826 nt_header->OptionalHeader.CheckSum = checksum;
828 FreeLibrary (hImagehelp);
831 close_file_data (&in_file);
832 close_file_data (&out_file);
835 /* eof */