Update copyright year to 2014 by running admin/update-copyright.
[emacs.git] / src / unexw32.c
blob5411cd2a95c3d3a16b8b47532b07a1b8c5b4e4ba
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 /* Startup code for running on NT. When we are running as the dumped
89 version, we need to bootstrap our heap and .bss section into our
90 address space before we can actually hand off control to the startup
91 code supplied by NT (primarily because that code relies upon malloc ()). */
92 void
93 _start (void)
95 extern void mainCRTStartup (void);
97 #if 1
98 /* Give us a way to debug problems with crashes on startup when
99 running under the MSVC profiler. */
100 if (GetEnvironmentVariable ("EMACS_DEBUG", NULL, 0) > 0)
101 DebugBreak ();
102 #endif
104 /* Cache system info, e.g., the NT page size. */
105 cache_system_info ();
107 /* Grab our malloc arena space now, before CRT starts up. */
108 init_heap ();
110 /* This prevents ctrl-c's in shells running while we're suspended from
111 having us exit. */
112 SetConsoleCtrlHandler ((PHANDLER_ROUTINE) ctrl_c_handler, TRUE);
114 /* Prevent Emacs from being locked up (eg. in batch mode) when
115 accessing devices that aren't mounted (eg. removable media drives). */
116 SetErrorMode (SEM_FAILCRITICALERRORS);
117 mainCRTStartup ();
121 /* File handling. */
123 /* Implementation note: this and the next functions work with ANSI
124 codepage encoded file names! */
126 open_input_file (file_data *p_file, char *filename)
128 HANDLE file;
129 HANDLE file_mapping;
130 void *file_base;
131 unsigned long size, upper_size;
133 file = CreateFileA (filename, GENERIC_READ, FILE_SHARE_READ, NULL,
134 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
135 if (file == INVALID_HANDLE_VALUE)
136 return FALSE;
138 size = GetFileSize (file, &upper_size);
139 file_mapping = CreateFileMapping (file, NULL, PAGE_READONLY,
140 0, size, NULL);
141 if (!file_mapping)
142 return FALSE;
144 file_base = MapViewOfFile (file_mapping, FILE_MAP_READ, 0, 0, size);
145 if (file_base == 0)
146 return FALSE;
148 p_file->name = filename;
149 p_file->size = size;
150 p_file->file = file;
151 p_file->file_mapping = file_mapping;
152 p_file->file_base = file_base;
154 return TRUE;
158 open_output_file (file_data *p_file, char *filename, unsigned long size)
160 HANDLE file;
161 HANDLE file_mapping;
162 void *file_base;
164 /* We delete any existing FILENAME because loadup.el will create a
165 hard link to it under the name emacs-XX.YY.ZZ.nn.exe. Evidently,
166 overwriting a file on Unix breaks any hard links to it, but that
167 doesn't happen on Windows. If we don't delete the file before
168 creating it, all the emacs-XX.YY.ZZ.nn.exe end up being hard
169 links to the same file, which defeats the purpose of these hard
170 links: being able to run previous builds. */
171 DeleteFileA (filename);
172 file = CreateFileA (filename, GENERIC_READ | GENERIC_WRITE, 0, NULL,
173 CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
174 if (file == INVALID_HANDLE_VALUE)
175 return FALSE;
177 file_mapping = CreateFileMapping (file, NULL, PAGE_READWRITE,
178 0, size, NULL);
179 if (!file_mapping)
180 return FALSE;
182 file_base = MapViewOfFile (file_mapping, FILE_MAP_WRITE, 0, 0, size);
183 if (file_base == 0)
184 return FALSE;
186 p_file->name = filename;
187 p_file->size = size;
188 p_file->file = file;
189 p_file->file_mapping = file_mapping;
190 p_file->file_base = file_base;
192 return TRUE;
195 /* Close the system structures associated with the given file. */
196 void
197 close_file_data (file_data *p_file)
199 UnmapViewOfFile (p_file->file_base);
200 CloseHandle (p_file->file_mapping);
201 /* For the case of output files, set final size. */
202 SetFilePointer (p_file->file, p_file->size, NULL, FILE_BEGIN);
203 SetEndOfFile (p_file->file);
204 CloseHandle (p_file->file);
208 /* Routines to manipulate NT executable file sections. */
210 /* Return pointer to section header for named section. */
211 IMAGE_SECTION_HEADER *
212 find_section (char * name, IMAGE_NT_HEADERS * nt_header)
214 PIMAGE_SECTION_HEADER section;
215 int i;
217 section = IMAGE_FIRST_SECTION (nt_header);
219 for (i = 0; i < nt_header->FileHeader.NumberOfSections; i++)
221 if (strcmp (section->Name, name) == 0)
222 return section;
223 section++;
225 return NULL;
228 /* Return pointer to section header for section containing the given
229 relative virtual address. */
230 IMAGE_SECTION_HEADER *
231 rva_to_section (DWORD_PTR rva, IMAGE_NT_HEADERS * nt_header)
233 PIMAGE_SECTION_HEADER section;
234 int i;
236 section = IMAGE_FIRST_SECTION (nt_header);
238 for (i = 0; i < nt_header->FileHeader.NumberOfSections; i++)
240 /* Some linkers (eg. the NT SDK linker I believe) swapped the
241 meaning of these two values - or rather, they ignored
242 VirtualSize entirely and always set it to zero. This affects
243 some very old exes (eg. gzip dated Dec 1993). Since
244 w32_executable_type relies on this function to work reliably,
245 we need to cope with this. */
246 DWORD_PTR real_size = max (section->SizeOfRawData,
247 section->Misc.VirtualSize);
248 if (rva >= section->VirtualAddress
249 && rva < section->VirtualAddress + real_size)
250 return section;
251 section++;
253 return NULL;
256 /* Return pointer to section header for section containing the given
257 offset in its raw data area. */
258 IMAGE_SECTION_HEADER *
259 offset_to_section (DWORD_PTR offset, IMAGE_NT_HEADERS * nt_header)
261 PIMAGE_SECTION_HEADER section;
262 int i;
264 section = IMAGE_FIRST_SECTION (nt_header);
266 for (i = 0; i < nt_header->FileHeader.NumberOfSections; i++)
268 if (offset >= section->PointerToRawData
269 && offset < section->PointerToRawData + section->SizeOfRawData)
270 return section;
271 section++;
273 return NULL;
276 /* Return offset to an object in dst, given offset in src. We assume
277 there is at least one section in both src and dst images, and that
278 the some sections may have been added to dst (after sections in src). */
279 DWORD_PTR
280 relocate_offset (DWORD_PTR offset,
281 IMAGE_NT_HEADERS * src_nt_header,
282 IMAGE_NT_HEADERS * dst_nt_header)
284 PIMAGE_SECTION_HEADER src_section = IMAGE_FIRST_SECTION (src_nt_header);
285 PIMAGE_SECTION_HEADER dst_section = IMAGE_FIRST_SECTION (dst_nt_header);
286 int i = 0;
288 while (offset >= src_section->PointerToRawData)
290 if (offset < src_section->PointerToRawData + src_section->SizeOfRawData)
291 break;
292 i++;
293 if (i == src_nt_header->FileHeader.NumberOfSections)
295 /* Handle offsets after the last section. */
296 dst_section = IMAGE_FIRST_SECTION (dst_nt_header);
297 dst_section += dst_nt_header->FileHeader.NumberOfSections - 1;
298 while (dst_section->PointerToRawData == 0)
299 dst_section--;
300 while (src_section->PointerToRawData == 0)
301 src_section--;
302 return offset
303 + (dst_section->PointerToRawData + dst_section->SizeOfRawData)
304 - (src_section->PointerToRawData + src_section->SizeOfRawData);
306 src_section++;
307 dst_section++;
309 return offset +
310 (dst_section->PointerToRawData - src_section->PointerToRawData);
313 #define OFFSET_TO_RVA(offset, section) \
314 ((section)->VirtualAddress + ((DWORD_PTR)(offset) - (section)->PointerToRawData))
316 #define RVA_TO_OFFSET(rva, section) \
317 ((section)->PointerToRawData + ((DWORD_PTR)(rva) - (section)->VirtualAddress))
319 #define RVA_TO_SECTION_OFFSET(rva, section) \
320 ((DWORD_PTR)(rva) - (section)->VirtualAddress)
322 /* Convert address in executing image to RVA. */
323 #define PTR_TO_RVA(ptr) ((DWORD_PTR)(ptr) - (DWORD_PTR) GetModuleHandle (NULL))
325 #define RVA_TO_PTR(var,section,filedata) \
326 ((unsigned char *)(RVA_TO_OFFSET (var,section) + (filedata).file_base))
328 #define PTR_TO_OFFSET(ptr, pfile_data) \
329 ((unsigned char *)(ptr) - (pfile_data)->file_base)
331 #define OFFSET_TO_PTR(offset, pfile_data) \
332 ((pfile_data)->file_base + (DWORD_PTR)(offset))
335 /* Flip through the executable and cache the info necessary for dumping. */
336 void
337 get_section_info (file_data *p_infile)
339 PIMAGE_DOS_HEADER dos_header;
340 PIMAGE_NT_HEADERS nt_header;
341 int overlap;
343 dos_header = (PIMAGE_DOS_HEADER) p_infile->file_base;
344 if (dos_header->e_magic != IMAGE_DOS_SIGNATURE)
346 printf ("Unknown EXE header in %s...bailing.\n", p_infile->name);
347 exit (1);
349 nt_header = (PIMAGE_NT_HEADERS) (((DWORD_PTR) dos_header) +
350 dos_header->e_lfanew);
351 if (nt_header == NULL)
353 printf ("Failed to find IMAGE_NT_HEADER in %s...bailing.\n",
354 p_infile->name);
355 exit (1);
358 /* Check the NT header signature ... */
359 if (nt_header->Signature != IMAGE_NT_SIGNATURE)
361 printf ("Invalid IMAGE_NT_SIGNATURE 0x%x in %s...bailing.\n",
362 nt_header->Signature, p_infile->name);
363 exit (1);
366 /* Locate the ".data" and ".bss" sections for Emacs. (Note that the
367 actual section names are probably different from these, and might
368 actually be the same section.)
370 We do this as follows: first we determine the virtual address
371 ranges in this process for the data and bss variables that we wish
372 to preserve. Then we map these VAs to the section entries in the
373 source image. Finally, we determine the new size of the raw data
374 area for the bss section, so we can make the new image the correct
375 size. */
377 /* We arrange for the Emacs initialized data to be in a separate
378 section if possible, because we cannot rely on my_begdata and
379 my_edata marking out the full extent of the initialized data, at
380 least on the Alpha where the linker freely reorders variables
381 across libraries. If we can arrange for this, all we need to do is
382 find the start and size of the EMDATA section. */
383 data_section = find_section ("EMDATA", nt_header);
384 if (data_section)
386 data_start = (char *) nt_header->OptionalHeader.ImageBase +
387 data_section->VirtualAddress;
388 data_size = data_section->Misc.VirtualSize;
390 else
392 /* Fallback on the old method if compiler doesn't support the
393 data_set #pragma (or its equivalent). */
394 data_start = my_begdata;
395 data_size = my_edata - my_begdata;
396 data_section = rva_to_section (PTR_TO_RVA (my_begdata), nt_header);
397 if (data_section != rva_to_section (PTR_TO_RVA (my_edata), nt_header))
399 printf ("Initialized data is not in a single section...bailing\n");
400 exit (1);
404 /* As noted in lastfile.c, the Alpha (but not the Intel) MSVC linker
405 globally segregates all static and public bss data (ie. across all
406 linked modules, not just per module), so we must take both static
407 and public bss areas into account to determine the true extent of
408 the bss area used by Emacs.
410 To be strictly correct, we dump the static and public bss areas
411 used by Emacs separately if non-overlapping (since otherwise we are
412 dumping bss data belonging to system libraries, eg. the static bss
413 system data on the Alpha). */
415 bss_start = my_begbss;
416 bss_size = my_endbss - my_begbss;
417 bss_section = rva_to_section (PTR_TO_RVA (my_begbss), nt_header);
418 if (bss_section != rva_to_section (PTR_TO_RVA (my_endbss), nt_header))
420 printf ("Uninitialized data is not in a single section...bailing\n");
421 exit (1);
423 /* Compute how much the .bss section's raw data will grow. */
424 extra_bss_size =
425 ROUND_UP (RVA_TO_SECTION_OFFSET (PTR_TO_RVA (my_endbss), bss_section),
426 nt_header->OptionalHeader.FileAlignment)
427 - bss_section->SizeOfRawData;
429 bss_start_static = my_begbss_static;
430 bss_size_static = my_endbss_static - my_begbss_static;
431 bss_section_static = rva_to_section (PTR_TO_RVA (my_begbss_static), nt_header);
432 if (bss_section_static != rva_to_section (PTR_TO_RVA (my_endbss_static), nt_header))
434 printf ("Uninitialized static data is not in a single section...bailing\n");
435 exit (1);
437 /* Compute how much the static .bss section's raw data will grow. */
438 extra_bss_size_static =
439 ROUND_UP (RVA_TO_SECTION_OFFSET (PTR_TO_RVA (my_endbss_static), bss_section_static),
440 nt_header->OptionalHeader.FileAlignment)
441 - bss_section_static->SizeOfRawData;
443 /* Combine the bss sections into one if they overlap. */
444 #ifdef _ALPHA_
445 overlap = 1; /* force all bss data to be dumped */
446 #else
447 overlap = 0;
448 #endif
449 if (bss_start < bss_start_static)
451 if (bss_start_static < bss_start + bss_size)
452 overlap = 1;
454 else
456 if (bss_start < bss_start_static + bss_size_static)
457 overlap = 1;
459 if (overlap)
461 if (bss_section != bss_section_static)
463 printf ("BSS data not in a single section...bailing\n");
464 exit (1);
466 bss_start = min (bss_start, bss_start_static);
467 bss_size = max (my_endbss, my_endbss_static) - bss_start;
468 bss_section_static = 0;
469 extra_bss_size_static = 0;
472 heap_section = rva_to_section (PTR_TO_RVA (get_heap_start ()), nt_header);
476 /* The dump routines. */
478 void
479 copy_executable_and_dump_data (file_data *p_infile,
480 file_data *p_outfile)
482 unsigned char *dst, *dst_save;
483 PIMAGE_DOS_HEADER dos_header;
484 PIMAGE_NT_HEADERS nt_header;
485 PIMAGE_NT_HEADERS dst_nt_header;
486 PIMAGE_SECTION_HEADER section;
487 PIMAGE_SECTION_HEADER dst_section;
488 DWORD_PTR offset;
489 int i;
490 int be_verbose = GetEnvironmentVariable ("DEBUG_DUMP", NULL, 0) > 0;
492 #define COPY_CHUNK(message, src, size, verbose) \
493 do { \
494 unsigned char *s = (void *)(src); \
495 unsigned long count = (size); \
496 if (verbose) \
498 printf ("%s\n", (message)); \
499 printf ("\t0x%08x Offset in input file.\n", s - p_infile->file_base); \
500 printf ("\t0x%08x Offset in output file.\n", dst - p_outfile->file_base); \
501 printf ("\t0x%08x Size in bytes.\n", count); \
503 memcpy (dst, s, count); \
504 dst += count; \
505 } while (0)
507 #define COPY_PROC_CHUNK(message, src, size, verbose) \
508 do { \
509 unsigned char *s = (void *)(src); \
510 unsigned long count = (size); \
511 if (verbose) \
513 printf ("%s\n", (message)); \
514 printf ("\t0x%08x Address in process.\n", s); \
515 printf ("\t0x%08x Offset in output file.\n", dst - p_outfile->file_base); \
516 printf ("\t0x%08x Size in bytes.\n", count); \
518 memcpy (dst, s, count); \
519 dst += count; \
520 } while (0)
522 #define DST_TO_OFFSET() PTR_TO_OFFSET (dst, p_outfile)
523 #define ROUND_UP_DST(align) \
524 (dst = p_outfile->file_base + ROUND_UP (DST_TO_OFFSET (), (align)))
525 #define ROUND_UP_DST_AND_ZERO(align) \
526 do { \
527 unsigned char *newdst = p_outfile->file_base \
528 + ROUND_UP (DST_TO_OFFSET (), (align)); \
529 /* Zero the alignment slop; it may actually initialize real data. */ \
530 memset (dst, 0, newdst - dst); \
531 dst = newdst; \
532 } while (0)
534 /* Copy the source image sequentially, ie. section by section after
535 copying the headers and section table, to simplify the process of
536 dumping the raw data for the bss and heap sections.
538 Note that dst is updated implicitly by each COPY_CHUNK. */
540 dos_header = (PIMAGE_DOS_HEADER) p_infile->file_base;
541 nt_header = (PIMAGE_NT_HEADERS) (((DWORD_PTR) dos_header) +
542 dos_header->e_lfanew);
543 section = IMAGE_FIRST_SECTION (nt_header);
545 dst = (unsigned char *) p_outfile->file_base;
547 COPY_CHUNK ("Copying DOS header...", dos_header,
548 (DWORD_PTR) nt_header - (DWORD_PTR) dos_header, be_verbose);
549 dst_nt_header = (PIMAGE_NT_HEADERS) dst;
550 COPY_CHUNK ("Copying NT header...", nt_header,
551 (DWORD_PTR) section - (DWORD_PTR) nt_header, be_verbose);
552 dst_section = (PIMAGE_SECTION_HEADER) dst;
553 COPY_CHUNK ("Copying section table...", section,
554 nt_header->FileHeader.NumberOfSections * sizeof (*section),
555 be_verbose);
557 /* Align the first section's raw data area, and set the header size
558 field accordingly. */
559 ROUND_UP_DST_AND_ZERO (dst_nt_header->OptionalHeader.FileAlignment);
560 dst_nt_header->OptionalHeader.SizeOfHeaders = DST_TO_OFFSET ();
562 for (i = 0; i < nt_header->FileHeader.NumberOfSections; i++)
564 char msg[100];
565 /* Windows section names are fixed 8-char strings, only
566 zero-terminated if the name is shorter than 8 characters. */
567 sprintf (msg, "Copying raw data for %.8s...", section->Name);
569 dst_save = dst;
571 /* Update the file-relative offset for this section's raw data (if
572 it has any) in case things have been relocated; we will update
573 the other offsets below once we know where everything is. */
574 if (dst_section->PointerToRawData)
575 dst_section->PointerToRawData = DST_TO_OFFSET ();
577 /* Can always copy the original raw data. */
578 COPY_CHUNK
579 (msg, OFFSET_TO_PTR (section->PointerToRawData, p_infile),
580 section->SizeOfRawData, be_verbose);
581 /* Ensure alignment slop is zeroed. */
582 ROUND_UP_DST_AND_ZERO (dst_nt_header->OptionalHeader.FileAlignment);
584 /* Note that various sections below may be aliases. */
585 if (section == data_section)
587 dst = dst_save
588 + RVA_TO_SECTION_OFFSET (PTR_TO_RVA (data_start), dst_section);
589 COPY_PROC_CHUNK ("Dumping initialized data...",
590 data_start, data_size, be_verbose);
591 dst = dst_save + dst_section->SizeOfRawData;
593 if (section == bss_section)
595 /* Dump contents of bss variables, adjusting the section's raw
596 data size as necessary. */
597 dst = dst_save
598 + RVA_TO_SECTION_OFFSET (PTR_TO_RVA (bss_start), dst_section);
599 COPY_PROC_CHUNK ("Dumping bss data...", bss_start,
600 bss_size, be_verbose);
601 ROUND_UP_DST (dst_nt_header->OptionalHeader.FileAlignment);
602 dst_section->PointerToRawData = PTR_TO_OFFSET (dst_save, p_outfile);
603 /* Determine new size of raw data area. */
604 dst = max (dst, dst_save + dst_section->SizeOfRawData);
605 dst_section->SizeOfRawData = dst - dst_save;
606 dst_section->Characteristics &= ~IMAGE_SCN_CNT_UNINITIALIZED_DATA;
607 dst_section->Characteristics |= IMAGE_SCN_CNT_INITIALIZED_DATA;
609 if (section == bss_section_static)
611 /* Dump contents of static bss variables, adjusting the
612 section's raw data size as necessary. */
613 dst = dst_save
614 + RVA_TO_SECTION_OFFSET (PTR_TO_RVA (bss_start_static), dst_section);
615 COPY_PROC_CHUNK ("Dumping static bss data...", bss_start_static,
616 bss_size_static, be_verbose);
617 ROUND_UP_DST (dst_nt_header->OptionalHeader.FileAlignment);
618 dst_section->PointerToRawData = PTR_TO_OFFSET (dst_save, p_outfile);
619 /* Determine new size of raw data area. */
620 dst = max (dst, dst_save + dst_section->SizeOfRawData);
621 dst_section->SizeOfRawData = dst - dst_save;
622 dst_section->Characteristics &= ~IMAGE_SCN_CNT_UNINITIALIZED_DATA;
623 dst_section->Characteristics |= IMAGE_SCN_CNT_INITIALIZED_DATA;
625 if (section == heap_section)
627 DWORD_PTR heap_start = (DWORD_PTR) get_heap_start ();
628 DWORD_PTR heap_size = get_committed_heap_size ();
630 /* Dump the used portion of the predump heap, adjusting the
631 section's size to the appropriate size. */
632 dst = dst_save
633 + RVA_TO_SECTION_OFFSET (PTR_TO_RVA (heap_start), dst_section);
634 COPY_PROC_CHUNK ("Dumping heap...", heap_start, heap_size,
635 be_verbose);
636 ROUND_UP_DST (dst_nt_header->OptionalHeader.FileAlignment);
637 dst_section->PointerToRawData = PTR_TO_OFFSET (dst_save, p_outfile);
638 /* Determine new size of raw data area. */
639 dst = max (dst, dst_save + dst_section->SizeOfRawData);
640 dst_section->SizeOfRawData = dst - dst_save;
641 /* Reduce the size of the heap section to fit (must be last
642 section). */
643 dst_nt_header->OptionalHeader.SizeOfImage -=
644 dst_section->Misc.VirtualSize
645 - ROUND_UP (dst_section->SizeOfRawData,
646 dst_nt_header->OptionalHeader.SectionAlignment);
647 dst_section->Misc.VirtualSize =
648 ROUND_UP (dst_section->SizeOfRawData,
649 dst_nt_header->OptionalHeader.SectionAlignment);
650 dst_section->Characteristics &= ~IMAGE_SCN_CNT_UNINITIALIZED_DATA;
651 dst_section->Characteristics |= IMAGE_SCN_CNT_INITIALIZED_DATA;
654 /* Align the section's raw data area. */
655 ROUND_UP_DST (dst_nt_header->OptionalHeader.FileAlignment);
657 section++;
658 dst_section++;
661 /* Copy remainder of source image. */
663 section--;
664 while (section->PointerToRawData == 0);
665 offset = ROUND_UP (section->PointerToRawData + section->SizeOfRawData,
666 nt_header->OptionalHeader.FileAlignment);
667 COPY_CHUNK
668 ("Copying remainder of executable...",
669 OFFSET_TO_PTR (offset, p_infile),
670 p_infile->size - offset, be_verbose);
672 /* Final size for new image. */
673 p_outfile->size = DST_TO_OFFSET ();
675 /* Now patch up remaining file-relative offsets. */
676 section = IMAGE_FIRST_SECTION (nt_header);
677 dst_section = IMAGE_FIRST_SECTION (dst_nt_header);
679 #define ADJUST_OFFSET(var) \
680 do { \
681 if ((var) != 0) \
682 (var) = relocate_offset ((var), nt_header, dst_nt_header); \
683 } while (0)
685 dst_nt_header->OptionalHeader.SizeOfInitializedData = 0;
686 dst_nt_header->OptionalHeader.SizeOfUninitializedData = 0;
687 for (i = 0; i < dst_nt_header->FileHeader.NumberOfSections; i++)
689 /* Recompute data sizes for completeness. */
690 if (dst_section[i].Characteristics & IMAGE_SCN_CNT_INITIALIZED_DATA)
691 dst_nt_header->OptionalHeader.SizeOfInitializedData +=
692 ROUND_UP (dst_section[i].Misc.VirtualSize, dst_nt_header->OptionalHeader.FileAlignment);
693 else if (dst_section[i].Characteristics & IMAGE_SCN_CNT_UNINITIALIZED_DATA)
694 dst_nt_header->OptionalHeader.SizeOfUninitializedData +=
695 ROUND_UP (dst_section[i].Misc.VirtualSize, dst_nt_header->OptionalHeader.FileAlignment);
697 ADJUST_OFFSET (dst_section[i].PointerToLinenumbers);
700 ADJUST_OFFSET (dst_nt_header->FileHeader.PointerToSymbolTable);
702 /* Update offsets in debug directory entries. */
704 IMAGE_DATA_DIRECTORY debug_dir =
705 dst_nt_header->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_DEBUG];
706 PIMAGE_DEBUG_DIRECTORY debug_entry;
708 section = rva_to_section (debug_dir.VirtualAddress, dst_nt_header);
709 if (section)
711 debug_entry = (PIMAGE_DEBUG_DIRECTORY)
712 (RVA_TO_OFFSET (debug_dir.VirtualAddress, section) + p_outfile->file_base);
713 debug_dir.Size /= sizeof (IMAGE_DEBUG_DIRECTORY);
715 for (i = 0; i < debug_dir.Size; i++, debug_entry++)
716 ADJUST_OFFSET (debug_entry->PointerToRawData);
722 /* Dump out .data and .bss sections into a new executable. */
723 void
724 unexec (const char *new_name, const char *old_name)
726 file_data in_file, out_file;
727 char out_filename[MAX_PATH], in_filename[MAX_PATH], new_name_a[MAX_PATH];
728 unsigned long size;
729 char *p;
730 char *q;
732 /* Ignore old_name, and get our actual location from the OS. */
733 if (!GetModuleFileNameA (NULL, in_filename, MAX_PATH))
734 abort ();
736 /* Can't use dostounix_filename here, since that needs its file name
737 argument encoded in UTF-8. */
738 for (p = in_filename; *p; p = CharNextA (p))
739 if (*p == '\\')
740 *p = '/';
742 strcpy (out_filename, in_filename);
743 filename_to_ansi (new_name, new_name_a);
745 /* Change the base of the output filename to match the requested name. */
746 if ((p = strrchr (out_filename, '/')) == NULL)
747 abort ();
748 /* The filenames have already been expanded, and will be in Unix
749 format, so it is safe to expect an absolute name. */
750 if ((q = strrchr (new_name_a, '/')) == NULL)
751 abort ();
752 strcpy (p, q);
754 /* Make sure that the output filename has the ".exe" extension...patch
755 it up if not. */
756 p = out_filename + strlen (out_filename) - 4;
757 if (strcmp (p, ".exe"))
758 strcat (out_filename, ".exe");
760 printf ("Dumping from %s\n", in_filename);
761 printf (" to %s\n", out_filename);
763 /* We need to round off our heap to NT's page size. */
764 round_heap (get_page_size ());
766 /* Open the undumped executable file. */
767 if (!open_input_file (&in_file, in_filename))
769 printf ("Failed to open %s (%d)...bailing.\n",
770 in_filename, GetLastError ());
771 exit (1);
774 /* Get the interesting section info, like start and size of .bss... */
775 get_section_info (&in_file);
777 /* The size of the dumped executable is the size of the original
778 executable plus the size of the heap and the size of the .bss section. */
779 size = in_file.size +
780 get_committed_heap_size () +
781 extra_bss_size +
782 extra_bss_size_static;
783 if (!open_output_file (&out_file, out_filename, size))
785 printf ("Failed to open %s (%d)...bailing.\n",
786 out_filename, GetLastError ());
787 exit (1);
790 /* Set the flag (before dumping). */
791 using_dynamic_heap = TRUE;
793 copy_executable_and_dump_data (&in_file, &out_file);
795 /* Patch up header fields; profiler is picky about this. */
797 PIMAGE_DOS_HEADER dos_header;
798 PIMAGE_NT_HEADERS nt_header;
799 HANDLE hImagehelp = LoadLibrary ("imagehlp.dll");
800 DWORD headersum;
801 DWORD checksum;
803 dos_header = (PIMAGE_DOS_HEADER) out_file.file_base;
804 nt_header = (PIMAGE_NT_HEADERS) ((char *) dos_header + dos_header->e_lfanew);
806 nt_header->OptionalHeader.CheckSum = 0;
807 // nt_header->FileHeader.TimeDateStamp = time (NULL);
808 // dos_header->e_cp = size / 512;
809 // nt_header->OptionalHeader.SizeOfImage = size;
811 pfnCheckSumMappedFile = (void *) GetProcAddress (hImagehelp, "CheckSumMappedFile");
812 if (pfnCheckSumMappedFile)
814 // nt_header->FileHeader.TimeDateStamp = time (NULL);
815 pfnCheckSumMappedFile (out_file.file_base,
816 out_file.size,
817 &headersum,
818 &checksum);
819 nt_header->OptionalHeader.CheckSum = checksum;
821 FreeLibrary (hImagehelp);
824 close_file_data (&in_file);
825 close_file_data (&out_file);
828 /* eof */