source: trunk/src/kernel32/wprocess.cpp@ 21381

Last change on this file since 21381 was 21381, checked in by dmik, 15 years ago

Implemented compiler-level SEH (try/catch) support for GCC.

File size: 100.6 KB
Line 
1/* $Id: wprocess.cpp,v 1.194 2004-02-24 11:46:10 sandervl Exp $ */
2
3/*
4 * Win32 process functions
5 *
6 * Copyright 1998-2000 Sander van Leeuwen (sandervl@xs4all.nl)
7 * Copyright 2000 knut st. osmundsen (knut.stange.osmundsen@mynd.no)
8 * Copyright 2003 Innotek Systemberatung GmbH (sandervl@innotek.de)
9 *
10 *
11 * NOTE: Even though Odin32 OS/2 apps don't switch FS selectors,
12 * we still allocate a TEB to store misc information.
13 *
14 * TODO: What happens when a dll is first loaded as LOAD_LIBRARY_AS_DATAFILE
15 * and then for real? (first one not freed of course)
16 *
17 * Project Odin Software License can be found in LICENSE.TXT
18 *
19 */
20#include <odin.h>
21#include <odinwrap.h>
22#include <os2win.h>
23#include <stdio.h>
24#include <stdlib.h>
25#include <string.h>
26
27#include <unicode.h>
28#include "windllbase.h"
29#include "winexebase.h"
30#include "windllpeldr.h"
31#include "winexepeldr.h"
32#include "windlllx.h"
33#include <vmutex.h>
34#include <handlemanager.h>
35#include <odinpe.h>
36
37#include "odin32validate.h"
38#include "exceptutil.h"
39#include "asmutil.h"
40#include "oslibdos.h"
41#include "oslibmisc.h"
42#include "oslibdebug.h"
43#include "hmcomm.h"
44
45#include "console.h"
46#include "wincon.h"
47#include "versionos2.h" /*PLF Wed 98-03-18 02:36:51*/
48#include <wprocess.h>
49#include "mmap.h"
50#include "initterm.h"
51#include "directory.h"
52
53#include <win\ntddk.h>
54#include <win\psapi.h>
55
56#include <custombuild.h>
57
58#define DBG_LOCALLOG DBG_wprocess
59#include "dbglocal.h"
60
61#ifdef PROFILE
62#include <perfview.h>
63#include <profiler.h>
64#endif /* PROFILE */
65
66
67ODINDEBUGCHANNEL(KERNEL32-WPROCESS)
68
69
70//environ.cpp
71char *CreateNewEnvironment(char *lpEnvironment);
72
73/*******************************************************************************
74* Global Variables *
75*******************************************************************************/
76BOOL fIsOS2Image = FALSE; /* TRUE -> Odin32 OS/2 application (not converted!) */
77 /* FALSE -> otherwise */
78BOOL fSwitchTIBSel = TRUE; // TRUE -> switch TIB selectors
79 // FALSE -> don't
80BOOL fSEHEnabled = FALSE; // TRUE -> SEH support enabled
81 // FALSE -> not enabled
82BOOL fExitProcess = FALSE;
83
84//Commandlines
85PCSTR pszCmdLineA; /* ASCII/ANSII commandline. */
86PCWSTR pszCmdLineW; /* Unicode commandline. */
87
88//Process database
89PDB ProcessPDB = {0};
90ENVDB ProcessENVDB = {0};
91CONCTRLDATA ProcessConCtrlData = {0};
92STARTUPINFOA StartupInfo = {0};
93CHAR unknownPDBData[16] = {0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0 ,0 ,0};
94USHORT ProcessTIBSel = 0;
95DWORD *TIBFlatPtr = 0;
96
97//list of thread database structures
98static TEB *threadList = 0;
99static VMutex threadListMutex;
100
101/**
102 * LoadLibraryExA callback for LX Dlls, it's call only on the initial load.
103 * Maintained by ODIN_SetLxDllLoadCallback().
104 * Note! Because of some hacks it may also be called from Win32LxDll::Release().
105 */
106PFNLXDLLLOAD pfnLxDllLoadCallback = NULL;
107
108
109//******************************************************************************
110//******************************************************************************
111VOID WIN32API EnableSEH()
112{
113 if(!fSEHEnabled) {
114 ODIN_SetTIBSwitch(TRUE);
115 fSEHEnabled = TRUE;
116 }
117 return;
118}
119//******************************************************************************
120//******************************************************************************
121TEB *WIN32API GetThreadTEB()
122{
123 if(TIBFlatPtr == NULL) {
124 return 0;
125 }
126 return (TEB *)*TIBFlatPtr;
127}
128//******************************************************************************
129//******************************************************************************
130TEB *WIN32API GetTEBFromThreadId(ULONG threadId)
131{
132 TEB *teb = threadList;
133
134 threadListMutex.enter();
135 while(teb) {
136 if(teb->o.odin.threadId == threadId) {
137 break;
138 }
139 teb = teb->o.odin.next;
140 }
141 threadListMutex.leave();
142 return teb;
143}
144//******************************************************************************
145//******************************************************************************
146TEB *WIN32API GetTEBFromThreadHandle(HANDLE hThread)
147{
148 TEB *teb = threadList;
149
150 threadListMutex.enter();
151 while(teb) {
152 if(teb->o.odin.hThread == hThread) {
153 break;
154 }
155 teb = teb->o.odin.next;
156 }
157 threadListMutex.leave();
158 return teb;
159}
160//******************************************************************************
161//Allocate TEB structure for new thread
162//******************************************************************************
163TEB *WIN32API CreateTEB(HANDLE hThread, DWORD dwThreadId)
164{
165 USHORT tibsel;
166 TEB *winteb;
167
168 if(OSLibAllocSel(sizeof(TEB), &tibsel) == FALSE)
169 {
170 dprintf(("InitializeTIB: selector alloc failed!!"));
171 DebugInt3();
172 return NULL;
173 }
174 winteb = (TEB *)OSLibSelToFlat(tibsel);
175 if(winteb == NULL)
176 {
177 dprintf(("InitializeTIB: DosSelToFlat failed!!"));
178 DebugInt3();
179 return NULL;
180 }
181 memset(winteb, 0, sizeof(TEB));
182 dprintf(("TIB selector %x; linaddr 0x%x", tibsel, winteb));
183
184 threadListMutex.enter();
185 TEB *teblast = threadList;
186 if(!teblast) {
187 threadList = winteb;
188 winteb->o.odin.next = NULL;
189 }
190 else {
191 while(teblast->o.odin.next) {
192 teblast = teblast->o.odin.next;
193 }
194 teblast->o.odin.next = winteb;
195 }
196 threadListMutex.leave();
197
198 winteb->except = (PVOID)-1; /* 00 Head of exception handling chain */
199 winteb->htask16 = (USHORT)OSLibGetPIB(PIB_TASKHNDL); /* 0c Win16 task handle */
200 winteb->stack_sel = getSS(); /* 0e 16-bit stack selector */
201 winteb->self = winteb; /* 18 Pointer to this structure */
202 winteb->flags = TEBF_WIN32; /* 1c Flags */
203 winteb->queue = 0; /* 28 Message queue */
204 winteb->tls_ptr = &winteb->tls_array[0]; /* 2c Pointer to TLS array */
205 winteb->process = &ProcessPDB; /* 30 owning process (used by NT3.51 applets)*/
206 winteb->delta_priority = THREAD_PRIORITY_NORMAL;
207 winteb->process = &ProcessPDB;
208
209 //store selector of new TEB
210 winteb->teb_sel = tibsel;
211
212 winteb->o.odin.hThread = hThread;
213 winteb->o.odin.threadId = dwThreadId;
214
215 // Event semaphore (auto-reset) to signal message post to MsgWaitForMultipleObjects
216 winteb->o.odin.hPostMsgEvent = CreateEventA(NULL, FALSE, FALSE, NULL);
217
218 return winteb;
219}
220//******************************************************************************
221// Set up the TIB selector and memory for the main thread
222//******************************************************************************
223TEB *WIN32API InitializeMainThread()
224{
225 HANDLE hThreadMain;
226 TEB *teb;
227
228 //Allocate one dword to store the flat address of our TEB
229 dprintf(("InitializeMainThread Process handle %x, id %x", GetCurrentProcess(), GetCurrentProcessId()));
230
231 TIBFlatPtr = (DWORD *)OSLibAllocThreadLocalMemory(1);
232 if(TIBFlatPtr == 0) {
233 dprintf(("InitializeTIB: local thread memory alloc failed!!"));
234 DebugInt3();
235 return NULL;
236 }
237 //SvL: This doesn't really create a thread, but only sets up the
238 // handle of thread 0
239 hThreadMain = HMCreateThread(NULL, 0, 0, 0, 0, 0, TRUE);
240
241 //create and initialize TEB
242 teb = CreateTEB(hThreadMain, GetCurrentThreadId());
243 if(teb == NULL || InitializeThread(teb, TRUE) == FALSE) {
244 DebugInt3();
245 return NULL;
246 }
247
248 ProcessTIBSel = teb->teb_sel;
249
250 //todo initialize PDB during process creation
251 //todo: initialize TLS array if required
252 //TLS in executable always TLS index 0?
253//// ProcessPDB.exit_code = 0x103; /* STILL_ACTIVE */
254 ProcessPDB.threads = 1;
255 ProcessPDB.running_threads = 1;
256 ProcessPDB.ring0_threads = 1;
257 ProcessPDB.system_heap = GetProcessHeap();
258 ProcessPDB.parent = 0;
259 ProcessPDB.group = &ProcessPDB;
260 ProcessPDB.priority = 8; /* Normal */
261 ProcessPDB.heap = ProcessPDB.system_heap; /* will be changed later on */
262 ProcessPDB.next = NULL;
263 ProcessPDB.winver = 0xffff; /* to be determined */
264 ProcessPDB.server_pid = (void *)GetCurrentProcessId();
265 ProcessPDB.tls_bits[0] = 0; //all tls slots are free
266 ProcessPDB.tls_bits[1] = 0;
267
268 GetSystemTime(&ProcessPDB.creationTime);
269
270 /* Initialize the critical section */
271 InitializeCriticalSection(&ProcessPDB.crit_section );
272
273 //initialize the environment db entry.
274 ProcessPDB.env_db = &ProcessENVDB;
275 ProcessENVDB.startup_info = &StartupInfo;
276 ProcessENVDB.environ = GetEnvironmentStringsA();
277 ProcessENVDB.cmd_line = (CHAR*)(void*)pszCmdLineA;
278 ProcessENVDB.cmd_lineW = (WCHAR*)(void*)pszCmdLineW;
279 ProcessENVDB.break_handlers = &ProcessConCtrlData;
280 ProcessConCtrlData.fIgnoreCtrlC = FALSE; /* TODO! Should be inherited from parent. */
281 ProcessConCtrlData.pHead = ProcessConCtrlData.pTail = (PCONCTRL)malloc(sizeof(CONCTRL));
282 ProcessConCtrlData.pHead->pfnHandler = (void*)DefaultConsoleCtrlHandler;
283 ProcessConCtrlData.pHead->pNext = ProcessConCtrlData.pHead->pPrev = NULL;
284 ProcessConCtrlData.pHead->flFlags = ODIN32_CONCTRL_FLAGS_INIT;
285 InitializeCriticalSection(&ProcessENVDB.section);
286
287 ProcessPDB.unknown10 = (PVOID)&unknownPDBData[0];
288 //initialize the startup info part of the db entry.
289 O32_GetStartupInfo(&StartupInfo);
290 StartupInfo.cb = sizeof(StartupInfo);
291 /* Set some defaults as GetStartupInfo() used to set... */
292 if (!(StartupInfo.dwFlags & STARTF_USESHOWWINDOW))
293 StartupInfo.wShowWindow= SW_NORMAL;
294 /* must be NULL for VC runtime */
295 StartupInfo.lpReserved = NULL;
296 StartupInfo.cbReserved2 = NULL;
297 if (!StartupInfo.lpDesktop)
298 StartupInfo.lpDesktop = "Desktop";
299 if (!StartupInfo.lpTitle)
300 StartupInfo.lpTitle = "Title";
301 ProcessENVDB.hStdin = StartupInfo.hStdInput = GetStdHandle(STD_INPUT_HANDLE);
302 ProcessENVDB.hStdout = StartupInfo.hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE);
303 ProcessENVDB.hStderr = StartupInfo.hStdError = GetStdHandle(STD_ERROR_HANDLE);
304
305 return teb;
306}
307//******************************************************************************
308// Set up the TEB structure of the CURRENT (!) thread
309//******************************************************************************
310BOOL WIN32API InitializeThread(TEB *winteb, BOOL fMainThread)
311{
312 //store TEB address in thread locale memory for easy retrieval
313 *TIBFlatPtr = (DWORD)winteb;
314
315//// winteb->exit_code = 0x103; /* STILL_ACTIVE */
316
317 winteb->stack_top = (PVOID)OSLibGetTIB(TIB_STACKTOP); /* 04 Top of thread stack */
318 winteb->stack_top = (PVOID)(((ULONG)winteb->stack_top + 0xFFF) & ~0xFFF);
319 //round to next page (OS/2 doesn't return a nice rounded value)
320 winteb->stack_low = (PVOID)OSLibGetTIB(TIB_STACKLOW); /* 08 Stack low-water mark */
321 //round to page boundary (OS/2 doesn't return a nice rounded value)
322 winteb->stack_low = (PVOID)((ULONG)winteb->stack_low & ~0xFFF);
323
324 winteb->o.odin.OrgTIBSel = GetFS();
325 winteb->o.odin.pWsockData = NULL;
326#ifdef DEBUG
327 winteb->o.odin.dbgCallDepth = 0;
328#endif
329 winteb->o.odin.pMessageBuffer = NULL;
330 winteb->o.odin.lcid = GetUserDefaultLCID();
331
332 if(OSLibGetPIB(PIB_TASKTYPE) == TASKTYPE_PM)
333 {
334 winteb->flags = 0; //todo gui
335 }
336 else winteb->flags = 0; //todo textmode
337
338 //Initialize thread security objects (TODO: Not complete)
339 SID_IDENTIFIER_AUTHORITY sidIdAuth = {0};
340 winteb->o.odin.threadinfo.dwType = SECTYPE_PROCESS | SECTYPE_INITIALIZED;
341
342 RtlAllocateAndInitializeSid(&sidIdAuth, 1, 0, 0, 0, 0, 0, 0, 0, 0, &winteb->o.odin.threadinfo.SidUser.User.Sid);
343
344 winteb->o.odin.threadinfo.SidUser.User.Attributes = 0; //?????????
345
346 winteb->o.odin.threadinfo.pTokenGroups = (TOKEN_GROUPS*)malloc(sizeof(TOKEN_GROUPS));
347 winteb->o.odin.threadinfo.pTokenGroups->GroupCount = 1;
348
349 RtlAllocateAndInitializeSid(&sidIdAuth, 1, 0, 0, 0, 0, 0, 0, 0, 0, &winteb->o.odin.threadinfo.PrimaryGroup.PrimaryGroup);
350
351 winteb->o.odin.threadinfo.pTokenGroups->Groups[0].Sid = winteb->o.odin.threadinfo.PrimaryGroup.PrimaryGroup;
352 winteb->o.odin.threadinfo.pTokenGroups->Groups[0].Attributes = 0; //????
353// pPrivilegeSet = NULL;
354// pTokenPrivileges= NULL;
355// TokenOwner = {0};
356// DefaultDACL = {0};
357// TokenSource = {0};
358 winteb->o.odin.threadinfo.TokenType = TokenPrimary;
359
360 dprintf(("InitializeTIB setup TEB with selector %x", winteb->teb_sel));
361 dprintf(("InitializeTIB: FS(%x):[0] = %x", GetFS(), QueryExceptionChain()));
362 return TRUE;
363}
364//******************************************************************************
365// Destroy the TIB selector and memory for the current thread
366//******************************************************************************
367void WIN32API DestroyTEB(TEB *winteb)
368{
369 SHORT orgtibsel;
370
371 dprintf(("DestroyTIB: FS = %x", GetFS()));
372 dprintf(("DestroyTIB: FS:[0] = %x", QueryExceptionChain()));
373
374 orgtibsel = winteb->o.odin.OrgTIBSel;
375
376 dprintf(("DestroyTIB: OSLibFreeSel %x", winteb->teb_sel));
377
378 threadListMutex.enter();
379 TEB *curteb = threadList;
380 if(curteb == winteb) {
381 threadList = winteb->o.odin.next;
382 }
383 else {
384 while(curteb->o.odin.next != winteb) {
385 curteb = curteb->o.odin.next;
386 if(curteb == NULL) {
387 dprintf(("DestroyTIB: couldn't find teb %x", winteb));
388 DebugInt3();
389 break;
390 }
391 }
392 if(curteb) {
393 curteb->o.odin.next = winteb->o.odin.next;
394 }
395 }
396 threadListMutex.leave();
397
398 // free allocated memory for security structures
399 free( winteb->o.odin.threadinfo.pTokenGroups );
400
401 // free PostMessage event semaphore
402 if(winteb->o.odin.hPostMsgEvent) {
403 CloseHandle(winteb->o.odin.hPostMsgEvent);
404 }
405
406 // free shared memory for WM_COPYDATA
407 if (winteb->o.odin.pWM_COPYDATA)
408 {
409 dprintf(("DestroyTEB: freeing WM_COPYDATA: %#p", winteb->o.odin.pWM_COPYDATA));
410 _sfree(winteb->o.odin.pWM_COPYDATA);
411 }
412
413#ifdef DEBUG
414 if (winteb->o.odin.arrstrCallStack != NULL)
415 free( winteb->o.odin.arrstrCallStack );
416#endif
417
418 //Restore our original FS selector
419 SetFS(orgtibsel);
420
421 //And free our own
422 OSLibFreeSel(winteb->teb_sel);
423
424 *TIBFlatPtr = 0;
425
426 dprintf(("DestroyTIB: FS(%x):[0] = %x", GetFS(), QueryExceptionChain()));
427 return;
428}
429//******************************************************************************
430//******************************************************************************
431ULONG WIN32API GetProcessTIBSel()
432{
433 if(fExitProcess) {
434 return 0;
435 }
436 return ProcessTIBSel;
437}
438/******************************************************************************/
439/******************************************************************************/
440void SetPDBInstance(HINSTANCE hInstance)
441{
442 ProcessPDB.hInstance = hInstance;
443}
444/******************************************************************************/
445/******************************************************************************/
446void WIN32API RestoreOS2TIB()
447{
448 SHORT orgtibsel;
449 TEB *winteb;
450
451 //If we're running an Odin32 OS/2 application (not converted!), then we
452 //we don't switch FS selectors
453 if(!fSwitchTIBSel) {
454 return;
455 }
456
457 winteb = (TEB *)*TIBFlatPtr;
458 if(winteb) {
459 orgtibsel = winteb->o.odin.OrgTIBSel;
460
461 //Restore our original FS selector
462 SetFS(orgtibsel);
463 }
464}
465/******************************************************************************/
466//Switch to WIN32 TIB (FS selector)
467//NOTE: This is not done for Odin32 applications (LX), unless
468// fForceSwitch is TRUE)
469/******************************************************************************/
470USHORT WIN32API SetWin32TIB(BOOL fForceSwitch)
471{
472 SHORT win32tibsel;
473 TEB *winteb;
474
475 //If we're running an Odin32 OS/2 application (not converted!), then we
476 //we don't switch FS selectors
477 if(!fSwitchTIBSel && !fForceSwitch) {
478 return GetFS();
479 }
480
481 winteb = (TEB *)*TIBFlatPtr;
482 if(winteb) {
483 win32tibsel = winteb->teb_sel;
484
485 //Restore our win32 FS selector
486 return SetReturnFS(win32tibsel);
487 }
488 else {
489 return GetFS();
490 }
491 // nested calls are OK, OS2ToWinCallback for instance
492 //else DebugInt3();
493
494 return GetFS();
495}
496//******************************************************************************
497// ODIN_SetTIBSwitch: override TIB switching
498//
499// Parameters:
500// BOOL fSwitchTIB
501// FALSE -> no TIB selector switching
502// TRUE -> force TIB selector switching
503//
504//******************************************************************************
505void WIN32API ODIN_SetTIBSwitch(BOOL fSwitchTIB)
506{
507 dprintf(("ODIN_SetTIBSwitch %d", fSwitchTIB));
508 if (!fSEHEnabled) {
509 fSwitchTIBSel = fSwitchTIB;
510 if(fSwitchTIBSel) {
511 SetWin32TIB();
512 }
513 else RestoreOS2TIB();
514 } else {
515 dprintf(("ODIN_SetTIBSwitch: ignored due to fSEHEnabled = TRUE"));
516 }
517}
518//******************************************************************************
519//******************************************************************************
520//#define DEBUG_HEAPSTATE
521#ifdef DEBUG_HEAPSTATE
522char *pszHeapDump = NULL;
523char *pszHeapDumpStart = NULL;
524
525int _LNK_CONV callback_function(const void *pentry, size_t sz, int useflag, int status,
526 const char *filename, size_t line)
527{
528 if (_HEAPOK != status) {
529// dprintf(("status is not _HEAPOK."));
530 return 1;
531 }
532 if (_USEDENTRY == useflag && sz && filename && line && pszHeapDump) {
533 sprintf(pszHeapDump, "allocated %08x %u at %s %d\n", pentry, sz, filename, line);
534 pszHeapDump += strlen(pszHeapDump);
535 }
536
537 return 0;
538}
539//******************************************************************************
540//******************************************************************************
541#endif
542VOID WIN32API ExitProcess(DWORD exitcode)
543{
544 HANDLE hThread = GetCurrentThread();
545 TEB *teb;
546
547 dprintf(("KERNEL32: ExitProcess %d (time %x)", exitcode, GetCurrentTime()));
548 dprintf(("KERNEL32: ExitProcess FS = %x\n", GetFS()));
549
550 fExitProcess = TRUE;
551
552 // Lower priority of all threads to minimize the chance that they're scheduled
553 // during ExitProcess. Can't kill them as that's possibly dangerous (deadlocks
554 // in WGSS for instance)
555 threadListMutex.enter();
556 teb = threadList;
557 while(teb) {
558 if(teb->o.odin.hThread != hThread) {
559 dprintf(("Active thread id %d, handle %x", LOWORD(teb->o.odin.threadId), teb->o.odin.hThread));
560 SetThreadPriority(teb->o.odin.hThread, THREAD_PRIORITY_LOWEST);
561 }
562 teb = teb->o.odin.next;
563 }
564 threadListMutex.leave();
565
566 HMDeviceCommClass::CloseOverlappedIOHandlers();
567
568 //detach all dlls (LIFO order) before really unloading them; this
569 //should take care of circular dependencies (crash while accessing
570 //memory of a dll that has just been freed)
571 dprintf(("********************************************"));
572 dprintf(("**** Detach process from all dlls -- START"));
573 Win32DllBase::detachProcessFromAllDlls();
574 dprintf(("**** Detach process from all dlls -- END"));
575 dprintf(("********************************************"));
576
577 if(WinExe) {
578 delete(WinExe);
579 WinExe = NULL;
580 }
581
582 //Note: Needs to be done after deleting WinExe (destruction of exe + dll objects)
583 //Flush and delete all open memory mapped files
584 Win32MemMap::deleteAll();
585
586 //SvL: We must make sure no threads are still suspended (with SuspendThread)
587 // OS/2 seems to be unable to terminate the process otherwise (exitlist hang)
588 threadListMutex.enter();
589 teb = threadList;
590 while(teb) {
591 dprintf(("Active thread id %d, handle %x", LOWORD(teb->o.odin.threadId), teb->o.odin.hThread));
592 if(teb->o.odin.hThread != hThread) {
593 if(teb->o.odin.dwSuspend > 0) {
594 //kill any threads that are suspended; dangerous, but so is calling
595 //SuspendThread; we assume the app knew what it was doing
596 TerminateThread(teb->o.odin.hThread, 0);
597 ResumeThread(teb->o.odin.hThread);
598 }
599 else SetThreadPriority(teb->o.odin.hThread, THREAD_PRIORITY_LOWEST);
600 }
601 teb = teb->o.odin.next;
602 }
603 threadListMutex.leave();
604
605#ifdef DEBUG_HEAPSTATE
606 pszHeapDumpStart = pszHeapDump = (char *)malloc(10*1024*1024);
607 _heap_walk(callback_function);
608 dprintf((pszHeapDumpStart));
609 free(pszHeapDumpStart);
610#endif
611
612#ifdef PROFILE
613 // Note: after this point we do not expect any more Win32-API calls,
614 // so this is probably the best time to dump the gathered profiling
615 // information
616 PerfView_Write();
617 ProfilerWrite();
618 ProfilerTerminate();
619#endif /* PROFILE */
620
621 //Restore original OS/2 TIB selector
622 teb = GetThreadTEB();
623 if(teb) DestroyTEB(teb);
624 SetExceptionChain((ULONG)-1);
625
626 //avoid crashes since win32 & OS/2 exception handler aren't identical
627 //(terminate process generates two exceptions)
628 /* @@@PH 1998/02/12 Added Console Support */
629 if (iConsoleIsActive())
630 iConsoleWaitClose();
631
632 dprintf(("KERNEL32: ExitProcess done (time %x)", GetCurrentTime()));
633#ifndef DEBUG
634 OSLibDisablePopups();
635#endif
636 O32_ExitProcess(exitcode);
637}
638//******************************************************************************
639//******************************************************************************
640BOOL WIN32API FreeLibrary(HINSTANCE hinstance)
641{
642 Win32DllBase *winmod;
643 BOOL rc;
644
645 SetLastError(ERROR_SUCCESS);
646 //Ignore FreeLibary for executable
647 if(WinExe && hinstance == WinExe->getInstanceHandle()) {
648 return TRUE;
649 }
650
651 winmod = Win32DllBase::findModule(hinstance);
652 if(winmod) {
653 dprintf(("FreeLibrary %s", winmod->getName()));
654 //Only free it when the nrDynamicLibRef != 0
655 //This prevent problems after ExitProcess:
656 //i.e. dll A is referenced by our exe and loaded with LoadLibrary by dll B
657 // During ExitProcess it's unloaded once (before dll B), dll B calls
658 // FreeLibrary, but our exe also has a reference -> unloaded too many times
659 if(winmod->isDynamicLib()) {
660 winmod->decDynamicLib();
661 winmod->Release();
662 }
663 else {
664 dprintf(("Skipping dynamic unload as nrDynamicLibRef == 0"));
665 }
666 return(TRUE);
667 }
668 dprintf(("WARNING: KERNEL32: FreeLibrary %s %x NOT FOUND!", OSLibGetDllName(hinstance), hinstance));
669 return(TRUE);
670}
671/*****************************************************************************
672 * Name : VOID WIN32API FreeLibraryAndExitThread
673 * Purpose : The FreeLibraryAndExitThread function decrements the reference
674 * count of a loaded dynamic-link library (DLL) by one, and then
675 * calls ExitThread to terminate the calling thread.
676 * The function does not return.
677 *
678 * The FreeLibraryAndExitThread function gives threads that are
679 * created and executed within a dynamic-link library an opportunity
680 * to safely unload the DLL and terminate themselves.
681 * Parameters:
682 * Variables :
683 * Result :
684 * Remark :
685 *****************************************************************************/
686VOID WIN32API FreeLibraryAndExitThread( HMODULE hLibModule, DWORD dwExitCode)
687{
688
689 dprintf(("KERNEL32: FreeLibraryAndExitThread(%08x,%08x)", hLibModule, dwExitCode));
690 FreeLibrary(hLibModule);
691 ExitThread(dwExitCode);
692}
693/******************************************************************************/
694/******************************************************************************/
695/**
696 * LoadLibraryA can be used to map a DLL module into the calling process's
697 * addressspace. It returns a handle that can be used with GetProcAddress to
698 * get addresses of exported entry points (functions and variables).
699 *
700 * LoadLibraryA can also be used to map executable (.exe) modules into the
701 * address to access resources in the module. However, LoadLibrary can't be
702 * used to run an executable (.exe) module.
703 *
704 * @returns Handle to the library which was loaded.
705 * @param lpszLibFile Pointer to zero ASCII string giving the name of the
706 * executable image (either a Dll or an Exe) which is to be
707 * loaded.
708 *
709 * If no extention is specified the default .DLL extention is
710 * appended to the name. End the filename with an '.' if the
711 * file does not have an extention (and don't want the .DLL
712 * appended).
713 *
714 * If no path is specified, this API will use the Odin32
715 * standard search strategy to find the file. This strategy
716 * is described in the method Win32ImageBase::findDLL.
717 *
718 * This API likes to have backslashes (\), but will probably
719 * accept forward slashes too. Win32 SDK docs says that it
720 * should not contain forward slashes.
721 *
722 * Win32 SDK docs adds:
723 * "The name specified is the file name of the module and
724 * is not related to the name stored in the library module
725 * itself, as specified by the LIBRARY keyword in the
726 * module-definition (.def) file."
727 *
728 * @sketch Call LoadLibraryExA with flags set to 0.
729 * @status Odin32 Completely Implemented.
730 * @author Sander van Leeuwen (sandervl@xs4all.nl)
731 * knut st. osmundsen (knut.stange.osmundsen@pmsc.no)
732 * @remark Forwards to LoadLibraryExA.
733 */
734HINSTANCE WIN32API LoadLibraryA(LPCTSTR lpszLibFile)
735{
736 HINSTANCE hDll;
737
738 dprintf(("KERNEL32: LoadLibraryA(%s) --> LoadLibraryExA(lpszLibFile, 0, 0)",
739 lpszLibFile));
740 hDll = LoadLibraryExA(lpszLibFile, 0, 0);
741 dprintf(("KERNEL32: LoadLibraryA(%s) returns 0x%x",
742 lpszLibFile, hDll));
743 return hDll;
744}
745
746
747/**
748 * LoadLibraryW can be used to map a DLL module into the calling process's
749 * addressspace. It returns a handle that can be used with GetProcAddress to
750 * get addresses of exported entry points (functions and variables).
751 *
752 * LoadLibraryW can also be used to map executable (.exe) modules into the
753 * address to access resources in the module. However, LoadLibrary can't be
754 * used to run an executable (.exe) module.
755 *
756 * @returns Handle to the library which was loaded.
757 * @param lpszLibFile Pointer to Unicode string giving the name of
758 * the executable image (either a Dll or an Exe) which is to
759 * be loaded.
760 *
761 * If no extention is specified the default .DLL extention is
762 * appended to the name. End the filename with an '.' if the
763 * file does not have an extention (and don't want the .DLL
764 * appended).
765 *
766 * If no path is specified, this API will use the Odin32
767 * standard search strategy to find the file. This strategy
768 * is described in the method Win32ImageBase::findDLL.
769 *
770 * This API likes to have backslashes (\), but will probably
771 * accept forward slashes too. Win32 SDK docs says that it
772 * should not contain forward slashes.
773 *
774 * Win32 SDK docs adds:
775 * "The name specified is the file name of the module and
776 * is not related to the name stored in the library module
777 * itself, as specified by the LIBRARY keyword in the
778 * module-definition (.def) file."
779 *
780 * @sketch Convert Unicode name to ascii.
781 * Call LoadLibraryExA with flags set to 0.
782 * free ascii string.
783 * @status Odin32 Completely Implemented.
784 * @author Sander van Leeuwen (sandervl@xs4all.nl)
785 * knut st. osmundsen (knut.stange.osmundsen@pmsc.no)
786 * @remark Forwards to LoadLibraryExA.
787 */
788HINSTANCE WIN32API LoadLibraryW(LPCWSTR lpszLibFile)
789{
790 char * pszAsciiLibFile;
791 HINSTANCE hDll;
792
793 pszAsciiLibFile = UnicodeToAsciiString(lpszLibFile);
794 dprintf(("KERNEL32: LoadLibraryW(%s) --> LoadLibraryExA(lpszLibFile, 0, 0)",
795 pszAsciiLibFile));
796 hDll = LoadLibraryExA(pszAsciiLibFile, NULL, 0);
797 dprintf(("KERNEL32: LoadLibraryW(%s) returns 0x%x",
798 pszAsciiLibFile, hDll));
799 FreeAsciiString(pszAsciiLibFile);
800
801 return hDll;
802}
803
804//******************************************************************************
805//Custom build function to disable loading of LX dlls
806static BOOL fDisableLXDllLoading = FALSE;
807//******************************************************************************
808void WIN32API ODIN_DisableLXDllLoading()
809{
810 fDisableLXDllLoading = TRUE;
811}
812
813
814/**
815 * Custombuild API for registering a callback for LX Dll loading thru LoadLibrary*().
816 * @returns Success indicator.
817 * @param pfn Pointer to callback.
818 * NULL if callback is deregistered.
819 */
820BOOL WIN32API ODIN_SetLxDllLoadCallback(PFNLXDLLLOAD pfn)
821{
822 pfnLxDllLoadCallback = pfn;
823 return TRUE;
824}
825
826
827/**
828 * LoadLibraryExA can be used to map a DLL module into the calling process's
829 * addressspace. It returns a handle that can be used with GetProcAddress to
830 * get addresses of exported entry points (functions and variables).
831 *
832 * LoadLibraryExA can also be used to map executable (.exe) modules into the
833 * address to access resources in the module. However, LoadLibrary can't be
834 * used to run an executable (.exe) module.
835 *
836 * @returns Handle to the library which was loaded.
837 * @param lpszLibFile Pointer to Unicode string giving the name of
838 * the executable image (either a Dll or an Exe) which is to
839 * be loaded.
840 *
841 * If no extention is specified the default .DLL extention is
842 * appended to the name. End the filename with an '.' if the
843 * file does not have an extention (and don't want the .DLL
844 * appended).
845 *
846 * If no path is specified, this API will use the Odin32
847 * standard search strategy to find the file. This strategy
848 * is described in the method Win32ImageBase::findDLL.
849 * This may be alterned by the LOAD_WITH_ALTERED_SEARCH_PATH
850 * flag, see below.
851 *
852 * This API likes to have backslashes (\), but will probably
853 * accept forward slashes too. Win32 SDK docs says that it
854 * should not contain forward slashes.
855 *
856 * Win32 SDK docs adds:
857 * "The name specified is the file name of the module and
858 * is not related to the name stored in the library module
859 * itself, as specified by the LIBRARY keyword in the
860 * module-definition (.def) file."
861 *
862 * @param hFile Reserved. Must be 0.
863 *
864 * @param dwFlags Flags which specifies the taken when loading the module.
865 * The value 0 makes it identical to LoadLibraryA/W.
866 *
867 * Flags:
868 *
869 * DONT_RESOLVE_DLL_REFERENCES
870 * (WinNT/2K feature): Don't load imported modules and
871 * hence don't resolve imported symbols.
872 * DllMain isn't called either. (Which is obvious since
873 * it may use one of the importe symbols.)
874 *
875 * On the other hand, if this flag is NOT set, the system
876 * load imported modules, resolves imported symbols, calls
877 * DllMain for process and thread init and term (if wished
878 * by the module).
879 *
880 *
881 * LOAD_LIBRARY_AS_DATAFILE
882 * If this flag is set, the module is mapped into the
883 * address space but is not prepared for execution. Though
884 * it's preparted for resource API. Hence, you'll use this
885 * flag when you want to load a DLL for extracting
886 * messages or resources from it.
887 *
888 * The resulting handle can be used with any Odin32 API
889 * which operates on resources.
890 * (WinNt/2k supports all resource APIs while Win9x don't
891 * support the specialized resource APIs: LoadBitmap,
892 * LoadCursor, LoadIcon, LoadImage, LoadMenu.)
893 *
894 *
895 * LOAD_WITH_ALTERED_SEARCH_PATH
896 * If this flag is set and lpszLibFile specifies a path
897 * we'll use an alternative file search strategy to find
898 * imported modules. This stratgy is simply to use the
899 * path of the module being loaded instead of the path
900 * of the executable module as the first location
901 * to search for imported modules.
902 *
903 * If this flag is clear, the standard Odin32 standard
904 * search strategy. See Win32ImageBase::findDll for
905 * further information.
906 *
907 * not implemented yet.
908 *
909 * @status Open32 Partially Implemented.
910 * @author Sander van Leeuwen (sandervl@xs4all.nl)
911 * knut st. osmundsen (knut.stange.osmundsen@pmsc.no)
912 * @remark Forwards to LoadLibraryExA.
913 */
914HINSTANCE WIN32API LoadLibraryExA(LPCTSTR lpszLibFile, HFILE hFile, DWORD dwFlags)
915{
916 HINSTANCE hDll;
917 Win32DllBase * pModule;
918 char szModname[CCHMAXPATH];
919 BOOL fPath; /* Flags which is set if the */
920 /* lpszLibFile contains a path. */
921 ULONG fPE; /* isPEImage return value. */
922 DWORD Characteristics; //file header's Characteristics
923 char *dot;
924
925 /** @sketch
926 * Some parameter validations is probably useful.
927 */
928 if (!VALID_PSZ(lpszLibFile))
929 {
930 dprintf(("KERNEL32: LoadLibraryExA(0x%x, 0x%x, 0x%x): invalid pointer lpszLibFile = 0x%x\n",
931 lpszLibFile, hFile, dwFlags, lpszLibFile));
932 SetLastError(ERROR_INVALID_PARAMETER); //or maybe ERROR_ACCESS_DENIED is more appropriate?
933 return NULL;
934 }
935 if (!VALID_PSZMAXSIZE(lpszLibFile, CCHMAXPATH))
936 {
937 dprintf(("KERNEL32: LoadLibraryExA(%s, 0x%x, 0x%x): lpszLibFile string too long, %d\n",
938 lpszLibFile, hFile, dwFlags, strlen(lpszLibFile)));
939 SetLastError(ERROR_INVALID_PARAMETER);
940 return NULL;
941 }
942 if ((dwFlags & ~(DONT_RESOLVE_DLL_REFERENCES | LOAD_WITH_ALTERED_SEARCH_PATH | LOAD_LIBRARY_AS_DATAFILE)) != 0)
943 {
944 dprintf(("KERNEL32: LoadLibraryExA(%s, 0x%x, 0x%x): dwFlags have invalid or unsupported flags\n",
945 lpszLibFile, hFile, dwFlags));
946 SetLastError(ERROR_INVALID_PARAMETER);
947 return NULL;
948 }
949
950 /** @sketch
951 * First we'll see if the module is allready loaded - either as the EXE or as DLL.
952 * IF Executable present AND libfile matches the modname of the executable THEN
953 * RETURN instance handle of executable.
954 * Endif
955 * IF allready loaded THEN
956 * IF it's a LX dll which isn't loaded and we're using the PeLoader THEN
957 * Set Load library.
958 * Endif
959 * Inc dynamic reference count.
960 * Inc reference count.
961 * RETURN instance handle.
962 * Endif
963 */
964 strcpy(szModname, ODINHelperStripUNC((char*)lpszLibFile));
965 strupr(szModname);
966 dot = strchr(szModname, '.');
967 if(dot == NULL) {
968 //if there's no extension or trainling dot, we
969 //assume it's a dll (see Win32 SDK docs)
970 strcat(szModname, DLL_EXTENSION);
971 }
972 else {
973 if(dot[1] == 0) {
974 //a trailing dot means the module has no extension (SDK docs)
975 *dot = 0;
976 }
977 }
978 if (WinExe != NULL && WinExe->matchModName(szModname))
979 return WinExe->getInstanceHandle();
980
981 pModule = Win32DllBase::findModule((LPSTR)szModname);
982 if (pModule)
983 {
984 pModule->incDynamicLib();
985 pModule->AddRef();
986 dprintf(("KERNEL32: LoadLibraryExA(%s, 0x%x, 0x%x): returns 0x%x. Dll found %s",
987 szModname, hFile, dwFlags, pModule->getInstanceHandle(), pModule->getFullPath()));
988 return pModule->getInstanceHandle();
989 }
990
991
992 /** @sketch
993 * Test if lpszLibFile has a path or not.
994 * Copy the lpszLibFile to szModname, rename the dll and uppercase the name.
995 * IF it hasn't a path THEN
996 * Issue a findDll to find the dll/executable to be loaded.
997 * IF the Dll isn't found THEN
998 * Set last error and RETURN.
999 * Endif.
1000 * Endif
1001 */
1002 fPath = strchr(szModname, '\\') || strchr(szModname, '/');
1003 Win32DllBase::renameDll(szModname);
1004
1005 if (!fPath)
1006 {
1007 char szModName2[CCHMAXPATH];
1008 strcpy(szModName2, szModname);
1009 if (!Win32ImageBase::findDll(szModName2, szModname, sizeof(szModname)))
1010 {
1011 dprintf(("KERNEL32: LoadLibraryExA(%s, 0x%x, 0x%x): module wasn't found. returns NULL",
1012 lpszLibFile, hFile, dwFlags));
1013 SetLastError(ERROR_FILE_NOT_FOUND);
1014 return NULL;
1015 }
1016 }
1017
1018 //test if dll is in PE or LX format
1019 fPE = Win32ImageBase::isPEImage(szModname, &Characteristics, NULL);
1020
1021 /** @sketch
1022 * IF (fDisableLXDllLoading && (!fPeLoader || fPE == failure)) THEN
1023 * Try load the executable using LoadLibrary
1024 * IF successfully loaded THEN
1025 * Try find registered/pe2lx object.
1026 * IF callback Then
1027 * If callback give green light Then
1028 * Find registered lx object.
1029 * Else
1030 * Unload it if loaded.
1031 * Endif
1032 * Endif
1033 * IF module object found Then
1034 * IF LX dll and is using the PE Loader THEN
1035 * Set Load library.
1036 * Inc reference count.
1037 * Endif
1038 * Inc dynamic reference count.
1039 * RETURN successfully.
1040 * Else
1041 * fail.
1042 * Endif
1043 * Endif
1044 * Endif
1045 */
1046 //only call OS/2 if LX binary or win32k process
1047 if (!fDisableLXDllLoading && (!fPeLoader || fPE != ERROR_SUCCESS))
1048 {
1049 hDll = OSLibDosLoadModule(szModname);
1050 if (hDll)
1051 {
1052 /* OS/2 dll, system dll, converted dll or win32k took care of it. */
1053 pModule = Win32DllBase::findModuleByOS2Handle(hDll);
1054 /* Custombuild customizing may take care of it too. */
1055 if (pfnLxDllLoadCallback)
1056 {
1057 /* If callback says yes, continue load it, else fail. */
1058 if (pfnLxDllLoadCallback(hDll, pModule ? pModule->getInstanceHandle() : NULL))
1059 pModule = Win32DllBase::findModuleByOS2Handle(hDll);
1060 else if (pModule)
1061 {
1062 pModule->Release();
1063 pModule = NULL;
1064 }
1065 }
1066 if (pModule)
1067 {
1068 if (pModule->isLxDll())
1069 {
1070 ((Win32LxDll *)pModule)->setDllHandleOS2(hDll);
1071 if (fPeLoader && pModule->AddRef() == -1)
1072 { //-1 -> load failed (attachProcess)
1073 delete pModule;
1074 SetLastError(ERROR_INVALID_EXE_SIGNATURE);
1075 dprintf(("Dll %s refused to be loaded; aborting", szModname));
1076 return 0;
1077 }
1078
1079 }
1080 pModule->incDynamicLib();
1081 }
1082 else if (fExeStarted && !fIsOS2Image) {
1083 OSLibDosFreeModule(hDll);
1084 SetLastError(ERROR_INVALID_EXE_SIGNATURE);
1085 dprintf(("Dll %s is not an Odin dll; unload & return failure", szModname));
1086 return 0;
1087 }
1088 else {
1089 /* bird 2001-07-10:
1090 * let's fail right away instead of hitting DebugInt3s and fail other places.
1091 * This is very annoying when running Opera on a debug build with netscape/2
1092 * plugins present. We'll make this conditional for the time being.
1093 */
1094 static BOOL fFailIfUnregisteredLX = -1;
1095 if (fFailIfUnregisteredLX == -1)
1096 fFailIfUnregisteredLX = getenv("ODIN32.FAIL_IF_UNREGISTEREDLX") != NULL;
1097 if (fExeStarted && fFailIfUnregisteredLX)
1098 {
1099 dprintf(("KERNEL32: LoadLibraryExA(%s, 0x%x, 0x%x): returns 0x%x. Loaded OS/2 dll %s using DosLoadModule. returns NULL.",
1100 lpszLibFile, hFile, dwFlags, hDll, szModname));
1101 SetLastError(ERROR_INVALID_EXE_SIGNATURE);
1102 return NULL;
1103 }
1104 dprintf(("KERNEL32: LoadLibraryExA(%s, 0x%x, 0x%x): returns 0x%x. Loaded OS/2 dll %s using DosLoadModule.",
1105 lpszLibFile, hFile, dwFlags, hDll, szModname));
1106 return hDll; //happens when LoadLibrary is called in kernel32's initterm (nor harmful)
1107 }
1108 dprintf(("KERNEL32: LoadLibraryExA(%s, 0x%x, 0x%x): returns 0x%x. Loaded %s using DosLoadModule.",
1109 lpszLibFile, hFile, dwFlags, hDll, szModname));
1110 return pModule->getInstanceHandle();
1111 }
1112 dprintf(("KERNEL32: LoadLibraryExA(%s, 0x%x, 0x%x): DosLoadModule (%s) failed. LastError=%d",
1113 lpszLibFile, hFile, dwFlags, szModname, GetLastError()));
1114 }
1115 else
1116 hDll = NULL;
1117
1118
1119 /** @sketch
1120 * If PE image THEN
1121 * IF LOAD_LIBRARY_AS_DATAFILE or Executable THEN
1122 *
1123 *
1124 * Try load the file using the Win32PeLdrDll class.
1125 * <sketch continued further down>
1126 * Else
1127 * Set last error.
1128 * (hDll is NULL)
1129 * Endif
1130 * return hDll.
1131 */
1132 if(fPE == ERROR_SUCCESS)
1133 {
1134 Win32PeLdrDll *peldrDll;
1135
1136 //SvL: If executable -> load as data file (only resources)
1137 if(!(Characteristics & IMAGE_FILE_DLL))
1138 {
1139 dwFlags |= (LOAD_LIBRARY_AS_DATAFILE | DONT_RESOLVE_DLL_REFERENCES);
1140 }
1141
1142 peldrDll = new Win32PeLdrDll(szModname);
1143 if (peldrDll == NULL)
1144 {
1145 dprintf(("KERNEL32: LoadLibraryExA(%s, 0x%x, 0x%x): Failed to created instance of Win32PeLdrDll. returns NULL.",
1146 lpszLibFile, hFile, dwFlags));
1147 SetLastError(ERROR_NOT_ENOUGH_MEMORY);
1148 return NULL;
1149 }
1150
1151 /** @sketch
1152 * Process dwFlags
1153 */
1154 if (dwFlags & LOAD_LIBRARY_AS_DATAFILE)
1155 {
1156 dprintf(("KERNEL32: LoadLibraryExA(%s, 0x%x, 0x%x): LOAD_LIBRARY_AS_DATAFILE",
1157 lpszLibFile, hFile, dwFlags));
1158 peldrDll->setLoadAsDataFile();
1159 peldrDll->disableLibraryCalls();
1160 }
1161 if (dwFlags & DONT_RESOLVE_DLL_REFERENCES)
1162 {
1163 dprintf(("KERNEL32: LoadLibraryExA(%s, 0x%x, 0x%x): DONT_RESOLVE_DLL_REFERENCES",
1164 lpszLibFile, hFile, dwFlags));
1165 peldrDll->disableLibraryCalls();
1166 peldrDll->disableImportHandling();
1167 }
1168 if (dwFlags & LOAD_WITH_ALTERED_SEARCH_PATH)
1169 {
1170 dprintf(("KERNEL32: LoadLibraryExA(%s, 0x%x, 0x%x): Warning dwFlags LOAD_WITH_ALTERED_SEARCH_PATH is not implemented.",
1171 lpszLibFile, hFile, dwFlags));
1172 //peldrDll->setLoadWithAlteredSearchPath();
1173 }
1174
1175 /** @sketch
1176 * Initiate the peldr DLL.
1177 * IF successful init THEN
1178 * Inc dynamic ref count.
1179 * Inc ref count.
1180 * Attach to process
1181 * IF successful THEN
1182 * hDLL <- instance handle.
1183 * ELSE
1184 * set last error
1185 * delete Win32PeLdrDll instance.
1186 * Endif
1187 * ELSE
1188 * set last error
1189 * delete Win32PeLdrDll instance.
1190 * Endif.
1191 */
1192 if(peldrDll->init(0) == LDRERROR_SUCCESS)
1193 {
1194 peldrDll->AddRef();
1195 if (peldrDll->attachProcess())
1196 {
1197 hDll = peldrDll->getInstanceHandle();
1198 //Must be called *after* attachprocess, since attachprocess may also
1199 //trigger LoadLibrary calls
1200 //Those dlls must not be put in front of this dll in the dynamic
1201 //dll list; or else the unload order is wrong:
1202 //i.e. RPAP3260 loads PNRS3260 in DLL_PROCESS_ATTACH
1203 // this means that in ExitProcess, PNRS3260 needs to be removed
1204 // first since RPAP3260 depends on it
1205 peldrDll->incDynamicLib();
1206 }
1207 else
1208 {
1209 dprintf(("KERNEL32: LoadLibraryExA(%s, 0x%x, 0x%x): attachProcess call to Win32PeLdrDll instance failed. returns NULL.",
1210 lpszLibFile, hFile, dwFlags));
1211 SetLastError(ERROR_DLL_INIT_FAILED);
1212 delete peldrDll;
1213 return NULL;
1214 }
1215 }
1216 else
1217 {
1218 dprintf(("KERNEL32: LoadLibraryExA(%s, 0x%x, 0x%x): Failed to init Win32PeLdrDll instance. error=%d returns NULL.",
1219 lpszLibFile, hFile, dwFlags, peldrDll->getError()));
1220 SetLastError(ERROR_INVALID_EXE_SIGNATURE);
1221 delete peldrDll;
1222 return NULL;
1223 }
1224 }
1225 else
1226 {
1227 dprintf(("KERNEL32: LoadLibraryExA(%s, 0x%x, 0x%x) library wasn't found (%s) or isn't loadable; err %x",
1228 lpszLibFile, hFile, dwFlags, szModname, fPE));
1229 SetLastError(fPE);
1230 return NULL;
1231 }
1232
1233 return hDll;
1234}
1235
1236
1237/**
1238 * LoadLibraryExW can be used to map a DLL module into the calling process's
1239 * addressspace. It returns a handle that can be used with GetProcAddress to
1240 * get addresses of exported entry points (functions and variables).
1241 *
1242 * LoadLibraryExW can also be used to map executable (.exe) modules into the
1243 * address to access resources in the module. However, LoadLibrary can't be
1244 * used to run an executable (.exe) module.
1245 *
1246 * @returns Handle to the library which was loaded.
1247 * @param lpszLibFile Pointer to Unicode string giving the name of
1248 * the executable image (either a Dll or an Exe) which is to
1249 * be loaded.
1250 *
1251 * If no extention is specified the default .DLL extention is
1252 * appended to the name. End the filename with an '.' if the
1253 * file does not have an extention (and don't want the .DLL
1254 * appended).
1255 *
1256 * If no path is specified, this API will use the Odin32
1257 * standard search strategy to find the file. This strategy
1258 * is described in the method Win32ImageBase::findDLL.
1259 * This may be alterned by the LOAD_WITH_ALTERED_SEARCH_PATH
1260 * flag, see below.
1261 *
1262 * This API likes to have backslashes (\), but will probably
1263 * accept forward slashes too. Win32 SDK docs says that it
1264 * should not contain forward slashes.
1265 *
1266 * Win32 SDK docs adds:
1267 * "The name specified is the file name of the module and
1268 * is not related to the name stored in the library module
1269 * itself, as specified by the LIBRARY keyword in the
1270 * module-definition (.def) file."
1271 *
1272 * @param hFile Reserved. Must be 0.
1273 *
1274 * @param dwFlags Flags which specifies the taken when loading the module.
1275 * The value 0 makes it identical to LoadLibraryA/W.
1276 *
1277 * Flags:
1278 *
1279 * DONT_RESOLVE_DLL_REFERENCES
1280 * (WinNT/2K feature): Don't load imported modules and
1281 * hence don't resolve imported symbols.
1282 * DllMain isn't called either. (Which is obvious since
1283 * it may use one of the importe symbols.)
1284 *
1285 * On the other hand, if this flag is NOT set, the system
1286 * load imported modules, resolves imported symbols, calls
1287 * DllMain for process and thread init and term (if wished
1288 * by the module).
1289 *
1290 * LOAD_LIBRARY_AS_DATAFILE
1291 * If this flag is set, the module is mapped into the
1292 * address space but is not prepared for execution. Though
1293 * it's preparted for resource API. Hence, you'll use this
1294 * flag when you want to load a DLL for extracting
1295 * messages or resources from it.
1296 *
1297 * The resulting handle can be used with any Odin32 API
1298 * which operates on resources.
1299 * (WinNt/2k supports all resource APIs while Win9x don't
1300 * support the specialized resource APIs: LoadBitmap,
1301 * LoadCursor, LoadIcon, LoadImage, LoadMenu.)
1302 *
1303 * LOAD_WITH_ALTERED_SEARCH_PATH
1304 * If this flag is set and lpszLibFile specifies a path
1305 * we'll use an alternative file search strategy to find
1306 * imported modules. This stratgy is simply to use the
1307 * path of the module being loaded instead of the path
1308 * of the executable module as the first location
1309 * to search for imported modules.
1310 *
1311 * If this flag is clear, the standard Odin32 standard
1312 * search strategy. See Win32ImageBase::findDll for
1313 * further information.
1314 *
1315 * @sketch Convert Unicode name to ascii.
1316 * Call LoadLibraryExA.
1317 * Free ascii string.
1318 * return handle from LoadLibraryExA.
1319 * @status Open32 Partially Implemented.
1320 * @author Sander van Leeuwen (sandervl@xs4all.nl)
1321 * knut st. osmundsen (knut.stange.osmundsen@pmsc.no)
1322 * @remark Forwards to LoadLibraryExA.
1323 */
1324HINSTANCE WIN32API LoadLibraryExW(LPCWSTR lpszLibFile, HFILE hFile, DWORD dwFlags)
1325{
1326 char * pszAsciiLibFile;
1327 HINSTANCE hDll;
1328
1329 pszAsciiLibFile = UnicodeToAsciiString(lpszLibFile);
1330 dprintf(("KERNEL32: LoadLibraryExW(%s, 0x%x, 0x%x) --> LoadLibraryExA",
1331 pszAsciiLibFile, hFile, dwFlags));
1332 hDll = LoadLibraryExA(pszAsciiLibFile, hFile, dwFlags);
1333 dprintf(("KERNEL32: LoadLibraryExW(%s, 0x%x, 0x%x) returns 0x%x",
1334 pszAsciiLibFile, hFile, dwFlags, hDll));
1335 FreeAsciiString(pszAsciiLibFile);
1336
1337 return hDll;
1338}
1339//******************************************************************************
1340//******************************************************************************
1341HINSTANCE16 WIN32API LoadLibrary16(LPCTSTR lpszLibFile)
1342{
1343 dprintf(("ERROR: LoadLibrary16 %s, not implemented", lpszLibFile));
1344 return 0;
1345}
1346//******************************************************************************
1347//******************************************************************************
1348VOID WIN32API FreeLibrary16(HINSTANCE16 hinstance)
1349{
1350 dprintf(("ERROR: FreeLibrary16 %x, not implemented", hinstance));
1351}
1352//******************************************************************************
1353//******************************************************************************
1354FARPROC WIN32API GetProcAddress16(HMODULE hModule, LPCSTR lpszProc)
1355{
1356 dprintf(("ERROR: GetProcAddress16 %x %x, not implemented", hModule, lpszProc));
1357 return 0;
1358}
1359
1360
1361/**
1362 * Internal function which gets the commandline (string) used to start the current process.
1363 * @returns OS/2 / Windows return code
1364 * On successful return (NO_ERROR) the global variables
1365 * pszCmdLineA and pszCmdLineW are set.
1366 *
1367 * @param pszPeExe Pass in the name of the PE exe of this process. We'll
1368 * us this as exename and skip the first argument (ie. argv[1]).
1369 * If NULL we'll use the commandline from OS/2 as it is.
1370 * @status Completely implemented and tested.
1371 * @author knut st. osmundsen (knut.stange.osmundsen@mynd.no)
1372 */
1373ULONG InitCommandLine(const char *pszPeExe)
1374{
1375 PCHAR pib_pchcmd; /* PIB pointer to commandline. */
1376 CHAR szFilename[CCHMAXPATH]; /* Filename buffer used to get the exe filename in. */
1377 ULONG cch; /* Commandline string length. (including terminator) */
1378 PSZ psz; /* Temporary string pointer. */
1379 PSZ psz2; /* Temporary string pointer. */
1380 APIRET rc; /* OS/2 return code. */
1381 BOOL fQuotes; /* Flag used to remember if the exe filename should be in quotes. */
1382
1383 /** @sketch
1384 * Get commandline from the PIB.
1385 */
1386 pib_pchcmd = (PCHAR)OSLibGetPIB(PIB_PCHCMD);
1387
1388 /** @sketch
1389 * Two methods of making the commandline:
1390 * (1) The first argument is skipped and the second is used as exe filname.
1391 * This applies to PE.EXE launched processes only.
1392 * (2) No skipping. First argument is the exe filename.
1393 * This applies to all but PE.EXE launched processes.
1394 *
1395 * Note: We could do some code size optimization here. Much of the code for
1396 * the two methods are nearly identical.
1397 *
1398 */
1399 if(pszPeExe)
1400 {
1401 /** @sketch
1402 * Allocate memory for the commandline.
1403 * Build commandline:
1404 * Copy exe filename.
1405 * Add arguments.
1406 */
1407 cch = strlen(pszPeExe)+1;
1408
1409 // PH 2002-04-11
1410 // Note: intentional memory leak, pszCmdLineW will not be freed
1411 // or allocated after process startup
1412 pszCmdLineA = psz = (PSZ)malloc(cch);
1413 if (psz == NULL)
1414 {
1415 dprintf(("KERNEL32: InitCommandLine(%p): malloc(%d) failed\n", pszPeExe, cch));
1416 return ERROR_NOT_ENOUGH_MEMORY;
1417 }
1418 strcpy((char *)pszCmdLineA, pszPeExe);
1419
1420 rc = NO_ERROR;
1421 }
1422 else
1423 {
1424 /** @sketch Method (2):
1425 * First we'll have to determin the size of the commandline.
1426 *
1427 * As we don't assume that OS/2 allways puts a fully qualified EXE name
1428 * as the first string, we'll check if it's empty - and get the modulename
1429 * in that case - and allways get the fully qualified filename.
1430 */
1431 if (pib_pchcmd == NULL || pib_pchcmd[0] == '\0')
1432 {
1433 rc = OSLibDosQueryModuleName(OSLibGetPIB(PIB_HMTE), sizeof(szFilename), szFilename);
1434 if (rc != NO_ERROR)
1435 {
1436 dprintf(("KERNEL32: InitCommandLine(%p): OSLibQueryModuleName(0x%x,...) failed with rc=%d\n",
1437 pszPeExe, OSLibGetPIB(PIB_HMTE), rc));
1438 return rc;
1439 }
1440 }
1441 else
1442 {
1443 rc = OSLibDosQueryPathInfo(pib_pchcmd, FIL_QUERYFULLNAME, szFilename, sizeof(szFilename));
1444 if (rc != NO_ERROR)
1445 {
1446 dprintf(("KERNEL32: InitCommandLine(%p): (info) OSLibDosQueryPathInfo failed with rc=%d\n", pszPeExe, rc));
1447 strcpy(szFilename, pib_pchcmd);
1448 rc = NO_ERROR;
1449 }
1450 }
1451
1452 /** @sketch
1453 * We're still measuring the size of the commandline:
1454 * Check if we have to quote the exe filename.
1455 * Determin the length of the executable name including quotes and '\0'-terminator.
1456 * Count the length of the arguments. (We here count's all argument strings.)
1457 */
1458 fQuotes = strchr(szFilename, ' ') != NULL;
1459 cch = strlen(szFilename) + fQuotes*2 + 1;
1460 if (pib_pchcmd != NULL)
1461 {
1462 psz2 = pib_pchcmd + strlen(pib_pchcmd) + 1;
1463 while (*psz2 != '\0')
1464 {
1465 register int cchTmp = strlen(psz2) + 1; /* + 1 is for terminator (psz2) and space (cch). */
1466 psz2 += cchTmp;
1467 cch += cchTmp;
1468 }
1469 }
1470
1471 /** @sketch
1472 * Allocate memory for the commandline.
1473 * Build commandline:
1474 * Copy exe filename.
1475 * Add arguments.
1476 */
1477 pszCmdLineA = psz = (PSZ)malloc(cch);
1478 if (psz == NULL)
1479 {
1480 dprintf(("KERNEL32: InitCommandLine(%p): malloc(%d) failed\n", pszPeExe, cch));
1481 return ERROR_NOT_ENOUGH_MEMORY;
1482 }
1483
1484 if (fQuotes)
1485 *psz++ = '"';
1486 strcpy(psz, szFilename);
1487 psz += strlen(psz);
1488 if (fQuotes)
1489 {
1490 *psz++ = '"';
1491 *psz = '\0';
1492 }
1493
1494 if (pib_pchcmd != NULL)
1495 {
1496 psz2 = pib_pchcmd + strlen(pib_pchcmd) + 1;
1497 while (*psz2 != '\0')
1498 {
1499 register int cchTmp = strlen(psz2) + 1; /* + 1 is for terminator (psz). */
1500 *psz++ = ' '; /* add space */
1501 memcpy(psz, psz2, cchTmp);
1502 psz2 += cchTmp;
1503 psz += cchTmp - 1;
1504 }
1505 }
1506 }
1507
1508 /** @sketch
1509 * If successfully build ASCII commandline then convert it to UniCode.
1510 */
1511 if (rc == NO_ERROR)
1512 {
1513 // PH 2002-04-11
1514 // Note: intentional memory leak, pszCmdLineW will not be freed
1515 // or allocated after process startup
1516 cch = strlen(pszCmdLineA) + 1;
1517
1518 pszCmdLineW = (WCHAR*)malloc(cch * 2);
1519 if (pszCmdLineW != NULL) {
1520 //Translate from OS/2 to Windows codepage & ascii to unicode
1521 MultiByteToWideChar(CP_OEMCP, 0, pszCmdLineA, -1, (LPWSTR)pszCmdLineW, cch-1);
1522 ((LPWSTR)pszCmdLineW)[cch-1] = 0;
1523
1524 //ascii command line is still in OS/2 codepage, so convert it
1525 WideCharToMultiByte(CP_ACP, 0, pszCmdLineW, -1, (LPSTR)pszCmdLineA, cch-1, 0, NULL);
1526 ((LPSTR)pszCmdLineA)[cch-1] = 0;
1527 }
1528 else
1529 {
1530 DebugInt3();
1531 dprintf(("KERNEL32: InitCommandLine(%p): malloc(%d) failed (2)\n", pszPeExe, cch));
1532 rc = ERROR_NOT_ENOUGH_MEMORY;
1533 }
1534 }
1535
1536 return rc;
1537}
1538
1539/**
1540 * Gets the command line of the current process.
1541 * @returns On success:
1542 * Command line of the current process. One single string.
1543 * The first part of the command line string is the executable filename
1544 * of the current process. It might be in quotes if it contains spaces.
1545 * The rest of the string is arguments.
1546 *
1547 * On error:
1548 * NULL. Last error set. (does Win32 set last error this?)
1549 * @sketch IF not inited THEN
1550 * Init commandline assuming !PE.EXE
1551 * IF init failes THEN set last error.
1552 * ENDIF
1553 * return ASCII/ANSI commandline.
1554 * @status Completely implemented and tested.
1555 * @author knut st. osmundsen (knut.stange.osmundsen@mynd.no)
1556 * @remark The Ring-3 PeLdr is resposible for calling InitCommandLine before anyone
1557 * is able to call this function.
1558 */
1559LPCSTR WIN32API GetCommandLineA(VOID)
1560{
1561 /*
1562 * Check if the commandline is initiated.
1563 * If not we'll have to do it.
1564 * ASSUMES that if not inited this isn't a PE.EXE lauched process.
1565 */
1566 if (pszCmdLineA == NULL)
1567 {
1568 APIRET rc;
1569 rc = InitCommandLine(NULL);
1570 if (rc != NULL)
1571 SetLastError(rc);
1572 }
1573
1574 dprintf(("KERNEL32: GetCommandLineA: %s\n", pszCmdLineA));
1575 return pszCmdLineA;
1576}
1577
1578
1579/**
1580 * Gets the command line of the current process.
1581 * @returns On success:
1582 * Command line of the current process. One single string.
1583 * The first part of the command line string is the executable filename
1584 * of the current process. It might be in quotes if it contains spaces.
1585 * The rest of the string is arguments.
1586 *
1587 * On error:
1588 * NULL. Last error set. (does Win32 set last error this?)
1589 * @sketch IF not inited THEN
1590 * Init commandline assuming !PE.EXE
1591 * IF init failes THEN set last error.
1592 * ENDIF
1593 * return Unicode commandline.
1594 * @status Completely implemented and tested.
1595 * @author knut st. osmundsen (knut.stange.osmundsen@mynd.no)
1596 * @remark The Ring-3 PeLdr is resposible for calling InitCommandLine before anyone
1597 * is able to call this function.
1598 */
1599LPCWSTR WIN32API GetCommandLineW(void)
1600{
1601 /*
1602 * Check if the commandline is initiated.
1603 * If not we'll have to do it.
1604 * ASSUMES that if not inited this isn't a PE.EXE lauched process.
1605 */
1606 if (pszCmdLineW == NULL)
1607 {
1608 APIRET rc;
1609 rc = InitCommandLine(NULL);
1610 if (rc != NULL)
1611 SetLastError(rc);
1612 }
1613
1614 dprintf(("KERNEL32: GetCommandLineW: %ls\n", pszCmdLineW));
1615 return pszCmdLineW;
1616}
1617
1618
1619/**
1620 * GetModuleFileName gets the full path and file name for the specified module.
1621 * @returns Bytes written to the buffer (lpszPath). This count includes the
1622 * terminating '\0'.
1623 * On error 0 is returned. Last error is set.
1624 *
1625 * 2002-04-25 PH
1626 * Q - Do we set ERROR_BUFFER_OVERFLOW when cch > cchPath?
1627 * Q - Does NT really set the last error?
1628 * A > Win2k does not set LastError here, remains OK
1629 *
1630 * While GetModuleFileName does add a trailing termination zero
1631 * if there is enough room, the returned number of characters
1632 * *MUST NOT* include the zero character!
1633 * (Notes R6 Installer on Win2kSP6, verified Testcase)
1634 *
1635 * @param hModule Handle to the module you like to get the file name to.
1636 * @param lpszPath Output buffer for full path and file name.
1637 * @param cchPath Size of the lpszPath buffer.
1638 * @sketch Validate lpszPath.
1639 * Find the module object using handle.
1640 * If found Then
1641 * Get full path from module object.
1642 * If found path Then
1643 * Copy path to buffer and set the number of bytes written.
1644 * Else
1645 * IPE!
1646 * Else
1647 * Call Open32 GetModuleFileName. (kernel32 initterm needs/needed this)
1648 * Log result.
1649 * Return number of bytes written to the buffer.
1650 *
1651 * @status Completely implemented, Open32.
1652 * @author knut st. osmundsen (knut.stange.osmundsen@mynd.no)
1653 * Sander van Leeuwen (sandervl@xs4all.nl)
1654 * Patrick Haller (patrick.haller@innotek.de)
1655 * @remark - Do we still have to call Open32?
1656 */
1657DWORD WIN32API GetModuleFileNameA(HMODULE hModule, LPTSTR lpszPath, DWORD cchPath)
1658{
1659 Win32ImageBase * pMod; /* Pointer to the module object. */
1660 DWORD cch = 0; /* Length of the */
1661
1662 // PH 2002-04-24 Note:
1663 // WIN2k just crashes in NTDLL if lpszPath is invalid!
1664 if (!VALID_PSZ(lpszPath))
1665 {
1666 dprintf(("KERNEL32: GetModuleFileNameA(0x%x, 0x%x, 0x%x): invalid pointer lpszLibFile = 0x%x\n",
1667 hModule, lpszPath, cchPath, lpszPath));
1668 SetLastError(ERROR_INVALID_PARAMETER); //or maybe ERROR_ACCESS_DENIED is more appropriate?
1669 return 0;
1670 }
1671
1672 pMod = Win32ImageBase::findModule(hModule);
1673 if (pMod != NULL)
1674 {
1675 const char *pszFn = pMod->getFullPath();
1676 if (pszFn)
1677 {
1678 cch = strlen(pszFn);
1679 if (cch >= cchPath)
1680 cch = cchPath;
1681 else
1682 // if there is sufficient room for the zero termination,
1683 // write it additionally, uncounted
1684 lpszPath[cch] = '\0';
1685
1686 memcpy(lpszPath, pszFn, cch);
1687 }
1688 else
1689 {
1690 dprintf(("KERNEL32: GetModuleFileNameA(%x,...): IPE - getFullPath returned NULL or empty string\n"));
1691 DebugInt3();
1692 SetLastError(ERROR_INVALID_HANDLE);
1693 }
1694 }
1695 else
1696 {
1697 SetLastError(ERROR_INVALID_HANDLE);
1698 //only needed for call inside kernel32's initterm (profile init)
1699 //(console init only it seems...)
1700 cch = OSLibDosGetModuleFileName(hModule, lpszPath, cchPath);
1701 }
1702
1703 if (cch > 0)
1704 dprintf(("KERNEL32: GetModuleFileNameA(%x %x): %s %d\n", hModule, lpszPath, lpszPath, cch));
1705 else
1706 dprintf(("KERNEL32: WARNING: GetModuleFileNameA(%x,...) - not found!", hModule));
1707
1708 return cch;
1709}
1710
1711
1712/**
1713 * GetModuleFileName gets the full path and file name for the specified module.
1714 * @returns Bytes written to the buffer (lpszPath). This count includes the
1715 * terminating '\0'.
1716 * On error 0 is returned. Last error is set.
1717 * @param hModule Handle to the module you like to get the file name to.
1718 * @param lpszPath Output buffer for full path and file name.
1719 * @param cchPath Size of the lpszPath buffer.
1720 * @sketch Find the module object using handle.
1721 * If found Then
1722 * get full path from module object.
1723 * If found path Then
1724 * Determin path length.
1725 * Translate the path to into the buffer.
1726 * Else
1727 * IPE.
1728 * else
1729 * SetLastError to invalid handle.
1730 * Log result.
1731 * return number of bytes written to the buffer.
1732 *
1733 * @status Completely implemented.
1734 * @author knut st. osmundsen (knut.stange.osmundsen@mynd.no)
1735 * @remark - We do _NOT_ call Open32.
1736 * - Do we set ERROR_BUFFER_OVERFLOW when cch > cchPath?
1737 * - Does NT really set the last error?
1738 */
1739DWORD WIN32API GetModuleFileNameW(HMODULE hModule, LPWSTR lpszPath, DWORD cchPath)
1740{
1741 Win32ImageBase * pMod;
1742 DWORD cch = 0;
1743
1744 if (!VALID_PSZ(lpszPath))
1745 {
1746 dprintf(("KERNEL32: GetModuleFileNameW(0x%x, 0x%x, 0x%x): invalid pointer lpszLibFile = 0x%x\n",
1747 hModule, lpszPath, cchPath, lpszPath));
1748 SetLastError(ERROR_INVALID_PARAMETER); //or maybe ERROR_ACCESS_DENIED is more appropriate?
1749 return 0;
1750 }
1751
1752 pMod = Win32ImageBase::findModule(hModule);
1753 if (pMod != NULL)
1754 {
1755 const char *pszFn = pMod->getFullPath();
1756 if (pszFn || *pszFn != '\0')
1757 {
1758 cch = strlen(pszFn) + 1;
1759 if (cch > cchPath)
1760 cch = cchPath;
1761 AsciiToUnicodeN(pszFn, lpszPath, cch);
1762 }
1763 else
1764 {
1765 dprintf(("KERNEL32: GetModuleFileNameW(%x,...): IPE - getFullPath returned NULL or empty string\n"));
1766 DebugInt3();
1767 SetLastError(ERROR_INVALID_HANDLE);
1768 }
1769 }
1770 else
1771 SetLastError(ERROR_INVALID_HANDLE);
1772
1773 if (cch > 0)
1774 dprintf(("KERNEL32: GetModuleFileNameW(%x,...): %s %d\n", hModule, lpszPath, cch));
1775 else
1776 dprintf(("KERNEL32: WARNING: GetModuleFileNameW(%x,...) - not found!", hModule));
1777
1778 return cch;
1779}
1780
1781
1782//******************************************************************************
1783//NOTE: GetModuleHandleA does NOT support files with multiple dots (i.e.
1784// very.weird.exe)
1785//
1786// hinst = LoadLibrary("WINSPOOL.DRV"); -> succeeds
1787// hinst2 = GetModuleHandle("WINSPOOL.DRV"); -> succeeds
1788// hinst3 = GetModuleHandle("WINSPOOL."); -> fails
1789// hinst4 = GetModuleHandle("WINSPOOL"); -> fails
1790// hinst = LoadLibrary("KERNEL32.DLL"); -> succeeds
1791// hinst2 = GetModuleHandle("KERNEL32.DLL"); -> succeeds
1792// hinst3 = GetModuleHandle("KERNEL32."); -> fails
1793// hinst4 = GetModuleHandle("KERNEL32"); -> succeeds
1794// Same behaviour as observed in NT4, SP6
1795//******************************************************************************
1796HANDLE WIN32API GetModuleHandleA(LPCTSTR lpszModule)
1797{
1798 HANDLE hMod = 0;
1799 Win32DllBase *windll;
1800 char szModule[CCHMAXPATH];
1801 char *dot;
1802
1803 if(lpszModule == NULL)
1804 {
1805 if(WinExe)
1806 hMod = WinExe->getInstanceHandle();
1807 else
1808 {
1809 // // Just fail this API
1810 // hMod = 0;
1811 // SetLastError(ERROR_INVALID_HANDLE);
1812 // Wrong: in an ODIN32-LX environment, just
1813 // assume a fake handle
1814 hMod = -1;
1815 }
1816 }
1817 else
1818 {
1819 strcpy(szModule, OSLibStripPath((char *)lpszModule));
1820 strupr(szModule);
1821 dot = strchr(szModule, '.');
1822 if(dot == NULL) {
1823 //if no extension -> add .DLL (see SDK docs)
1824 strcat(szModule, DLL_EXTENSION);
1825 }
1826 else {
1827 if(dot[1] == 0) {
1828 //a trailing dot means the module has no extension (SDK docs)
1829 *dot = 0;
1830 }
1831 }
1832 if(WinExe && WinExe->matchModName(szModule)) {
1833 hMod = WinExe->getInstanceHandle();
1834 }
1835 else {
1836 windll = Win32DllBase::findModule(szModule);
1837 if(windll) {
1838 hMod = windll->getInstanceHandle();
1839 }
1840 }
1841 }
1842 dprintf(("KERNEL32: GetModuleHandle %s returned %X\n", lpszModule, hMod));
1843 return(hMod);
1844}
1845//******************************************************************************
1846//******************************************************************************
1847HMODULE WIN32API GetModuleHandleW(LPCWSTR lpwszModuleName)
1848{
1849 HMODULE rc;
1850 char *astring = NULL;
1851
1852 if (NULL != lpwszModuleName)
1853 astring = UnicodeToAsciiString((LPWSTR)lpwszModuleName);
1854
1855 rc = GetModuleHandleA(astring);
1856 dprintf(("KERNEL32: OS2GetModuleHandleW %s returned %X\n", astring, rc));
1857
1858 if (NULL != astring)
1859 FreeAsciiString(astring);
1860
1861 return(rc);
1862}
1863//******************************************************************************
1864//Checks whether program is LX or PE
1865//******************************************************************************
1866BOOL WIN32API ODIN_IsWin32App(LPSTR lpszProgramPath)
1867{
1868 DWORD Characteristics;
1869
1870 return Win32ImageBase::isPEImage(lpszProgramPath, &Characteristics, NULL) == NO_ERROR;
1871}
1872//******************************************************************************
1873//******************************************************************************
1874static char szPECmdLoader[260] = "";
1875static char szPEGUILoader[260] = "";
1876static char szNELoader[260] = "";
1877//******************************************************************************
1878//Set default paths for PE & NE loaders
1879//******************************************************************************
1880BOOL InitLoaders()
1881{
1882 sprintf(szPECmdLoader, "%s\\PEC.EXE", InternalGetSystemDirectoryA());
1883 sprintf(szPEGUILoader, "%s\\PE.EXE", InternalGetSystemDirectoryA());
1884 sprintf(szNELoader, "%s\\W16ODIN.EXE", InternalGetSystemDirectoryA());
1885
1886 return TRUE;
1887}
1888//******************************************************************************
1889//Override loader names (PEC, PE, W16ODIN)
1890//******************************************************************************
1891BOOL WIN32API ODIN_SetLoaders(LPCSTR pszPECmdLoader, LPCSTR pszPEGUILoader,
1892 LPCSTR pszNELoader)
1893{
1894 if(pszPECmdLoader) dprintf(("PE Cmd %s", pszPECmdLoader));
1895 if(pszPEGUILoader) dprintf(("PE GUI %s", pszPEGUILoader));
1896 if(pszNELoader) dprintf(("NE %s", pszNELoader));
1897 if(pszPECmdLoader) strcpy(szPECmdLoader, pszPECmdLoader);
1898 if(pszPEGUILoader) strcpy(szPEGUILoader, pszPEGUILoader);
1899 if(pszNELoader) strcpy(szNELoader, pszNELoader);
1900
1901 return TRUE;
1902}
1903//******************************************************************************
1904//******************************************************************************
1905BOOL WIN32API ODIN_QueryLoaders(LPSTR pszPECmdLoader, INT cchPECmdLoader,
1906 LPSTR pszPEGUILoader, INT cchPEGUILoader,
1907 LPSTR pszNELoader, INT cchNELoader)
1908{
1909 if(pszPECmdLoader) strncpy(pszPECmdLoader, szPECmdLoader, cchPECmdLoader);
1910 if(pszPEGUILoader) strncpy(pszPEGUILoader, szPEGUILoader, cchPEGUILoader);
1911 if(pszNELoader) strncpy(pszNELoader, szNELoader, cchNELoader);
1912
1913 return TRUE;
1914}
1915//******************************************************************************
1916//******************************************************************************
1917BOOL WINAPI CreateProcessA( LPCSTR lpApplicationName, LPSTR lpCommandLine,
1918 LPSECURITY_ATTRIBUTES lpProcessAttributes,
1919 LPSECURITY_ATTRIBUTES lpThreadAttributes,
1920 BOOL bInheritHandles, DWORD dwCreationFlags,
1921 LPVOID lpEnvironment, LPCSTR lpCurrentDirectory,
1922 LPSTARTUPINFOA lpStartupInfo,
1923 LPPROCESS_INFORMATION lpProcessInfo )
1924{
1925 STARTUPINFOA startinfo;
1926 TEB *pThreadDB = (TEB*)GetThreadTEB();
1927 char *cmdline = NULL, *newenv = NULL, *oldlibpath = NULL;
1928 BOOL rc;
1929
1930 dprintf(("KERNEL32: CreateProcessA %s cline:%s inherit:%d cFlags:%x Env:%x CurDir:%s StartupFlags:%x\n",
1931 lpApplicationName, lpCommandLine, bInheritHandles, dwCreationFlags,
1932 lpEnvironment, lpCurrentDirectory, lpStartupInfo));
1933
1934#ifdef DEBUG
1935 if(lpStartupInfo) {
1936 dprintf(("lpStartupInfo->lpReserved %x", lpStartupInfo->lpReserved));
1937 dprintf(("lpStartupInfo->lpDesktop %x", lpStartupInfo->lpDesktop));
1938 dprintf(("lpStartupInfo->lpTitle %s", lpStartupInfo->lpTitle));
1939 dprintf(("lpStartupInfo->dwX %x", lpStartupInfo->dwX));
1940 dprintf(("lpStartupInfo->dwY %x", lpStartupInfo->dwY));
1941 dprintf(("lpStartupInfo->dwXSize %x", lpStartupInfo->dwXSize));
1942 dprintf(("lpStartupInfo->dwYSize %x", lpStartupInfo->dwYSize));
1943 dprintf(("lpStartupInfo->dwXCountChars %x", lpStartupInfo->dwXCountChars));
1944 dprintf(("lpStartupInfo->dwYCountChars %x", lpStartupInfo->dwYCountChars));
1945 dprintf(("lpStartupInfo->dwFillAttribute %x", lpStartupInfo->dwFillAttribute));
1946 dprintf(("lpStartupInfo->dwFlags %x", lpStartupInfo->dwFlags));
1947 dprintf(("lpStartupInfo->wShowWindow %x", lpStartupInfo->wShowWindow));
1948 dprintf(("lpStartupInfo->hStdInput %x", lpStartupInfo->hStdInput));
1949 dprintf(("lpStartupInfo->hStdOutput %x", lpStartupInfo->hStdOutput));
1950 dprintf(("lpStartupInfo->hStdError %x", lpStartupInfo->hStdError));
1951 }
1952#endif
1953
1954 if(bInheritHandles && lpStartupInfo->dwFlags & STARTF_USESTDHANDLES)
1955 {
1956 //Translate standard handles if the child needs to inherit them
1957 int retcode = 0;
1958
1959 memcpy(&startinfo, lpStartupInfo, sizeof(startinfo));
1960 if(lpStartupInfo->hStdInput) {
1961 retcode |= HMHandleTranslateToOS2(lpStartupInfo->hStdInput, &startinfo.hStdInput);
1962 }
1963 if(lpStartupInfo->hStdOutput) {
1964 retcode |= HMHandleTranslateToOS2(lpStartupInfo->hStdOutput, &startinfo.hStdOutput);
1965 }
1966 if(lpStartupInfo->hStdError) {
1967 retcode |= HMHandleTranslateToOS2(lpStartupInfo->hStdError, &startinfo.hStdError);
1968 }
1969
1970 if(retcode) {
1971 SetLastError(ERROR_INVALID_HANDLE);
1972 rc = FALSE;
1973 goto finished;
1974 }
1975
1976 lpStartupInfo = &startinfo;
1977 }
1978
1979 if(lpApplicationName) {
1980 if(lpCommandLine) {
1981 //skip exe name in lpCommandLine
1982 //TODO: doesn't work for directories with spaces!
1983 while(*lpCommandLine != 0 && *lpCommandLine != ' ')
1984 lpCommandLine++;
1985
1986 if(*lpCommandLine != 0) {
1987 lpCommandLine++;
1988 }
1989 cmdline = (char *)malloc(strlen(lpApplicationName)+strlen(lpCommandLine) + 16);
1990 sprintf(cmdline, "%s %s", lpApplicationName, lpCommandLine);
1991 }
1992 else {
1993 cmdline = (char *)malloc(strlen(lpApplicationName) + 16);
1994 sprintf(cmdline, "%s", lpApplicationName);
1995 }
1996 }
1997 else {
1998 cmdline = (char *)malloc(strlen(lpCommandLine) + 16);
1999 sprintf(cmdline, "%s", lpCommandLine);
2000 }
2001
2002 char szAppName[MAX_PATH];
2003 char buffer[MAX_PATH];
2004 DWORD fileAttr;
2005 char *exename;
2006
2007 szAppName[0] = 0;
2008
2009 exename = buffer;
2010 strncpy(buffer, cmdline, sizeof(buffer));
2011 buffer[MAX_PATH-1] = 0;
2012 if(*exename == '"') {
2013 exename++;
2014 while(*exename != 0 && *exename != '"')
2015 exename++;
2016
2017 if(*exename != 0) {
2018 *exename = 0;
2019 }
2020 exename++;
2021 if (SearchPathA( NULL, &buffer[1], ".exe", sizeof(szAppName), szAppName, NULL ) ||
2022 SearchPathA( NULL, &buffer[1], NULL, sizeof(szAppName), szAppName, NULL ))
2023 {
2024 //
2025 }
2026 }
2027 else {
2028 BOOL fTerminate = FALSE;
2029 DWORD fileAttr;
2030
2031 while(*exename != 0) {
2032 while(*exename != 0 && *exename != ' ')
2033 exename++;
2034
2035 if(*exename != 0) {
2036 *exename = 0;
2037 fTerminate = TRUE;
2038 }
2039 dprintf(("Trying '%s'", buffer ));
2040 if (SearchPathA( NULL, buffer, ".exe", sizeof(szAppName), szAppName, NULL ) ||
2041 SearchPathA( NULL, buffer, NULL, sizeof(szAppName), szAppName, NULL ))
2042 {
2043 if(fTerminate) exename++;
2044 break;
2045 }
2046 else
2047 {//maybe it's a short name
2048 if(GetLongPathNameA(buffer, szAppName, sizeof(szAppName)))
2049 {
2050 if(fTerminate) exename++;
2051 break;
2052 }
2053 }
2054 if(fTerminate) {
2055 *exename = ' ';
2056 exename++;
2057 fTerminate = FALSE;
2058 }
2059 }
2060 }
2061 lpCommandLine = cmdline + (exename - buffer); //start of command line parameters
2062
2063 fileAttr = GetFileAttributesA(szAppName);
2064 if(fileAttr == -1 || (fileAttr & FILE_ATTRIBUTE_DIRECTORY)) {
2065 dprintf(("CreateProcess: can't find executable!"));
2066
2067 SetLastError(ERROR_FILE_NOT_FOUND);
2068
2069 rc = FALSE;
2070 goto finished;
2071 }
2072
2073 if(lpEnvironment) {
2074 newenv = CreateNewEnvironment((char *)lpEnvironment);
2075 if(newenv == NULL) {
2076 SetLastError(ERROR_NOT_ENOUGH_MEMORY);
2077 rc = FALSE;
2078 goto finished;
2079 }
2080 lpEnvironment = newenv;
2081 }
2082
2083 DWORD Characteristics, SubSystem, fNEExe, fPEExe;
2084
2085 fPEExe = Win32ImageBase::isPEImage(szAppName, &Characteristics, &SubSystem, &fNEExe) == 0;
2086
2087 // open32 does not support DEBUG_ONLY_THIS_PROCESS
2088 if(dwCreationFlags & DEBUG_ONLY_THIS_PROCESS)
2089 dwCreationFlags |= DEBUG_PROCESS;
2090
2091 //Only use WGSS to launch the app if it's not PE or PE & win32k loaded
2092 if(!fPEExe || (fPEExe && fWin32k))
2093 {
2094
2095 trylaunchagain:
2096 if(O32_CreateProcess(szAppName, lpCommandLine, lpProcessAttributes,
2097 lpThreadAttributes, bInheritHandles, dwCreationFlags,
2098 lpEnvironment, lpCurrentDirectory, lpStartupInfo,
2099 lpProcessInfo) == TRUE)
2100 {
2101 if (dwCreationFlags & DEBUG_PROCESS && pThreadDB != NULL)
2102 {
2103 if(pThreadDB->o.odin.pidDebuggee != 0)
2104 {
2105 // TODO: handle this
2106 dprintf(("KERNEL32: CreateProcess ERROR: This thread is already a debugger\n"));
2107 }
2108 else
2109 {
2110 pThreadDB->o.odin.pidDebuggee = lpProcessInfo->dwProcessId;
2111 OSLibStartDebugger((ULONG*)&pThreadDB->o.odin.pidDebuggee);
2112 }
2113 }
2114 else pThreadDB->o.odin.pidDebuggee = 0;
2115
2116 if(lpProcessInfo)
2117 {
2118 lpProcessInfo->dwThreadId = MAKE_THREADID(lpProcessInfo->dwProcessId, lpProcessInfo->dwThreadId);
2119 }
2120
2121 rc = TRUE;
2122 goto finished;
2123 }
2124 else
2125 if(!oldlibpath)
2126 {//might have failed because it wants to load dlls in its current directory
2127 // Add the application directory to the ENDLIBPATH, so dlls can be found there
2128 // Only necessary for OS/2 applications
2129 oldlibpath = (char *)calloc(4096, 1);
2130 if(oldlibpath)
2131 {
2132 OSLibQueryBeginLibpath(oldlibpath, 4096);
2133
2134 char *tmp = strrchr(szAppName, '\\');
2135 if(tmp) *tmp = 0;
2136
2137 OSLibSetBeginLibpath(szAppName);
2138 if(tmp) *tmp = '\\';
2139
2140 goto trylaunchagain;
2141 }
2142
2143 }
2144 // verify why O32_CreateProcess actually failed.
2145 // If GetLastError() == 191 (ERROR_INVALID_EXE_SIGNATURE)
2146 // we can continue to call "PE.EXE".
2147 // Note: Open32 does not translate ERROR_INVALID_EXE_SIGNATURE,
2148 // it is also valid in Win32.
2149 DWORD dwError = GetLastError();
2150 if (ERROR_INVALID_EXE_SIGNATURE != dwError && ERROR_FILE_NOT_FOUND != dwError && ERROR_ACCESS_DENIED != dwError)
2151 {
2152 dprintf(("CreateProcess: O32_CreateProcess failed with rc=%d, not PE-executable !", dwError));
2153
2154 // the current value of GetLastError() is still valid.
2155 rc = FALSE;
2156 goto finished;
2157 }
2158 }
2159
2160 // else ...
2161
2162 //probably a win32 exe, so run it in the pe loader
2163 dprintf(("KERNEL32: CreateProcess %s %s", szAppName, lpCommandLine));
2164
2165 if(fPEExe)
2166 {
2167 LPCSTR lpszExecutable;
2168 int iNewCommandLineLength;
2169
2170 // calculate base length for the new command line
2171 iNewCommandLineLength = strlen(szAppName) + strlen(lpCommandLine);
2172
2173 if(SubSystem == IMAGE_SUBSYSTEM_WINDOWS_CUI)
2174 lpszExecutable = szPECmdLoader;
2175 else
2176 lpszExecutable = szPEGUILoader;
2177
2178 // 2002-04-24 PH
2179 // set the ODIN32.DEBUG_CHILD environment variable to start new PE processes
2180 // under a new instance of the (IPMD) debugger.
2181 const char *pszDebugChildArg = "";
2182#ifdef DEBUG
2183 char szDebugChild[512];
2184 const char *pszChildDebugger = getenv("ODIN32.DEBUG_CHILD");
2185 if (pszChildDebugger)
2186 {
2187 /*
2188 * Change the executable to the debugger (icsdebug.exe) and
2189 * move the previous executable onto the commandline.
2190 */
2191 szDebugChild[0] = ' ';
2192 strcpy(&szDebugChild[1], lpszExecutable);
2193 iNewCommandLineLength += strlen(&szDebugChild[0]);
2194
2195 pszDebugChildArg = &szDebugChild[0];
2196 lpszExecutable = pszChildDebugger;
2197 }
2198#endif
2199
2200 //SvL: Allright. Before we call O32_CreateProcess, we must take care of
2201 // lpCurrentDirectory ourselves. (Open32 ignores it!)
2202 if(lpCurrentDirectory) {
2203 char *newcmdline;
2204
2205 newcmdline = (char *)malloc(strlen(lpCurrentDirectory) + iNewCommandLineLength + 64);
2206 sprintf(newcmdline, "%s /OPT:[CURDIR=%s] %s %s", pszDebugChildArg, lpCurrentDirectory, szAppName, lpCommandLine);
2207 free(cmdline);
2208 cmdline = newcmdline;
2209 }
2210 else {
2211 char *newcmdline;
2212
2213 newcmdline = (char *)malloc(iNewCommandLineLength + 16);
2214 sprintf(newcmdline, "%s %s %s", pszDebugChildArg, szAppName, lpCommandLine);
2215 free(cmdline);
2216 cmdline = newcmdline;
2217 }
2218
2219 dprintf(("KERNEL32: CreateProcess starting [%s],[%s]",
2220 lpszExecutable,
2221 cmdline));
2222
2223 rc = O32_CreateProcess(lpszExecutable, (LPCSTR)cmdline,lpProcessAttributes,
2224 lpThreadAttributes, bInheritHandles, dwCreationFlags,
2225 lpEnvironment, lpCurrentDirectory, lpStartupInfo,
2226 lpProcessInfo);
2227 }
2228 else
2229 if(fNEExe) {//16 bits windows app
2230 char *newcmdline;
2231
2232 newcmdline = (char *)malloc(strlen(szAppName) + strlen(cmdline) + strlen(szPEGUILoader) + strlen(lpCommandLine) + 32);
2233
2234 sprintf(newcmdline, " /PELDR=[%s] %s", szPEGUILoader, szAppName, lpCommandLine);
2235 free(cmdline);
2236 cmdline = newcmdline;
2237 //Force Open32 to use DosStartSession (DosExecPgm won't do)
2238 dwCreationFlags |= CREATE_NEW_PROCESS_GROUP;
2239
2240 dprintf(("KERNEL32: CreateProcess starting [%s],[%s]",
2241 szNELoader,
2242 cmdline));
2243 rc = O32_CreateProcess(szNELoader, (LPCSTR)cmdline, lpProcessAttributes,
2244 lpThreadAttributes, bInheritHandles, dwCreationFlags,
2245 lpEnvironment, lpCurrentDirectory, lpStartupInfo,
2246 lpProcessInfo);
2247 }
2248 else {//os/2 app??
2249 rc = O32_CreateProcess(szAppName, (LPCSTR)lpCommandLine, lpProcessAttributes,
2250 lpThreadAttributes, bInheritHandles, dwCreationFlags,
2251 lpEnvironment, lpCurrentDirectory, lpStartupInfo,
2252 lpProcessInfo);
2253 }
2254 if(!lpEnvironment) {
2255 // Restore old ENDLIBPATH variable
2256 // TODO:
2257 }
2258
2259 if(rc == TRUE)
2260 {
2261 if (dwCreationFlags & DEBUG_PROCESS && pThreadDB != NULL)
2262 {
2263 if(pThreadDB->o.odin.pidDebuggee != 0)
2264 {
2265 // TODO: handle this
2266 dprintf(("KERNEL32: CreateProcess ERROR: This thread is already a debugger\n"));
2267 }
2268 else
2269 {
2270 pThreadDB->o.odin.pidDebuggee = lpProcessInfo->dwProcessId;
2271 OSLibStartDebugger((ULONG*)&pThreadDB->o.odin.pidDebuggee);
2272 }
2273 }
2274 else
2275 pThreadDB->o.odin.pidDebuggee = 0;
2276 }
2277 if(lpProcessInfo)
2278 {
2279 lpProcessInfo->dwThreadId = MAKE_THREADID(lpProcessInfo->dwProcessId, lpProcessInfo->dwThreadId);
2280 dprintf(("KERNEL32: CreateProcess returned %d hPro:%x hThr:%x pid:%x tid:%x\n",
2281 rc, lpProcessInfo->hProcess, lpProcessInfo->hThread,
2282 lpProcessInfo->dwProcessId,lpProcessInfo->dwThreadId));
2283 }
2284 else
2285 dprintf(("KERNEL32: CreateProcess returned %d\n", rc));
2286
2287finished:
2288
2289 if(oldlibpath) {
2290 OSLibSetBeginLibpath(oldlibpath);
2291 free(oldlibpath);
2292 }
2293 if(cmdline) free(cmdline);
2294 if(newenv) free(newenv);
2295 return(rc);
2296}
2297//******************************************************************************
2298//******************************************************************************
2299BOOL WIN32API CreateProcessW(LPCWSTR lpApplicationName, LPWSTR lpCommandLine,
2300 PSECURITY_ATTRIBUTES lpProcessAttributes,
2301 PSECURITY_ATTRIBUTES lpThreadAttributes,
2302 BOOL bInheritHandles, DWORD dwCreationFlags,
2303 LPVOID lpEnvironment,
2304 LPCWSTR lpCurrentDirectory, LPSTARTUPINFOW lpStartupInfo,
2305 LPPROCESS_INFORMATION lpProcessInfo)
2306{
2307 BOOL rc;
2308 char *astring1 = 0, *astring2 = 0, *astring3 = 0;
2309
2310 dprintf(("KERNEL32: CreateProcessW"));
2311 if(lpApplicationName)
2312 astring1 = UnicodeToAsciiString((LPWSTR)lpApplicationName);
2313 if(lpCommandLine)
2314 astring2 = UnicodeToAsciiString(lpCommandLine);
2315 if(lpCurrentDirectory)
2316 astring3 = UnicodeToAsciiString((LPWSTR)lpCurrentDirectory);
2317 rc = CreateProcessA(astring1, astring2, lpProcessAttributes, lpThreadAttributes,
2318 bInheritHandles, dwCreationFlags, lpEnvironment,
2319 astring3, (LPSTARTUPINFOA)lpStartupInfo,
2320 lpProcessInfo);
2321 if(astring3) FreeAsciiString(astring3);
2322 if(astring2) FreeAsciiString(astring2);
2323 if(astring1) FreeAsciiString(astring1);
2324 return(rc);
2325}
2326//******************************************************************************
2327//******************************************************************************
2328HINSTANCE WIN32API WinExec(LPCSTR lpCmdLine, UINT nCmdShow)
2329{
2330 STARTUPINFOA startinfo = {0};
2331 PROCESS_INFORMATION procinfo;
2332 DWORD rc;
2333 HINSTANCE hInstance;
2334
2335 dprintf(("KERNEL32: WinExec lpCmdLine='%s' nCmdShow=%d\n", lpCmdLine));
2336 startinfo.cb = sizeof(startinfo);
2337 startinfo.dwFlags = STARTF_USESHOWWINDOW;
2338 startinfo.wShowWindow = nCmdShow;
2339 if(CreateProcessA(NULL, (LPSTR)lpCmdLine, NULL, NULL, FALSE, 0, NULL, NULL,
2340 &startinfo, &procinfo) == FALSE)
2341 {
2342 hInstance = (HINSTANCE)GetLastError();
2343 if(hInstance >= 32) {
2344 hInstance = 11;
2345 }
2346 dprintf(("KERNEL32: WinExec failed with rc %d", hInstance));
2347 return hInstance;
2348 }
2349 //block until the launched app waits for input (or a timeout of 15 seconds)
2350 //TODO: Shouldn't call Open32, but the api in user32..
2351 if(fVersionWarp3) {
2352 Sleep(1000); //WaitForInputIdle not available in Warp 3
2353 }
2354 else {
2355 dprintf(("Calling WaitForInputIdle %x %d", procinfo.hProcess, 15000));
2356 rc = WaitForInputIdle(procinfo.hProcess, 15000);
2357#ifdef DEBUG
2358 if(rc != 0) {
2359 dprintf(("WinExec: WaitForInputIdle %x returned %x", procinfo.hProcess, rc));
2360 }
2361 else dprintf(("WinExec: WaitForInputIdle successfull"));
2362#endif
2363 }
2364 CloseHandle(procinfo.hThread);
2365 CloseHandle(procinfo.hProcess);
2366 return 33;
2367}
2368//******************************************************************************
2369//******************************************************************************
2370DWORD WIN32API WaitForInputIdle(HANDLE hProcess, DWORD dwTimeOut)
2371{
2372 dprintf(("USER32: WaitForInputIdle %x %d\n", hProcess, dwTimeOut));
2373
2374 if(fVersionWarp3) {
2375 Sleep(1000);
2376 return 0;
2377 }
2378 else return O32_WaitForInputIdle(hProcess, dwTimeOut);
2379}
2380/**********************************************************************
2381 * LoadModule (KERNEL32.499)
2382 *
2383 * Wine: 20000909
2384 *
2385 * Copyright 1995 Alexandre Julliard
2386 */
2387HINSTANCE WINAPI LoadModule( LPCSTR name, LPVOID paramBlock )
2388{
2389 LOADPARAMS *params = (LOADPARAMS *)paramBlock;
2390 PROCESS_INFORMATION info;
2391 STARTUPINFOA startup;
2392 HINSTANCE hInstance;
2393 LPSTR cmdline, p;
2394 char filename[MAX_PATH];
2395 BYTE len;
2396
2397 dprintf(("LoadModule %s %x", name, paramBlock));
2398
2399 if (!name) return ERROR_FILE_NOT_FOUND;
2400
2401 if (!SearchPathA( NULL, name, ".exe", sizeof(filename), filename, NULL ) &&
2402 !SearchPathA( NULL, name, NULL, sizeof(filename), filename, NULL ))
2403 return GetLastError();
2404
2405 len = (BYTE)params->lpCmdLine[0];
2406 if (!(cmdline = (LPSTR)HeapAlloc( GetProcessHeap(), 0, strlen(filename) + len + 2 )))
2407 return ERROR_NOT_ENOUGH_MEMORY;
2408
2409 strcpy( cmdline, filename );
2410 p = cmdline + strlen(cmdline);
2411 *p++ = ' ';
2412 memcpy( p, params->lpCmdLine + 1, len );
2413 p[len] = 0;
2414
2415 memset( &startup, 0, sizeof(startup) );
2416 startup.cb = sizeof(startup);
2417 if (params->lpCmdShow)
2418 {
2419 startup.dwFlags = STARTF_USESHOWWINDOW;
2420 startup.wShowWindow = params->lpCmdShow[1];
2421 }
2422
2423 if (CreateProcessA( filename, cmdline, NULL, NULL, FALSE, 0,
2424 params->lpEnvAddress, NULL, &startup, &info ))
2425 {
2426 /* Give 15 seconds to the app to come up */
2427 if ( WaitForInputIdle ( info.hProcess, 15000 ) == 0xFFFFFFFF )
2428 dprintf(("ERROR: WaitForInputIdle failed: Error %ld\n", GetLastError() ));
2429 hInstance = 33;
2430 /* Close off the handles */
2431 CloseHandle( info.hThread );
2432 CloseHandle( info.hProcess );
2433 }
2434 else if ((hInstance = GetLastError()) >= 32)
2435 {
2436 dprintf(("ERROR: Strange error set by CreateProcess: %d\n", hInstance ));
2437 hInstance = 11;
2438 }
2439
2440 HeapFree( GetProcessHeap(), 0, cmdline );
2441 return hInstance;
2442}
2443//******************************************************************************
2444//******************************************************************************
2445FARPROC WIN32API GetProcAddress(HMODULE hModule, LPCSTR lpszProc)
2446{
2447 Win32ImageBase *winmod;
2448 FARPROC proc = 0;
2449 ULONG ulAPIOrdinal;
2450
2451 if(hModule == 0 || hModule == -1 || (WinExe && hModule == WinExe->getInstanceHandle())) {
2452 winmod = WinExe;
2453 }
2454 else winmod = (Win32ImageBase *)Win32DllBase::findModule((HINSTANCE)hModule);
2455
2456 if(winmod) {
2457 ulAPIOrdinal = (ULONG)lpszProc;
2458 if (ulAPIOrdinal <= 0x0000FFFF) {
2459 proc = (FARPROC)winmod->getApi((int)ulAPIOrdinal);
2460 }
2461 else
2462 if (lpszProc && *lpszProc) {
2463 proc = (FARPROC)winmod->getApi((char *)lpszProc);
2464 }
2465 if(proc == 0) {
2466#ifdef DEBUG
2467 if(ulAPIOrdinal <= 0x0000FFFF) {
2468 dprintf(("GetProcAddress %x %x not found!", hModule, ulAPIOrdinal));
2469 }
2470 else dprintf(("GetProcAddress %x %s not found!", hModule, lpszProc));
2471#endif
2472 SetLastError(ERROR_PROC_NOT_FOUND);
2473 return 0;
2474 }
2475 if(HIWORD(lpszProc))
2476 dprintf(("KERNEL32: GetProcAddress %s from %X returned %X\n", lpszProc, hModule, proc));
2477 else dprintf(("KERNEL32: GetProcAddress %x from %X returned %X\n", lpszProc, hModule, proc));
2478
2479 SetLastError(ERROR_SUCCESS);
2480 return proc;
2481 }
2482 proc = (FARPROC)OSLibDosGetProcAddress(hModule, lpszProc);
2483 if(HIWORD(lpszProc))
2484 dprintf(("KERNEL32: GetProcAddress %s from %X returned %X\n", lpszProc, hModule, proc));
2485 else dprintf(("KERNEL32: GetProcAddress %x from %X returned %X\n", lpszProc, hModule, proc));
2486 SetLastError(ERROR_SUCCESS);
2487 return(proc);
2488}
2489//******************************************************************************
2490// ODIN_SetProcAddress: Override a dll export
2491//
2492// Parameters:
2493// HMODULE hModule Module handle
2494// LPCSTR lpszProc Export name or ordinal
2495// FARPROC pfnNewProc New export function address
2496//
2497// Returns: Success -> old address of export
2498// Failure -> -1
2499//
2500//******************************************************************************
2501FARPROC WIN32API ODIN_SetProcAddress(HMODULE hModule, LPCSTR lpszProc,
2502 FARPROC pfnNewProc)
2503{
2504 Win32ImageBase *winmod;
2505 FARPROC proc;
2506 ULONG ulAPIOrdinal;
2507
2508 if(hModule == 0 || hModule == -1 || (WinExe && hModule == WinExe->getInstanceHandle())) {
2509 winmod = WinExe;
2510 }
2511 else winmod = (Win32ImageBase *)Win32DllBase::findModule((HINSTANCE)hModule);
2512
2513 if(winmod) {
2514 ulAPIOrdinal = (ULONG)lpszProc;
2515 if (ulAPIOrdinal <= 0x0000FFFF) {
2516 proc = (FARPROC)winmod->setApi((int)ulAPIOrdinal, (ULONG)pfnNewProc);
2517 }
2518 else proc = (FARPROC)winmod->setApi((char *)lpszProc, (ULONG)pfnNewProc);
2519 if(proc == 0) {
2520#ifdef DEBUG
2521 if(ulAPIOrdinal <= 0x0000FFFF) {
2522 dprintf(("ODIN_SetProcAddress %x %x not found!", hModule, ulAPIOrdinal));
2523 }
2524 else dprintf(("ODIN_SetProcAddress %x %s not found!", hModule, lpszProc));
2525#endif
2526 SetLastError(ERROR_PROC_NOT_FOUND);
2527 return (FARPROC)-1;
2528 }
2529 if(HIWORD(lpszProc))
2530 dprintf(("KERNEL32: ODIN_SetProcAddress %s from %X returned %X\n", lpszProc, hModule, proc));
2531 else dprintf(("KERNEL32: ODIN_SetProcAddress %x from %X returned %X\n", lpszProc, hModule, proc));
2532
2533 SetLastError(ERROR_SUCCESS);
2534 return proc;
2535 }
2536 SetLastError(ERROR_INVALID_HANDLE);
2537 return (FARPROC)-1;
2538}
2539//******************************************************************************
2540//******************************************************************************
2541UINT WIN32API GetProcModuleFileNameA(ULONG lpvAddress, LPSTR lpszFileName, UINT cchFileNameMax)
2542{
2543 LPSTR lpszModuleName;
2544 Win32ImageBase *image = NULL;
2545 int len;
2546
2547 dprintf(("GetProcModuleFileNameA %x %x %d", lpvAddress, lpszFileName, cchFileNameMax));
2548
2549 if(WinExe && WinExe->insideModule(lpvAddress) && WinExe->insideModuleCode(lpvAddress)) {
2550 image = WinExe;
2551 }
2552 else {
2553 Win32DllBase *dll = Win32DllBase::findModuleByAddr(lpvAddress);
2554 if(dll && dll->insideModuleCode(lpvAddress)) {
2555 image = dll;
2556 }
2557 }
2558 if(image == NULL) {
2559 dprintf(("GetProcModuleFileNameA: address not found!!"));
2560 return 0;
2561 }
2562 len = strlen(image->getFullPath());
2563 if(len < cchFileNameMax) {
2564 strcpy(lpszFileName, image->getFullPath());
2565 return len+1; //??
2566 }
2567 else {
2568 dprintf(("GetProcModuleFileNameA: destination string too small!!"));
2569 return 0;
2570 }
2571}
2572//******************************************************************************
2573//******************************************************************************
2574BOOL WIN32API DisableThreadLibraryCalls(HMODULE hModule)
2575{
2576 Win32DllBase *winmod;
2577 FARPROC proc;
2578 ULONG ulAPIOrdinal;
2579
2580 winmod = Win32DllBase::findModule((HINSTANCE)hModule);
2581 if(winmod)
2582 {
2583 // don't call ATTACH/DETACH thread functions in DLL
2584 winmod->disableThreadLibraryCalls();
2585 return TRUE;
2586 }
2587 else
2588 {
2589 // raise error condition
2590 SetLastError(ERROR_INVALID_HANDLE);
2591 return FALSE;
2592 }
2593}
2594//******************************************************************************
2595// Forwarder for PSAPI.DLL
2596//
2597// Returns the handles of all loaded modules
2598//
2599//******************************************************************************
2600BOOL WINAPI PSAPI_EnumProcessModules(HANDLE hProcess, HMODULE *lphModule,
2601 DWORD cb, LPDWORD lpcbNeeded)
2602{
2603 DWORD count;
2604 DWORD countMax;
2605 HMODULE hModule;
2606
2607 dprintf(("KERNEL32: EnumProcessModules %p, %ld, %p", lphModule, cb, lpcbNeeded));
2608
2609 if ( lphModule == NULL )
2610 cb = 0;
2611
2612 if ( lpcbNeeded != NULL )
2613 *lpcbNeeded = 0;
2614
2615 count = 0;
2616 countMax = cb / sizeof(HMODULE);
2617
2618 count = Win32DllBase::enumDlls(lphModule, countMax);
2619
2620 if ( lpcbNeeded != NULL )
2621 *lpcbNeeded = sizeof(HMODULE) * count;
2622
2623 return TRUE;
2624}
2625//******************************************************************************
2626// Forwarder for PSAPI.DLL
2627//
2628// Returns some information about the module identified by hModule
2629//
2630//******************************************************************************
2631BOOL WINAPI PSAPI_GetModuleInformation(HANDLE hProcess, HMODULE hModule,
2632 LPMODULEINFO lpmodinfo, DWORD cb)
2633{
2634 BOOL ret = FALSE;
2635 Win32DllBase *winmod = NULL;
2636
2637 dprintf(("KERNEL32: GetModuleInformation hModule=%x", hModule));
2638
2639 if (!lpmodinfo || cb < sizeof(MODULEINFO)) return FALSE;
2640
2641 winmod = Win32DllBase::findModule((HINSTANCE)hModule);
2642 if (!winmod) {
2643 dprintf(("GetModuleInformation failed to find module"));
2644 return FALSE;
2645 }
2646
2647 lpmodinfo->SizeOfImage = winmod->getImageSize();
2648 lpmodinfo->EntryPoint = winmod->getEntryPoint();
2649 lpmodinfo->lpBaseOfDll = (void*)hModule;
2650
2651 return TRUE;
2652}
2653//******************************************************************************
2654//******************************************************************************
2655/**
2656 * Gets the startup info which was passed to CreateProcess when
2657 * this process was created.
2658 *
2659 * @param lpStartupInfo Where to put the startup info.
2660 * Please don't change the strings :)
2661 * @status Partially Implemented.
2662 * @author knut st. osmundsen <bird@anduin.net>
2663 * @remark The three pointers of the structure is just fake.
2664 * @remark Pretty much identical to current wine code.
2665 */
2666void WIN32API GetStartupInfoA(LPSTARTUPINFOA lpStartupInfo)
2667{
2668 dprintf2(("KERNEL32: GetStartupInfoA %x\n", lpStartupInfo));
2669 *lpStartupInfo = StartupInfo;
2670}
2671
2672
2673/**
2674 * Gets the startup info which was passed to CreateProcess when
2675 * this process was created.
2676 *
2677 * @param lpStartupInfo Where to put the startup info.
2678 * Please don't change the strings :)
2679 * @status Partially Implemented.
2680 * @author knut st. osmundsen <bird@anduin.net>
2681 * @remark The three pointers of the structure is just fake.
2682 * @remark Similar to wine code, but they use RtlCreateUnicodeStringFromAsciiz
2683 * for creating the UNICODE strings and are doing so for each call.
2684 * As I don't wanna call NTDLL code from kernel32 I take the easy path.
2685 */
2686void WIN32API GetStartupInfoW(LPSTARTUPINFOW lpStartupInfo)
2687{
2688 /*
2689 * Converted once, this information shouldn't change...
2690 */
2691
2692 dprintf2(("KERNEL32: GetStartupInfoW %x\n", lpStartupInfo));
2693
2694 //assumes the structs are identical but for the strings pointed to.
2695 memcpy(lpStartupInfo, &StartupInfo, sizeof(STARTUPINFOA));
2696 lpStartupInfo->cb = sizeof(STARTUPINFOW); /* this really should be the same size else we're in for trouble.. :) */
2697
2698 /*
2699 * First time conversion only as this should be pretty static.
2700 * See remark!
2701 */
2702 static LPWSTR pwcReserved = NULL;
2703 static LPWSTR pwcDesktop = NULL;
2704 static LPWSTR pwcTitle = NULL;
2705
2706 if (lpStartupInfo->lpReserved && pwcReserved)
2707 pwcReserved = AsciiToUnicodeString((LPCSTR)lpStartupInfo->lpReserved);
2708 lpStartupInfo->lpReserved = pwcReserved;
2709
2710 if (lpStartupInfo->lpDesktop && pwcDesktop)
2711 pwcDesktop = AsciiToUnicodeString((LPCSTR)lpStartupInfo->lpDesktop);
2712 lpStartupInfo->lpDesktop = pwcDesktop;
2713
2714 if (lpStartupInfo->lpTitle && pwcTitle)
2715 pwcTitle = AsciiToUnicodeString((LPCSTR)lpStartupInfo->lpTitle);
2716 lpStartupInfo->lpTitle = pwcTitle;
2717}
2718
Note: See TracBrowser for help on using the repository browser.