Avoid leaving garbage on screen when using 'raise' display property
[emacs.git] / src / unexw32.c
blob904447c3ec946f9ab18d8e556dd4fa9f5e82b6a6
1 /* unexec for GNU Emacs on Windows NT.
2 Copyright (C) 1994, 2001-2017 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 (at
9 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 (__stdcall * pfnCheckSumMappedFile) (LPVOID BaseAddress,
38 DWORD FileLength,
39 LPDWORD HeaderSum,
40 LPDWORD CheckSum);
42 extern BOOL ctrl_c_handler (unsigned long type);
44 extern char my_begdata[];
45 extern char my_begbss[];
46 extern char *my_begbss_static;
48 #include "w32heap.h"
50 /* Basically, our "initialized" flag. */
51 BOOL using_dynamic_heap = FALSE;
53 void get_section_info (file_data *p_file);
54 void copy_executable_and_dump_data (file_data *, file_data *);
55 void dump_bss_and_heap (file_data *p_infile, file_data *p_outfile);
57 /* Cached info about the .data section in the executable. */
58 PIMAGE_SECTION_HEADER data_section;
59 PCHAR data_start = 0;
60 DWORD_PTR data_size = 0;
62 /* Cached info about the .bss section in the executable. */
63 PIMAGE_SECTION_HEADER bss_section;
64 PCHAR bss_start = 0;
65 DWORD_PTR bss_size = 0;
66 DWORD_PTR extra_bss_size = 0;
67 /* bss data that is static might be discontiguous from non-static. */
68 PIMAGE_SECTION_HEADER bss_section_static;
69 PCHAR bss_start_static = 0;
70 DWORD_PTR bss_size_static = 0;
71 DWORD_PTR extra_bss_size_static = 0;
73 /* MinGW64 doesn't add a leading underscore to external symbols,
74 whereas configure.ac sets up LD_SWITCH_SYSTEM_TEMACS to force the
75 entry point at __start, with two underscores. */
76 #ifdef __MINGW64__
77 #define _start __start
78 #endif
80 extern void mainCRTStartup (void);
82 /* Startup code for running on NT. When we are running as the dumped
83 version, we need to bootstrap our heap and .bss section into our
84 address space before we can actually hand off control to the startup
85 code supplied by NT (primarily because that code relies upon malloc ()). */
86 void _start (void);
88 void
89 _start (void)
92 #if 1
93 /* Give us a way to debug problems with crashes on startup when
94 running under the MSVC profiler. */
95 if (GetEnvironmentVariable ("EMACS_DEBUG", NULL, 0) > 0)
96 DebugBreak ();
97 #endif
99 /* Cache system info, e.g., the NT page size. */
100 cache_system_info ();
102 /* Grab our malloc arena space now, before CRT starts up. */
103 init_heap ();
105 /* This prevents ctrl-c's in shells running while we're suspended from
106 having us exit. */
107 SetConsoleCtrlHandler ((PHANDLER_ROUTINE) ctrl_c_handler, TRUE);
109 /* Prevent Emacs from being locked up (eg. in batch mode) when
110 accessing devices that aren't mounted (eg. removable media drives). */
111 SetErrorMode (SEM_FAILCRITICALERRORS);
112 mainCRTStartup ();
116 /* File handling. */
118 /* Implementation note: this and the next functions work with ANSI
119 codepage encoded file names! */
121 open_input_file (file_data *p_file, char *filename)
123 HANDLE file;
124 HANDLE file_mapping;
125 void *file_base;
126 unsigned long size, upper_size;
128 file = CreateFileA (filename, GENERIC_READ, FILE_SHARE_READ, NULL,
129 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
130 if (file == INVALID_HANDLE_VALUE)
131 return FALSE;
133 size = GetFileSize (file, &upper_size);
134 file_mapping = CreateFileMapping (file, NULL, PAGE_READONLY,
135 0, size, NULL);
136 if (!file_mapping)
137 return FALSE;
139 file_base = MapViewOfFile (file_mapping, FILE_MAP_READ, 0, 0, size);
140 if (file_base == 0)
141 return FALSE;
143 p_file->name = filename;
144 p_file->size = size;
145 p_file->file = file;
146 p_file->file_mapping = file_mapping;
147 p_file->file_base = file_base;
149 return TRUE;
153 open_output_file (file_data *p_file, char *filename, unsigned long size)
155 HANDLE file;
156 HANDLE file_mapping;
157 void *file_base;
159 /* We delete any existing FILENAME because loadup.el will create a
160 hard link to it under the name emacs-XX.YY.ZZ.nn.exe. Evidently,
161 overwriting a file on Unix breaks any hard links to it, but that
162 doesn't happen on Windows. If we don't delete the file before
163 creating it, all the emacs-XX.YY.ZZ.nn.exe end up being hard
164 links to the same file, which defeats the purpose of these hard
165 links: being able to run previous builds. */
166 DeleteFileA (filename);
167 file = CreateFileA (filename, GENERIC_READ | GENERIC_WRITE, 0, NULL,
168 CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
169 if (file == INVALID_HANDLE_VALUE)
170 return FALSE;
172 file_mapping = CreateFileMapping (file, NULL, PAGE_READWRITE,
173 0, size, NULL);
174 if (!file_mapping)
175 return FALSE;
177 file_base = MapViewOfFile (file_mapping, FILE_MAP_WRITE, 0, 0, size);
178 if (file_base == 0)
179 return FALSE;
181 p_file->name = filename;
182 p_file->size = size;
183 p_file->file = file;
184 p_file->file_mapping = file_mapping;
185 p_file->file_base = file_base;
187 return TRUE;
190 /* Close the system structures associated with the given file. */
191 void
192 close_file_data (file_data *p_file)
194 UnmapViewOfFile (p_file->file_base);
195 CloseHandle (p_file->file_mapping);
196 /* For the case of output files, set final size. */
197 SetFilePointer (p_file->file, p_file->size, NULL, FILE_BEGIN);
198 SetEndOfFile (p_file->file);
199 CloseHandle (p_file->file);
203 /* Routines to manipulate NT executable file sections. */
205 /* Return pointer to section header for named section. */
206 IMAGE_SECTION_HEADER *
207 find_section (const char * name, IMAGE_NT_HEADERS * nt_header)
209 PIMAGE_SECTION_HEADER section;
210 int i;
212 section = IMAGE_FIRST_SECTION (nt_header);
214 for (i = 0; i < nt_header->FileHeader.NumberOfSections; i++)
216 if (strcmp ((char *)section->Name, name) == 0)
217 return section;
218 section++;
220 return NULL;
223 /* Return pointer to section header for section containing the given
224 relative virtual address. */
225 IMAGE_SECTION_HEADER *
226 rva_to_section (DWORD_PTR rva, IMAGE_NT_HEADERS * nt_header)
228 PIMAGE_SECTION_HEADER section;
229 int i;
231 section = IMAGE_FIRST_SECTION (nt_header);
233 for (i = 0; i < nt_header->FileHeader.NumberOfSections; i++)
235 /* Some linkers (eg. the NT SDK linker I believe) swapped the
236 meaning of these two values - or rather, they ignored
237 VirtualSize entirely and always set it to zero. This affects
238 some very old exes (eg. gzip dated Dec 1993). Since
239 w32_executable_type relies on this function to work reliably,
240 we need to cope with this. */
241 DWORD_PTR real_size = max (section->SizeOfRawData,
242 section->Misc.VirtualSize);
243 if (rva >= section->VirtualAddress
244 && rva < section->VirtualAddress + real_size)
245 return section;
246 section++;
248 return NULL;
251 #if 0 /* unused */
252 /* Return pointer to section header for section containing the given
253 offset in its raw data area. */
254 static IMAGE_SECTION_HEADER *
255 offset_to_section (DWORD_PTR offset, IMAGE_NT_HEADERS * nt_header)
257 PIMAGE_SECTION_HEADER section;
258 int i;
260 section = IMAGE_FIRST_SECTION (nt_header);
262 for (i = 0; i < nt_header->FileHeader.NumberOfSections; i++)
264 if (offset >= section->PointerToRawData
265 && offset < section->PointerToRawData + section->SizeOfRawData)
266 return section;
267 section++;
269 return NULL;
271 #endif
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 static 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 RVA_TO_OFFSET(rva, section) \
311 ((section)->PointerToRawData + ((DWORD_PTR)(rva) - (section)->VirtualAddress))
313 #define RVA_TO_SECTION_OFFSET(rva, section) \
314 ((DWORD_PTR)(rva) - (section)->VirtualAddress)
316 /* Convert address in executing image to RVA. */
317 #define PTR_TO_RVA(ptr) ((DWORD_PTR)(ptr) - (DWORD_PTR) GetModuleHandle (NULL))
319 #define PTR_TO_OFFSET(ptr, pfile_data) \
320 ((unsigned char *)(ptr) - (pfile_data)->file_base)
322 #define OFFSET_TO_PTR(offset, pfile_data) \
323 ((pfile_data)->file_base + (DWORD_PTR)(offset))
325 #if 0 /* unused */
326 #define OFFSET_TO_RVA(offset, section) \
327 ((section)->VirtualAddress + ((DWORD_PTR)(offset) - (section)->PointerToRawData))
329 #define RVA_TO_PTR(var,section,filedata) \
330 ((unsigned char *)(RVA_TO_OFFSET (var,section) + (filedata).file_base))
331 #endif
334 /* Flip through the executable and cache the info necessary for dumping. */
335 void
336 get_section_info (file_data *p_infile)
338 PIMAGE_DOS_HEADER dos_header;
339 PIMAGE_NT_HEADERS nt_header;
340 int overlap;
342 dos_header = (PIMAGE_DOS_HEADER) p_infile->file_base;
343 if (dos_header->e_magic != IMAGE_DOS_SIGNATURE)
345 printf ("Unknown EXE header in %s...bailing.\n", p_infile->name);
346 exit (1);
348 nt_header = (PIMAGE_NT_HEADERS) (((DWORD_PTR) dos_header) +
349 dos_header->e_lfanew);
350 if (nt_header == NULL)
352 printf ("Failed to find IMAGE_NT_HEADER in %s...bailing.\n",
353 p_infile->name);
354 exit (1);
357 /* Check the NT header signature ... */
358 if (nt_header->Signature != IMAGE_NT_SIGNATURE)
360 printf ("Invalid IMAGE_NT_SIGNATURE 0x%x in %s...bailing.\n",
361 nt_header->Signature, p_infile->name);
362 exit (1);
365 /* Locate the ".data" and ".bss" sections for Emacs. (Note that the
366 actual section names are probably different from these, and might
367 actually be the same section.)
369 We do this as follows: first we determine the virtual address
370 ranges in this process for the data and bss variables that we wish
371 to preserve. Then we map these VAs to the section entries in the
372 source image. Finally, we determine the new size of the raw data
373 area for the bss section, so we can make the new image the correct
374 size. */
376 /* We arrange for the Emacs initialized data to be in a separate
377 section if possible, because we cannot rely on my_begdata and
378 my_edata marking out the full extent of the initialized data, at
379 least on the Alpha where the linker freely reorders variables
380 across libraries. If we can arrange for this, all we need to do is
381 find the start and size of the EMDATA section. */
382 data_section = find_section ("EMDATA", nt_header);
383 if (data_section)
385 data_start = (char *) nt_header->OptionalHeader.ImageBase +
386 data_section->VirtualAddress;
387 data_size = data_section->Misc.VirtualSize;
389 else
391 /* Fallback on the old method if compiler doesn't support the
392 data_set #pragma (or its equivalent). */
393 data_start = my_begdata;
394 data_size = my_edata - my_begdata;
395 data_section = rva_to_section (PTR_TO_RVA (my_begdata), nt_header);
396 if (data_section != rva_to_section (PTR_TO_RVA (my_edata), nt_header))
398 printf ("Initialized data is not in a single section...bailing\n");
399 exit (1);
403 /* As noted in lastfile.c, the Alpha (but not the Intel) MSVC linker
404 globally segregates all static and public bss data (ie. across all
405 linked modules, not just per module), so we must take both static
406 and public bss areas into account to determine the true extent of
407 the bss area used by Emacs.
409 To be strictly correct, we dump the static and public bss areas
410 used by Emacs separately if non-overlapping (since otherwise we are
411 dumping bss data belonging to system libraries, eg. the static bss
412 system data on the Alpha). */
414 bss_start = my_begbss;
415 bss_size = my_endbss - my_begbss;
416 bss_section = rva_to_section (PTR_TO_RVA (my_begbss), nt_header);
417 if (bss_section != rva_to_section (PTR_TO_RVA (my_endbss), nt_header))
419 printf ("Uninitialized data is not in a single section...bailing\n");
420 exit (1);
422 /* Compute how much the .bss section's raw data will grow. */
423 extra_bss_size =
424 ROUND_UP (RVA_TO_SECTION_OFFSET (PTR_TO_RVA (my_endbss), bss_section),
425 nt_header->OptionalHeader.FileAlignment)
426 - bss_section->SizeOfRawData;
428 bss_start_static = my_begbss_static;
429 bss_size_static = my_endbss_static - my_begbss_static;
430 bss_section_static = rva_to_section (PTR_TO_RVA (my_begbss_static), nt_header);
431 if (bss_section_static != rva_to_section (PTR_TO_RVA (my_endbss_static), nt_header))
433 printf ("Uninitialized static data is not in a single section...bailing\n");
434 exit (1);
436 /* Compute how much the static .bss section's raw data will grow. */
437 extra_bss_size_static =
438 ROUND_UP (RVA_TO_SECTION_OFFSET (PTR_TO_RVA (my_endbss_static), bss_section_static),
439 nt_header->OptionalHeader.FileAlignment)
440 - bss_section_static->SizeOfRawData;
442 /* Combine the bss sections into one if they overlap. */
443 #ifdef _ALPHA_
444 overlap = 1; /* force all bss data to be dumped */
445 #else
446 overlap = 0;
447 #endif
448 if (bss_start < bss_start_static)
450 if (bss_start_static < bss_start + bss_size)
451 overlap = 1;
453 else
455 if (bss_start < bss_start_static + bss_size_static)
456 overlap = 1;
458 if (overlap)
460 if (bss_section != bss_section_static)
462 printf ("BSS data not in a single section...bailing\n");
463 exit (1);
465 bss_start = min (bss_start, bss_start_static);
466 bss_size = max (my_endbss, my_endbss_static) - bss_start;
467 bss_section_static = 0;
468 extra_bss_size = max (extra_bss_size, extra_bss_size_static);
469 extra_bss_size_static = 0;
474 /* The dump routines. */
476 void
477 copy_executable_and_dump_data (file_data *p_infile,
478 file_data *p_outfile)
480 unsigned char *dst, *dst_save;
481 PIMAGE_DOS_HEADER dos_header;
482 PIMAGE_NT_HEADERS nt_header;
483 PIMAGE_NT_HEADERS dst_nt_header;
484 PIMAGE_SECTION_HEADER section;
485 PIMAGE_SECTION_HEADER dst_section;
486 DWORD_PTR offset;
487 int i;
488 int be_verbose = GetEnvironmentVariable ("DEBUG_DUMP", NULL, 0) > 0;
490 #define COPY_CHUNK(message, src, size, verbose) \
491 do { \
492 unsigned char *s = (void *)(src); \
493 unsigned long count = (size); \
494 if (verbose) \
496 printf ("%s\n", (message)); \
497 printf ("\t0x%08x Offset in input file.\n", s - p_infile->file_base); \
498 printf ("\t0x%08x Offset in output file.\n", dst - p_outfile->file_base); \
499 printf ("\t0x%08x Size in bytes.\n", count); \
501 memcpy (dst, s, count); \
502 dst += count; \
503 } while (0)
505 #define COPY_PROC_CHUNK(message, src, size, verbose) \
506 do { \
507 unsigned char *s = (void *)(src); \
508 unsigned long count = (size); \
509 if (verbose) \
511 printf ("%s\n", (message)); \
512 printf ("\t0x%p Address in process.\n", s); \
513 printf ("\t0x%p Base output file.\n", p_outfile->file_base); \
514 printf ("\t0x%p Offset in output file.\n", dst - p_outfile->file_base); \
515 printf ("\t0x%p Address in output file.\n", dst); \
516 printf ("\t0x%p 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;
626 /* Align the section's raw data area. */
627 ROUND_UP_DST (dst_nt_header->OptionalHeader.FileAlignment);
629 section++;
630 dst_section++;
633 /* Copy remainder of source image. */
635 section--;
636 while (section->PointerToRawData == 0);
637 offset = ROUND_UP (section->PointerToRawData + section->SizeOfRawData,
638 nt_header->OptionalHeader.FileAlignment);
639 COPY_CHUNK
640 ("Copying remainder of executable...",
641 OFFSET_TO_PTR (offset, p_infile),
642 p_infile->size - offset, be_verbose);
644 /* Final size for new image. */
645 p_outfile->size = DST_TO_OFFSET ();
647 /* Now patch up remaining file-relative offsets. */
648 section = IMAGE_FIRST_SECTION (nt_header);
649 dst_section = IMAGE_FIRST_SECTION (dst_nt_header);
651 #define ADJUST_OFFSET(var) \
652 do { \
653 if ((var) != 0) \
654 (var) = relocate_offset ((var), nt_header, dst_nt_header); \
655 } while (0)
657 dst_nt_header->OptionalHeader.SizeOfInitializedData = 0;
658 dst_nt_header->OptionalHeader.SizeOfUninitializedData = 0;
659 for (i = 0; i < dst_nt_header->FileHeader.NumberOfSections; i++)
661 /* Recompute data sizes for completeness. */
662 if (dst_section[i].Characteristics & IMAGE_SCN_CNT_INITIALIZED_DATA)
663 dst_nt_header->OptionalHeader.SizeOfInitializedData +=
664 ROUND_UP (dst_section[i].Misc.VirtualSize, dst_nt_header->OptionalHeader.FileAlignment);
665 else if (dst_section[i].Characteristics & IMAGE_SCN_CNT_UNINITIALIZED_DATA)
666 dst_nt_header->OptionalHeader.SizeOfUninitializedData +=
667 ROUND_UP (dst_section[i].Misc.VirtualSize, dst_nt_header->OptionalHeader.FileAlignment);
669 ADJUST_OFFSET (dst_section[i].PointerToLinenumbers);
672 ADJUST_OFFSET (dst_nt_header->FileHeader.PointerToSymbolTable);
674 /* Update offsets in debug directory entries. */
676 IMAGE_DATA_DIRECTORY debug_dir =
677 dst_nt_header->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_DEBUG];
678 PIMAGE_DEBUG_DIRECTORY debug_entry;
680 section = rva_to_section (debug_dir.VirtualAddress, dst_nt_header);
681 if (section)
683 debug_entry = (PIMAGE_DEBUG_DIRECTORY)
684 (RVA_TO_OFFSET (debug_dir.VirtualAddress, section) + p_outfile->file_base);
685 debug_dir.Size /= sizeof (IMAGE_DEBUG_DIRECTORY);
687 for (i = 0; i < debug_dir.Size; i++, debug_entry++)
688 ADJUST_OFFSET (debug_entry->PointerToRawData);
694 /* Dump out .data and .bss sections into a new executable. */
695 void
696 unexec (const char *new_name, const char *old_name)
698 file_data in_file, out_file;
699 char out_filename[MAX_PATH], in_filename[MAX_PATH], new_name_a[MAX_PATH];
700 unsigned long size;
701 char *p;
702 char *q;
704 /* Ignore old_name, and get our actual location from the OS. */
705 if (!GetModuleFileNameA (NULL, in_filename, MAX_PATH))
706 abort ();
708 /* Can't use dostounix_filename here, since that needs its file name
709 argument encoded in UTF-8. */
710 for (p = in_filename; *p; p = CharNextA (p))
711 if (*p == '\\')
712 *p = '/';
714 strcpy (out_filename, in_filename);
715 filename_to_ansi (new_name, new_name_a);
717 /* Change the base of the output filename to match the requested name. */
718 if ((p = strrchr (out_filename, '/')) == NULL)
719 abort ();
720 /* The filenames have already been expanded, and will be in Unix
721 format, so it is safe to expect an absolute name. */
722 if ((q = strrchr (new_name_a, '/')) == NULL)
723 abort ();
724 strcpy (p, q);
726 #ifdef ENABLE_CHECKING
727 report_temacs_memory_usage ();
728 #endif
730 /* Make sure that the output filename has the ".exe" extension...patch
731 it up if not. */
732 p = out_filename + strlen (out_filename) - 4;
733 if (strcmp (p, ".exe"))
734 strcat (out_filename, ".exe");
736 printf ("Dumping from %s\n", in_filename);
737 printf (" to %s\n", out_filename);
739 /* Open the undumped executable file. */
740 if (!open_input_file (&in_file, in_filename))
742 printf ("Failed to open %s (%d)...bailing.\n",
743 in_filename, GetLastError ());
744 exit (1);
747 /* Get the interesting section info, like start and size of .bss... */
748 get_section_info (&in_file);
750 /* The size of the dumped executable is the size of the original
751 executable plus the size of the heap and the size of the .bss section. */
752 size = in_file.size +
753 extra_bss_size +
754 extra_bss_size_static;
755 if (!open_output_file (&out_file, out_filename, size))
757 printf ("Failed to open %s (%d)...bailing.\n",
758 out_filename, GetLastError ());
759 exit (1);
762 /* Set the flag (before dumping). */
763 using_dynamic_heap = TRUE;
765 copy_executable_and_dump_data (&in_file, &out_file);
767 /* Unset it because it is plain wrong to keep it after dumping.
768 Malloc can still occur! */
769 using_dynamic_heap = FALSE;
771 /* Patch up header fields; profiler is picky about this. */
773 PIMAGE_DOS_HEADER dos_header;
774 PIMAGE_NT_HEADERS nt_header;
775 HANDLE hImagehelp = LoadLibrary ("imagehlp.dll");
776 DWORD headersum;
777 DWORD checksum;
779 dos_header = (PIMAGE_DOS_HEADER) out_file.file_base;
780 nt_header = (PIMAGE_NT_HEADERS) ((char *) dos_header + dos_header->e_lfanew);
782 nt_header->OptionalHeader.CheckSum = 0;
783 // nt_header->FileHeader.TimeDateStamp = time (NULL);
784 // dos_header->e_cp = size / 512;
785 // nt_header->OptionalHeader.SizeOfImage = size;
787 pfnCheckSumMappedFile = (void *) GetProcAddress (hImagehelp, "CheckSumMappedFile");
788 if (pfnCheckSumMappedFile)
790 // nt_header->FileHeader.TimeDateStamp = time (NULL);
791 pfnCheckSumMappedFile (out_file.file_base,
792 out_file.size,
793 &headersum,
794 &checksum);
795 nt_header->OptionalHeader.CheckSum = checksum;
797 FreeLibrary (hImagehelp);
800 close_file_data (&in_file);
801 close_file_data (&out_file);
804 /* eof */