* progmodes/cfengine.el: Use symbol motion commands instead of extending the word...
[emacs.git] / src / unexw32.c
blobe8b553a87d3123cf2a41217b68e00249d1fb860a
1 /* unexec for GNU Emacs on Windows NT.
2 Copyright (C) 1994, 2001-2013 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. */
124 open_input_file (file_data *p_file, char *filename)
126 HANDLE file;
127 HANDLE file_mapping;
128 void *file_base;
129 unsigned long size, upper_size;
131 file = CreateFile (filename, GENERIC_READ, FILE_SHARE_READ, NULL,
132 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
133 if (file == INVALID_HANDLE_VALUE)
134 return FALSE;
136 size = GetFileSize (file, &upper_size);
137 file_mapping = CreateFileMapping (file, NULL, PAGE_READONLY,
138 0, size, NULL);
139 if (!file_mapping)
140 return FALSE;
142 file_base = MapViewOfFile (file_mapping, FILE_MAP_READ, 0, 0, size);
143 if (file_base == 0)
144 return FALSE;
146 p_file->name = filename;
147 p_file->size = size;
148 p_file->file = file;
149 p_file->file_mapping = file_mapping;
150 p_file->file_base = file_base;
152 return TRUE;
156 open_output_file (file_data *p_file, char *filename, unsigned long size)
158 HANDLE file;
159 HANDLE file_mapping;
160 void *file_base;
162 file = CreateFile (filename, GENERIC_READ | GENERIC_WRITE, 0, NULL,
163 CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
164 if (file == INVALID_HANDLE_VALUE)
165 return FALSE;
167 file_mapping = CreateFileMapping (file, NULL, PAGE_READWRITE,
168 0, size, NULL);
169 if (!file_mapping)
170 return FALSE;
172 file_base = MapViewOfFile (file_mapping, FILE_MAP_WRITE, 0, 0, size);
173 if (file_base == 0)
174 return FALSE;
176 p_file->name = filename;
177 p_file->size = size;
178 p_file->file = file;
179 p_file->file_mapping = file_mapping;
180 p_file->file_base = file_base;
182 return TRUE;
185 /* Close the system structures associated with the given file. */
186 void
187 close_file_data (file_data *p_file)
189 UnmapViewOfFile (p_file->file_base);
190 CloseHandle (p_file->file_mapping);
191 /* For the case of output files, set final size. */
192 SetFilePointer (p_file->file, p_file->size, NULL, FILE_BEGIN);
193 SetEndOfFile (p_file->file);
194 CloseHandle (p_file->file);
198 /* Routines to manipulate NT executable file sections. */
200 /* Return pointer to section header for named section. */
201 IMAGE_SECTION_HEADER *
202 find_section (char * name, IMAGE_NT_HEADERS * nt_header)
204 PIMAGE_SECTION_HEADER section;
205 int i;
207 section = IMAGE_FIRST_SECTION (nt_header);
209 for (i = 0; i < nt_header->FileHeader.NumberOfSections; i++)
211 if (strcmp (section->Name, name) == 0)
212 return section;
213 section++;
215 return NULL;
218 /* Return pointer to section header for section containing the given
219 relative virtual address. */
220 IMAGE_SECTION_HEADER *
221 rva_to_section (DWORD_PTR rva, IMAGE_NT_HEADERS * nt_header)
223 PIMAGE_SECTION_HEADER section;
224 int i;
226 section = IMAGE_FIRST_SECTION (nt_header);
228 for (i = 0; i < nt_header->FileHeader.NumberOfSections; i++)
230 /* Some linkers (eg. the NT SDK linker I believe) swapped the
231 meaning of these two values - or rather, they ignored
232 VirtualSize entirely and always set it to zero. This affects
233 some very old exes (eg. gzip dated Dec 1993). Since
234 w32_executable_type relies on this function to work reliably,
235 we need to cope with this. */
236 DWORD_PTR real_size = max (section->SizeOfRawData,
237 section->Misc.VirtualSize);
238 if (rva >= section->VirtualAddress
239 && rva < section->VirtualAddress + real_size)
240 return section;
241 section++;
243 return NULL;
246 /* Return pointer to section header for section containing the given
247 offset in its raw data area. */
248 IMAGE_SECTION_HEADER *
249 offset_to_section (DWORD_PTR offset, IMAGE_NT_HEADERS * nt_header)
251 PIMAGE_SECTION_HEADER section;
252 int i;
254 section = IMAGE_FIRST_SECTION (nt_header);
256 for (i = 0; i < nt_header->FileHeader.NumberOfSections; i++)
258 if (offset >= section->PointerToRawData
259 && offset < section->PointerToRawData + section->SizeOfRawData)
260 return section;
261 section++;
263 return NULL;
266 /* Return offset to an object in dst, given offset in src. We assume
267 there is at least one section in both src and dst images, and that
268 the some sections may have been added to dst (after sections in src). */
269 DWORD_PTR
270 relocate_offset (DWORD_PTR offset,
271 IMAGE_NT_HEADERS * src_nt_header,
272 IMAGE_NT_HEADERS * dst_nt_header)
274 PIMAGE_SECTION_HEADER src_section = IMAGE_FIRST_SECTION (src_nt_header);
275 PIMAGE_SECTION_HEADER dst_section = IMAGE_FIRST_SECTION (dst_nt_header);
276 int i = 0;
278 while (offset >= src_section->PointerToRawData)
280 if (offset < src_section->PointerToRawData + src_section->SizeOfRawData)
281 break;
282 i++;
283 if (i == src_nt_header->FileHeader.NumberOfSections)
285 /* Handle offsets after the last section. */
286 dst_section = IMAGE_FIRST_SECTION (dst_nt_header);
287 dst_section += dst_nt_header->FileHeader.NumberOfSections - 1;
288 while (dst_section->PointerToRawData == 0)
289 dst_section--;
290 while (src_section->PointerToRawData == 0)
291 src_section--;
292 return offset
293 + (dst_section->PointerToRawData + dst_section->SizeOfRawData)
294 - (src_section->PointerToRawData + src_section->SizeOfRawData);
296 src_section++;
297 dst_section++;
299 return offset +
300 (dst_section->PointerToRawData - src_section->PointerToRawData);
303 #define OFFSET_TO_RVA(offset, section) \
304 ((section)->VirtualAddress + ((DWORD_PTR)(offset) - (section)->PointerToRawData))
306 #define RVA_TO_OFFSET(rva, section) \
307 ((section)->PointerToRawData + ((DWORD_PTR)(rva) - (section)->VirtualAddress))
309 #define RVA_TO_SECTION_OFFSET(rva, section) \
310 ((DWORD_PTR)(rva) - (section)->VirtualAddress)
312 /* Convert address in executing image to RVA. */
313 #define PTR_TO_RVA(ptr) ((DWORD_PTR)(ptr) - (DWORD_PTR) GetModuleHandle (NULL))
315 #define RVA_TO_PTR(var,section,filedata) \
316 ((unsigned char *)(RVA_TO_OFFSET (var,section) + (filedata).file_base))
318 #define PTR_TO_OFFSET(ptr, pfile_data) \
319 ((unsigned char *)(ptr) - (pfile_data)->file_base)
321 #define OFFSET_TO_PTR(offset, pfile_data) \
322 ((pfile_data)->file_base + (DWORD_PTR)(offset))
325 /* Flip through the executable and cache the info necessary for dumping. */
326 void
327 get_section_info (file_data *p_infile)
329 PIMAGE_DOS_HEADER dos_header;
330 PIMAGE_NT_HEADERS nt_header;
331 int overlap;
333 dos_header = (PIMAGE_DOS_HEADER) p_infile->file_base;
334 if (dos_header->e_magic != IMAGE_DOS_SIGNATURE)
336 printf ("Unknown EXE header in %s...bailing.\n", p_infile->name);
337 exit (1);
339 nt_header = (PIMAGE_NT_HEADERS) (((DWORD_PTR) dos_header) +
340 dos_header->e_lfanew);
341 if (nt_header == NULL)
343 printf ("Failed to find IMAGE_NT_HEADER in %s...bailing.\n",
344 p_infile->name);
345 exit (1);
348 /* Check the NT header signature ... */
349 if (nt_header->Signature != IMAGE_NT_SIGNATURE)
351 printf ("Invalid IMAGE_NT_SIGNATURE 0x%x in %s...bailing.\n",
352 nt_header->Signature, p_infile->name);
353 exit (1);
356 /* Locate the ".data" and ".bss" sections for Emacs. (Note that the
357 actual section names are probably different from these, and might
358 actually be the same section.)
360 We do this as follows: first we determine the virtual address
361 ranges in this process for the data and bss variables that we wish
362 to preserve. Then we map these VAs to the section entries in the
363 source image. Finally, we determine the new size of the raw data
364 area for the bss section, so we can make the new image the correct
365 size. */
367 /* We arrange for the Emacs initialized data to be in a separate
368 section if possible, because we cannot rely on my_begdata and
369 my_edata marking out the full extent of the initialized data, at
370 least on the Alpha where the linker freely reorders variables
371 across libraries. If we can arrange for this, all we need to do is
372 find the start and size of the EMDATA section. */
373 data_section = find_section ("EMDATA", nt_header);
374 if (data_section)
376 data_start = (char *) nt_header->OptionalHeader.ImageBase +
377 data_section->VirtualAddress;
378 data_size = data_section->Misc.VirtualSize;
380 else
382 /* Fallback on the old method if compiler doesn't support the
383 data_set #pragma (or its equivalent). */
384 data_start = my_begdata;
385 data_size = my_edata - my_begdata;
386 data_section = rva_to_section (PTR_TO_RVA (my_begdata), nt_header);
387 if (data_section != rva_to_section (PTR_TO_RVA (my_edata), nt_header))
389 printf ("Initialized data is not in a single section...bailing\n");
390 exit (1);
394 /* As noted in lastfile.c, the Alpha (but not the Intel) MSVC linker
395 globally segregates all static and public bss data (ie. across all
396 linked modules, not just per module), so we must take both static
397 and public bss areas into account to determine the true extent of
398 the bss area used by Emacs.
400 To be strictly correct, we dump the static and public bss areas
401 used by Emacs separately if non-overlapping (since otherwise we are
402 dumping bss data belonging to system libraries, eg. the static bss
403 system data on the Alpha). */
405 bss_start = my_begbss;
406 bss_size = my_endbss - my_begbss;
407 bss_section = rva_to_section (PTR_TO_RVA (my_begbss), nt_header);
408 if (bss_section != rva_to_section (PTR_TO_RVA (my_endbss), nt_header))
410 printf ("Uninitialized data is not in a single section...bailing\n");
411 exit (1);
413 /* Compute how much the .bss section's raw data will grow. */
414 extra_bss_size =
415 ROUND_UP (RVA_TO_SECTION_OFFSET (PTR_TO_RVA (my_endbss), bss_section),
416 nt_header->OptionalHeader.FileAlignment)
417 - bss_section->SizeOfRawData;
419 bss_start_static = my_begbss_static;
420 bss_size_static = my_endbss_static - my_begbss_static;
421 bss_section_static = rva_to_section (PTR_TO_RVA (my_begbss_static), nt_header);
422 if (bss_section_static != rva_to_section (PTR_TO_RVA (my_endbss_static), nt_header))
424 printf ("Uninitialized static data is not in a single section...bailing\n");
425 exit (1);
427 /* Compute how much the static .bss section's raw data will grow. */
428 extra_bss_size_static =
429 ROUND_UP (RVA_TO_SECTION_OFFSET (PTR_TO_RVA (my_endbss_static), bss_section_static),
430 nt_header->OptionalHeader.FileAlignment)
431 - bss_section_static->SizeOfRawData;
433 /* Combine the bss sections into one if they overlap. */
434 #ifdef _ALPHA_
435 overlap = 1; /* force all bss data to be dumped */
436 #else
437 overlap = 0;
438 #endif
439 if (bss_start < bss_start_static)
441 if (bss_start_static < bss_start + bss_size)
442 overlap = 1;
444 else
446 if (bss_start < bss_start_static + bss_size_static)
447 overlap = 1;
449 if (overlap)
451 if (bss_section != bss_section_static)
453 printf ("BSS data not in a single section...bailing\n");
454 exit (1);
456 bss_start = min (bss_start, bss_start_static);
457 bss_size = max (my_endbss, my_endbss_static) - bss_start;
458 bss_section_static = 0;
459 extra_bss_size_static = 0;
462 heap_section = rva_to_section (PTR_TO_RVA (get_heap_start ()), nt_header);
466 /* The dump routines. */
468 void
469 copy_executable_and_dump_data (file_data *p_infile,
470 file_data *p_outfile)
472 unsigned char *dst, *dst_save;
473 PIMAGE_DOS_HEADER dos_header;
474 PIMAGE_NT_HEADERS nt_header;
475 PIMAGE_NT_HEADERS dst_nt_header;
476 PIMAGE_SECTION_HEADER section;
477 PIMAGE_SECTION_HEADER dst_section;
478 DWORD_PTR offset;
479 int i;
480 int be_verbose = GetEnvironmentVariable ("DEBUG_DUMP", NULL, 0) > 0;
482 #define COPY_CHUNK(message, src, size, verbose) \
483 do { \
484 unsigned char *s = (void *)(src); \
485 unsigned long count = (size); \
486 if (verbose) \
488 printf ("%s\n", (message)); \
489 printf ("\t0x%08x Offset in input file.\n", s - p_infile->file_base); \
490 printf ("\t0x%08x Offset in output file.\n", dst - p_outfile->file_base); \
491 printf ("\t0x%08x Size in bytes.\n", count); \
493 memcpy (dst, s, count); \
494 dst += count; \
495 } while (0)
497 #define COPY_PROC_CHUNK(message, src, size, verbose) \
498 do { \
499 unsigned char *s = (void *)(src); \
500 unsigned long count = (size); \
501 if (verbose) \
503 printf ("%s\n", (message)); \
504 printf ("\t0x%08x Address in process.\n", s); \
505 printf ("\t0x%08x Offset in output file.\n", dst - p_outfile->file_base); \
506 printf ("\t0x%08x Size in bytes.\n", count); \
508 memcpy (dst, s, count); \
509 dst += count; \
510 } while (0)
512 #define DST_TO_OFFSET() PTR_TO_OFFSET (dst, p_outfile)
513 #define ROUND_UP_DST(align) \
514 (dst = p_outfile->file_base + ROUND_UP (DST_TO_OFFSET (), (align)))
515 #define ROUND_UP_DST_AND_ZERO(align) \
516 do { \
517 unsigned char *newdst = p_outfile->file_base \
518 + ROUND_UP (DST_TO_OFFSET (), (align)); \
519 /* Zero the alignment slop; it may actually initialize real data. */ \
520 memset (dst, 0, newdst - dst); \
521 dst = newdst; \
522 } while (0)
524 /* Copy the source image sequentially, ie. section by section after
525 copying the headers and section table, to simplify the process of
526 dumping the raw data for the bss and heap sections.
528 Note that dst is updated implicitly by each COPY_CHUNK. */
530 dos_header = (PIMAGE_DOS_HEADER) p_infile->file_base;
531 nt_header = (PIMAGE_NT_HEADERS) (((DWORD_PTR) dos_header) +
532 dos_header->e_lfanew);
533 section = IMAGE_FIRST_SECTION (nt_header);
535 dst = (unsigned char *) p_outfile->file_base;
537 COPY_CHUNK ("Copying DOS header...", dos_header,
538 (DWORD_PTR) nt_header - (DWORD_PTR) dos_header, be_verbose);
539 dst_nt_header = (PIMAGE_NT_HEADERS) dst;
540 COPY_CHUNK ("Copying NT header...", nt_header,
541 (DWORD_PTR) section - (DWORD_PTR) nt_header, be_verbose);
542 dst_section = (PIMAGE_SECTION_HEADER) dst;
543 COPY_CHUNK ("Copying section table...", section,
544 nt_header->FileHeader.NumberOfSections * sizeof (*section),
545 be_verbose);
547 /* Align the first section's raw data area, and set the header size
548 field accordingly. */
549 ROUND_UP_DST_AND_ZERO (dst_nt_header->OptionalHeader.FileAlignment);
550 dst_nt_header->OptionalHeader.SizeOfHeaders = DST_TO_OFFSET ();
552 for (i = 0; i < nt_header->FileHeader.NumberOfSections; i++)
554 char msg[100];
555 /* Windows section names are fixed 8-char strings, only
556 zero-terminated if the name is shorter than 8 characters. */
557 sprintf (msg, "Copying raw data for %.8s...", section->Name);
559 dst_save = dst;
561 /* Update the file-relative offset for this section's raw data (if
562 it has any) in case things have been relocated; we will update
563 the other offsets below once we know where everything is. */
564 if (dst_section->PointerToRawData)
565 dst_section->PointerToRawData = DST_TO_OFFSET ();
567 /* Can always copy the original raw data. */
568 COPY_CHUNK
569 (msg, OFFSET_TO_PTR (section->PointerToRawData, p_infile),
570 section->SizeOfRawData, be_verbose);
571 /* Ensure alignment slop is zeroed. */
572 ROUND_UP_DST_AND_ZERO (dst_nt_header->OptionalHeader.FileAlignment);
574 /* Note that various sections below may be aliases. */
575 if (section == data_section)
577 dst = dst_save
578 + RVA_TO_SECTION_OFFSET (PTR_TO_RVA (data_start), dst_section);
579 COPY_PROC_CHUNK ("Dumping initialized data...",
580 data_start, data_size, be_verbose);
581 dst = dst_save + dst_section->SizeOfRawData;
583 if (section == bss_section)
585 /* Dump contents of bss variables, adjusting the section's raw
586 data size as necessary. */
587 dst = dst_save
588 + RVA_TO_SECTION_OFFSET (PTR_TO_RVA (bss_start), dst_section);
589 COPY_PROC_CHUNK ("Dumping bss data...", bss_start,
590 bss_size, be_verbose);
591 ROUND_UP_DST (dst_nt_header->OptionalHeader.FileAlignment);
592 dst_section->PointerToRawData = PTR_TO_OFFSET (dst_save, p_outfile);
593 /* Determine new size of raw data area. */
594 dst = max (dst, dst_save + dst_section->SizeOfRawData);
595 dst_section->SizeOfRawData = dst - dst_save;
596 dst_section->Characteristics &= ~IMAGE_SCN_CNT_UNINITIALIZED_DATA;
597 dst_section->Characteristics |= IMAGE_SCN_CNT_INITIALIZED_DATA;
599 if (section == bss_section_static)
601 /* Dump contents of static bss variables, adjusting the
602 section's raw data size as necessary. */
603 dst = dst_save
604 + RVA_TO_SECTION_OFFSET (PTR_TO_RVA (bss_start_static), dst_section);
605 COPY_PROC_CHUNK ("Dumping static bss data...", bss_start_static,
606 bss_size_static, be_verbose);
607 ROUND_UP_DST (dst_nt_header->OptionalHeader.FileAlignment);
608 dst_section->PointerToRawData = PTR_TO_OFFSET (dst_save, p_outfile);
609 /* Determine new size of raw data area. */
610 dst = max (dst, dst_save + dst_section->SizeOfRawData);
611 dst_section->SizeOfRawData = dst - dst_save;
612 dst_section->Characteristics &= ~IMAGE_SCN_CNT_UNINITIALIZED_DATA;
613 dst_section->Characteristics |= IMAGE_SCN_CNT_INITIALIZED_DATA;
615 if (section == heap_section)
617 DWORD_PTR heap_start = (DWORD_PTR) get_heap_start ();
618 DWORD_PTR heap_size = get_committed_heap_size ();
620 /* Dump the used portion of the predump heap, adjusting the
621 section's size to the appropriate size. */
622 dst = dst_save
623 + RVA_TO_SECTION_OFFSET (PTR_TO_RVA (heap_start), dst_section);
624 COPY_PROC_CHUNK ("Dumping heap...", heap_start, heap_size,
625 be_verbose);
626 ROUND_UP_DST (dst_nt_header->OptionalHeader.FileAlignment);
627 dst_section->PointerToRawData = PTR_TO_OFFSET (dst_save, p_outfile);
628 /* Determine new size of raw data area. */
629 dst = max (dst, dst_save + dst_section->SizeOfRawData);
630 dst_section->SizeOfRawData = dst - dst_save;
631 /* Reduce the size of the heap section to fit (must be last
632 section). */
633 dst_nt_header->OptionalHeader.SizeOfImage -=
634 dst_section->Misc.VirtualSize
635 - ROUND_UP (dst_section->SizeOfRawData,
636 dst_nt_header->OptionalHeader.SectionAlignment);
637 dst_section->Misc.VirtualSize =
638 ROUND_UP (dst_section->SizeOfRawData,
639 dst_nt_header->OptionalHeader.SectionAlignment);
640 dst_section->Characteristics &= ~IMAGE_SCN_CNT_UNINITIALIZED_DATA;
641 dst_section->Characteristics |= IMAGE_SCN_CNT_INITIALIZED_DATA;
644 /* Align the section's raw data area. */
645 ROUND_UP_DST (dst_nt_header->OptionalHeader.FileAlignment);
647 section++;
648 dst_section++;
651 /* Copy remainder of source image. */
653 section--;
654 while (section->PointerToRawData == 0);
655 offset = ROUND_UP (section->PointerToRawData + section->SizeOfRawData,
656 nt_header->OptionalHeader.FileAlignment);
657 COPY_CHUNK
658 ("Copying remainder of executable...",
659 OFFSET_TO_PTR (offset, p_infile),
660 p_infile->size - offset, be_verbose);
662 /* Final size for new image. */
663 p_outfile->size = DST_TO_OFFSET ();
665 /* Now patch up remaining file-relative offsets. */
666 section = IMAGE_FIRST_SECTION (nt_header);
667 dst_section = IMAGE_FIRST_SECTION (dst_nt_header);
669 #define ADJUST_OFFSET(var) \
670 do { \
671 if ((var) != 0) \
672 (var) = relocate_offset ((var), nt_header, dst_nt_header); \
673 } while (0)
675 dst_nt_header->OptionalHeader.SizeOfInitializedData = 0;
676 dst_nt_header->OptionalHeader.SizeOfUninitializedData = 0;
677 for (i = 0; i < dst_nt_header->FileHeader.NumberOfSections; i++)
679 /* Recompute data sizes for completeness. */
680 if (dst_section[i].Characteristics & IMAGE_SCN_CNT_INITIALIZED_DATA)
681 dst_nt_header->OptionalHeader.SizeOfInitializedData +=
682 ROUND_UP (dst_section[i].Misc.VirtualSize, dst_nt_header->OptionalHeader.FileAlignment);
683 else if (dst_section[i].Characteristics & IMAGE_SCN_CNT_UNINITIALIZED_DATA)
684 dst_nt_header->OptionalHeader.SizeOfUninitializedData +=
685 ROUND_UP (dst_section[i].Misc.VirtualSize, dst_nt_header->OptionalHeader.FileAlignment);
687 ADJUST_OFFSET (dst_section[i].PointerToLinenumbers);
690 ADJUST_OFFSET (dst_nt_header->FileHeader.PointerToSymbolTable);
692 /* Update offsets in debug directory entries. */
694 IMAGE_DATA_DIRECTORY debug_dir =
695 dst_nt_header->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_DEBUG];
696 PIMAGE_DEBUG_DIRECTORY debug_entry;
698 section = rva_to_section (debug_dir.VirtualAddress, dst_nt_header);
699 if (section)
701 debug_entry = (PIMAGE_DEBUG_DIRECTORY)
702 (RVA_TO_OFFSET (debug_dir.VirtualAddress, section) + p_outfile->file_base);
703 debug_dir.Size /= sizeof (IMAGE_DEBUG_DIRECTORY);
705 for (i = 0; i < debug_dir.Size; i++, debug_entry++)
706 ADJUST_OFFSET (debug_entry->PointerToRawData);
712 /* Dump out .data and .bss sections into a new executable. */
713 void
714 unexec (const char *new_name, const char *old_name)
716 file_data in_file, out_file;
717 char out_filename[MAX_PATH], in_filename[MAX_PATH];
718 unsigned long size;
719 char *p;
720 char *q;
722 /* Ignore old_name, and get our actual location from the OS. */
723 if (!GetModuleFileName (NULL, in_filename, MAX_PATH))
724 abort ();
725 dostounix_filename (in_filename, 0);
726 strcpy (out_filename, in_filename);
728 /* Change the base of the output filename to match the requested name. */
729 if ((p = strrchr (out_filename, '/')) == NULL)
730 abort ();
731 /* The filenames have already been expanded, and will be in Unix
732 format, so it is safe to expect an absolute name. */
733 if ((q = strrchr (new_name, '/')) == NULL)
734 abort ();
735 strcpy (p, q);
737 /* Make sure that the output filename has the ".exe" extension...patch
738 it up if not. */
739 p = out_filename + strlen (out_filename) - 4;
740 if (strcmp (p, ".exe"))
741 strcat (out_filename, ".exe");
743 printf ("Dumping from %s\n", in_filename);
744 printf (" to %s\n", out_filename);
746 /* We need to round off our heap to NT's page size. */
747 round_heap (get_page_size ());
749 /* Open the undumped executable file. */
750 if (!open_input_file (&in_file, in_filename))
752 printf ("Failed to open %s (%d)...bailing.\n",
753 in_filename, GetLastError ());
754 exit (1);
757 /* Get the interesting section info, like start and size of .bss... */
758 get_section_info (&in_file);
760 /* The size of the dumped executable is the size of the original
761 executable plus the size of the heap and the size of the .bss section. */
762 size = in_file.size +
763 get_committed_heap_size () +
764 extra_bss_size +
765 extra_bss_size_static;
766 if (!open_output_file (&out_file, out_filename, size))
768 printf ("Failed to open %s (%d)...bailing.\n",
769 out_filename, GetLastError ());
770 exit (1);
773 /* Set the flag (before dumping). */
774 using_dynamic_heap = TRUE;
776 copy_executable_and_dump_data (&in_file, &out_file);
778 /* Patch up header fields; profiler is picky about this. */
780 PIMAGE_DOS_HEADER dos_header;
781 PIMAGE_NT_HEADERS nt_header;
782 HANDLE hImagehelp = LoadLibrary ("imagehlp.dll");
783 DWORD headersum;
784 DWORD checksum;
786 dos_header = (PIMAGE_DOS_HEADER) out_file.file_base;
787 nt_header = (PIMAGE_NT_HEADERS) ((char *) dos_header + dos_header->e_lfanew);
789 nt_header->OptionalHeader.CheckSum = 0;
790 // nt_header->FileHeader.TimeDateStamp = time (NULL);
791 // dos_header->e_cp = size / 512;
792 // nt_header->OptionalHeader.SizeOfImage = size;
794 pfnCheckSumMappedFile = (void *) GetProcAddress (hImagehelp, "CheckSumMappedFile");
795 if (pfnCheckSumMappedFile)
797 // nt_header->FileHeader.TimeDateStamp = time (NULL);
798 pfnCheckSumMappedFile (out_file.file_base,
799 out_file.size,
800 &headersum,
801 &checksum);
802 nt_header->OptionalHeader.CheckSum = checksum;
804 FreeLibrary (hImagehelp);
807 close_file_data (&in_file);
808 close_file_data (&out_file);
811 /* eof */