Merge from origin/emacs-24
[emacs.git] / src / unexw32.c
blob5c1c1f3f391bbd375df74cfd3bd84e6bfecb6b02
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_begbss[];
47 extern char *my_begbss_static;
49 #include "w32heap.h"
51 /* Basically, our "initialized" flag. */
52 BOOL using_dynamic_heap = FALSE;
54 int open_input_file (file_data *p_file, char *name);
55 int open_output_file (file_data *p_file, char *name, unsigned long size);
56 void close_file_data (file_data *p_file);
58 void get_section_info (file_data *p_file);
59 void copy_executable_and_dump_data (file_data *, file_data *);
60 void dump_bss_and_heap (file_data *p_infile, file_data *p_outfile);
62 /* Cached info about the .data section in the executable. */
63 PIMAGE_SECTION_HEADER data_section;
64 PCHAR data_start = 0;
65 DWORD_PTR data_size = 0;
67 /* Cached info about the .bss section in the executable. */
68 PIMAGE_SECTION_HEADER bss_section;
69 PCHAR bss_start = 0;
70 DWORD_PTR bss_size = 0;
71 DWORD_PTR extra_bss_size = 0;
72 /* bss data that is static might be discontiguous from non-static. */
73 PIMAGE_SECTION_HEADER bss_section_static;
74 PCHAR bss_start_static = 0;
75 DWORD_PTR bss_size_static = 0;
76 DWORD_PTR extra_bss_size_static = 0;
78 /* MinGW64 doesn't add a leading underscore to external symbols,
79 whereas configure.ac sets up LD_SWITCH_SYSTEM_TEMACS to force the
80 entry point at __start, with two underscores. */
81 #ifdef __MINGW64__
82 #define _start __start
83 #endif
85 /* Startup code for running on NT. When we are running as the dumped
86 version, we need to bootstrap our heap and .bss section into our
87 address space before we can actually hand off control to the startup
88 code supplied by NT (primarily because that code relies upon malloc ()). */
89 void
90 _start (void)
92 extern void mainCRTStartup (void);
94 #if 1
95 /* Give us a way to debug problems with crashes on startup when
96 running under the MSVC profiler. */
97 if (GetEnvironmentVariable ("EMACS_DEBUG", NULL, 0) > 0)
98 DebugBreak ();
99 #endif
101 /* Cache system info, e.g., the NT page size. */
102 cache_system_info ();
104 /* Grab our malloc arena space now, before CRT starts up. */
105 init_heap ();
107 /* This prevents ctrl-c's in shells running while we're suspended from
108 having us exit. */
109 SetConsoleCtrlHandler ((PHANDLER_ROUTINE) ctrl_c_handler, TRUE);
111 /* Prevent Emacs from being locked up (eg. in batch mode) when
112 accessing devices that aren't mounted (eg. removable media drives). */
113 SetErrorMode (SEM_FAILCRITICALERRORS);
114 mainCRTStartup ();
118 /* File handling. */
120 /* Implementation note: this and the next functions work with ANSI
121 codepage encoded file names! */
123 open_input_file (file_data *p_file, char *filename)
125 HANDLE file;
126 HANDLE file_mapping;
127 void *file_base;
128 unsigned long size, upper_size;
130 file = CreateFileA (filename, GENERIC_READ, FILE_SHARE_READ, NULL,
131 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
132 if (file == INVALID_HANDLE_VALUE)
133 return FALSE;
135 size = GetFileSize (file, &upper_size);
136 file_mapping = CreateFileMapping (file, NULL, PAGE_READONLY,
137 0, size, NULL);
138 if (!file_mapping)
139 return FALSE;
141 file_base = MapViewOfFile (file_mapping, FILE_MAP_READ, 0, 0, size);
142 if (file_base == 0)
143 return FALSE;
145 p_file->name = filename;
146 p_file->size = size;
147 p_file->file = file;
148 p_file->file_mapping = file_mapping;
149 p_file->file_base = file_base;
151 return TRUE;
155 open_output_file (file_data *p_file, char *filename, unsigned long size)
157 HANDLE file;
158 HANDLE file_mapping;
159 void *file_base;
161 /* We delete any existing FILENAME because loadup.el will create a
162 hard link to it under the name emacs-XX.YY.ZZ.nn.exe. Evidently,
163 overwriting a file on Unix breaks any hard links to it, but that
164 doesn't happen on Windows. If we don't delete the file before
165 creating it, all the emacs-XX.YY.ZZ.nn.exe end up being hard
166 links to the same file, which defeats the purpose of these hard
167 links: being able to run previous builds. */
168 DeleteFileA (filename);
169 file = CreateFileA (filename, GENERIC_READ | GENERIC_WRITE, 0, NULL,
170 CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
171 if (file == INVALID_HANDLE_VALUE)
172 return FALSE;
174 file_mapping = CreateFileMapping (file, NULL, PAGE_READWRITE,
175 0, size, NULL);
176 if (!file_mapping)
177 return FALSE;
179 file_base = MapViewOfFile (file_mapping, FILE_MAP_WRITE, 0, 0, size);
180 if (file_base == 0)
181 return FALSE;
183 p_file->name = filename;
184 p_file->size = size;
185 p_file->file = file;
186 p_file->file_mapping = file_mapping;
187 p_file->file_base = file_base;
189 return TRUE;
192 /* Close the system structures associated with the given file. */
193 void
194 close_file_data (file_data *p_file)
196 UnmapViewOfFile (p_file->file_base);
197 CloseHandle (p_file->file_mapping);
198 /* For the case of output files, set final size. */
199 SetFilePointer (p_file->file, p_file->size, NULL, FILE_BEGIN);
200 SetEndOfFile (p_file->file);
201 CloseHandle (p_file->file);
205 /* Routines to manipulate NT executable file sections. */
207 /* Return pointer to section header for named section. */
208 IMAGE_SECTION_HEADER *
209 find_section (char * name, IMAGE_NT_HEADERS * nt_header)
211 PIMAGE_SECTION_HEADER section;
212 int i;
214 section = IMAGE_FIRST_SECTION (nt_header);
216 for (i = 0; i < nt_header->FileHeader.NumberOfSections; i++)
218 if (strcmp (section->Name, name) == 0)
219 return section;
220 section++;
222 return NULL;
225 /* Return pointer to section header for section containing the given
226 relative virtual address. */
227 IMAGE_SECTION_HEADER *
228 rva_to_section (DWORD_PTR rva, IMAGE_NT_HEADERS * nt_header)
230 PIMAGE_SECTION_HEADER section;
231 int i;
233 section = IMAGE_FIRST_SECTION (nt_header);
235 for (i = 0; i < nt_header->FileHeader.NumberOfSections; i++)
237 /* Some linkers (eg. the NT SDK linker I believe) swapped the
238 meaning of these two values - or rather, they ignored
239 VirtualSize entirely and always set it to zero. This affects
240 some very old exes (eg. gzip dated Dec 1993). Since
241 w32_executable_type relies on this function to work reliably,
242 we need to cope with this. */
243 DWORD_PTR real_size = max (section->SizeOfRawData,
244 section->Misc.VirtualSize);
245 if (rva >= section->VirtualAddress
246 && rva < section->VirtualAddress + real_size)
247 return section;
248 section++;
250 return NULL;
253 /* Return pointer to section header for section containing the given
254 offset in its raw data area. */
255 IMAGE_SECTION_HEADER *
256 offset_to_section (DWORD_PTR offset, IMAGE_NT_HEADERS * nt_header)
258 PIMAGE_SECTION_HEADER section;
259 int i;
261 section = IMAGE_FIRST_SECTION (nt_header);
263 for (i = 0; i < nt_header->FileHeader.NumberOfSections; i++)
265 if (offset >= section->PointerToRawData
266 && offset < section->PointerToRawData + section->SizeOfRawData)
267 return section;
268 section++;
270 return NULL;
273 /* Return offset to an object in dst, given offset in src. We assume
274 there is at least one section in both src and dst images, and that
275 the some sections may have been added to dst (after sections in src). */
276 DWORD_PTR
277 relocate_offset (DWORD_PTR offset,
278 IMAGE_NT_HEADERS * src_nt_header,
279 IMAGE_NT_HEADERS * dst_nt_header)
281 PIMAGE_SECTION_HEADER src_section = IMAGE_FIRST_SECTION (src_nt_header);
282 PIMAGE_SECTION_HEADER dst_section = IMAGE_FIRST_SECTION (dst_nt_header);
283 int i = 0;
285 while (offset >= src_section->PointerToRawData)
287 if (offset < src_section->PointerToRawData + src_section->SizeOfRawData)
288 break;
289 i++;
290 if (i == src_nt_header->FileHeader.NumberOfSections)
292 /* Handle offsets after the last section. */
293 dst_section = IMAGE_FIRST_SECTION (dst_nt_header);
294 dst_section += dst_nt_header->FileHeader.NumberOfSections - 1;
295 while (dst_section->PointerToRawData == 0)
296 dst_section--;
297 while (src_section->PointerToRawData == 0)
298 src_section--;
299 return offset
300 + (dst_section->PointerToRawData + dst_section->SizeOfRawData)
301 - (src_section->PointerToRawData + src_section->SizeOfRawData);
303 src_section++;
304 dst_section++;
306 return offset +
307 (dst_section->PointerToRawData - src_section->PointerToRawData);
310 #define OFFSET_TO_RVA(offset, section) \
311 ((section)->VirtualAddress + ((DWORD_PTR)(offset) - (section)->PointerToRawData))
313 #define RVA_TO_OFFSET(rva, section) \
314 ((section)->PointerToRawData + ((DWORD_PTR)(rva) - (section)->VirtualAddress))
316 #define RVA_TO_SECTION_OFFSET(rva, section) \
317 ((DWORD_PTR)(rva) - (section)->VirtualAddress)
319 /* Convert address in executing image to RVA. */
320 #define PTR_TO_RVA(ptr) ((DWORD_PTR)(ptr) - (DWORD_PTR) GetModuleHandle (NULL))
322 #define RVA_TO_PTR(var,section,filedata) \
323 ((unsigned char *)(RVA_TO_OFFSET (var,section) + (filedata).file_base))
325 #define PTR_TO_OFFSET(ptr, pfile_data) \
326 ((unsigned char *)(ptr) - (pfile_data)->file_base)
328 #define OFFSET_TO_PTR(offset, pfile_data) \
329 ((pfile_data)->file_base + (DWORD_PTR)(offset))
332 /* Flip through the executable and cache the info necessary for dumping. */
333 void
334 get_section_info (file_data *p_infile)
336 PIMAGE_DOS_HEADER dos_header;
337 PIMAGE_NT_HEADERS nt_header;
338 int overlap;
340 dos_header = (PIMAGE_DOS_HEADER) p_infile->file_base;
341 if (dos_header->e_magic != IMAGE_DOS_SIGNATURE)
343 printf ("Unknown EXE header in %s...bailing.\n", p_infile->name);
344 exit (1);
346 nt_header = (PIMAGE_NT_HEADERS) (((DWORD_PTR) dos_header) +
347 dos_header->e_lfanew);
348 if (nt_header == NULL)
350 printf ("Failed to find IMAGE_NT_HEADER in %s...bailing.\n",
351 p_infile->name);
352 exit (1);
355 /* Check the NT header signature ... */
356 if (nt_header->Signature != IMAGE_NT_SIGNATURE)
358 printf ("Invalid IMAGE_NT_SIGNATURE 0x%x in %s...bailing.\n",
359 nt_header->Signature, p_infile->name);
360 exit (1);
363 /* Locate the ".data" and ".bss" sections for Emacs. (Note that the
364 actual section names are probably different from these, and might
365 actually be the same section.)
367 We do this as follows: first we determine the virtual address
368 ranges in this process for the data and bss variables that we wish
369 to preserve. Then we map these VAs to the section entries in the
370 source image. Finally, we determine the new size of the raw data
371 area for the bss section, so we can make the new image the correct
372 size. */
374 /* We arrange for the Emacs initialized data to be in a separate
375 section if possible, because we cannot rely on my_begdata and
376 my_edata marking out the full extent of the initialized data, at
377 least on the Alpha where the linker freely reorders variables
378 across libraries. If we can arrange for this, all we need to do is
379 find the start and size of the EMDATA section. */
380 data_section = find_section ("EMDATA", nt_header);
381 if (data_section)
383 data_start = (char *) nt_header->OptionalHeader.ImageBase +
384 data_section->VirtualAddress;
385 data_size = data_section->Misc.VirtualSize;
387 else
389 /* Fallback on the old method if compiler doesn't support the
390 data_set #pragma (or its equivalent). */
391 data_start = my_begdata;
392 data_size = my_edata - my_begdata;
393 data_section = rva_to_section (PTR_TO_RVA (my_begdata), nt_header);
394 if (data_section != rva_to_section (PTR_TO_RVA (my_edata), nt_header))
396 printf ("Initialized data is not in a single section...bailing\n");
397 exit (1);
401 /* As noted in lastfile.c, the Alpha (but not the Intel) MSVC linker
402 globally segregates all static and public bss data (ie. across all
403 linked modules, not just per module), so we must take both static
404 and public bss areas into account to determine the true extent of
405 the bss area used by Emacs.
407 To be strictly correct, we dump the static and public bss areas
408 used by Emacs separately if non-overlapping (since otherwise we are
409 dumping bss data belonging to system libraries, eg. the static bss
410 system data on the Alpha). */
412 bss_start = my_begbss;
413 bss_size = my_endbss - my_begbss;
414 bss_section = rva_to_section (PTR_TO_RVA (my_begbss), nt_header);
415 if (bss_section != rva_to_section (PTR_TO_RVA (my_endbss), nt_header))
417 printf ("Uninitialized data is not in a single section...bailing\n");
418 exit (1);
420 /* Compute how much the .bss section's raw data will grow. */
421 extra_bss_size =
422 ROUND_UP (RVA_TO_SECTION_OFFSET (PTR_TO_RVA (my_endbss), bss_section),
423 nt_header->OptionalHeader.FileAlignment)
424 - bss_section->SizeOfRawData;
426 bss_start_static = my_begbss_static;
427 bss_size_static = my_endbss_static - my_begbss_static;
428 bss_section_static = rva_to_section (PTR_TO_RVA (my_begbss_static), nt_header);
429 if (bss_section_static != rva_to_section (PTR_TO_RVA (my_endbss_static), nt_header))
431 printf ("Uninitialized static data is not in a single section...bailing\n");
432 exit (1);
434 /* Compute how much the static .bss section's raw data will grow. */
435 extra_bss_size_static =
436 ROUND_UP (RVA_TO_SECTION_OFFSET (PTR_TO_RVA (my_endbss_static), bss_section_static),
437 nt_header->OptionalHeader.FileAlignment)
438 - bss_section_static->SizeOfRawData;
440 /* Combine the bss sections into one if they overlap. */
441 #ifdef _ALPHA_
442 overlap = 1; /* force all bss data to be dumped */
443 #else
444 overlap = 0;
445 #endif
446 if (bss_start < bss_start_static)
448 if (bss_start_static < bss_start + bss_size)
449 overlap = 1;
451 else
453 if (bss_start < bss_start_static + bss_size_static)
454 overlap = 1;
456 if (overlap)
458 if (bss_section != bss_section_static)
460 printf ("BSS data not in a single section...bailing\n");
461 exit (1);
463 bss_start = min (bss_start, bss_start_static);
464 bss_size = max (my_endbss, my_endbss_static) - bss_start;
465 bss_section_static = 0;
466 extra_bss_size_static = 0;
471 /* The dump routines. */
473 void
474 copy_executable_and_dump_data (file_data *p_infile,
475 file_data *p_outfile)
477 unsigned char *dst, *dst_save;
478 PIMAGE_DOS_HEADER dos_header;
479 PIMAGE_NT_HEADERS nt_header;
480 PIMAGE_NT_HEADERS dst_nt_header;
481 PIMAGE_SECTION_HEADER section;
482 PIMAGE_SECTION_HEADER dst_section;
483 DWORD_PTR offset;
484 int i;
485 int be_verbose = GetEnvironmentVariable ("DEBUG_DUMP", NULL, 0) > 0;
487 #define COPY_CHUNK(message, src, size, verbose) \
488 do { \
489 unsigned char *s = (void *)(src); \
490 unsigned long count = (size); \
491 if (verbose) \
493 printf ("%s\n", (message)); \
494 printf ("\t0x%08x Offset in input file.\n", s - p_infile->file_base); \
495 printf ("\t0x%08x Offset in output file.\n", dst - p_outfile->file_base); \
496 printf ("\t0x%08x Size in bytes.\n", count); \
498 memcpy (dst, s, count); \
499 dst += count; \
500 } while (0)
502 #define COPY_PROC_CHUNK(message, src, size, verbose) \
503 do { \
504 unsigned char *s = (void *)(src); \
505 unsigned long count = (size); \
506 if (verbose) \
508 printf ("%s\n", (message)); \
509 printf ("\t0x%p Address in process.\n", s); \
510 printf ("\t0x%p Base output file.\n", p_outfile->file_base); \
511 printf ("\t0x%p Offset in output file.\n", dst - p_outfile->file_base); \
512 printf ("\t0x%p Address in output file.\n", dst); \
513 printf ("\t0x%p Size in bytes.\n", count); \
515 memcpy (dst, s, count); \
516 dst += count; \
517 } while (0)
519 #define DST_TO_OFFSET() PTR_TO_OFFSET (dst, p_outfile)
520 #define ROUND_UP_DST(align) \
521 (dst = p_outfile->file_base + ROUND_UP (DST_TO_OFFSET (), (align)))
522 #define ROUND_UP_DST_AND_ZERO(align) \
523 do { \
524 unsigned char *newdst = p_outfile->file_base \
525 + ROUND_UP (DST_TO_OFFSET (), (align)); \
526 /* Zero the alignment slop; it may actually initialize real data. */ \
527 memset (dst, 0, newdst - dst); \
528 dst = newdst; \
529 } while (0)
531 /* Copy the source image sequentially, ie. section by section after
532 copying the headers and section table, to simplify the process of
533 dumping the raw data for the bss and heap sections.
535 Note that dst is updated implicitly by each COPY_CHUNK. */
537 dos_header = (PIMAGE_DOS_HEADER) p_infile->file_base;
538 nt_header = (PIMAGE_NT_HEADERS) (((DWORD_PTR) dos_header) +
539 dos_header->e_lfanew);
540 section = IMAGE_FIRST_SECTION (nt_header);
542 dst = (unsigned char *) p_outfile->file_base;
544 COPY_CHUNK ("Copying DOS header...", dos_header,
545 (DWORD_PTR) nt_header - (DWORD_PTR) dos_header, be_verbose);
546 dst_nt_header = (PIMAGE_NT_HEADERS) dst;
547 COPY_CHUNK ("Copying NT header...", nt_header,
548 (DWORD_PTR) section - (DWORD_PTR) nt_header, be_verbose);
549 dst_section = (PIMAGE_SECTION_HEADER) dst;
550 COPY_CHUNK ("Copying section table...", section,
551 nt_header->FileHeader.NumberOfSections * sizeof (*section),
552 be_verbose);
554 /* Align the first section's raw data area, and set the header size
555 field accordingly. */
556 ROUND_UP_DST_AND_ZERO (dst_nt_header->OptionalHeader.FileAlignment);
557 dst_nt_header->OptionalHeader.SizeOfHeaders = DST_TO_OFFSET ();
559 for (i = 0; i < nt_header->FileHeader.NumberOfSections; i++)
561 char msg[100];
562 /* Windows section names are fixed 8-char strings, only
563 zero-terminated if the name is shorter than 8 characters. */
564 sprintf (msg, "Copying raw data for %.8s...", section->Name);
566 dst_save = dst;
568 /* Update the file-relative offset for this section's raw data (if
569 it has any) in case things have been relocated; we will update
570 the other offsets below once we know where everything is. */
571 if (dst_section->PointerToRawData)
572 dst_section->PointerToRawData = DST_TO_OFFSET ();
574 /* Can always copy the original raw data. */
575 COPY_CHUNK
576 (msg, OFFSET_TO_PTR (section->PointerToRawData, p_infile),
577 section->SizeOfRawData, be_verbose);
578 /* Ensure alignment slop is zeroed. */
579 ROUND_UP_DST_AND_ZERO (dst_nt_header->OptionalHeader.FileAlignment);
581 /* Note that various sections below may be aliases. */
582 if (section == data_section)
584 dst = dst_save
585 + RVA_TO_SECTION_OFFSET (PTR_TO_RVA (data_start), dst_section);
586 COPY_PROC_CHUNK ("Dumping initialized data...",
587 data_start, data_size, be_verbose);
588 dst = dst_save + dst_section->SizeOfRawData;
590 if (section == bss_section)
592 /* Dump contents of bss variables, adjusting the section's raw
593 data size as necessary. */
594 dst = dst_save
595 + RVA_TO_SECTION_OFFSET (PTR_TO_RVA (bss_start), dst_section);
596 COPY_PROC_CHUNK ("Dumping bss data...", bss_start,
597 bss_size, be_verbose);
598 ROUND_UP_DST (dst_nt_header->OptionalHeader.FileAlignment);
599 dst_section->PointerToRawData = PTR_TO_OFFSET (dst_save, p_outfile);
600 /* Determine new size of raw data area. */
601 dst = max (dst, dst_save + dst_section->SizeOfRawData);
602 dst_section->SizeOfRawData = dst - dst_save;
603 dst_section->Characteristics &= ~IMAGE_SCN_CNT_UNINITIALIZED_DATA;
604 dst_section->Characteristics |= IMAGE_SCN_CNT_INITIALIZED_DATA;
606 if (section == bss_section_static)
608 /* Dump contents of static bss variables, adjusting the
609 section's raw data size as necessary. */
610 dst = dst_save
611 + RVA_TO_SECTION_OFFSET (PTR_TO_RVA (bss_start_static), dst_section);
612 COPY_PROC_CHUNK ("Dumping static bss data...", bss_start_static,
613 bss_size_static, be_verbose);
614 ROUND_UP_DST (dst_nt_header->OptionalHeader.FileAlignment);
615 dst_section->PointerToRawData = PTR_TO_OFFSET (dst_save, p_outfile);
616 /* Determine new size of raw data area. */
617 dst = max (dst, dst_save + dst_section->SizeOfRawData);
618 dst_section->SizeOfRawData = dst - dst_save;
619 dst_section->Characteristics &= ~IMAGE_SCN_CNT_UNINITIALIZED_DATA;
620 dst_section->Characteristics |= IMAGE_SCN_CNT_INITIALIZED_DATA;
623 /* Align the section's raw data area. */
624 ROUND_UP_DST (dst_nt_header->OptionalHeader.FileAlignment);
626 section++;
627 dst_section++;
630 /* Copy remainder of source image. */
632 section--;
633 while (section->PointerToRawData == 0);
634 offset = ROUND_UP (section->PointerToRawData + section->SizeOfRawData,
635 nt_header->OptionalHeader.FileAlignment);
636 COPY_CHUNK
637 ("Copying remainder of executable...",
638 OFFSET_TO_PTR (offset, p_infile),
639 p_infile->size - offset, be_verbose);
641 /* Final size for new image. */
642 p_outfile->size = DST_TO_OFFSET ();
644 /* Now patch up remaining file-relative offsets. */
645 section = IMAGE_FIRST_SECTION (nt_header);
646 dst_section = IMAGE_FIRST_SECTION (dst_nt_header);
648 #define ADJUST_OFFSET(var) \
649 do { \
650 if ((var) != 0) \
651 (var) = relocate_offset ((var), nt_header, dst_nt_header); \
652 } while (0)
654 dst_nt_header->OptionalHeader.SizeOfInitializedData = 0;
655 dst_nt_header->OptionalHeader.SizeOfUninitializedData = 0;
656 for (i = 0; i < dst_nt_header->FileHeader.NumberOfSections; i++)
658 /* Recompute data sizes for completeness. */
659 if (dst_section[i].Characteristics & IMAGE_SCN_CNT_INITIALIZED_DATA)
660 dst_nt_header->OptionalHeader.SizeOfInitializedData +=
661 ROUND_UP (dst_section[i].Misc.VirtualSize, dst_nt_header->OptionalHeader.FileAlignment);
662 else if (dst_section[i].Characteristics & IMAGE_SCN_CNT_UNINITIALIZED_DATA)
663 dst_nt_header->OptionalHeader.SizeOfUninitializedData +=
664 ROUND_UP (dst_section[i].Misc.VirtualSize, dst_nt_header->OptionalHeader.FileAlignment);
666 ADJUST_OFFSET (dst_section[i].PointerToLinenumbers);
669 ADJUST_OFFSET (dst_nt_header->FileHeader.PointerToSymbolTable);
671 /* Update offsets in debug directory entries. */
673 IMAGE_DATA_DIRECTORY debug_dir =
674 dst_nt_header->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_DEBUG];
675 PIMAGE_DEBUG_DIRECTORY debug_entry;
677 section = rva_to_section (debug_dir.VirtualAddress, dst_nt_header);
678 if (section)
680 debug_entry = (PIMAGE_DEBUG_DIRECTORY)
681 (RVA_TO_OFFSET (debug_dir.VirtualAddress, section) + p_outfile->file_base);
682 debug_dir.Size /= sizeof (IMAGE_DEBUG_DIRECTORY);
684 for (i = 0; i < debug_dir.Size; i++, debug_entry++)
685 ADJUST_OFFSET (debug_entry->PointerToRawData);
691 /* Dump out .data and .bss sections into a new executable. */
692 void
693 unexec (const char *new_name, const char *old_name)
695 file_data in_file, out_file;
696 char out_filename[MAX_PATH], in_filename[MAX_PATH], new_name_a[MAX_PATH];
697 unsigned long size;
698 char *p;
699 char *q;
701 /* Ignore old_name, and get our actual location from the OS. */
702 if (!GetModuleFileNameA (NULL, in_filename, MAX_PATH))
703 abort ();
705 /* Can't use dostounix_filename here, since that needs its file name
706 argument encoded in UTF-8. */
707 for (p = in_filename; *p; p = CharNextA (p))
708 if (*p == '\\')
709 *p = '/';
711 strcpy (out_filename, in_filename);
712 filename_to_ansi (new_name, new_name_a);
714 /* Change the base of the output filename to match the requested name. */
715 if ((p = strrchr (out_filename, '/')) == NULL)
716 abort ();
717 /* The filenames have already been expanded, and will be in Unix
718 format, so it is safe to expect an absolute name. */
719 if ((q = strrchr (new_name_a, '/')) == NULL)
720 abort ();
721 strcpy (p, q);
723 #ifdef ENABLE_CHECKING
724 report_temacs_memory_usage ();
725 #endif
727 /* Make sure that the output filename has the ".exe" extension...patch
728 it up if not. */
729 p = out_filename + strlen (out_filename) - 4;
730 if (strcmp (p, ".exe"))
731 strcat (out_filename, ".exe");
733 printf ("Dumping from %s\n", in_filename);
734 printf (" to %s\n", out_filename);
736 /* Open the undumped executable file. */
737 if (!open_input_file (&in_file, in_filename))
739 printf ("Failed to open %s (%d)...bailing.\n",
740 in_filename, GetLastError ());
741 exit (1);
744 /* Get the interesting section info, like start and size of .bss... */
745 get_section_info (&in_file);
747 /* The size of the dumped executable is the size of the original
748 executable plus the size of the heap and the size of the .bss section. */
749 size = in_file.size +
750 extra_bss_size +
751 extra_bss_size_static;
752 if (!open_output_file (&out_file, out_filename, size))
754 printf ("Failed to open %s (%d)...bailing.\n",
755 out_filename, GetLastError ());
756 exit (1);
759 /* Set the flag (before dumping). */
760 using_dynamic_heap = TRUE;
762 copy_executable_and_dump_data (&in_file, &out_file);
764 /* Unset it because it is plain wrong to keep it after dumping.
765 Malloc can still occur! */
766 using_dynamic_heap = FALSE;
768 /* Patch up header fields; profiler is picky about this. */
770 PIMAGE_DOS_HEADER dos_header;
771 PIMAGE_NT_HEADERS nt_header;
772 HANDLE hImagehelp = LoadLibrary ("imagehlp.dll");
773 DWORD headersum;
774 DWORD checksum;
776 dos_header = (PIMAGE_DOS_HEADER) out_file.file_base;
777 nt_header = (PIMAGE_NT_HEADERS) ((char *) dos_header + dos_header->e_lfanew);
779 nt_header->OptionalHeader.CheckSum = 0;
780 // nt_header->FileHeader.TimeDateStamp = time (NULL);
781 // dos_header->e_cp = size / 512;
782 // nt_header->OptionalHeader.SizeOfImage = size;
784 pfnCheckSumMappedFile = (void *) GetProcAddress (hImagehelp, "CheckSumMappedFile");
785 if (pfnCheckSumMappedFile)
787 // nt_header->FileHeader.TimeDateStamp = time (NULL);
788 pfnCheckSumMappedFile (out_file.file_base,
789 out_file.size,
790 &headersum,
791 &checksum);
792 nt_header->OptionalHeader.CheckSum = checksum;
794 FreeLibrary (hImagehelp);
797 close_file_data (&in_file);
798 close_file_data (&out_file);
801 /* eof */