source: trunk/src/peldr/pe.cpp@ 7970

Last change on this file since 7970 was 7970, checked in by sandervl, 24 years ago

DF: Added support for WINDOWSPATH environment variable; PE searches for executables in directories listed in WINDOWSPATH

File size: 14.3 KB
Line 
1/* $Id: pe.cpp,v 1.32 2002-02-20 09:45:49 sandervl Exp $ */
2
3/*
4 * PELDR main exe loader code
5 *
6 * Copyright 1998-2001 Sander van Leeuwen (sandervl@xs4all.nl)
7 *
8 * Command line options:
9 * /OPT:[x1=y,x2=z,..]
10 * x = CURDIR -> set current directory to y
11 * (not other options available at this time)
12 *
13 * Project Odin Software License can be found in LICENSE.TXT
14 *
15 */
16#define INCL_DOSFILEMGR /* File Manager values */
17#define INCL_DOSERRORS /* DOS Error values */
18#define INCL_DOSPROCESS /* DOS Process values */
19#define INCL_DOSMISC /* DOS Miscellanous values */
20#define INCL_DOSMODULEMGR
21#define INCL_DOSSESMGR
22#define INCL_WIN
23#include <os2.h>
24#include <bseord.h>
25#include <stdio.h>
26#include <string.h>
27#include <stdlib.h>
28#include <string.h>
29#include <assert.h>
30#include <win32type.h>
31#include <misc.h>
32#include <wprocess.h>
33#include <win\peexe.h>
34#include "pe.h"
35
36char INFO_BANNER[] = "Usage: PE winexe commandline";
37char szErrorTitle[] = "Odin";
38char szLoadErrorMsg[] = "Can't load executable";
39char szFileNotFound[] = "File not found.";
40char szFileErrorMsg[] = "File IO error";
41char szPEErrorMsg[] = "Not a valid win32 exe. (perhaps 16 bits windows)";
42char szCPUErrorMsg[] = "Executable doesn't run on x86 machines";
43char szExeErrorMsg[] = "File isn't an executable";
44char szInteralErrorMsg[]= "Internal Error";
45char szNoKernel32Msg[] = "Can't load/find kernel32.dll (rc=%d, module %s)";
46char szDosInfoBlocks[] = "DosInfoBlocks failed!";
47char szErrDosStartSession[] = "Failed to start win16 session (rc=%d)";
48
49char fullpath[CCHMAXPATH];
50
51typedef HAB (* APIENTRY WININITIALIZEPROC)(ULONG flOptions);
52typedef BOOL (* APIENTRY WINTERMINATEPROC)(HAB hab);
53typedef HMQ (* APIENTRY WINCREATEMSGQUEUEPROC) (HAB hab, LONG cmsg);
54typedef BOOL (* APIENTRY WINDESTROYMSGQUEUEPROC) (HMQ hmq);
55typedef ULONG (* APIENTRY WINMESSAGEBOXPROC) (HWND hwndParent,
56 HWND hwndOwner,
57 PCSZ pszText,
58 PCSZ pszCaption,
59 ULONG idWindow,
60 ULONG flStyle);
61typedef void (* KRNL32EXCEPTPROC) (void *exceptframe);
62
63WININITIALIZEPROC MyWinInitialize = 0;
64WINTERMINATEPROC MyWinTerminate = 0;
65WINCREATEMSGQUEUEPROC MyWinCreateMsgQueue = 0;
66WINDESTROYMSGQUEUEPROC MyWinDestroyMsgQueue = 0;
67WINMESSAGEBOXPROC MyWinMessageBox = 0;
68KRNL32EXCEPTPROC Krnl32SetExceptionHandler = 0;
69KRNL32EXCEPTPROC Krnl32UnsetExceptionHandler = 0;
70
71//should be the same as in ..\kernel32\winexepeldr.h
72typedef BOOL (* WIN32API WIN32CTOR)(char *, char *, char *, ULONG, BOOL, BOOL);
73
74WIN32CTOR CreateWin32Exe = 0;
75ULONG reservedMemory = 0;
76BOOL fConsoleApp = FALSE;
77
78BOOL AllocateExeMem(char *filename, BOOL *fNEExe);
79
80//******************************************************************************
81//******************************************************************************
82int main(int argc, char *argv[])
83{
84 HAB hab = 0; /* PM anchor block handle */
85 HMQ hmq = 0; /* Message queue handle */
86 char exeName[CCHMAXPATH];
87 char fullpath[CCHMAXPATH];
88 char errorMod[CCHMAXPATH];
89 char *pszErrorMsg = NULL;
90 APIRET rc;
91 HMODULE hmodPMWin = 0, hmodKernel32 = 0;
92 PTIB ptib;
93 PPIB ppib;
94 char *cmdline, *win32cmdline, *peoptions, *newcmdline;
95 BOOL fQuote = FALSE, fVioConsole, fIsNEExe, fEndOfCmdLine = FALSE;
96 int nrTries = 1;
97
98 if(argc >= 2) {
99 if(DosGetInfoBlocks(&ptib, &ppib) == 0) {
100tryagain:
101 cmdline = ppib->pib_pchcmd;
102 cmdline += strlen(cmdline)+1; //skip pe.exe
103 peoptions = strstr(cmdline, "/OPT:[");
104 if(peoptions) {
105 newcmdline = strchr(peoptions, ']');
106 if(newcmdline) {
107 cmdline = newcmdline+1;
108 }
109#ifdef DEBUG
110 else _interrupt(3); //should not happen!
111#endif
112 }
113 while(*cmdline == ' ') cmdline++; //skip leading space
114 if(*cmdline == '"') {
115 cmdline++;
116 fQuote = TRUE;
117 }
118 win32cmdline = cmdline;
119
120 strncpy(exeName, cmdline, sizeof(exeName)-1);
121 exeName[sizeof(exeName)-1] = 0;
122 char *p = exeName;
123 if(fQuote) {
124 while(*p != '"' && *p != 0) p++;
125 }
126 else {
127 for(int i=0;i<nrTries;i++) {
128 while(*p != ' ' && *p != 0) p++;
129 if(*p == 0) break;
130 if(i != nrTries-1) {
131 while(*p == ' ' && *p != 0) p++;
132 }
133 }
134 if(nrTries > 1 && *p == 0) {
135 fEndOfCmdLine = TRUE;
136 }
137 }
138 *p = 0;
139 strupr(exeName);
140 cmdline = strstr(exeName, ".EXE");
141 if(cmdline) {
142 cmdline[4] = 0;
143 win32cmdline += ((ULONG)cmdline - (ULONG)exeName) + 4;
144 }
145 else {
146 win32cmdline += strlen(exeName);
147 if(strstr(exeName, ".") == NULL) {
148 strcat(exeName, ".EXE");
149 }
150 }
151 if(fQuote) win32cmdline++;
152 while(*win32cmdline == ' ') win32cmdline++; //skip spaces
153
154 cmdline = exeName + strlen(exeName) - 1;
155 while(*cmdline == ' ') cmdline--;
156 cmdline[1] = 0;
157
158 char drive[_MAX_DRIVE];
159 char dir[_MAX_DIR];
160 char fname[_MAX_FNAME];
161 char ext[_MAX_EXT];
162 char exeShortName[_MAX_FNAME+_MAX_EXT];
163 _splitpath(exeName, drive, dir, fname, ext);
164
165 strcpy(fullpath, drive);
166 strcat(fullpath, dir);
167
168 strcpy(exeShortName, fname);
169 strcat(exeShortName, ext);
170
171 if ( strlen(fullpath) == 0 ) {
172 DosSearchPath( SEARCH_CUR_DIRECTORY | SEARCH_ENVIRONMENT | SEARCH_IGNORENETERRS
173 , "WINDOWSPATH" /* environment value */
174 , exeShortName /* Name of file to look for */
175 , exeName /* Result of the search */
176 , sizeof(exeName) /* Length of search buffer */
177 );
178 }
179
180 FILESTATUS3 fstat3;
181 if(DosQueryPathInfo(exeName, FIL_STANDARD, (PVOID)&fstat3, sizeof(fstat3)))
182 {
183 nrTries++;
184 if(fEndOfCmdLine) {
185 pszErrorMsg = szFileNotFound;
186 goto failerror;
187 }
188
189 if(*win32cmdline != NULL && !fQuote) {
190 goto tryagain;
191 }
192 }
193 }
194 else {//should never happen!
195 pszErrorMsg = szDosInfoBlocks;
196 goto failerror;
197 }
198 AllocateExeMem(exeName, &fIsNEExe);
199 if(fIsNEExe) {
200 STARTDATA sdata = {0};
201 ULONG idSession;
202 PID pid;
203
204 sdata.Length = sizeof(sdata);
205 sdata.PgmName = "w16odin.exe";
206 strcpy(fullpath, exeName);
207 strcat(fullpath, " ");
208 strcat(fullpath, win32cmdline);
209 sdata.PgmInputs = fullpath;
210 sdata.FgBg = SSF_FGBG_FORE;
211 sdata.SessionType = SSF_TYPE_WINDOWEDVDM;
212 rc = DosStartSession(&sdata, &idSession, &pid);
213 if(rc) {
214 sprintf(fullpath, szErrDosStartSession, rc);
215 pszErrorMsg = fullpath;
216 goto failerror;
217 }
218 return 0;
219 }
220 }
221
222#ifdef COMMAND_LINE_VERSION
223 if(DosGetInfoBlocks(&ptib, &ppib) == 0) {
224 //switch process type to PM so the command line app can create PM
225 //windows
226 ppib->pib_ultype = 3;
227 }
228#endif
229
230 rc = DosLoadModule(exeName, sizeof(exeName), "PMWIN.DLL", &hmodPMWin);
231 rc = DosQueryProcAddr(hmodPMWin, ORD_WIN32INITIALIZE, NULL, (PFN *)&MyWinInitialize);
232 rc = DosQueryProcAddr(hmodPMWin, ORD_WIN32TERMINATE, NULL, (PFN *)&MyWinTerminate);
233 rc = DosQueryProcAddr(hmodPMWin, ORD_WIN32CREATEMSGQUEUE, NULL, (PFN *)&MyWinCreateMsgQueue);
234 rc = DosQueryProcAddr(hmodPMWin, ORD_WIN32DESTROYMSGQUEUE, NULL, (PFN *)&MyWinDestroyMsgQueue);
235 rc = DosQueryProcAddr(hmodPMWin, ORD_WIN32MESSAGEBOX, NULL, (PFN *)&MyWinMessageBox);
236
237 if ((hab = MyWinInitialize(0)) == 0L) /* Initialize PM */
238 goto fail;
239
240 hmq = MyWinCreateMsgQueue(hab, 0);
241
242 if(argc < 2) {
243 MyWinMessageBox(HWND_DESKTOP, NULL, INFO_BANNER, szErrorTitle, 0, MB_OK | MB_ERROR | MB_MOVEABLE);
244 goto fail;
245 }
246
247 errorMod[0] = 0;
248 rc = DosLoadModule(errorMod, sizeof(errorMod), "KERNEL32.DLL", &hmodKernel32);
249 if(rc) {
250 sprintf(fullpath, szNoKernel32Msg, rc, errorMod);
251 MyWinMessageBox(HWND_DESKTOP, NULL, fullpath, szErrorTitle, 0, MB_OK | MB_ERROR | MB_MOVEABLE);
252 goto fail;
253 }
254 rc = DosQueryProcAddr(hmodKernel32, 0, "_CreateWin32PeLdrExe@24", (PFN *)&CreateWin32Exe);
255
256#ifdef COMMAND_LINE_VERSION
257 fVioConsole = TRUE;
258#else
259 fVioConsole = FALSE;
260#endif
261 if(CreateWin32Exe(exeName, win32cmdline, peoptions, reservedMemory, fConsoleApp, fVioConsole) == FALSE) {
262 goto fail;
263 }
264
265 if(hmq) MyWinDestroyMsgQueue( hmq ); /* Tidy up... */
266 MyWinTerminate( hab ); /* Terminate the application */
267
268 DosFreeModule(hmodPMWin);
269 DosFreeModule(hmodKernel32);
270 return 0;
271
272fail:
273 if(hmq) MyWinDestroyMsgQueue( hmq ); /* Tidy up... */
274 if(hab) MyWinTerminate( hab ); /* Terminate the application */
275
276 if(hmodPMWin) DosFreeModule(hmodPMWin);
277 if(hmodKernel32) DosFreeModule(hmodKernel32);
278 return(1);
279
280failerror:
281 rc = DosLoadModule(exeName, sizeof(exeName), "PMWIN.DLL", &hmodPMWin);
282 rc = DosQueryProcAddr(hmodPMWin, ORD_WIN32INITIALIZE, NULL, (PFN *)&MyWinInitialize);
283 rc = DosQueryProcAddr(hmodPMWin, ORD_WIN32TERMINATE, NULL, (PFN *)&MyWinTerminate);
284 rc = DosQueryProcAddr(hmodPMWin, ORD_WIN32CREATEMSGQUEUE, NULL, (PFN *)&MyWinCreateMsgQueue);
285 rc = DosQueryProcAddr(hmodPMWin, ORD_WIN32DESTROYMSGQUEUE, NULL, (PFN *)&MyWinDestroyMsgQueue);
286 rc = DosQueryProcAddr(hmodPMWin, ORD_WIN32MESSAGEBOX, NULL, (PFN *)&MyWinMessageBox);
287 if(rc == 0) {
288 if ((hab = MyWinInitialize(0)) == 0L) /* Initialize PM */
289 goto fail;
290
291 hmq = MyWinCreateMsgQueue(hab, 0);
292
293 MyWinMessageBox(HWND_DESKTOP, NULL, pszErrorMsg, szErrorTitle, 0, MB_OK | MB_ERROR | MB_MOVEABLE);
294 }
295 if(hmq) MyWinDestroyMsgQueue( hmq ); /* Tidy up... */
296 if(hab) MyWinTerminate( hab ); /* Terminate the application */
297 if(hmodPMWin) DosFreeModule(hmodPMWin);
298 return 1;
299}
300//******************************************************************************
301//SvL: Reserve memory for win32 exes without fixups
302// This is done before any Odin or PMWIN dll is loaded, so we'll get
303// a very low virtual address. (which is exactly what we want)
304//******************************************************************************
305BOOL AllocateExeMem(char *filename, BOOL *fNEExe)
306{
307 HFILE dllfile = 0;
308 char szFileName[CCHMAXPATH], *tmp;
309 char szResult[CCHMAXPATH];
310 ULONG action, ulRead, signature;
311 APIRET rc;
312 IMAGE_DOS_HEADER doshdr;
313 IMAGE_OPTIONAL_HEADER oh;
314 IMAGE_FILE_HEADER fh;
315 ULONG address = 0;
316 ULONG *memallocs;
317 ULONG alloccnt = 0;
318 ULONG diff, i, baseAddress;
319 ULONG ulSysinfo, flAllocMem = 0;
320 BOOL ret = FALSE;
321
322 *fNEExe = FALSE;
323 strcpy(szFileName, filename);
324
325 rc = DosOpen(szFileName, &dllfile, &action, 0, FILE_READONLY, OPEN_ACTION_OPEN_IF_EXISTS|OPEN_ACTION_FAIL_IF_NEW, OPEN_SHARE_DENYNONE|OPEN_ACCESS_READONLY, NULL);
326 if(rc != 0) {
327 if(!strstr(szFileName, ".EXE")) {
328 strcat(szFileName,".EXE");
329 }
330 }
331 else DosClose(dllfile);
332
333 rc = DosOpen(szFileName, &dllfile, &action, 0, FILE_READONLY, OPEN_ACTION_OPEN_IF_EXISTS|OPEN_ACTION_FAIL_IF_NEW, OPEN_SHARE_DENYNONE|OPEN_ACCESS_READONLY, NULL);
334 if(rc) {
335 if(DosSearchPath(SEARCH_IGNORENETERRS|SEARCH_ENVIRONMENT, "PATH",
336 szFileName, szResult, sizeof(szResult)) != 0) {
337 goto end; //oops
338 }
339 rc = DosOpen(szResult, &dllfile, &action, 0, FILE_READONLY, OPEN_ACTION_OPEN_IF_EXISTS|OPEN_ACTION_FAIL_IF_NEW, OPEN_SHARE_DENYNONE|OPEN_ACCESS_READONLY, NULL);
340 if(rc) {
341 goto end; //oops
342 }
343 }
344
345 //read dos header
346 if(DosRead(dllfile, (LPVOID)&doshdr, sizeof(doshdr), &ulRead)) {
347 goto end;
348 }
349 if(DosSetFilePtr(dllfile, doshdr.e_lfanew, FILE_BEGIN, &ulRead)) {
350 goto end;
351 }
352 //read signature dword
353 if(DosRead(dllfile, (LPVOID)&signature, sizeof(signature), &ulRead)) {
354 goto end;
355 }
356 //read pe header
357 if(DosRead(dllfile, (LPVOID)&fh, sizeof(fh), &ulRead)) {
358 goto end;
359 }
360 //read optional header
361 if(DosRead(dllfile, (LPVOID)&oh, sizeof(oh), &ulRead)) {
362 goto end;
363 }
364 if(doshdr.e_magic != IMAGE_DOS_SIGNATURE || signature != IMAGE_NT_SIGNATURE) {
365 if(LOWORD(signature) == IMAGE_OS2_SIGNATURE) {
366 *fNEExe = TRUE;
367 }
368 goto end;
369 }
370 fConsoleApp = (oh.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_CUI);
371
372 // check for high memory support
373 rc = DosQuerySysInfo(QSV_VIRTUALADDRESSLIMIT, QSV_VIRTUALADDRESSLIMIT, &ulSysinfo, sizeof(ulSysinfo));
374 if (rc == 0 && ulSysinfo > 512) //VirtualAddresslimit is in MB
375 {
376 flAllocMem = PAG_ANY; // high memory support. Let's use it!
377 }
378
379 //Reserve enough space to store 4096 pointers to 1MB memory chunks
380 memallocs = (ULONG *)alloca(4096*sizeof(ULONG *));
381 if(memallocs == NULL) {
382 goto end; //oops
383 }
384
385 if(oh.ImageBase < 512*1024*1024) {
386 flAllocMem = 0;
387 }
388 else {
389 if(flAllocMem == 0) {
390 goto end; //no support for > 512 MB
391 }
392 }
393 while(TRUE) {
394 rc = DosAllocMem((PPVOID)&address, FALLOC_SIZE, PAG_READ | flAllocMem);
395 if(rc) break;
396
397 if(address + FALLOC_SIZE >= oh.ImageBase) {
398 if(address > oh.ImageBase) {//we've passed it!
399 DosFreeMem((PVOID)address);
400 break;
401 }
402 //found the right address
403 DosFreeMem((PVOID)address);
404
405 diff = oh.ImageBase - address;
406 if(diff) {
407 rc = DosAllocMem((PPVOID)&address, diff, PAG_READ | flAllocMem);
408 if(rc) break;
409 }
410 rc = DosAllocMem((PPVOID)&baseAddress, oh.SizeOfImage, PAG_READ | PAG_WRITE | flAllocMem);
411 if(rc) break;
412
413 if(diff) DosFreeMem((PVOID)address);
414
415 reservedMemory = baseAddress;
416 break;
417 }
418 memallocs[alloccnt++] = address;
419 }
420 for(i=0;i<alloccnt;i++) {
421 DosFreeMem((PVOID)memallocs[i]);
422 }
423 ret = TRUE;
424end:
425 if(dllfile) DosClose(dllfile);
426 return ret;
427}
428//******************************************************************************
429//******************************************************************************
Note: See TracBrowser for help on using the repository browser.