XEmacs 21.2.29 "Hestia".
[chise/xemacs-chise.git.1] / src / unexnt.c
1 /* unexec for GNU Emacs on Windows NT.
2    Copyright (C) 1994 Free Software Foundation, Inc.
3
4 This file is part of XEmacs.
5
6 XEmacs is free software; you can redistribute it and/or modify it
7 under the terms of the GNU General Public License as published by the
8 Free Software Foundation; either version 2, or (at your option) any
9 later version.
10
11 XEmacs is distributed in the hope that it will be useful, but WITHOUT
12 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
14 for more details.
15
16 You should have received a copy of the GNU General Public License
17 along with XEmacs; see the file COPYING.  If not, write to the Free
18 Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
19 02111-1307, USA.
20
21    Geoff Voelker (voelker@cs.washington.edu) 8-12-94 */
22
23 /* Adapted for XEmacs by David Hobley <david@spook-le0.cia.com.au> */
24
25 /* The linkers that come with MSVC >= 4.0 merge .bss into .data and reorder
26  * uninitialised data so that the .data section looks like:
27  *
28  *      crt0 initialised data
29  *      emacs initialised data
30  *              <my_edata>
31  *      library initialised data
32  *              <start of bss part of .data>
33  *      emacs static uninitialised data
34  *      library static uninitialised data
35  *      emacs global uninitialised data
36  *              <my_ebss>
37  *      library global uninitialised data
38  *
39  * This means that we can't use the normal my_ebss in lastfile.c trick to
40  * differentiate between unitialised data that belongs to emacs and
41  * uninitialised data that belongs to system libraries. This is bad because
42  * we do want to initialise the emacs data, but we don't want to initialise
43  * the system library data.
44  *
45  * To solve this problem using MSVC >= 5.0 we use a pragma directive to tell
46  * the compiler to put emacs's data (both initialised and uninitialised) in
47  * a separate section in the executable, and we only dump that section. This
48  * means that all files that define initialized data must include config.h
49  * to pick up the pragma. We don't try to make any part of that section
50  * read-only.
51  *
52  * This pragma directive isn't supported by the MSVC 4.x compiler. Instead,
53  * we dump crt0 initialised data and library static uninitialised data in
54  * addition to the emacs data. This is wrong, but we appear to be able to
55  * get away with it. A proper fix might involve the introduction of a static
56  * version of my_ebss in lastfile.c and a new firstfile.c file.  jhar */
57
58 #include <config.h>
59 #include <stdlib.h>     /* _fmode */
60 #include <stdio.h>
61 #include <fcntl.h>
62 #include <windows.h>
63
64 /* From IMAGEHLP.H which is not installed by default by MSVC < 5 */
65 /* The IMAGEHLP.DLL library is not distributed by default with Windows95 */
66 PIMAGE_NT_HEADERS
67 (__stdcall * pfnCheckSumMappedFile) (LPVOID BaseAddress, DWORD FileLength,
68                                      LPDWORD HeaderSum, LPDWORD CheckSum);
69
70 #if 0
71 extern BOOL ctrl_c_handler (unsigned long type);
72 #endif
73
74 #include "ntheap.h"
75
76 /* Sync with FSF Emacs 19.34.6 note: struct file_data is now defined in ntheap.h */
77
78 enum {
79   HEAP_UNINITIALIZED = 1,
80   HEAP_UNLOADED,
81   HEAP_LOADED
82 };
83
84 /* Basically, our "initialized" flag.  */
85 int heap_state = HEAP_UNINITIALIZED;
86
87 /* So we can find our heap in the file to recreate it.  */
88 unsigned long heap_index_in_executable = UNINIT_LONG;
89
90 void get_section_info (file_data *p_file);
91 void copy_executable_and_dump_data_section (file_data *, file_data *);
92 void dump_bss_and_heap (file_data *p_infile, file_data *p_outfile);
93
94 /* Cached info about the .data section in the executable.  */
95 PUCHAR data_start_va = UNINIT_PTR;
96 DWORD  data_start_file = UNINIT_LONG;
97 DWORD  data_size = UNINIT_LONG;
98
99 /* Cached info about the .bss section in the executable.  */
100 PUCHAR bss_start = UNINIT_PTR;
101 DWORD  bss_size = UNINIT_LONG;
102
103 #ifdef HAVE_NTGUI
104 HINSTANCE hinst = NULL;
105 HINSTANCE hprevinst = NULL;
106 LPSTR lpCmdLine = "";
107 int nCmdShow = 0;
108 #endif /* HAVE_NTGUI */
109
110 /* Startup code for running on NT.  When we are running as the dumped
111    version, we need to bootstrap our heap and .bss section into our
112    address space before we can actually hand off control to the startup
113    code supplied by NT (primarily because that code relies upon malloc ()).  */
114
115 /* **********************
116    Hackers please remember, this _start() thingy is *not* called neither
117    when dumping portably, nor when running from temacs! Do not put
118    significant XEmacs initialization here!
119    ********************** */
120
121 void
122 _start (void)
123 {
124   extern void mainCRTStartup (void);
125
126   /* Cache system info, e.g., the NT page size.  */
127   cache_system_info ();
128
129   /* If we're a dumped version of emacs then we need to recreate
130      our heap and play tricks with our .bss section.  Do this before
131      start up.  (WARNING:  Do not put any code before this section
132      that relies upon malloc () and runs in the dumped version.  It
133      won't work.)  */
134   if (heap_state == HEAP_UNLOADED) 
135     {
136       char executable_path[MAX_PATH];
137
138       if (GetModuleFileName (NULL, executable_path, MAX_PATH) == 0) 
139         {
140           exit (1);
141         }
142
143       /* #### This is super-bogus. When I rename xemacs.exe,
144          the renamed file still loads its heap from xemacs.exe --kkm */
145 #if 0
146       {
147         /* To allow profiling, make sure executable_path names the .exe
148            file, not the file created by the profiler */
149         char *p = strrchr (executable_path, '\\');
150         strcpy (p+1, PATH_PROGNAME ".exe");
151       }
152 #endif
153
154       recreate_heap (executable_path);
155       heap_state = HEAP_LOADED;
156     }
157
158   /* #### This is bogus, too. _fmode is set to different values
159      when we run `xemacs' and `temacs run-emacs'. The sooner we
160      hit and fix all the weirdities this causes us, the better --kkm */
161 #if 0
162   /* The default behavior is to treat files as binary and patch up
163      text files appropriately, in accordance with the MSDOS code.  */
164   _fmode = O_BINARY;
165 #endif
166
167 #if 0
168   /* This prevents ctrl-c's in shells running while we're suspended from
169      having us exit.  */
170   SetConsoleCtrlHandler ((PHANDLER_ROUTINE) ctrl_c_handler, TRUE);
171 #endif
172
173   /* Invoke the NT CRT startup routine now that our housecleaning
174      is finished.  */
175 #ifdef HAVE_NTGUI
176   /* determine WinMain args like crt0.c does */
177   hinst = GetModuleHandle(NULL);
178   lpCmdLine = GetCommandLine();
179   nCmdShow = SW_SHOWDEFAULT;
180 #endif
181   mainCRTStartup ();
182 }
183
184 /* Dump out .data and .bss sections into a new executable.  */
185 void
186 unexec (char *new_name, char *old_name, void *start_data, void *start_bss,
187         void *entry_address)
188 {
189   file_data in_file, out_file;
190   char out_filename[MAX_PATH], in_filename[MAX_PATH];
191   unsigned long size;
192   char *ptr;
193   HANDLE hImagehelp;
194   
195   /* Make sure that the input and output filenames have the
196      ".exe" extension...patch them up if they don't.  */
197   strcpy (in_filename, old_name);
198   ptr = in_filename + strlen (in_filename) - 4;
199   if (strcmp (ptr, ".exe"))
200     strcat (in_filename, ".exe");
201
202   strcpy (out_filename, new_name);
203   ptr = out_filename + strlen (out_filename) - 4;
204   if (strcmp (ptr, ".exe"))
205     strcat (out_filename, ".exe");
206
207   printf ("Dumping from %s\n", in_filename);
208   printf ("          to %s\n", out_filename);
209
210   /* We need to round off our heap to NT's allocation unit (64KB).  */
211   round_heap (get_allocation_unit ());
212
213   /* Open the undumped executable file.  */
214   if (!open_input_file (&in_file, in_filename))
215     {
216       printf ("Failed to open %s (%d)...bailing.\n", 
217               in_filename, GetLastError ());
218       exit (1);
219     }
220
221   /* Get the interesting section info, like start and size of .bss...  */
222   get_section_info (&in_file);
223
224   /* The size of the dumped executable is the size of the original
225      executable plus the size of the heap and the size of the .bss section.  */
226   heap_index_in_executable = (unsigned long)
227     round_to_next ((unsigned char *) in_file.size, get_allocation_unit ());
228   size = heap_index_in_executable + get_committed_heap_size () + bss_size;
229   if (!open_output_file (&out_file, out_filename, size))
230     {
231       printf ("Failed to open %s (%d)...bailing.\n", 
232               out_filename, GetLastError ());
233       exit (1);
234     }
235
236   /* Set the flag (before dumping).  */
237   heap_state = HEAP_UNLOADED;
238
239   copy_executable_and_dump_data_section (&in_file, &out_file);
240   dump_bss_and_heap (&in_file, &out_file);
241
242   /* Patch up header fields; profiler is picky about this. */
243   hImagehelp = LoadLibrary ("imagehlp.dll");
244   if (hImagehelp)
245   {
246     PIMAGE_DOS_HEADER dos_header;
247     PIMAGE_NT_HEADERS nt_header;
248     DWORD  headersum;
249     DWORD  checksum;
250
251     dos_header = (PIMAGE_DOS_HEADER) out_file.file_base;
252     nt_header = (PIMAGE_NT_HEADERS) ((char *) dos_header + dos_header->e_lfanew);
253
254     nt_header->OptionalHeader.CheckSum = 0;
255 //    nt_header->FileHeader.TimeDateStamp = time (NULL);
256 //    dos_header->e_cp = size / 512;
257 //    nt_header->OptionalHeader.SizeOfImage = size;
258
259     pfnCheckSumMappedFile = (void *) GetProcAddress (hImagehelp, "CheckSumMappedFile");
260     if (pfnCheckSumMappedFile)
261       {
262 //      nt_header->FileHeader.TimeDateStamp = time (NULL);
263         pfnCheckSumMappedFile (out_file.file_base,
264                                out_file.size,
265                                &headersum,
266                                &checksum);
267         nt_header->OptionalHeader.CheckSum = checksum;
268       }
269     FreeLibrary (hImagehelp);
270   }
271
272   close_file_data (&in_file);
273   close_file_data (&out_file);
274 }
275
276
277 /* File handling.  */
278
279
280 int
281 open_output_file (file_data *p_file, const char *filename, unsigned long size)
282 {
283   HANDLE file;
284   HANDLE file_mapping;
285   void  *file_base;
286
287   file = CreateFile (filename, GENERIC_READ | GENERIC_WRITE, 0, NULL,
288                      CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
289   if (file == INVALID_HANDLE_VALUE) 
290     return FALSE;
291
292   file_mapping = CreateFileMapping (file, NULL, PAGE_READWRITE, 
293                                     0, size, NULL);
294   if (!file_mapping) 
295     return FALSE;
296   
297   file_base = MapViewOfFile (file_mapping, FILE_MAP_WRITE, 0, 0, size);
298   if (file_base == 0) 
299     return FALSE;
300   
301   p_file->name = filename;
302   p_file->size = size;
303   p_file->file = file;
304   p_file->file_mapping = file_mapping;
305   p_file->file_base = file_base;
306
307   return TRUE;
308 }
309
310 /* Routines to manipulate NT executable file sections.  */
311
312 #ifndef DUMP_SEPARATE_SECTION
313 static void
314 get_bss_info_from_map_file (file_data *p_infile, PUCHAR *p_bss_start, 
315                             DWORD *p_bss_size)
316 {
317   int n, start, len;
318   char map_filename[MAX_PATH];
319   char buffer[256];
320   FILE *map;
321
322   /* Overwrite the .exe extension on the executable file name with
323      the .map extension.  */
324   strcpy (map_filename, p_infile->name);
325   n = strlen (map_filename) - 3;
326   strcpy (&map_filename[n], "map");
327
328   map = fopen (map_filename, "r");
329   if (!map)
330     {
331       printf ("Failed to open map file %s, error %d...bailing out.\n",
332               map_filename, GetLastError ());
333       exit (-1);
334     }
335
336   while (fgets (buffer, sizeof (buffer), map))
337     {
338       if (!(strstr (buffer, ".bss") && strstr (buffer, "DATA")))
339         continue;
340       n = sscanf (buffer, " %*d:%x %x", &start, &len);
341       if (n != 2)
342         {
343           printf ("Failed to scan the .bss section line:\n%s", buffer);
344           exit (-1);
345         }
346       break;
347     }
348   *p_bss_start = (PUCHAR) start;
349   *p_bss_size = (DWORD) len;
350 }
351 #endif
352
353 /* Flip through the executable and cache the info necessary for dumping.  */
354 static void
355 get_section_info (file_data *p_infile)
356 {
357   PIMAGE_DOS_HEADER dos_header;
358   PIMAGE_NT_HEADERS nt_header;
359   PIMAGE_SECTION_HEADER section, data_section;
360   unsigned char *ptr;
361   int i;
362   
363   dos_header = (PIMAGE_DOS_HEADER) p_infile->file_base;
364   if (dos_header->e_magic != IMAGE_DOS_SIGNATURE) 
365     {
366       printf ("Unknown EXE header in %s...bailing.\n", p_infile->name);
367       exit (1);
368     }
369   nt_header = (PIMAGE_NT_HEADERS) (((unsigned long) dos_header) + 
370                                    dos_header->e_lfanew);
371   if (nt_header == NULL) 
372     {
373       printf ("Failed to find IMAGE_NT_HEADER in %s...bailing.\n", 
374              p_infile->name);
375       exit (1);
376     }
377
378   /* Check the NT header signature ...  */
379   if (nt_header->Signature != IMAGE_NT_SIGNATURE) 
380     {
381       printf ("Invalid IMAGE_NT_SIGNATURE 0x%x in %s...bailing.\n",
382               nt_header->Signature, p_infile->name);
383     }
384
385   /* Flip through the sections for .data and .bss ...  */
386   section = (PIMAGE_SECTION_HEADER) IMAGE_FIRST_SECTION (nt_header);
387   for (i = 0; i < nt_header->FileHeader.NumberOfSections; i++) 
388     {
389 #ifndef DUMP_SEPARATE_SECTION
390       if (!strcmp (section->Name, ".bss")) 
391         {
392           extern int my_ebss;           /* From lastfile.c  */
393
394           ptr = (char *) nt_header->OptionalHeader.ImageBase +
395             section->VirtualAddress;
396           bss_start = ptr;
397           bss_size = (char*)&my_ebss - (char*)bss_start;
398         }
399
400       if (!strcmp (section->Name, ".data")) 
401 #else
402       if (!strcmp (section->Name, "xdata"))
403 #endif
404         {
405           extern char my_edata[];       /* From lastfile.c  */
406
407           /* The .data section.  */
408           data_section = section;
409           ptr = (char *) nt_header->OptionalHeader.ImageBase +
410             section->VirtualAddress;
411           data_start_va = ptr;
412           data_start_file = section->PointerToRawData;
413
414 #ifndef DUMP_SEPARATE_SECTION
415           /* Write only the part of the section that contains emacs data. */
416           data_size = my_edata - data_start_va;
417 #else
418           /* Write back the full section.  */
419           data_size = section->SizeOfRawData;
420
421           /* This code doesn't know how to grow the raw size of a section. */
422           if (section->SizeOfRawData < section->Misc.VirtualSize)
423             {
424               printf ("The emacs data section is smaller than expected"
425                       "...bailing.\n");
426               exit (1);
427             }
428 #endif
429         }
430       section++;
431     }
432
433 #ifndef DUMP_SEPARATE_SECTION
434   if (bss_start == UNINIT_PTR)
435     {
436       /* Starting with MSVC 4.0, the .bss section has been eliminated
437          and appended virtually to the end of the .data section.  Our
438          only hint about where the .bss section starts in the address
439          comes from the SizeOfRawData field in the .data section
440          header.  Unfortunately, this field is only approximate, as it
441          is a rounded number and is typically rounded just beyond the
442          start of the .bss section.  To find the start and size of the
443          .bss section exactly, we have to peek into the map file.  */
444       extern int my_ebss;
445
446       get_bss_info_from_map_file (p_infile, &ptr, &bss_size);
447       bss_start = ptr + nt_header->OptionalHeader.ImageBase
448         + data_section->VirtualAddress;
449       bss_size = (char*)&my_ebss - (char*)bss_start;
450     }
451 #else
452   bss_size = 0;
453 #endif
454 }
455
456
457 /* The dump routines.  */
458
459 #ifdef DEBUG_XEMACS
460 #define DUMP_MSG(x) printf x
461 #else
462 #define DUMP_MSG(x)
463 #endif
464
465 static void
466 copy_executable_and_dump_data_section (file_data *p_infile,
467                                        file_data *p_outfile)
468 {
469   unsigned char *data_file, *data_va;
470   unsigned long size, index;
471
472   /* Get a pointer to where the raw data should go in the executable file.  */
473   data_file = (char *) p_outfile->file_base + data_start_file;
474
475   /* Get a pointer to the raw data in our address space.  */
476   data_va = data_start_va;
477
478   size = (DWORD) data_file - (DWORD) p_outfile->file_base;
479   DUMP_MSG (("Copying executable up to data section...\n"));
480   DUMP_MSG (("\t0x%08x Offset in input file.\n", 0));
481   DUMP_MSG (("\t0x%08x Offset in output file.\n", 0));
482   DUMP_MSG (("\t0x%08x Size in bytes.\n", size));
483   memcpy (p_outfile->file_base, p_infile->file_base, size);
484
485   size = data_size;
486   DUMP_MSG (("Dumping data section...\n"));
487   DUMP_MSG (("\t0x%08x Address in process.\n", data_va));
488   DUMP_MSG (("\t0x%08x Offset in output file.\n", 
489              data_file - p_outfile->file_base));
490   DUMP_MSG (("\t0x%08x Size in bytes.\n", size));
491   memcpy (data_file, data_va, size);
492
493   index = (DWORD) data_file + size - (DWORD) p_outfile->file_base;
494   size = p_infile->size - index;
495   DUMP_MSG (("Copying rest of executable...\n"));
496   DUMP_MSG (("\t0x%08x Offset in input file.\n", index));
497   DUMP_MSG (("\t0x%08x Offset in output file.\n", index));
498   DUMP_MSG (("\t0x%08x Size in bytes.\n", size));
499   memcpy ((char *) p_outfile->file_base + index, 
500           (char *) p_infile->file_base + index, size);
501 }
502
503 static void
504 dump_bss_and_heap (file_data *p_infile, file_data *p_outfile)
505 {
506     unsigned char *heap_data;
507     unsigned long size, index;
508
509     DUMP_MSG (("Dumping heap onto end of executable...\n"));
510
511     index = heap_index_in_executable;
512     size = get_committed_heap_size ();
513     heap_data = get_heap_start ();
514
515     DUMP_MSG (("\t0x%08x Heap start in process.\n", heap_data));
516     DUMP_MSG (("\t0x%08x Heap offset in executable.\n", index));
517     DUMP_MSG (("\t0x%08x Heap size in bytes.\n", size));
518
519     memcpy ((PUCHAR) p_outfile->file_base + index, heap_data, size);
520
521 #ifndef DUMP_SEPARATE_SECTION
522     DUMP_MSG (("Dumping bss onto end of executable...\n"));
523     
524     index += size;
525     size = bss_size;
526
527     DUMP_MSG (("\t0x%08x BSS start in process.\n", bss_start));
528     DUMP_MSG (("\t0x%08x BSS offset in executable.\n", index));
529     DUMP_MSG (("\t0x%08x BSS size in bytes.\n", size));
530     memcpy ((char *) p_outfile->file_base + index, bss_start, size);
531 #endif
532 }
533
534 #undef DUMP_MSG
535
536 /* Reload and remap routines.  */
537
538
539 /* Load the dumped .bss section into the .bss area of our address space.  */
540 /* Already done if the .bss  was part of a separate emacs data section */
541 void
542 read_in_bss (char *filename)
543 {
544 #ifndef DUMP_SEPARATE_SECTION
545   HANDLE file;
546   unsigned long index, n_read;
547
548   file = CreateFile (filename, GENERIC_READ, FILE_SHARE_READ, NULL,
549                      OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
550   if (file == INVALID_HANDLE_VALUE)
551     abort ();
552   
553   /* Seek to where the .bss section is tucked away after the heap...  */
554   index = heap_index_in_executable + get_committed_heap_size ();
555   if (SetFilePointer (file, index, NULL, FILE_BEGIN) == 0xFFFFFFFF) 
556     abort ();
557
558   /* Ok, read in the saved .bss section and initialize all 
559      uninitialized variables.  */
560   if (!ReadFile (file, bss_start, bss_size, &n_read, NULL))
561     abort ();
562
563   CloseHandle (file);
564 #endif
565 }
566
567 /* Map the heap dumped into the executable file into our address space.  */
568 void 
569 map_in_heap (char *filename)
570 {
571   HANDLE file;
572   HANDLE file_mapping;
573   void  *file_base;
574   unsigned long size, upper_size, n_read;
575
576   file = CreateFile (filename, GENERIC_READ, FILE_SHARE_READ, NULL,
577                      OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
578   if (file == INVALID_HANDLE_VALUE) 
579     abort ();
580
581   size = GetFileSize (file, &upper_size);
582   file_mapping = CreateFileMapping (file, NULL, PAGE_WRITECOPY, 
583                                     0, size, NULL);
584   if (!file_mapping) 
585     abort ();
586
587   size = get_committed_heap_size ();
588   file_base = MapViewOfFileEx (file_mapping, FILE_MAP_COPY, 0, 
589                                heap_index_in_executable, size,
590                                get_heap_start ());
591   if (file_base != 0) 
592     {
593       return;
594     }
595
596   /* If we don't succeed with the mapping, then copy from the 
597      data into the heap.  */
598
599   CloseHandle (file_mapping);
600
601   if (VirtualAlloc (get_heap_start (), get_committed_heap_size (),
602                     MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) == NULL)
603     abort ();
604
605   /* Seek to the location of the heap data in the executable.  */
606   if (SetFilePointer (file, heap_index_in_executable,
607                       NULL, FILE_BEGIN) == 0xFFFFFFFF)
608     abort ();
609
610   /* Read in the data.  */
611   if (!ReadFile (file, get_heap_start (), 
612                  get_committed_heap_size (), &n_read, NULL))
613     abort ();
614
615   CloseHandle (file);
616 }