Merge from emacs-24; up to 2012-12-27T08:21:08Z!rgm@gnu.org
[bpt/emacs.git] / src / unexw32.c
CommitLineData
3b7ad313 1/* unexec for GNU Emacs on Windows NT.
ab422c4d 2 Copyright (C) 1994, 2001-2013 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
KH
87
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 ()). */
92void
93_start (void)
94{
95 extern void mainCRTStartup (void);
96
7fef47a3 97#if 1
43640c4d
GV
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
103
2147fb50
KH
104 /* Cache system info, e.g., the NT page size. */
105 cache_system_info ();
106
5b79dba5
AI
107 /* Grab our malloc arena space now, before CRT starts up. */
108 init_heap ();
2147fb50 109
2147fb50
KH
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);
113
467af476
AI
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);
2147fb50
KH
117 mainCRTStartup ();
118}
119
2147fb50
KH
120
121/* File handling. */
122
43640c4d 123int
2147fb50
KH
124open_input_file (file_data *p_file, char *filename)
125{
126 HANDLE file;
127 HANDLE file_mapping;
128 void *file_base;
129 unsigned long size, upper_size;
130
131 file = CreateFile (filename, GENERIC_READ, FILE_SHARE_READ, NULL,
132 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
177c0ea7 133 if (file == INVALID_HANDLE_VALUE)
43640c4d 134 return FALSE;
2147fb50
KH
135
136 size = GetFileSize (file, &upper_size);
177c0ea7 137 file_mapping = CreateFileMapping (file, NULL, PAGE_READONLY,
2147fb50 138 0, size, NULL);
177c0ea7 139 if (!file_mapping)
43640c4d 140 return FALSE;
2147fb50
KH
141
142 file_base = MapViewOfFile (file_mapping, FILE_MAP_READ, 0, 0, size);
177c0ea7 143 if (file_base == 0)
43640c4d 144 return FALSE;
2147fb50
KH
145
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;
43640c4d
GV
151
152 return TRUE;
2147fb50
KH
153}
154
43640c4d 155int
2147fb50
KH
156open_output_file (file_data *p_file, char *filename, unsigned long size)
157{
158 HANDLE file;
159 HANDLE file_mapping;
160 void *file_base;
cd6885f3 161
2147fb50
KH
162 file = CreateFile (filename, GENERIC_READ | GENERIC_WRITE, 0, NULL,
163 CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
177c0ea7 164 if (file == INVALID_HANDLE_VALUE)
43640c4d
GV
165 return FALSE;
166
177c0ea7 167 file_mapping = CreateFileMapping (file, NULL, PAGE_READWRITE,
2147fb50 168 0, size, NULL);
177c0ea7 169 if (!file_mapping)
43640c4d 170 return FALSE;
177c0ea7 171
2147fb50 172 file_base = MapViewOfFile (file_mapping, FILE_MAP_WRITE, 0, 0, size);
177c0ea7 173 if (file_base == 0)
43640c4d 174 return FALSE;
177c0ea7 175
2147fb50
KH
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;
43640c4d
GV
181
182 return TRUE;
2147fb50
KH
183}
184
185/* Close the system structures associated with the given file. */
43640c4d 186void
2147fb50
KH
187close_file_data (file_data *p_file)
188{
5b79dba5
AI
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);
2147fb50
KH
195}
196
197
198/* Routines to manipulate NT executable file sections. */
199
43640c4d
GV
200/* Return pointer to section header for named section. */
201IMAGE_SECTION_HEADER *
202find_section (char * name, IMAGE_NT_HEADERS * nt_header)
203{
204 PIMAGE_SECTION_HEADER section;
205 int i;
206
207 section = IMAGE_FIRST_SECTION (nt_header);
208
209 for (i = 0; i < nt_header->FileHeader.NumberOfSections; i++)
210 {
211 if (strcmp (section->Name, name) == 0)
212 return section;
213 section++;
214 }
215 return NULL;
216}
217
218/* Return pointer to section header for section containing the given
219 relative virtual address. */
220IMAGE_SECTION_HEADER *
62aba0d4 221rva_to_section (DWORD_PTR rva, IMAGE_NT_HEADERS * nt_header)
43640c4d
GV
222{
223 PIMAGE_SECTION_HEADER section;
224 int i;
225
226 section = IMAGE_FIRST_SECTION (nt_header);
227
228 for (i = 0; i < nt_header->FileHeader.NumberOfSections; i++)
2147fb50 229 {
5b79dba5
AI
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. */
62aba0d4 236 DWORD_PTR real_size = max (section->SizeOfRawData,
5b79dba5 237 section->Misc.VirtualSize);
43640c4d 238 if (rva >= section->VirtualAddress
5b79dba5
AI
239 && rva < section->VirtualAddress + real_size)
240 return section;
241 section++;
242 }
243 return NULL;
244}
245
246/* Return pointer to section header for section containing the given
247 offset in its raw data area. */
248IMAGE_SECTION_HEADER *
62aba0d4 249offset_to_section (DWORD_PTR offset, IMAGE_NT_HEADERS * nt_header)
5b79dba5
AI
250{
251 PIMAGE_SECTION_HEADER section;
252 int i;
253
254 section = IMAGE_FIRST_SECTION (nt_header);
255
256 for (i = 0; i < nt_header->FileHeader.NumberOfSections; i++)
257 {
258 if (offset >= section->PointerToRawData
259 && offset < section->PointerToRawData + section->SizeOfRawData)
43640c4d
GV
260 return section;
261 section++;
2147fb50 262 }
43640c4d 263 return NULL;
2147fb50
KH
264}
265
5b79dba5
AI
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). */
62aba0d4
FP
269DWORD_PTR
270relocate_offset (DWORD_PTR offset,
5b79dba5
AI
271 IMAGE_NT_HEADERS * src_nt_header,
272 IMAGE_NT_HEADERS * dst_nt_header)
273{
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;
277
278 while (offset >= src_section->PointerToRawData)
279 {
280 if (offset < src_section->PointerToRawData + src_section->SizeOfRawData)
281 break;
282 i++;
283 if (i == src_nt_header->FileHeader.NumberOfSections)
284 {
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);
295 }
296 src_section++;
297 dst_section++;
298 }
299 return offset +
300 (dst_section->PointerToRawData - src_section->PointerToRawData);
301}
302
303#define OFFSET_TO_RVA(offset, section) \
2d7d1608 304 ((section)->VirtualAddress + ((DWORD_PTR)(offset) - (section)->PointerToRawData))
5b79dba5
AI
305
306#define RVA_TO_OFFSET(rva, section) \
2d7d1608 307 ((section)->PointerToRawData + ((DWORD_PTR)(rva) - (section)->VirtualAddress))
5b79dba5
AI
308
309#define RVA_TO_SECTION_OFFSET(rva, section) \
2d7d1608 310 ((DWORD_PTR)(rva) - (section)->VirtualAddress)
5b79dba5
AI
311
312/* Convert address in executing image to RVA. */
62aba0d4 313#define PTR_TO_RVA(ptr) ((DWORD_PTR)(ptr) - (DWORD_PTR) GetModuleHandle (NULL))
5b79dba5 314
e9bdb9c9 315#define RVA_TO_PTR(var,section,filedata) \
2d7d1608 316 ((unsigned char *)(RVA_TO_OFFSET (var,section) + (filedata).file_base))
e9bdb9c9 317
5b79dba5 318#define PTR_TO_OFFSET(ptr, pfile_data) \
49dc9682 319 ((unsigned char *)(ptr) - (pfile_data)->file_base)
5b79dba5
AI
320
321#define OFFSET_TO_PTR(offset, pfile_data) \
62aba0d4 322 ((pfile_data)->file_base + (DWORD_PTR)(offset))
5b79dba5 323
43640c4d 324
2147fb50 325/* Flip through the executable and cache the info necessary for dumping. */
49dc9682 326void
2147fb50
KH
327get_section_info (file_data *p_infile)
328{
329 PIMAGE_DOS_HEADER dos_header;
330 PIMAGE_NT_HEADERS nt_header;
5b79dba5 331 int overlap;
177c0ea7 332
2147fb50 333 dos_header = (PIMAGE_DOS_HEADER) p_infile->file_base;
177c0ea7 334 if (dos_header->e_magic != IMAGE_DOS_SIGNATURE)
2147fb50
KH
335 {
336 printf ("Unknown EXE header in %s...bailing.\n", p_infile->name);
337 exit (1);
338 }
62aba0d4 339 nt_header = (PIMAGE_NT_HEADERS) (((DWORD_PTR) dos_header) +
2147fb50 340 dos_header->e_lfanew);
177c0ea7 341 if (nt_header == NULL)
2147fb50 342 {
177c0ea7 343 printf ("Failed to find IMAGE_NT_HEADER in %s...bailing.\n",
2147fb50
KH
344 p_infile->name);
345 exit (1);
346 }
347
348 /* Check the NT header signature ... */
177c0ea7 349 if (nt_header->Signature != IMAGE_NT_SIGNATURE)
2147fb50
KH
350 {
351 printf ("Invalid IMAGE_NT_SIGNATURE 0x%x in %s...bailing.\n",
352 nt_header->Signature, p_infile->name);
5b79dba5 353 exit (1);
2147fb50
KH
354 }
355
5b79dba5
AI
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.)
359
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. */
366
e3ddd18c
AI
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)
2147fb50 375 {
e3ddd18c
AI
376 data_start = (char *) nt_header->OptionalHeader.ImageBase +
377 data_section->VirtualAddress;
378 data_size = data_section->Misc.VirtualSize;
379 }
380 else
381 {
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))
388 {
389 printf ("Initialized data is not in a single section...bailing\n");
390 exit (1);
391 }
5b79dba5
AI
392 }
393
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.
399
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). */
404
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))
409 {
410 printf ("Uninitialized data is not in a single section...bailing\n");
411 exit (1);
412 }
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;
418
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))
423 {
424 printf ("Uninitialized static data is not in a single section...bailing\n");
425 exit (1);
426 }
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;
432
433 /* Combine the bss sections into one if they overlap. */
972ee7e0
AI
434#ifdef _ALPHA_
435 overlap = 1; /* force all bss data to be dumped */
436#else
5b79dba5 437 overlap = 0;
972ee7e0 438#endif
5b79dba5
AI
439 if (bss_start < bss_start_static)
440 {
441 if (bss_start_static < bss_start + bss_size)
442 overlap = 1;
443 }
444 else
445 {
446 if (bss_start < bss_start_static + bss_size_static)
447 overlap = 1;
448 }
449 if (overlap)
450 {
451 if (bss_section != bss_section_static)
2147fb50 452 {
5b79dba5
AI
453 printf ("BSS data not in a single section...bailing\n");
454 exit (1);
2147fb50 455 }
5b79dba5
AI
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;
460 }
461
462 heap_section = rva_to_section (PTR_TO_RVA (get_heap_start ()), nt_header);
463}
464
465
466/* The dump routines. */
467
49dc9682 468void
177c0ea7 469copy_executable_and_dump_data (file_data *p_infile,
5b79dba5
AI
470 file_data *p_outfile)
471{
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;
62aba0d4 478 DWORD_PTR offset;
5b79dba5 479 int i;
4162f25f 480 int be_verbose = GetEnvironmentVariable ("DEBUG_DUMP", NULL, 0) > 0;
5b79dba5 481
4162f25f 482#define COPY_CHUNK(message, src, size, verbose) \
5b79dba5
AI
483 do { \
484 unsigned char *s = (void *)(src); \
485 unsigned long count = (size); \
4162f25f
EZ
486 if (verbose) \
487 { \
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); \
492 } \
5b79dba5
AI
493 memcpy (dst, s, count); \
494 dst += count; \
495 } while (0)
496
4162f25f 497#define COPY_PROC_CHUNK(message, src, size, verbose) \
5b79dba5
AI
498 do { \
499 unsigned char *s = (void *)(src); \
500 unsigned long count = (size); \
4162f25f
EZ
501 if (verbose) \
502 { \
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); \
507 } \
5b79dba5
AI
508 memcpy (dst, s, count); \
509 dst += count; \
510 } while (0)
511
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)))
7fef47a3
AI
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)
5b79dba5
AI
523
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.
527
528 Note that dst is updated implicitly by each COPY_CHUNK. */
529
530 dos_header = (PIMAGE_DOS_HEADER) p_infile->file_base;
62aba0d4 531 nt_header = (PIMAGE_NT_HEADERS) (((DWORD_PTR) dos_header) +
5b79dba5
AI
532 dos_header->e_lfanew);
533 section = IMAGE_FIRST_SECTION (nt_header);
177c0ea7 534
5b79dba5
AI
535 dst = (unsigned char *) p_outfile->file_base;
536
537 COPY_CHUNK ("Copying DOS header...", dos_header,
62aba0d4 538 (DWORD_PTR) nt_header - (DWORD_PTR) dos_header, be_verbose);
5b79dba5
AI
539 dst_nt_header = (PIMAGE_NT_HEADERS) dst;
540 COPY_CHUNK ("Copying NT header...", nt_header,
62aba0d4 541 (DWORD_PTR) section - (DWORD_PTR) nt_header, be_verbose);
5b79dba5
AI
542 dst_section = (PIMAGE_SECTION_HEADER) dst;
543 COPY_CHUNK ("Copying section table...", section,
4162f25f
EZ
544 nt_header->FileHeader.NumberOfSections * sizeof (*section),
545 be_verbose);
5b79dba5 546
7fef47a3
AI
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 ();
551
5b79dba5
AI
552 for (i = 0; i < nt_header->FileHeader.NumberOfSections; i++)
553 {
554 char msg[100];
4162f25f
EZ
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);
5b79dba5 558
5b79dba5
AI
559 dst_save = dst;
560
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 ();
566
567 /* Can always copy the original raw data. */
568 COPY_CHUNK
569 (msg, OFFSET_TO_PTR (section->PointerToRawData, p_infile),
4162f25f 570 section->SizeOfRawData, be_verbose);
7fef47a3
AI
571 /* Ensure alignment slop is zeroed. */
572 ROUND_UP_DST_AND_ZERO (dst_nt_header->OptionalHeader.FileAlignment);
5b79dba5
AI
573
574 /* Note that various sections below may be aliases. */
575 if (section == data_section)
2147fb50 576 {
5b79dba5
AI
577 dst = dst_save
578 + RVA_TO_SECTION_OFFSET (PTR_TO_RVA (data_start), dst_section);
4162f25f
EZ
579 COPY_PROC_CHUNK ("Dumping initialized data...",
580 data_start, data_size, be_verbose);
5b79dba5 581 dst = dst_save + dst_section->SizeOfRawData;
2147fb50 582 }
5b79dba5 583 if (section == bss_section)
43640c4d 584 {
5b79dba5
AI
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);
4162f25f
EZ
589 COPY_PROC_CHUNK ("Dumping bss data...", bss_start,
590 bss_size, be_verbose);
5b79dba5
AI
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;
43640c4d 598 }
5b79dba5
AI
599 if (section == bss_section_static)
600 {
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);
4162f25f
EZ
605 COPY_PROC_CHUNK ("Dumping static bss data...", bss_start_static,
606 bss_size_static, 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;
614 }
615 if (section == heap_section)
616 {
62aba0d4
FP
617 DWORD_PTR heap_start = (DWORD_PTR) get_heap_start ();
618 DWORD_PTR heap_size = get_committed_heap_size ();
5b79dba5
AI
619
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);
4162f25f
EZ
624 COPY_PROC_CHUNK ("Dumping heap...", heap_start, heap_size,
625 be_verbose);
5b79dba5
AI
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;
642 }
643
7fef47a3
AI
644 /* Align the section's raw data area. */
645 ROUND_UP_DST (dst_nt_header->OptionalHeader.FileAlignment);
646
2147fb50 647 section++;
5b79dba5 648 dst_section++;
2147fb50 649 }
a610993d 650
5b79dba5
AI
651 /* Copy remainder of source image. */
652 do
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),
4162f25f 660 p_infile->size - offset, be_verbose);
5b79dba5
AI
661
662 /* Final size for new image. */
663 p_outfile->size = DST_TO_OFFSET ();
664
665 /* Now patch up remaining file-relative offsets. */
666 section = IMAGE_FIRST_SECTION (nt_header);
667 dst_section = IMAGE_FIRST_SECTION (dst_nt_header);
668
669#define ADJUST_OFFSET(var) \
670 do { \
671 if ((var) != 0) \
672 (var) = relocate_offset ((var), nt_header, dst_nt_header); \
673 } while (0)
674
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++)
a610993d 678 {
5b79dba5
AI
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);
686
687 ADJUST_OFFSET (dst_section[i].PointerToLinenumbers);
a610993d 688 }
2147fb50 689
5b79dba5 690 ADJUST_OFFSET (dst_nt_header->FileHeader.PointerToSymbolTable);
2147fb50 691
5b79dba5
AI
692 /* Update offsets in debug directory entries. */
693 {
694 IMAGE_DATA_DIRECTORY debug_dir =
695 dst_nt_header->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_DEBUG];
696 PIMAGE_DEBUG_DIRECTORY debug_entry;
2147fb50 697
5b79dba5
AI
698 section = rva_to_section (debug_dir.VirtualAddress, dst_nt_header);
699 if (section)
700 {
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);
2147fb50 704
5b79dba5
AI
705 for (i = 0; i < debug_dir.Size; i++, debug_entry++)
706 ADJUST_OFFSET (debug_entry->PointerToRawData);
707 }
708 }
2147fb50
KH
709}
710
711
5b79dba5 712/* Dump out .data and .bss sections into a new executable. */
381259ef 713void
dd5ecd6b 714unexec (const char *new_name, const char *old_name)
9c8056fe 715{
5b79dba5
AI
716 file_data in_file, out_file;
717 char out_filename[MAX_PATH], in_filename[MAX_PATH];
718 unsigned long size;
49dc9682
AI
719 char *p;
720 char *q;
721
722 /* Ignore old_name, and get our actual location from the OS. */
723 if (!GetModuleFileName (NULL, in_filename, MAX_PATH))
724 abort ();
e7ac588e 725 dostounix_filename (in_filename, 0);
49dc9682
AI
726 strcpy (out_filename, in_filename);
727
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);
177c0ea7 736
49dc9682
AI
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"))
5b79dba5 741 strcat (out_filename, ".exe");
2147fb50 742
5b79dba5
AI
743 printf ("Dumping from %s\n", in_filename);
744 printf (" to %s\n", out_filename);
2147fb50 745
5b79dba5
AI
746 /* We need to round off our heap to NT's page size. */
747 round_heap (get_page_size ());
198fdd15 748
5b79dba5
AI
749 /* Open the undumped executable file. */
750 if (!open_input_file (&in_file, in_filename))
751 {
177c0ea7 752 printf ("Failed to open %s (%d)...bailing.\n",
5b79dba5
AI
753 in_filename, GetLastError ());
754 exit (1);
755 }
2147fb50 756
5b79dba5
AI
757 /* Get the interesting section info, like start and size of .bss... */
758 get_section_info (&in_file);
2147fb50 759
5b79dba5
AI
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))
198fdd15 767 {
177c0ea7 768 printf ("Failed to open %s (%d)...bailing.\n",
5b79dba5
AI
769 out_filename, GetLastError ());
770 exit (1);
198fdd15
GV
771 }
772
5b79dba5
AI
773 /* Set the flag (before dumping). */
774 using_dynamic_heap = TRUE;
198fdd15 775
5b79dba5 776 copy_executable_and_dump_data (&in_file, &out_file);
198fdd15 777
5b79dba5
AI
778 /* Patch up header fields; profiler is picky about this. */
779 {
780 PIMAGE_DOS_HEADER dos_header;
781 PIMAGE_NT_HEADERS nt_header;
782 HANDLE hImagehelp = LoadLibrary ("imagehlp.dll");
783 DWORD headersum;
784 DWORD checksum;
198fdd15 785
5b79dba5
AI
786 dos_header = (PIMAGE_DOS_HEADER) out_file.file_base;
787 nt_header = (PIMAGE_NT_HEADERS) ((char *) dos_header + dos_header->e_lfanew);
198fdd15 788
5b79dba5
AI
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;
793
794 pfnCheckSumMappedFile = (void *) GetProcAddress (hImagehelp, "CheckSumMappedFile");
795 if (pfnCheckSumMappedFile)
796 {
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;
803 }
804 FreeLibrary (hImagehelp);
805 }
198fdd15 806
5b79dba5
AI
807 close_file_data (&in_file);
808 close_file_data (&out_file);
2147fb50 809}
5b79dba5
AI
810
811/* eof */