lisp/ChangeLog: Fix last entry.
[emacs.git] / src / unexw32.c
blob7cbd95a46fedd24b648fc97e29c04b39857219bc
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 /* MinGW64 doesn't add a leading underscore to external symbols,
87 whereas configure.ac sets up LD_SWITCH_SYSTEM_TEMACS to force the
88 entry point at __start, with two underscores. */
89 #ifdef __MINGW64__
90 #define _start __start
91 #endif
93 /* Startup code for running on NT. When we are running as the dumped
94 version, we need to bootstrap our heap and .bss section into our
95 address space before we can actually hand off control to the startup
96 code supplied by NT (primarily because that code relies upon malloc ()). */
97 void
98 _start (void)
100 extern void mainCRTStartup (void);
102 #if 1
103 /* Give us a way to debug problems with crashes on startup when
104 running under the MSVC profiler. */
105 if (GetEnvironmentVariable ("EMACS_DEBUG", NULL, 0) > 0)
106 DebugBreak ();
107 #endif
109 /* Cache system info, e.g., the NT page size. */
110 cache_system_info ();
112 /* Grab our malloc arena space now, before CRT starts up. */
113 init_heap ();
115 /* This prevents ctrl-c's in shells running while we're suspended from
116 having us exit. */
117 SetConsoleCtrlHandler ((PHANDLER_ROUTINE) ctrl_c_handler, TRUE);
119 /* Prevent Emacs from being locked up (eg. in batch mode) when
120 accessing devices that aren't mounted (eg. removable media drives). */
121 SetErrorMode (SEM_FAILCRITICALERRORS);
122 mainCRTStartup ();
126 /* File handling. */
128 /* Implementation note: this and the next functions work with ANSI
129 codepage encoded file names! */
131 open_input_file (file_data *p_file, char *filename)
133 HANDLE file;
134 HANDLE file_mapping;
135 void *file_base;
136 unsigned long size, upper_size;
138 file = CreateFileA (filename, GENERIC_READ, FILE_SHARE_READ, NULL,
139 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
140 if (file == INVALID_HANDLE_VALUE)
141 return FALSE;
143 size = GetFileSize (file, &upper_size);
144 file_mapping = CreateFileMapping (file, NULL, PAGE_READONLY,
145 0, size, NULL);
146 if (!file_mapping)
147 return FALSE;
149 file_base = MapViewOfFile (file_mapping, FILE_MAP_READ, 0, 0, size);
150 if (file_base == 0)
151 return FALSE;
153 p_file->name = filename;
154 p_file->size = size;
155 p_file->file = file;
156 p_file->file_mapping = file_mapping;
157 p_file->file_base = file_base;
159 return TRUE;
163 open_output_file (file_data *p_file, char *filename, unsigned long size)
165 HANDLE file;
166 HANDLE file_mapping;
167 void *file_base;
169 /* We delete any existing FILENAME because loadup.el will create a
170 hard link to it under the name emacs-XX.YY.ZZ.nn.exe. Evidently,
171 overwriting a file on Unix breaks any hard links to it, but that
172 doesn't happen on Windows. If we don't delete the file before
173 creating it, all the emacs-XX.YY.ZZ.nn.exe end up being hard
174 links to the same file, which defeats the purpose of these hard
175 links: being able to run previous builds. */
176 DeleteFileA (filename);
177 file = CreateFileA (filename, GENERIC_READ | GENERIC_WRITE, 0, NULL,
178 CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
179 if (file == INVALID_HANDLE_VALUE)
180 return FALSE;
182 file_mapping = CreateFileMapping (file, NULL, PAGE_READWRITE,
183 0, size, NULL);
184 if (!file_mapping)
185 return FALSE;
187 file_base = MapViewOfFile (file_mapping, FILE_MAP_WRITE, 0, 0, size);
188 if (file_base == 0)
189 return FALSE;
191 p_file->name = filename;
192 p_file->size = size;
193 p_file->file = file;
194 p_file->file_mapping = file_mapping;
195 p_file->file_base = file_base;
197 return TRUE;
200 /* Close the system structures associated with the given file. */
201 void
202 close_file_data (file_data *p_file)
204 UnmapViewOfFile (p_file->file_base);
205 CloseHandle (p_file->file_mapping);
206 /* For the case of output files, set final size. */
207 SetFilePointer (p_file->file, p_file->size, NULL, FILE_BEGIN);
208 SetEndOfFile (p_file->file);
209 CloseHandle (p_file->file);
213 /* Routines to manipulate NT executable file sections. */
215 /* Return pointer to section header for named section. */
216 IMAGE_SECTION_HEADER *
217 find_section (char * name, IMAGE_NT_HEADERS * nt_header)
219 PIMAGE_SECTION_HEADER section;
220 int i;
222 section = IMAGE_FIRST_SECTION (nt_header);
224 for (i = 0; i < nt_header->FileHeader.NumberOfSections; i++)
226 if (strcmp (section->Name, name) == 0)
227 return section;
228 section++;
230 return NULL;
233 /* Return pointer to section header for section containing the given
234 relative virtual address. */
235 IMAGE_SECTION_HEADER *
236 rva_to_section (DWORD_PTR rva, IMAGE_NT_HEADERS * nt_header)
238 PIMAGE_SECTION_HEADER section;
239 int i;
241 section = IMAGE_FIRST_SECTION (nt_header);
243 for (i = 0; i < nt_header->FileHeader.NumberOfSections; i++)
245 /* Some linkers (eg. the NT SDK linker I believe) swapped the
246 meaning of these two values - or rather, they ignored
247 VirtualSize entirely and always set it to zero. This affects
248 some very old exes (eg. gzip dated Dec 1993). Since
249 w32_executable_type relies on this function to work reliably,
250 we need to cope with this. */
251 DWORD_PTR real_size = max (section->SizeOfRawData,
252 section->Misc.VirtualSize);
253 if (rva >= section->VirtualAddress
254 && rva < section->VirtualAddress + real_size)
255 return section;
256 section++;
258 return NULL;
261 /* Return pointer to section header for section containing the given
262 offset in its raw data area. */
263 IMAGE_SECTION_HEADER *
264 offset_to_section (DWORD_PTR offset, IMAGE_NT_HEADERS * nt_header)
266 PIMAGE_SECTION_HEADER section;
267 int i;
269 section = IMAGE_FIRST_SECTION (nt_header);
271 for (i = 0; i < nt_header->FileHeader.NumberOfSections; i++)
273 if (offset >= section->PointerToRawData
274 && offset < section->PointerToRawData + section->SizeOfRawData)
275 return section;
276 section++;
278 return NULL;
281 /* Return offset to an object in dst, given offset in src. We assume
282 there is at least one section in both src and dst images, and that
283 the some sections may have been added to dst (after sections in src). */
284 DWORD_PTR
285 relocate_offset (DWORD_PTR offset,
286 IMAGE_NT_HEADERS * src_nt_header,
287 IMAGE_NT_HEADERS * dst_nt_header)
289 PIMAGE_SECTION_HEADER src_section = IMAGE_FIRST_SECTION (src_nt_header);
290 PIMAGE_SECTION_HEADER dst_section = IMAGE_FIRST_SECTION (dst_nt_header);
291 int i = 0;
293 while (offset >= src_section->PointerToRawData)
295 if (offset < src_section->PointerToRawData + src_section->SizeOfRawData)
296 break;
297 i++;
298 if (i == src_nt_header->FileHeader.NumberOfSections)
300 /* Handle offsets after the last section. */
301 dst_section = IMAGE_FIRST_SECTION (dst_nt_header);
302 dst_section += dst_nt_header->FileHeader.NumberOfSections - 1;
303 while (dst_section->PointerToRawData == 0)
304 dst_section--;
305 while (src_section->PointerToRawData == 0)
306 src_section--;
307 return offset
308 + (dst_section->PointerToRawData + dst_section->SizeOfRawData)
309 - (src_section->PointerToRawData + src_section->SizeOfRawData);
311 src_section++;
312 dst_section++;
314 return offset +
315 (dst_section->PointerToRawData - src_section->PointerToRawData);
318 #define OFFSET_TO_RVA(offset, section) \
319 ((section)->VirtualAddress + ((DWORD_PTR)(offset) - (section)->PointerToRawData))
321 #define RVA_TO_OFFSET(rva, section) \
322 ((section)->PointerToRawData + ((DWORD_PTR)(rva) - (section)->VirtualAddress))
324 #define RVA_TO_SECTION_OFFSET(rva, section) \
325 ((DWORD_PTR)(rva) - (section)->VirtualAddress)
327 /* Convert address in executing image to RVA. */
328 #define PTR_TO_RVA(ptr) ((DWORD_PTR)(ptr) - (DWORD_PTR) GetModuleHandle (NULL))
330 #define RVA_TO_PTR(var,section,filedata) \
331 ((unsigned char *)(RVA_TO_OFFSET (var,section) + (filedata).file_base))
333 #define PTR_TO_OFFSET(ptr, pfile_data) \
334 ((unsigned char *)(ptr) - (pfile_data)->file_base)
336 #define OFFSET_TO_PTR(offset, pfile_data) \
337 ((pfile_data)->file_base + (DWORD_PTR)(offset))
340 /* Flip through the executable and cache the info necessary for dumping. */
341 void
342 get_section_info (file_data *p_infile)
344 PIMAGE_DOS_HEADER dos_header;
345 PIMAGE_NT_HEADERS nt_header;
346 int overlap;
348 dos_header = (PIMAGE_DOS_HEADER) p_infile->file_base;
349 if (dos_header->e_magic != IMAGE_DOS_SIGNATURE)
351 printf ("Unknown EXE header in %s...bailing.\n", p_infile->name);
352 exit (1);
354 nt_header = (PIMAGE_NT_HEADERS) (((DWORD_PTR) dos_header) +
355 dos_header->e_lfanew);
356 if (nt_header == NULL)
358 printf ("Failed to find IMAGE_NT_HEADER in %s...bailing.\n",
359 p_infile->name);
360 exit (1);
363 /* Check the NT header signature ... */
364 if (nt_header->Signature != IMAGE_NT_SIGNATURE)
366 printf ("Invalid IMAGE_NT_SIGNATURE 0x%x in %s...bailing.\n",
367 nt_header->Signature, p_infile->name);
368 exit (1);
371 /* Locate the ".data" and ".bss" sections for Emacs. (Note that the
372 actual section names are probably different from these, and might
373 actually be the same section.)
375 We do this as follows: first we determine the virtual address
376 ranges in this process for the data and bss variables that we wish
377 to preserve. Then we map these VAs to the section entries in the
378 source image. Finally, we determine the new size of the raw data
379 area for the bss section, so we can make the new image the correct
380 size. */
382 /* We arrange for the Emacs initialized data to be in a separate
383 section if possible, because we cannot rely on my_begdata and
384 my_edata marking out the full extent of the initialized data, at
385 least on the Alpha where the linker freely reorders variables
386 across libraries. If we can arrange for this, all we need to do is
387 find the start and size of the EMDATA section. */
388 data_section = find_section ("EMDATA", nt_header);
389 if (data_section)
391 data_start = (char *) nt_header->OptionalHeader.ImageBase +
392 data_section->VirtualAddress;
393 data_size = data_section->Misc.VirtualSize;
395 else
397 /* Fallback on the old method if compiler doesn't support the
398 data_set #pragma (or its equivalent). */
399 data_start = my_begdata;
400 data_size = my_edata - my_begdata;
401 data_section = rva_to_section (PTR_TO_RVA (my_begdata), nt_header);
402 if (data_section != rva_to_section (PTR_TO_RVA (my_edata), nt_header))
404 printf ("Initialized data is not in a single section...bailing\n");
405 exit (1);
409 /* As noted in lastfile.c, the Alpha (but not the Intel) MSVC linker
410 globally segregates all static and public bss data (ie. across all
411 linked modules, not just per module), so we must take both static
412 and public bss areas into account to determine the true extent of
413 the bss area used by Emacs.
415 To be strictly correct, we dump the static and public bss areas
416 used by Emacs separately if non-overlapping (since otherwise we are
417 dumping bss data belonging to system libraries, eg. the static bss
418 system data on the Alpha). */
420 bss_start = my_begbss;
421 bss_size = my_endbss - my_begbss;
422 bss_section = rva_to_section (PTR_TO_RVA (my_begbss), nt_header);
423 if (bss_section != rva_to_section (PTR_TO_RVA (my_endbss), nt_header))
425 printf ("Uninitialized data is not in a single section...bailing\n");
426 exit (1);
428 /* Compute how much the .bss section's raw data will grow. */
429 extra_bss_size =
430 ROUND_UP (RVA_TO_SECTION_OFFSET (PTR_TO_RVA (my_endbss), bss_section),
431 nt_header->OptionalHeader.FileAlignment)
432 - bss_section->SizeOfRawData;
434 bss_start_static = my_begbss_static;
435 bss_size_static = my_endbss_static - my_begbss_static;
436 bss_section_static = rva_to_section (PTR_TO_RVA (my_begbss_static), nt_header);
437 if (bss_section_static != rva_to_section (PTR_TO_RVA (my_endbss_static), nt_header))
439 printf ("Uninitialized static data is not in a single section...bailing\n");
440 exit (1);
442 /* Compute how much the static .bss section's raw data will grow. */
443 extra_bss_size_static =
444 ROUND_UP (RVA_TO_SECTION_OFFSET (PTR_TO_RVA (my_endbss_static), bss_section_static),
445 nt_header->OptionalHeader.FileAlignment)
446 - bss_section_static->SizeOfRawData;
448 /* Combine the bss sections into one if they overlap. */
449 #ifdef _ALPHA_
450 overlap = 1; /* force all bss data to be dumped */
451 #else
452 overlap = 0;
453 #endif
454 if (bss_start < bss_start_static)
456 if (bss_start_static < bss_start + bss_size)
457 overlap = 1;
459 else
461 if (bss_start < bss_start_static + bss_size_static)
462 overlap = 1;
464 if (overlap)
466 if (bss_section != bss_section_static)
468 printf ("BSS data not in a single section...bailing\n");
469 exit (1);
471 bss_start = min (bss_start, bss_start_static);
472 bss_size = max (my_endbss, my_endbss_static) - bss_start;
473 bss_section_static = 0;
474 extra_bss_size_static = 0;
479 /* The dump routines. */
481 void
482 copy_executable_and_dump_data (file_data *p_infile,
483 file_data *p_outfile)
485 unsigned char *dst, *dst_save;
486 PIMAGE_DOS_HEADER dos_header;
487 PIMAGE_NT_HEADERS nt_header;
488 PIMAGE_NT_HEADERS dst_nt_header;
489 PIMAGE_SECTION_HEADER section;
490 PIMAGE_SECTION_HEADER dst_section;
491 DWORD_PTR offset;
492 int i;
493 int be_verbose = GetEnvironmentVariable ("DEBUG_DUMP", NULL, 0) > 0;
495 #define COPY_CHUNK(message, src, size, verbose) \
496 do { \
497 unsigned char *s = (void *)(src); \
498 unsigned long count = (size); \
499 if (verbose) \
501 printf ("%s\n", (message)); \
502 printf ("\t0x%08x Offset in input file.\n", s - p_infile->file_base); \
503 printf ("\t0x%08x Offset in output file.\n", dst - p_outfile->file_base); \
504 printf ("\t0x%08x Size in bytes.\n", count); \
506 memcpy (dst, s, count); \
507 dst += count; \
508 } while (0)
510 #define COPY_PROC_CHUNK(message, src, size, verbose) \
511 do { \
512 unsigned char *s = (void *)(src); \
513 unsigned long count = (size); \
514 if (verbose) \
516 printf ("%s\n", (message)); \
517 printf ("\t0x%p Address in process.\n", s); \
518 printf ("\t0x%p Base output file.\n", p_outfile->file_base); \
519 printf ("\t0x%p Offset in output file.\n", dst - p_outfile->file_base); \
520 printf ("\t0x%p Address in output file.\n", dst); \
521 printf ("\t0x%p Size in bytes.\n", count); \
523 memcpy (dst, s, count); \
524 dst += count; \
525 } while (0)
527 #define DST_TO_OFFSET() PTR_TO_OFFSET (dst, p_outfile)
528 #define ROUND_UP_DST(align) \
529 (dst = p_outfile->file_base + ROUND_UP (DST_TO_OFFSET (), (align)))
530 #define ROUND_UP_DST_AND_ZERO(align) \
531 do { \
532 unsigned char *newdst = p_outfile->file_base \
533 + ROUND_UP (DST_TO_OFFSET (), (align)); \
534 /* Zero the alignment slop; it may actually initialize real data. */ \
535 memset (dst, 0, newdst - dst); \
536 dst = newdst; \
537 } while (0)
539 /* Copy the source image sequentially, ie. section by section after
540 copying the headers and section table, to simplify the process of
541 dumping the raw data for the bss and heap sections.
543 Note that dst is updated implicitly by each COPY_CHUNK. */
545 dos_header = (PIMAGE_DOS_HEADER) p_infile->file_base;
546 nt_header = (PIMAGE_NT_HEADERS) (((DWORD_PTR) dos_header) +
547 dos_header->e_lfanew);
548 section = IMAGE_FIRST_SECTION (nt_header);
550 dst = (unsigned char *) p_outfile->file_base;
552 COPY_CHUNK ("Copying DOS header...", dos_header,
553 (DWORD_PTR) nt_header - (DWORD_PTR) dos_header, be_verbose);
554 dst_nt_header = (PIMAGE_NT_HEADERS) dst;
555 COPY_CHUNK ("Copying NT header...", nt_header,
556 (DWORD_PTR) section - (DWORD_PTR) nt_header, be_verbose);
557 dst_section = (PIMAGE_SECTION_HEADER) dst;
558 COPY_CHUNK ("Copying section table...", section,
559 nt_header->FileHeader.NumberOfSections * sizeof (*section),
560 be_verbose);
562 /* Align the first section's raw data area, and set the header size
563 field accordingly. */
564 ROUND_UP_DST_AND_ZERO (dst_nt_header->OptionalHeader.FileAlignment);
565 dst_nt_header->OptionalHeader.SizeOfHeaders = DST_TO_OFFSET ();
567 for (i = 0; i < nt_header->FileHeader.NumberOfSections; i++)
569 char msg[100];
570 /* Windows section names are fixed 8-char strings, only
571 zero-terminated if the name is shorter than 8 characters. */
572 sprintf (msg, "Copying raw data for %.8s...", section->Name);
574 dst_save = dst;
576 /* Update the file-relative offset for this section's raw data (if
577 it has any) in case things have been relocated; we will update
578 the other offsets below once we know where everything is. */
579 if (dst_section->PointerToRawData)
580 dst_section->PointerToRawData = DST_TO_OFFSET ();
582 /* Can always copy the original raw data. */
583 COPY_CHUNK
584 (msg, OFFSET_TO_PTR (section->PointerToRawData, p_infile),
585 section->SizeOfRawData, be_verbose);
586 /* Ensure alignment slop is zeroed. */
587 ROUND_UP_DST_AND_ZERO (dst_nt_header->OptionalHeader.FileAlignment);
589 /* Note that various sections below may be aliases. */
590 if (section == data_section)
592 dst = dst_save
593 + RVA_TO_SECTION_OFFSET (PTR_TO_RVA (data_start), dst_section);
594 COPY_PROC_CHUNK ("Dumping initialized data...",
595 data_start, data_size, be_verbose);
596 dst = dst_save + dst_section->SizeOfRawData;
598 if (section == bss_section)
600 /* Dump contents of bss variables, adjusting the section's raw
601 data size as necessary. */
602 dst = dst_save
603 + RVA_TO_SECTION_OFFSET (PTR_TO_RVA (bss_start), dst_section);
604 COPY_PROC_CHUNK ("Dumping bss data...", bss_start,
605 bss_size, be_verbose);
606 ROUND_UP_DST (dst_nt_header->OptionalHeader.FileAlignment);
607 dst_section->PointerToRawData = PTR_TO_OFFSET (dst_save, p_outfile);
608 /* Determine new size of raw data area. */
609 dst = max (dst, dst_save + dst_section->SizeOfRawData);
610 dst_section->SizeOfRawData = dst - dst_save;
611 dst_section->Characteristics &= ~IMAGE_SCN_CNT_UNINITIALIZED_DATA;
612 dst_section->Characteristics |= IMAGE_SCN_CNT_INITIALIZED_DATA;
614 if (section == bss_section_static)
616 /* Dump contents of static bss variables, adjusting the
617 section's raw data size as necessary. */
618 dst = dst_save
619 + RVA_TO_SECTION_OFFSET (PTR_TO_RVA (bss_start_static), dst_section);
620 COPY_PROC_CHUNK ("Dumping static bss data...", bss_start_static,
621 bss_size_static, be_verbose);
622 ROUND_UP_DST (dst_nt_header->OptionalHeader.FileAlignment);
623 dst_section->PointerToRawData = PTR_TO_OFFSET (dst_save, p_outfile);
624 /* Determine new size of raw data area. */
625 dst = max (dst, dst_save + dst_section->SizeOfRawData);
626 dst_section->SizeOfRawData = dst - dst_save;
627 dst_section->Characteristics &= ~IMAGE_SCN_CNT_UNINITIALIZED_DATA;
628 dst_section->Characteristics |= IMAGE_SCN_CNT_INITIALIZED_DATA;
631 /* Align the section's raw data area. */
632 ROUND_UP_DST (dst_nt_header->OptionalHeader.FileAlignment);
634 section++;
635 dst_section++;
638 /* Copy remainder of source image. */
640 section--;
641 while (section->PointerToRawData == 0);
642 offset = ROUND_UP (section->PointerToRawData + section->SizeOfRawData,
643 nt_header->OptionalHeader.FileAlignment);
644 COPY_CHUNK
645 ("Copying remainder of executable...",
646 OFFSET_TO_PTR (offset, p_infile),
647 p_infile->size - offset, be_verbose);
649 /* Final size for new image. */
650 p_outfile->size = DST_TO_OFFSET ();
652 /* Now patch up remaining file-relative offsets. */
653 section = IMAGE_FIRST_SECTION (nt_header);
654 dst_section = IMAGE_FIRST_SECTION (dst_nt_header);
656 #define ADJUST_OFFSET(var) \
657 do { \
658 if ((var) != 0) \
659 (var) = relocate_offset ((var), nt_header, dst_nt_header); \
660 } while (0)
662 dst_nt_header->OptionalHeader.SizeOfInitializedData = 0;
663 dst_nt_header->OptionalHeader.SizeOfUninitializedData = 0;
664 for (i = 0; i < dst_nt_header->FileHeader.NumberOfSections; i++)
666 /* Recompute data sizes for completeness. */
667 if (dst_section[i].Characteristics & IMAGE_SCN_CNT_INITIALIZED_DATA)
668 dst_nt_header->OptionalHeader.SizeOfInitializedData +=
669 ROUND_UP (dst_section[i].Misc.VirtualSize, dst_nt_header->OptionalHeader.FileAlignment);
670 else if (dst_section[i].Characteristics & IMAGE_SCN_CNT_UNINITIALIZED_DATA)
671 dst_nt_header->OptionalHeader.SizeOfUninitializedData +=
672 ROUND_UP (dst_section[i].Misc.VirtualSize, dst_nt_header->OptionalHeader.FileAlignment);
674 ADJUST_OFFSET (dst_section[i].PointerToLinenumbers);
677 ADJUST_OFFSET (dst_nt_header->FileHeader.PointerToSymbolTable);
679 /* Update offsets in debug directory entries. */
681 IMAGE_DATA_DIRECTORY debug_dir =
682 dst_nt_header->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_DEBUG];
683 PIMAGE_DEBUG_DIRECTORY debug_entry;
685 section = rva_to_section (debug_dir.VirtualAddress, dst_nt_header);
686 if (section)
688 debug_entry = (PIMAGE_DEBUG_DIRECTORY)
689 (RVA_TO_OFFSET (debug_dir.VirtualAddress, section) + p_outfile->file_base);
690 debug_dir.Size /= sizeof (IMAGE_DEBUG_DIRECTORY);
692 for (i = 0; i < debug_dir.Size; i++, debug_entry++)
693 ADJUST_OFFSET (debug_entry->PointerToRawData);
699 /* Dump out .data and .bss sections into a new executable. */
700 void
701 unexec (const char *new_name, const char *old_name)
703 file_data in_file, out_file;
704 char out_filename[MAX_PATH], in_filename[MAX_PATH], new_name_a[MAX_PATH];
705 unsigned long size;
706 char *p;
707 char *q;
709 /* Ignore old_name, and get our actual location from the OS. */
710 if (!GetModuleFileNameA (NULL, in_filename, MAX_PATH))
711 abort ();
713 /* Can't use dostounix_filename here, since that needs its file name
714 argument encoded in UTF-8. */
715 for (p = in_filename; *p; p = CharNextA (p))
716 if (*p == '\\')
717 *p = '/';
719 strcpy (out_filename, in_filename);
720 filename_to_ansi (new_name, new_name_a);
722 /* Change the base of the output filename to match the requested name. */
723 if ((p = strrchr (out_filename, '/')) == NULL)
724 abort ();
725 /* The filenames have already been expanded, and will be in Unix
726 format, so it is safe to expect an absolute name. */
727 if ((q = strrchr (new_name_a, '/')) == NULL)
728 abort ();
729 strcpy (p, q);
731 #ifdef ENABLE_CHECKING
732 report_temacs_memory_usage ();
733 #endif
735 /* Make sure that the output filename has the ".exe" extension...patch
736 it up if not. */
737 p = out_filename + strlen (out_filename) - 4;
738 if (strcmp (p, ".exe"))
739 strcat (out_filename, ".exe");
741 printf ("Dumping from %s\n", in_filename);
742 printf (" to %s\n", out_filename);
744 /* Open the undumped executable file. */
745 if (!open_input_file (&in_file, in_filename))
747 printf ("Failed to open %s (%d)...bailing.\n",
748 in_filename, GetLastError ());
749 exit (1);
752 /* Get the interesting section info, like start and size of .bss... */
753 get_section_info (&in_file);
755 /* The size of the dumped executable is the size of the original
756 executable plus the size of the heap and the size of the .bss section. */
757 size = in_file.size +
758 extra_bss_size +
759 extra_bss_size_static;
760 if (!open_output_file (&out_file, out_filename, size))
762 printf ("Failed to open %s (%d)...bailing.\n",
763 out_filename, GetLastError ());
764 exit (1);
767 /* Set the flag (before dumping). */
768 using_dynamic_heap = TRUE;
770 copy_executable_and_dump_data (&in_file, &out_file);
772 /* Unset it because it is plain wrong to keep it after dumping.
773 Malloc can still occur! */
774 using_dynamic_heap = FALSE;
776 /* Patch up header fields; profiler is picky about this. */
778 PIMAGE_DOS_HEADER dos_header;
779 PIMAGE_NT_HEADERS nt_header;
780 HANDLE hImagehelp = LoadLibrary ("imagehlp.dll");
781 DWORD headersum;
782 DWORD checksum;
784 dos_header = (PIMAGE_DOS_HEADER) out_file.file_base;
785 nt_header = (PIMAGE_NT_HEADERS) ((char *) dos_header + dos_header->e_lfanew);
787 nt_header->OptionalHeader.CheckSum = 0;
788 // nt_header->FileHeader.TimeDateStamp = time (NULL);
789 // dos_header->e_cp = size / 512;
790 // nt_header->OptionalHeader.SizeOfImage = size;
792 pfnCheckSumMappedFile = (void *) GetProcAddress (hImagehelp, "CheckSumMappedFile");
793 if (pfnCheckSumMappedFile)
795 // nt_header->FileHeader.TimeDateStamp = time (NULL);
796 pfnCheckSumMappedFile (out_file.file_base,
797 out_file.size,
798 &headersum,
799 &checksum);
800 nt_header->OptionalHeader.CheckSum = checksum;
802 FreeLibrary (hImagehelp);
805 close_file_data (&in_file);
806 close_file_data (&out_file);
809 /* eof */