* emacs-lisp/byte-run.el (defmacro): Use same argument parsing as
[bpt/emacs.git] / src / unexw32.c
CommitLineData
3b7ad313 1/* unexec for GNU Emacs on Windows NT.
acaf905b 2 Copyright (C) 1994, 2001-2012 Free Software Foundation, Inc.
2147fb50 3
3b7ad313 4This file is part of GNU Emacs.
2147fb50 5
9ec0b715 6GNU Emacs is free software: you can redistribute it and/or modify
3b7ad313 7it under the terms of the GNU General Public License as published by
9ec0b715
GM
8the Free Software Foundation, either version 3 of the License, or
9(at your option) any later version.
2147fb50 10
3b7ad313
EN
11GNU Emacs is distributed in the hope that it will be useful,
12but WITHOUT ANY WARRANTY; without even the implied warranty of
13MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14GNU General Public License for more details.
2147fb50 15
3b7ad313 16You should have received a copy of the GNU General Public License
9ec0b715 17along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
2147fb50 18
9ec0b715 19/*
2147fb50
KH
20 Geoff Voelker (voelker@cs.washington.edu) 8-12-94
21*/
22
43640c4d 23#include <config.h>
ce701a33 24#include "unexec.h"
a68089e4 25#include "lisp.h"
501199a3 26#include "w32common.h"
a68089e4 27#include "w32.h"
43640c4d 28
2147fb50
KH
29#include <stdio.h>
30#include <fcntl.h>
43640c4d 31#include <time.h>
2147fb50
KH
32#include <windows.h>
33
43640c4d
GV
34/* Include relevant definitions from IMAGEHLP.H, which can be found
35 in \\win32sdk\mstools\samples\image\include\imagehlp.h. */
2147fb50 36
43640c4d
GV
37PIMAGE_NT_HEADERS
38(__stdcall * pfnCheckSumMappedFile) (LPVOID BaseAddress,
39 DWORD FileLength,
40 LPDWORD HeaderSum,
41 LPDWORD CheckSum);
2147fb50 42
43640c4d
GV
43extern BOOL ctrl_c_handler (unsigned long type);
44
45extern char my_begdata[];
46extern char my_edata[];
47extern char my_begbss[];
48extern char my_endbss[];
9c8056fe
GV
49extern char *my_begbss_static;
50extern char *my_endbss_static;
2147fb50 51
43640c4d 52#include "w32heap.h"
e54c8cd1 53
03887dd3
KH
54#undef min
55#undef max
56#define min(x, y) (((x) < (y)) ? (x) : (y))
57#define max(x, y) (((x) > (y)) ? (x) : (y))
58
2147fb50 59/* Basically, our "initialized" flag. */
5b79dba5 60BOOL using_dynamic_heap = FALSE;
2147fb50 61
43640c4d
GV
62int open_input_file (file_data *p_file, char *name);
63int open_output_file (file_data *p_file, char *name, unsigned long size);
2147fb50
KH
64void close_file_data (file_data *p_file);
65
66void get_section_info (file_data *p_file);
5b79dba5 67void copy_executable_and_dump_data (file_data *, file_data *);
2147fb50
KH
68void dump_bss_and_heap (file_data *p_infile, file_data *p_outfile);
69
70/* Cached info about the .data section in the executable. */
5b79dba5 71PIMAGE_SECTION_HEADER data_section;
49dc9682 72PCHAR data_start = 0;
62aba0d4 73DWORD_PTR data_size = 0;
2147fb50
KH
74
75/* Cached info about the .bss section in the executable. */
5b79dba5 76PIMAGE_SECTION_HEADER bss_section;
49dc9682 77PCHAR bss_start = 0;
62aba0d4
FP
78DWORD_PTR bss_size = 0;
79DWORD_PTR extra_bss_size = 0;
5b79dba5
AI
80/* bss data that is static might be discontiguous from non-static. */
81PIMAGE_SECTION_HEADER bss_section_static;
49dc9682 82PCHAR bss_start_static = 0;
62aba0d4
FP
83DWORD_PTR bss_size_static = 0;
84DWORD_PTR extra_bss_size_static = 0;
5b79dba5
AI
85
86PIMAGE_SECTION_HEADER heap_section;
2147fb50 87
78f9ea87
DC
88#ifdef HAVE_NTGUI
89extern HINSTANCE hinst;
90HINSTANCE hprevinst = NULL;
91LPSTR lpCmdLine = "";
92int nCmdShow = 0;
93#endif /* HAVE_NTGUI */
94
2147fb50
KH
95/* Startup code for running on NT. When we are running as the dumped
96 version, we need to bootstrap our heap and .bss section into our
97 address space before we can actually hand off control to the startup
98 code supplied by NT (primarily because that code relies upon malloc ()). */
99void
100_start (void)
101{
102 extern void mainCRTStartup (void);
103
7fef47a3 104#if 1
43640c4d
GV
105 /* Give us a way to debug problems with crashes on startup when
106 running under the MSVC profiler. */
107 if (GetEnvironmentVariable ("EMACS_DEBUG", NULL, 0) > 0)
108 DebugBreak ();
109#endif
110
2147fb50
KH
111 /* Cache system info, e.g., the NT page size. */
112 cache_system_info ();
113
5b79dba5
AI
114 /* Grab our malloc arena space now, before CRT starts up. */
115 init_heap ();
2147fb50 116
2147fb50
KH
117 /* This prevents ctrl-c's in shells running while we're suspended from
118 having us exit. */
119 SetConsoleCtrlHandler ((PHANDLER_ROUTINE) ctrl_c_handler, TRUE);
120
467af476
AI
121 /* Prevent Emacs from being locked up (eg. in batch mode) when
122 accessing devices that aren't mounted (eg. removable media drives). */
123 SetErrorMode (SEM_FAILCRITICALERRORS);
78f9ea87
DC
124
125 /* Invoke the NT CRT startup routine now that our housecleaning
126 is finished. */
127#ifdef HAVE_NTGUI
128 /* determine WinMain args like crt0.c does */
129 hinst = GetModuleHandle (NULL);
130 lpCmdLine = GetCommandLine ();
131 nCmdShow = SW_SHOWDEFAULT;
132#endif
2147fb50
KH
133 mainCRTStartup ();
134}
135
2147fb50
KH
136
137/* File handling. */
138
43640c4d 139int
2147fb50
KH
140open_input_file (file_data *p_file, char *filename)
141{
142 HANDLE file;
143 HANDLE file_mapping;
144 void *file_base;
145 unsigned long size, upper_size;
146
147 file = CreateFile (filename, GENERIC_READ, FILE_SHARE_READ, NULL,
148 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
177c0ea7 149 if (file == INVALID_HANDLE_VALUE)
43640c4d 150 return FALSE;
2147fb50
KH
151
152 size = GetFileSize (file, &upper_size);
177c0ea7 153 file_mapping = CreateFileMapping (file, NULL, PAGE_READONLY,
2147fb50 154 0, size, NULL);
177c0ea7 155 if (!file_mapping)
43640c4d 156 return FALSE;
2147fb50
KH
157
158 file_base = MapViewOfFile (file_mapping, FILE_MAP_READ, 0, 0, size);
177c0ea7 159 if (file_base == 0)
43640c4d 160 return FALSE;
2147fb50
KH
161
162 p_file->name = filename;
163 p_file->size = size;
164 p_file->file = file;
165 p_file->file_mapping = file_mapping;
166 p_file->file_base = file_base;
43640c4d
GV
167
168 return TRUE;
2147fb50
KH
169}
170
43640c4d 171int
2147fb50
KH
172open_output_file (file_data *p_file, char *filename, unsigned long size)
173{
174 HANDLE file;
175 HANDLE file_mapping;
176 void *file_base;
cd6885f3 177
2147fb50
KH
178 file = CreateFile (filename, GENERIC_READ | GENERIC_WRITE, 0, NULL,
179 CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
177c0ea7 180 if (file == INVALID_HANDLE_VALUE)
43640c4d
GV
181 return FALSE;
182
177c0ea7 183 file_mapping = CreateFileMapping (file, NULL, PAGE_READWRITE,
2147fb50 184 0, size, NULL);
177c0ea7 185 if (!file_mapping)
43640c4d 186 return FALSE;
177c0ea7 187
2147fb50 188 file_base = MapViewOfFile (file_mapping, FILE_MAP_WRITE, 0, 0, size);
177c0ea7 189 if (file_base == 0)
43640c4d 190 return FALSE;
177c0ea7 191
2147fb50
KH
192 p_file->name = filename;
193 p_file->size = size;
194 p_file->file = file;
195 p_file->file_mapping = file_mapping;
196 p_file->file_base = file_base;
43640c4d
GV
197
198 return TRUE;
2147fb50
KH
199}
200
201/* Close the system structures associated with the given file. */
43640c4d 202void
2147fb50
KH
203close_file_data (file_data *p_file)
204{
5b79dba5
AI
205 UnmapViewOfFile (p_file->file_base);
206 CloseHandle (p_file->file_mapping);
207 /* For the case of output files, set final size. */
208 SetFilePointer (p_file->file, p_file->size, NULL, FILE_BEGIN);
209 SetEndOfFile (p_file->file);
210 CloseHandle (p_file->file);
2147fb50
KH
211}
212
213
214/* Routines to manipulate NT executable file sections. */
215
43640c4d
GV
216/* Return pointer to section header for named section. */
217IMAGE_SECTION_HEADER *
218find_section (char * name, IMAGE_NT_HEADERS * nt_header)
219{
220 PIMAGE_SECTION_HEADER section;
221 int i;
222
223 section = IMAGE_FIRST_SECTION (nt_header);
224
225 for (i = 0; i < nt_header->FileHeader.NumberOfSections; i++)
226 {
227 if (strcmp (section->Name, name) == 0)
228 return section;
229 section++;
230 }
231 return NULL;
232}
233
234/* Return pointer to section header for section containing the given
235 relative virtual address. */
236IMAGE_SECTION_HEADER *
62aba0d4 237rva_to_section (DWORD_PTR rva, IMAGE_NT_HEADERS * nt_header)
43640c4d
GV
238{
239 PIMAGE_SECTION_HEADER section;
240 int i;
241
242 section = IMAGE_FIRST_SECTION (nt_header);
243
244 for (i = 0; i < nt_header->FileHeader.NumberOfSections; i++)
2147fb50 245 {
5b79dba5
AI
246 /* Some linkers (eg. the NT SDK linker I believe) swapped the
247 meaning of these two values - or rather, they ignored
248 VirtualSize entirely and always set it to zero. This affects
249 some very old exes (eg. gzip dated Dec 1993). Since
250 w32_executable_type relies on this function to work reliably,
251 we need to cope with this. */
62aba0d4 252 DWORD_PTR real_size = max (section->SizeOfRawData,
5b79dba5 253 section->Misc.VirtualSize);
43640c4d 254 if (rva >= section->VirtualAddress
5b79dba5
AI
255 && rva < section->VirtualAddress + real_size)
256 return section;
257 section++;
258 }
259 return NULL;
260}
261
262/* Return pointer to section header for section containing the given
263 offset in its raw data area. */
264IMAGE_SECTION_HEADER *
62aba0d4 265offset_to_section (DWORD_PTR offset, IMAGE_NT_HEADERS * nt_header)
5b79dba5
AI
266{
267 PIMAGE_SECTION_HEADER section;
268 int i;
269
270 section = IMAGE_FIRST_SECTION (nt_header);
271
272 for (i = 0; i < nt_header->FileHeader.NumberOfSections; i++)
273 {
274 if (offset >= section->PointerToRawData
275 && offset < section->PointerToRawData + section->SizeOfRawData)
43640c4d
GV
276 return section;
277 section++;
2147fb50 278 }
43640c4d 279 return NULL;
2147fb50
KH
280}
281
5b79dba5
AI
282/* Return offset to an object in dst, given offset in src. We assume
283 there is at least one section in both src and dst images, and that
284 the some sections may have been added to dst (after sections in src). */
62aba0d4
FP
285DWORD_PTR
286relocate_offset (DWORD_PTR offset,
5b79dba5
AI
287 IMAGE_NT_HEADERS * src_nt_header,
288 IMAGE_NT_HEADERS * dst_nt_header)
289{
290 PIMAGE_SECTION_HEADER src_section = IMAGE_FIRST_SECTION (src_nt_header);
291 PIMAGE_SECTION_HEADER dst_section = IMAGE_FIRST_SECTION (dst_nt_header);
292 int i = 0;
293
294 while (offset >= src_section->PointerToRawData)
295 {
296 if (offset < src_section->PointerToRawData + src_section->SizeOfRawData)
297 break;
298 i++;
299 if (i == src_nt_header->FileHeader.NumberOfSections)
300 {
301 /* Handle offsets after the last section. */
302 dst_section = IMAGE_FIRST_SECTION (dst_nt_header);
303 dst_section += dst_nt_header->FileHeader.NumberOfSections - 1;
304 while (dst_section->PointerToRawData == 0)
305 dst_section--;
306 while (src_section->PointerToRawData == 0)
307 src_section--;
308 return offset
309 + (dst_section->PointerToRawData + dst_section->SizeOfRawData)
310 - (src_section->PointerToRawData + src_section->SizeOfRawData);
311 }
312 src_section++;
313 dst_section++;
314 }
315 return offset +
316 (dst_section->PointerToRawData - src_section->PointerToRawData);
317}
318
319#define OFFSET_TO_RVA(offset, section) \
2d7d1608 320 ((section)->VirtualAddress + ((DWORD_PTR)(offset) - (section)->PointerToRawData))
5b79dba5
AI
321
322#define RVA_TO_OFFSET(rva, section) \
2d7d1608 323 ((section)->PointerToRawData + ((DWORD_PTR)(rva) - (section)->VirtualAddress))
5b79dba5
AI
324
325#define RVA_TO_SECTION_OFFSET(rva, section) \
2d7d1608 326 ((DWORD_PTR)(rva) - (section)->VirtualAddress)
5b79dba5
AI
327
328/* Convert address in executing image to RVA. */
62aba0d4 329#define PTR_TO_RVA(ptr) ((DWORD_PTR)(ptr) - (DWORD_PTR) GetModuleHandle (NULL))
5b79dba5 330
e9bdb9c9 331#define RVA_TO_PTR(var,section,filedata) \
2d7d1608 332 ((unsigned char *)(RVA_TO_OFFSET (var,section) + (filedata).file_base))
e9bdb9c9 333
5b79dba5 334#define PTR_TO_OFFSET(ptr, pfile_data) \
49dc9682 335 ((unsigned char *)(ptr) - (pfile_data)->file_base)
5b79dba5
AI
336
337#define OFFSET_TO_PTR(offset, pfile_data) \
62aba0d4 338 ((pfile_data)->file_base + (DWORD_PTR)(offset))
5b79dba5 339
43640c4d 340
2147fb50 341/* Flip through the executable and cache the info necessary for dumping. */
49dc9682 342void
2147fb50
KH
343get_section_info (file_data *p_infile)
344{
345 PIMAGE_DOS_HEADER dos_header;
346 PIMAGE_NT_HEADERS nt_header;
5b79dba5 347 int overlap;
177c0ea7 348
2147fb50 349 dos_header = (PIMAGE_DOS_HEADER) p_infile->file_base;
177c0ea7 350 if (dos_header->e_magic != IMAGE_DOS_SIGNATURE)
2147fb50
KH
351 {
352 printf ("Unknown EXE header in %s...bailing.\n", p_infile->name);
353 exit (1);
354 }
62aba0d4 355 nt_header = (PIMAGE_NT_HEADERS) (((DWORD_PTR) dos_header) +
2147fb50 356 dos_header->e_lfanew);
177c0ea7 357 if (nt_header == NULL)
2147fb50 358 {
177c0ea7 359 printf ("Failed to find IMAGE_NT_HEADER in %s...bailing.\n",
2147fb50
KH
360 p_infile->name);
361 exit (1);
362 }
363
364 /* Check the NT header signature ... */
177c0ea7 365 if (nt_header->Signature != IMAGE_NT_SIGNATURE)
2147fb50
KH
366 {
367 printf ("Invalid IMAGE_NT_SIGNATURE 0x%x in %s...bailing.\n",
368 nt_header->Signature, p_infile->name);
5b79dba5 369 exit (1);
2147fb50
KH
370 }
371
5b79dba5
AI
372 /* Locate the ".data" and ".bss" sections for Emacs. (Note that the
373 actual section names are probably different from these, and might
374 actually be the same section.)
375
376 We do this as follows: first we determine the virtual address
377 ranges in this process for the data and bss variables that we wish
378 to preserve. Then we map these VAs to the section entries in the
379 source image. Finally, we determine the new size of the raw data
380 area for the bss section, so we can make the new image the correct
381 size. */
382
e3ddd18c
AI
383 /* We arrange for the Emacs initialized data to be in a separate
384 section if possible, because we cannot rely on my_begdata and
385 my_edata marking out the full extent of the initialized data, at
386 least on the Alpha where the linker freely reorders variables
387 across libraries. If we can arrange for this, all we need to do is
388 find the start and size of the EMDATA section. */
389 data_section = find_section ("EMDATA", nt_header);
390 if (data_section)
2147fb50 391 {
e3ddd18c
AI
392 data_start = (char *) nt_header->OptionalHeader.ImageBase +
393 data_section->VirtualAddress;
394 data_size = data_section->Misc.VirtualSize;
395 }
396 else
397 {
398 /* Fallback on the old method if compiler doesn't support the
399 data_set #pragma (or its equivalent). */
400 data_start = my_begdata;
401 data_size = my_edata - my_begdata;
402 data_section = rva_to_section (PTR_TO_RVA (my_begdata), nt_header);
403 if (data_section != rva_to_section (PTR_TO_RVA (my_edata), nt_header))
404 {
405 printf ("Initialized data is not in a single section...bailing\n");
406 exit (1);
407 }
5b79dba5
AI
408 }
409
410 /* As noted in lastfile.c, the Alpha (but not the Intel) MSVC linker
411 globally segregates all static and public bss data (ie. across all
412 linked modules, not just per module), so we must take both static
413 and public bss areas into account to determine the true extent of
414 the bss area used by Emacs.
415
416 To be strictly correct, we dump the static and public bss areas
417 used by Emacs separately if non-overlapping (since otherwise we are
418 dumping bss data belonging to system libraries, eg. the static bss
419 system data on the Alpha). */
420
421 bss_start = my_begbss;
422 bss_size = my_endbss - my_begbss;
423 bss_section = rva_to_section (PTR_TO_RVA (my_begbss), nt_header);
424 if (bss_section != rva_to_section (PTR_TO_RVA (my_endbss), nt_header))
425 {
426 printf ("Uninitialized data is not in a single section...bailing\n");
427 exit (1);
428 }
429 /* Compute how much the .bss section's raw data will grow. */
430 extra_bss_size =
431 ROUND_UP (RVA_TO_SECTION_OFFSET (PTR_TO_RVA (my_endbss), bss_section),
432 nt_header->OptionalHeader.FileAlignment)
433 - bss_section->SizeOfRawData;
434
435 bss_start_static = my_begbss_static;
436 bss_size_static = my_endbss_static - my_begbss_static;
437 bss_section_static = rva_to_section (PTR_TO_RVA (my_begbss_static), nt_header);
438 if (bss_section_static != rva_to_section (PTR_TO_RVA (my_endbss_static), nt_header))
439 {
440 printf ("Uninitialized static data is not in a single section...bailing\n");
441 exit (1);
442 }
443 /* Compute how much the static .bss section's raw data will grow. */
444 extra_bss_size_static =
445 ROUND_UP (RVA_TO_SECTION_OFFSET (PTR_TO_RVA (my_endbss_static), bss_section_static),
446 nt_header->OptionalHeader.FileAlignment)
447 - bss_section_static->SizeOfRawData;
448
449 /* Combine the bss sections into one if they overlap. */
972ee7e0
AI
450#ifdef _ALPHA_
451 overlap = 1; /* force all bss data to be dumped */
452#else
5b79dba5 453 overlap = 0;
972ee7e0 454#endif
5b79dba5
AI
455 if (bss_start < bss_start_static)
456 {
457 if (bss_start_static < bss_start + bss_size)
458 overlap = 1;
459 }
460 else
461 {
462 if (bss_start < bss_start_static + bss_size_static)
463 overlap = 1;
464 }
465 if (overlap)
466 {
467 if (bss_section != bss_section_static)
2147fb50 468 {
5b79dba5
AI
469 printf ("BSS data not in a single section...bailing\n");
470 exit (1);
2147fb50 471 }
5b79dba5
AI
472 bss_start = min (bss_start, bss_start_static);
473 bss_size = max (my_endbss, my_endbss_static) - bss_start;
474 bss_section_static = 0;
475 extra_bss_size_static = 0;
476 }
477
478 heap_section = rva_to_section (PTR_TO_RVA (get_heap_start ()), nt_header);
479}
480
481
482/* The dump routines. */
483
49dc9682 484void
177c0ea7 485copy_executable_and_dump_data (file_data *p_infile,
5b79dba5
AI
486 file_data *p_outfile)
487{
488 unsigned char *dst, *dst_save;
489 PIMAGE_DOS_HEADER dos_header;
490 PIMAGE_NT_HEADERS nt_header;
491 PIMAGE_NT_HEADERS dst_nt_header;
492 PIMAGE_SECTION_HEADER section;
493 PIMAGE_SECTION_HEADER dst_section;
62aba0d4 494 DWORD_PTR offset;
5b79dba5 495 int i;
4162f25f 496 int be_verbose = GetEnvironmentVariable ("DEBUG_DUMP", NULL, 0) > 0;
5b79dba5 497
4162f25f 498#define COPY_CHUNK(message, src, size, verbose) \
5b79dba5
AI
499 do { \
500 unsigned char *s = (void *)(src); \
501 unsigned long count = (size); \
4162f25f
EZ
502 if (verbose) \
503 { \
504 printf ("%s\n", (message)); \
505 printf ("\t0x%08x Offset in input file.\n", s - p_infile->file_base); \
506 printf ("\t0x%08x Offset in output file.\n", dst - p_outfile->file_base); \
507 printf ("\t0x%08x Size in bytes.\n", count); \
508 } \
5b79dba5
AI
509 memcpy (dst, s, count); \
510 dst += count; \
511 } while (0)
512
4162f25f 513#define COPY_PROC_CHUNK(message, src, size, verbose) \
5b79dba5
AI
514 do { \
515 unsigned char *s = (void *)(src); \
516 unsigned long count = (size); \
4162f25f
EZ
517 if (verbose) \
518 { \
519 printf ("%s\n", (message)); \
520 printf ("\t0x%08x Address in process.\n", s); \
521 printf ("\t0x%08x Offset in output file.\n", dst - p_outfile->file_base); \
522 printf ("\t0x%08x Size in bytes.\n", count); \
523 } \
5b79dba5
AI
524 memcpy (dst, s, count); \
525 dst += count; \
526 } while (0)
527
528#define DST_TO_OFFSET() PTR_TO_OFFSET (dst, p_outfile)
529#define ROUND_UP_DST(align) \
530 (dst = p_outfile->file_base + ROUND_UP (DST_TO_OFFSET (), (align)))
7fef47a3
AI
531#define ROUND_UP_DST_AND_ZERO(align) \
532 do { \
533 unsigned char *newdst = p_outfile->file_base \
534 + ROUND_UP (DST_TO_OFFSET (), (align)); \
535 /* Zero the alignment slop; it may actually initialize real data. */ \
536 memset (dst, 0, newdst - dst); \
537 dst = newdst; \
538 } while (0)
5b79dba5
AI
539
540 /* Copy the source image sequentially, ie. section by section after
541 copying the headers and section table, to simplify the process of
542 dumping the raw data for the bss and heap sections.
543
544 Note that dst is updated implicitly by each COPY_CHUNK. */
545
546 dos_header = (PIMAGE_DOS_HEADER) p_infile->file_base;
62aba0d4 547 nt_header = (PIMAGE_NT_HEADERS) (((DWORD_PTR) dos_header) +
5b79dba5
AI
548 dos_header->e_lfanew);
549 section = IMAGE_FIRST_SECTION (nt_header);
177c0ea7 550
5b79dba5
AI
551 dst = (unsigned char *) p_outfile->file_base;
552
553 COPY_CHUNK ("Copying DOS header...", dos_header,
62aba0d4 554 (DWORD_PTR) nt_header - (DWORD_PTR) dos_header, be_verbose);
5b79dba5
AI
555 dst_nt_header = (PIMAGE_NT_HEADERS) dst;
556 COPY_CHUNK ("Copying NT header...", nt_header,
62aba0d4 557 (DWORD_PTR) section - (DWORD_PTR) nt_header, be_verbose);
5b79dba5
AI
558 dst_section = (PIMAGE_SECTION_HEADER) dst;
559 COPY_CHUNK ("Copying section table...", section,
4162f25f
EZ
560 nt_header->FileHeader.NumberOfSections * sizeof (*section),
561 be_verbose);
5b79dba5 562
7fef47a3
AI
563 /* Align the first section's raw data area, and set the header size
564 field accordingly. */
565 ROUND_UP_DST_AND_ZERO (dst_nt_header->OptionalHeader.FileAlignment);
566 dst_nt_header->OptionalHeader.SizeOfHeaders = DST_TO_OFFSET ();
567
5b79dba5
AI
568 for (i = 0; i < nt_header->FileHeader.NumberOfSections; i++)
569 {
570 char msg[100];
4162f25f
EZ
571 /* Windows section names are fixed 8-char strings, only
572 zero-terminated if the name is shorter than 8 characters. */
573 sprintf (msg, "Copying raw data for %.8s...", section->Name);
5b79dba5 574
5b79dba5
AI
575 dst_save = dst;
576
577 /* Update the file-relative offset for this section's raw data (if
578 it has any) in case things have been relocated; we will update
579 the other offsets below once we know where everything is. */
580 if (dst_section->PointerToRawData)
581 dst_section->PointerToRawData = DST_TO_OFFSET ();
582
583 /* Can always copy the original raw data. */
584 COPY_CHUNK
585 (msg, OFFSET_TO_PTR (section->PointerToRawData, p_infile),
4162f25f 586 section->SizeOfRawData, be_verbose);
7fef47a3
AI
587 /* Ensure alignment slop is zeroed. */
588 ROUND_UP_DST_AND_ZERO (dst_nt_header->OptionalHeader.FileAlignment);
5b79dba5
AI
589
590 /* Note that various sections below may be aliases. */
591 if (section == data_section)
2147fb50 592 {
5b79dba5
AI
593 dst = dst_save
594 + RVA_TO_SECTION_OFFSET (PTR_TO_RVA (data_start), dst_section);
4162f25f
EZ
595 COPY_PROC_CHUNK ("Dumping initialized data...",
596 data_start, data_size, be_verbose);
5b79dba5 597 dst = dst_save + dst_section->SizeOfRawData;
2147fb50 598 }
5b79dba5 599 if (section == bss_section)
43640c4d 600 {
5b79dba5
AI
601 /* Dump contents of bss variables, adjusting the section's raw
602 data size as necessary. */
603 dst = dst_save
604 + RVA_TO_SECTION_OFFSET (PTR_TO_RVA (bss_start), dst_section);
4162f25f
EZ
605 COPY_PROC_CHUNK ("Dumping bss data...", bss_start,
606 bss_size, be_verbose);
5b79dba5
AI
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;
43640c4d 614 }
5b79dba5
AI
615 if (section == bss_section_static)
616 {
617 /* Dump contents of static bss variables, adjusting the
618 section's raw data size as necessary. */
619 dst = dst_save
620 + RVA_TO_SECTION_OFFSET (PTR_TO_RVA (bss_start_static), dst_section);
4162f25f
EZ
621 COPY_PROC_CHUNK ("Dumping static bss data...", bss_start_static,
622 bss_size_static, be_verbose);
5b79dba5
AI
623 ROUND_UP_DST (dst_nt_header->OptionalHeader.FileAlignment);
624 dst_section->PointerToRawData = PTR_TO_OFFSET (dst_save, p_outfile);
625 /* Determine new size of raw data area. */
626 dst = max (dst, dst_save + dst_section->SizeOfRawData);
627 dst_section->SizeOfRawData = dst - dst_save;
628 dst_section->Characteristics &= ~IMAGE_SCN_CNT_UNINITIALIZED_DATA;
629 dst_section->Characteristics |= IMAGE_SCN_CNT_INITIALIZED_DATA;
630 }
631 if (section == heap_section)
632 {
62aba0d4
FP
633 DWORD_PTR heap_start = (DWORD_PTR) get_heap_start ();
634 DWORD_PTR heap_size = get_committed_heap_size ();
5b79dba5
AI
635
636 /* Dump the used portion of the predump heap, adjusting the
637 section's size to the appropriate size. */
638 dst = dst_save
639 + RVA_TO_SECTION_OFFSET (PTR_TO_RVA (heap_start), dst_section);
4162f25f
EZ
640 COPY_PROC_CHUNK ("Dumping heap...", heap_start, heap_size,
641 be_verbose);
5b79dba5
AI
642 ROUND_UP_DST (dst_nt_header->OptionalHeader.FileAlignment);
643 dst_section->PointerToRawData = PTR_TO_OFFSET (dst_save, p_outfile);
644 /* Determine new size of raw data area. */
645 dst = max (dst, dst_save + dst_section->SizeOfRawData);
646 dst_section->SizeOfRawData = dst - dst_save;
647 /* Reduce the size of the heap section to fit (must be last
648 section). */
649 dst_nt_header->OptionalHeader.SizeOfImage -=
650 dst_section->Misc.VirtualSize
651 - ROUND_UP (dst_section->SizeOfRawData,
652 dst_nt_header->OptionalHeader.SectionAlignment);
653 dst_section->Misc.VirtualSize =
654 ROUND_UP (dst_section->SizeOfRawData,
655 dst_nt_header->OptionalHeader.SectionAlignment);
656 dst_section->Characteristics &= ~IMAGE_SCN_CNT_UNINITIALIZED_DATA;
657 dst_section->Characteristics |= IMAGE_SCN_CNT_INITIALIZED_DATA;
658 }
659
7fef47a3
AI
660 /* Align the section's raw data area. */
661 ROUND_UP_DST (dst_nt_header->OptionalHeader.FileAlignment);
662
2147fb50 663 section++;
5b79dba5 664 dst_section++;
2147fb50 665 }
a610993d 666
5b79dba5
AI
667 /* Copy remainder of source image. */
668 do
669 section--;
670 while (section->PointerToRawData == 0);
671 offset = ROUND_UP (section->PointerToRawData + section->SizeOfRawData,
672 nt_header->OptionalHeader.FileAlignment);
673 COPY_CHUNK
674 ("Copying remainder of executable...",
675 OFFSET_TO_PTR (offset, p_infile),
4162f25f 676 p_infile->size - offset, be_verbose);
5b79dba5
AI
677
678 /* Final size for new image. */
679 p_outfile->size = DST_TO_OFFSET ();
680
681 /* Now patch up remaining file-relative offsets. */
682 section = IMAGE_FIRST_SECTION (nt_header);
683 dst_section = IMAGE_FIRST_SECTION (dst_nt_header);
684
685#define ADJUST_OFFSET(var) \
686 do { \
687 if ((var) != 0) \
688 (var) = relocate_offset ((var), nt_header, dst_nt_header); \
689 } while (0)
690
691 dst_nt_header->OptionalHeader.SizeOfInitializedData = 0;
692 dst_nt_header->OptionalHeader.SizeOfUninitializedData = 0;
693 for (i = 0; i < dst_nt_header->FileHeader.NumberOfSections; i++)
a610993d 694 {
5b79dba5
AI
695 /* Recompute data sizes for completeness. */
696 if (dst_section[i].Characteristics & IMAGE_SCN_CNT_INITIALIZED_DATA)
697 dst_nt_header->OptionalHeader.SizeOfInitializedData +=
698 ROUND_UP (dst_section[i].Misc.VirtualSize, dst_nt_header->OptionalHeader.FileAlignment);
699 else if (dst_section[i].Characteristics & IMAGE_SCN_CNT_UNINITIALIZED_DATA)
700 dst_nt_header->OptionalHeader.SizeOfUninitializedData +=
701 ROUND_UP (dst_section[i].Misc.VirtualSize, dst_nt_header->OptionalHeader.FileAlignment);
702
703 ADJUST_OFFSET (dst_section[i].PointerToLinenumbers);
a610993d 704 }
2147fb50 705
5b79dba5 706 ADJUST_OFFSET (dst_nt_header->FileHeader.PointerToSymbolTable);
2147fb50 707
5b79dba5
AI
708 /* Update offsets in debug directory entries. */
709 {
710 IMAGE_DATA_DIRECTORY debug_dir =
711 dst_nt_header->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_DEBUG];
712 PIMAGE_DEBUG_DIRECTORY debug_entry;
2147fb50 713
5b79dba5
AI
714 section = rva_to_section (debug_dir.VirtualAddress, dst_nt_header);
715 if (section)
716 {
717 debug_entry = (PIMAGE_DEBUG_DIRECTORY)
718 (RVA_TO_OFFSET (debug_dir.VirtualAddress, section) + p_outfile->file_base);
719 debug_dir.Size /= sizeof (IMAGE_DEBUG_DIRECTORY);
2147fb50 720
5b79dba5
AI
721 for (i = 0; i < debug_dir.Size; i++, debug_entry++)
722 ADJUST_OFFSET (debug_entry->PointerToRawData);
723 }
724 }
2147fb50
KH
725}
726
727
5b79dba5 728/* Dump out .data and .bss sections into a new executable. */
381259ef 729void
dd5ecd6b 730unexec (const char *new_name, const char *old_name)
9c8056fe 731{
5b79dba5
AI
732 file_data in_file, out_file;
733 char out_filename[MAX_PATH], in_filename[MAX_PATH];
734 unsigned long size;
49dc9682
AI
735 char *p;
736 char *q;
737
738 /* Ignore old_name, and get our actual location from the OS. */
739 if (!GetModuleFileName (NULL, in_filename, MAX_PATH))
740 abort ();
741 dostounix_filename (in_filename);
742 strcpy (out_filename, in_filename);
743
744 /* Change the base of the output filename to match the requested name. */
745 if ((p = strrchr (out_filename, '/')) == NULL)
746 abort ();
747 /* The filenames have already been expanded, and will be in Unix
748 format, so it is safe to expect an absolute name. */
749 if ((q = strrchr (new_name, '/')) == NULL)
750 abort ();
751 strcpy (p, q);
177c0ea7 752
49dc9682
AI
753 /* Make sure that the output filename has the ".exe" extension...patch
754 it up if not. */
755 p = out_filename + strlen (out_filename) - 4;
756 if (strcmp (p, ".exe"))
5b79dba5 757 strcat (out_filename, ".exe");
2147fb50 758
5b79dba5
AI
759 printf ("Dumping from %s\n", in_filename);
760 printf (" to %s\n", out_filename);
2147fb50 761
5b79dba5
AI
762 /* We need to round off our heap to NT's page size. */
763 round_heap (get_page_size ());
198fdd15 764
5b79dba5
AI
765 /* Open the undumped executable file. */
766 if (!open_input_file (&in_file, in_filename))
767 {
177c0ea7 768 printf ("Failed to open %s (%d)...bailing.\n",
5b79dba5
AI
769 in_filename, GetLastError ());
770 exit (1);
771 }
2147fb50 772
5b79dba5
AI
773 /* Get the interesting section info, like start and size of .bss... */
774 get_section_info (&in_file);
2147fb50 775
5b79dba5
AI
776 /* The size of the dumped executable is the size of the original
777 executable plus the size of the heap and the size of the .bss section. */
778 size = in_file.size +
779 get_committed_heap_size () +
780 extra_bss_size +
781 extra_bss_size_static;
782 if (!open_output_file (&out_file, out_filename, size))
198fdd15 783 {
177c0ea7 784 printf ("Failed to open %s (%d)...bailing.\n",
5b79dba5
AI
785 out_filename, GetLastError ());
786 exit (1);
198fdd15
GV
787 }
788
5b79dba5
AI
789 /* Set the flag (before dumping). */
790 using_dynamic_heap = TRUE;
198fdd15 791
5b79dba5 792 copy_executable_and_dump_data (&in_file, &out_file);
198fdd15 793
5b79dba5
AI
794 /* Patch up header fields; profiler is picky about this. */
795 {
796 PIMAGE_DOS_HEADER dos_header;
797 PIMAGE_NT_HEADERS nt_header;
798 HANDLE hImagehelp = LoadLibrary ("imagehlp.dll");
799 DWORD headersum;
800 DWORD checksum;
198fdd15 801
5b79dba5
AI
802 dos_header = (PIMAGE_DOS_HEADER) out_file.file_base;
803 nt_header = (PIMAGE_NT_HEADERS) ((char *) dos_header + dos_header->e_lfanew);
198fdd15 804
5b79dba5
AI
805 nt_header->OptionalHeader.CheckSum = 0;
806// nt_header->FileHeader.TimeDateStamp = time (NULL);
807// dos_header->e_cp = size / 512;
808// nt_header->OptionalHeader.SizeOfImage = size;
809
810 pfnCheckSumMappedFile = (void *) GetProcAddress (hImagehelp, "CheckSumMappedFile");
811 if (pfnCheckSumMappedFile)
812 {
813// nt_header->FileHeader.TimeDateStamp = time (NULL);
814 pfnCheckSumMappedFile (out_file.file_base,
815 out_file.size,
816 &headersum,
817 &checksum);
818 nt_header->OptionalHeader.CheckSum = checksum;
819 }
820 FreeLibrary (hImagehelp);
821 }
198fdd15 822
5b79dba5
AI
823 close_file_data (&in_file);
824 close_file_data (&out_file);
2147fb50 825}
5b79dba5
AI
826
827/* eof */