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

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

LoadLibraryExA: Report the correct error code (mapped from OS/2 APIRET) when loading an LX dll fails in DosLoadModule() instead of returning an unrelated PE loader error.

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 return NULL;
1115 }
1116 else
1117 hDll = NULL;
1118
1119
1120 /** @sketch
1121 * If PE image THEN
1122 * IF LOAD_LIBRARY_AS_DATAFILE or Executable THEN
1123 *
1124 *
1125 * Try load the file using the Win32PeLdrDll class.
1126 * <sketch continued further down>
1127 * Else
1128 * Set last error.
1129 * (hDll is NULL)
1130 * Endif
1131 * return hDll.
1132 */
1133 if(fPE == ERROR_SUCCESS)
1134 {
1135 Win32PeLdrDll *peldrDll;
1136
1137 //SvL: If executable -> load as data file (only resources)
1138 if(!(Characteristics & IMAGE_FILE_DLL))
1139 {
1140 dwFlags |= (LOAD_LIBRARY_AS_DATAFILE | DONT_RESOLVE_DLL_REFERENCES);
1141 }
1142
1143 peldrDll = new Win32PeLdrDll(szModname);
1144 if (peldrDll == NULL)
1145 {
1146 dprintf(("KERNEL32: LoadLibraryExA(%s, 0x%x, 0x%x): Failed to created instance of Win32PeLdrDll. returns NULL.",
1147 lpszLibFile, hFile, dwFlags));
1148 SetLastError(ERROR_NOT_ENOUGH_MEMORY);
1149 return NULL;
1150 }
1151
1152 /** @sketch
1153 * Process dwFlags
1154 */
1155 if (dwFlags & LOAD_LIBRARY_AS_DATAFILE)
1156 {
1157 dprintf(("KERNEL32: LoadLibraryExA(%s, 0x%x, 0x%x): LOAD_LIBRARY_AS_DATAFILE",
1158 lpszLibFile, hFile, dwFlags));
1159 peldrDll->setLoadAsDataFile();
1160 peldrDll->disableLibraryCalls();
1161 }
1162 if (dwFlags & DONT_RESOLVE_DLL_REFERENCES)
1163 {
1164 dprintf(("KERNEL32: LoadLibraryExA(%s, 0x%x, 0x%x): DONT_RESOLVE_DLL_REFERENCES",
1165 lpszLibFile, hFile, dwFlags));
1166 peldrDll->disableLibraryCalls();
1167 peldrDll->disableImportHandling();
1168 }
1169 if (dwFlags & LOAD_WITH_ALTERED_SEARCH_PATH)
1170 {
1171 dprintf(("KERNEL32: LoadLibraryExA(%s, 0x%x, 0x%x): Warning dwFlags LOAD_WITH_ALTERED_SEARCH_PATH is not implemented.",
1172 lpszLibFile, hFile, dwFlags));
1173 //peldrDll->setLoadWithAlteredSearchPath();
1174 }
1175
1176 /** @sketch
1177 * Initiate the peldr DLL.
1178 * IF successful init THEN
1179 * Inc dynamic ref count.
1180 * Inc ref count.
1181 * Attach to process
1182 * IF successful THEN
1183 * hDLL <- instance handle.
1184 * ELSE
1185 * set last error
1186 * delete Win32PeLdrDll instance.
1187 * Endif
1188 * ELSE
1189 * set last error
1190 * delete Win32PeLdrDll instance.
1191 * Endif.
1192 */
1193 if(peldrDll->init(0) == LDRERROR_SUCCESS)
1194 {
1195 peldrDll->AddRef();
1196 if (peldrDll->attachProcess())
1197 {
1198 hDll = peldrDll->getInstanceHandle();
1199 //Must be called *after* attachprocess, since attachprocess may also
1200 //trigger LoadLibrary calls
1201 //Those dlls must not be put in front of this dll in the dynamic
1202 //dll list; or else the unload order is wrong:
1203 //i.e. RPAP3260 loads PNRS3260 in DLL_PROCESS_ATTACH
1204 // this means that in ExitProcess, PNRS3260 needs to be removed
1205 // first since RPAP3260 depends on it
1206 peldrDll->incDynamicLib();
1207 }
1208 else
1209 {
1210 dprintf(("KERNEL32: LoadLibraryExA(%s, 0x%x, 0x%x): attachProcess call to Win32PeLdrDll instance failed. returns NULL.",
1211 lpszLibFile, hFile, dwFlags));
1212 SetLastError(ERROR_DLL_INIT_FAILED);
1213 delete peldrDll;
1214 return NULL;
1215 }
1216 }
1217 else
1218 {
1219 dprintf(("KERNEL32: LoadLibraryExA(%s, 0x%x, 0x%x): Failed to init Win32PeLdrDll instance. error=%d returns NULL.",
1220 lpszLibFile, hFile, dwFlags, peldrDll->getError()));
1221 SetLastError(ERROR_INVALID_EXE_SIGNATURE);
1222 delete peldrDll;
1223 return NULL;
1224 }
1225 }
1226 else
1227 {
1228 dprintf(("KERNEL32: LoadLibraryExA(%s, 0x%x, 0x%x) library wasn't found (%s) or isn't loadable; err %x",
1229 lpszLibFile, hFile, dwFlags, szModname, fPE));
1230 SetLastError(fPE);
1231 return NULL;
1232 }
1233
1234 return hDll;
1235}
1236
1237
1238/**
1239 * LoadLibraryExW can be used to map a DLL module into the calling process's
1240 * addressspace. It returns a handle that can be used with GetProcAddress to
1241 * get addresses of exported entry points (functions and variables).
1242 *
1243 * LoadLibraryExW can also be used to map executable (.exe) modules into the
1244 * address to access resources in the module. However, LoadLibrary can't be
1245 * used to run an executable (.exe) module.
1246 *
1247 * @returns Handle to the library which was loaded.
1248 * @param lpszLibFile Pointer to Unicode string giving the name of
1249 * the executable image (either a Dll or an Exe) which is to
1250 * be loaded.
1251 *
1252 * If no extention is specified the default .DLL extention is
1253 * appended to the name. End the filename with an '.' if the
1254 * file does not have an extention (and don't want the .DLL
1255 * appended).
1256 *
1257 * If no path is specified, this API will use the Odin32
1258 * standard search strategy to find the file. This strategy
1259 * is described in the method Win32ImageBase::findDLL.
1260 * This may be alterned by the LOAD_WITH_ALTERED_SEARCH_PATH
1261 * flag, see below.
1262 *
1263 * This API likes to have backslashes (\), but will probably
1264 * accept forward slashes too. Win32 SDK docs says that it
1265 * should not contain forward slashes.
1266 *
1267 * Win32 SDK docs adds:
1268 * "The name specified is the file name of the module and
1269 * is not related to the name stored in the library module
1270 * itself, as specified by the LIBRARY keyword in the
1271 * module-definition (.def) file."
1272 *
1273 * @param hFile Reserved. Must be 0.
1274 *
1275 * @param dwFlags Flags which specifies the taken when loading the module.
1276 * The value 0 makes it identical to LoadLibraryA/W.
1277 *
1278 * Flags:
1279 *
1280 * DONT_RESOLVE_DLL_REFERENCES
1281 * (WinNT/2K feature): Don't load imported modules and
1282 * hence don't resolve imported symbols.
1283 * DllMain isn't called either. (Which is obvious since
1284 * it may use one of the importe symbols.)
1285 *
1286 * On the other hand, if this flag is NOT set, the system
1287 * load imported modules, resolves imported symbols, calls
1288 * DllMain for process and thread init and term (if wished
1289 * by the module).
1290 *
1291 * LOAD_LIBRARY_AS_DATAFILE
1292 * If this flag is set, the module is mapped into the
1293 * address space but is not prepared for execution. Though
1294 * it's preparted for resource API. Hence, you'll use this
1295 * flag when you want to load a DLL for extracting
1296 * messages or resources from it.
1297 *
1298 * The resulting handle can be used with any Odin32 API
1299 * which operates on resources.
1300 * (WinNt/2k supports all resource APIs while Win9x don't
1301 * support the specialized resource APIs: LoadBitmap,
1302 * LoadCursor, LoadIcon, LoadImage, LoadMenu.)
1303 *
1304 * LOAD_WITH_ALTERED_SEARCH_PATH
1305 * If this flag is set and lpszLibFile specifies a path
1306 * we'll use an alternative file search strategy to find
1307 * imported modules. This stratgy is simply to use the
1308 * path of the module being loaded instead of the path
1309 * of the executable module as the first location
1310 * to search for imported modules.
1311 *
1312 * If this flag is clear, the standard Odin32 standard
1313 * search strategy. See Win32ImageBase::findDll for
1314 * further information.
1315 *
1316 * @sketch Convert Unicode name to ascii.
1317 * Call LoadLibraryExA.
1318 * Free ascii string.
1319 * return handle from LoadLibraryExA.
1320 * @status Open32 Partially Implemented.
1321 * @author Sander van Leeuwen (sandervl@xs4all.nl)
1322 * knut st. osmundsen (knut.stange.osmundsen@pmsc.no)
1323 * @remark Forwards to LoadLibraryExA.
1324 */
1325HINSTANCE WIN32API LoadLibraryExW(LPCWSTR lpszLibFile, HFILE hFile, DWORD dwFlags)
1326{
1327 char * pszAsciiLibFile;
1328 HINSTANCE hDll;
1329
1330 pszAsciiLibFile = UnicodeToAsciiString(lpszLibFile);
1331 dprintf(("KERNEL32: LoadLibraryExW(%s, 0x%x, 0x%x) --> LoadLibraryExA",
1332 pszAsciiLibFile, hFile, dwFlags));
1333 hDll = LoadLibraryExA(pszAsciiLibFile, hFile, dwFlags);
1334 dprintf(("KERNEL32: LoadLibraryExW(%s, 0x%x, 0x%x) returns 0x%x",
1335 pszAsciiLibFile, hFile, dwFlags, hDll));
1336 FreeAsciiString(pszAsciiLibFile);
1337
1338 return hDll;
1339}
1340//******************************************************************************
1341//******************************************************************************
1342HINSTANCE16 WIN32API LoadLibrary16(LPCTSTR lpszLibFile)
1343{
1344 dprintf(("ERROR: LoadLibrary16 %s, not implemented", lpszLibFile));
1345 return 0;
1346}
1347//******************************************************************************
1348//******************************************************************************
1349VOID WIN32API FreeLibrary16(HINSTANCE16 hinstance)
1350{
1351 dprintf(("ERROR: FreeLibrary16 %x, not implemented", hinstance));
1352}
1353//******************************************************************************
1354//******************************************************************************
1355FARPROC WIN32API GetProcAddress16(HMODULE hModule, LPCSTR lpszProc)
1356{
1357 dprintf(("ERROR: GetProcAddress16 %x %x, not implemented", hModule, lpszProc));
1358 return 0;
1359}
1360
1361
1362/**
1363 * Internal function which gets the commandline (string) used to start the current process.
1364 * @returns OS/2 / Windows return code
1365 * On successful return (NO_ERROR) the global variables
1366 * pszCmdLineA and pszCmdLineW are set.
1367 *
1368 * @param pszPeExe Pass in the name of the PE exe of this process. We'll
1369 * us this as exename and skip the first argument (ie. argv[1]).
1370 * If NULL we'll use the commandline from OS/2 as it is.
1371 * @status Completely implemented and tested.
1372 * @author knut st. osmundsen (knut.stange.osmundsen@mynd.no)
1373 */
1374ULONG InitCommandLine(const char *pszPeExe)
1375{
1376 PCHAR pib_pchcmd; /* PIB pointer to commandline. */
1377 CHAR szFilename[CCHMAXPATH]; /* Filename buffer used to get the exe filename in. */
1378 ULONG cch; /* Commandline string length. (including terminator) */
1379 PSZ psz; /* Temporary string pointer. */
1380 PSZ psz2; /* Temporary string pointer. */
1381 APIRET rc; /* OS/2 return code. */
1382 BOOL fQuotes; /* Flag used to remember if the exe filename should be in quotes. */
1383
1384 /** @sketch
1385 * Get commandline from the PIB.
1386 */
1387 pib_pchcmd = (PCHAR)OSLibGetPIB(PIB_PCHCMD);
1388
1389 /** @sketch
1390 * Two methods of making the commandline:
1391 * (1) The first argument is skipped and the second is used as exe filname.
1392 * This applies to PE.EXE launched processes only.
1393 * (2) No skipping. First argument is the exe filename.
1394 * This applies to all but PE.EXE launched processes.
1395 *
1396 * Note: We could do some code size optimization here. Much of the code for
1397 * the two methods are nearly identical.
1398 *
1399 */
1400 if(pszPeExe)
1401 {
1402 /** @sketch
1403 * Allocate memory for the commandline.
1404 * Build commandline:
1405 * Copy exe filename.
1406 * Add arguments.
1407 */
1408 cch = strlen(pszPeExe)+1;
1409
1410 // PH 2002-04-11
1411 // Note: intentional memory leak, pszCmdLineW will not be freed
1412 // or allocated after process startup
1413 pszCmdLineA = psz = (PSZ)malloc(cch);
1414 if (psz == NULL)
1415 {
1416 dprintf(("KERNEL32: InitCommandLine(%p): malloc(%d) failed\n", pszPeExe, cch));
1417 return ERROR_NOT_ENOUGH_MEMORY;
1418 }
1419 strcpy((char *)pszCmdLineA, pszPeExe);
1420
1421 rc = NO_ERROR;
1422 }
1423 else
1424 {
1425 /** @sketch Method (2):
1426 * First we'll have to determin the size of the commandline.
1427 *
1428 * As we don't assume that OS/2 allways puts a fully qualified EXE name
1429 * as the first string, we'll check if it's empty - and get the modulename
1430 * in that case - and allways get the fully qualified filename.
1431 */
1432 if (pib_pchcmd == NULL || pib_pchcmd[0] == '\0')
1433 {
1434 rc = OSLibDosQueryModuleName(OSLibGetPIB(PIB_HMTE), sizeof(szFilename), szFilename);
1435 if (rc != NO_ERROR)
1436 {
1437 dprintf(("KERNEL32: InitCommandLine(%p): OSLibQueryModuleName(0x%x,...) failed with rc=%d\n",
1438 pszPeExe, OSLibGetPIB(PIB_HMTE), rc));
1439 return rc;
1440 }
1441 }
1442 else
1443 {
1444 rc = OSLibDosQueryPathInfo(pib_pchcmd, FIL_QUERYFULLNAME, szFilename, sizeof(szFilename));
1445 if (rc != NO_ERROR)
1446 {
1447 dprintf(("KERNEL32: InitCommandLine(%p): (info) OSLibDosQueryPathInfo failed with rc=%d\n", pszPeExe, rc));
1448 strcpy(szFilename, pib_pchcmd);
1449 rc = NO_ERROR;
1450 }
1451 }
1452
1453 /** @sketch
1454 * We're still measuring the size of the commandline:
1455 * Check if we have to quote the exe filename.
1456 * Determin the length of the executable name including quotes and '\0'-terminator.
1457 * Count the length of the arguments. (We here count's all argument strings.)
1458 */
1459 fQuotes = strchr(szFilename, ' ') != NULL;
1460 cch = strlen(szFilename) + fQuotes*2 + 1;
1461 if (pib_pchcmd != NULL)
1462 {
1463 psz2 = pib_pchcmd + strlen(pib_pchcmd) + 1;
1464 while (*psz2 != '\0')
1465 {
1466 register int cchTmp = strlen(psz2) + 1; /* + 1 is for terminator (psz2) and space (cch). */
1467 psz2 += cchTmp;
1468 cch += cchTmp;
1469 }
1470 }
1471
1472 /** @sketch
1473 * Allocate memory for the commandline.
1474 * Build commandline:
1475 * Copy exe filename.
1476 * Add arguments.
1477 */
1478 pszCmdLineA = psz = (PSZ)malloc(cch);
1479 if (psz == NULL)
1480 {
1481 dprintf(("KERNEL32: InitCommandLine(%p): malloc(%d) failed\n", pszPeExe, cch));
1482 return ERROR_NOT_ENOUGH_MEMORY;
1483 }
1484
1485 if (fQuotes)
1486 *psz++ = '"';
1487 strcpy(psz, szFilename);
1488 psz += strlen(psz);
1489 if (fQuotes)
1490 {
1491 *psz++ = '"';
1492 *psz = '\0';
1493 }
1494
1495 if (pib_pchcmd != NULL)
1496 {
1497 psz2 = pib_pchcmd + strlen(pib_pchcmd) + 1;
1498 while (*psz2 != '\0')
1499 {
1500 register int cchTmp = strlen(psz2) + 1; /* + 1 is for terminator (psz). */
1501 *psz++ = ' '; /* add space */
1502 memcpy(psz, psz2, cchTmp);
1503 psz2 += cchTmp;
1504 psz += cchTmp - 1;
1505 }
1506 }
1507 }
1508
1509 /** @sketch
1510 * If successfully build ASCII commandline then convert it to UniCode.
1511 */
1512 if (rc == NO_ERROR)
1513 {
1514 // PH 2002-04-11
1515 // Note: intentional memory leak, pszCmdLineW will not be freed
1516 // or allocated after process startup
1517 cch = strlen(pszCmdLineA) + 1;
1518
1519 pszCmdLineW = (WCHAR*)malloc(cch * 2);
1520 if (pszCmdLineW != NULL) {
1521 //Translate from OS/2 to Windows codepage & ascii to unicode
1522 MultiByteToWideChar(CP_OEMCP, 0, pszCmdLineA, -1, (LPWSTR)pszCmdLineW, cch-1);
1523 ((LPWSTR)pszCmdLineW)[cch-1] = 0;
1524
1525 //ascii command line is still in OS/2 codepage, so convert it
1526 WideCharToMultiByte(CP_ACP, 0, pszCmdLineW, -1, (LPSTR)pszCmdLineA, cch-1, 0, NULL);
1527 ((LPSTR)pszCmdLineA)[cch-1] = 0;
1528 }
1529 else
1530 {
1531 DebugInt3();
1532 dprintf(("KERNEL32: InitCommandLine(%p): malloc(%d) failed (2)\n", pszPeExe, cch));
1533 rc = ERROR_NOT_ENOUGH_MEMORY;
1534 }
1535 }
1536
1537 return rc;
1538}
1539
1540/**
1541 * Gets the command line of the current process.
1542 * @returns On success:
1543 * Command line of the current process. One single string.
1544 * The first part of the command line string is the executable filename
1545 * of the current process. It might be in quotes if it contains spaces.
1546 * The rest of the string is arguments.
1547 *
1548 * On error:
1549 * NULL. Last error set. (does Win32 set last error this?)
1550 * @sketch IF not inited THEN
1551 * Init commandline assuming !PE.EXE
1552 * IF init failes THEN set last error.
1553 * ENDIF
1554 * return ASCII/ANSI commandline.
1555 * @status Completely implemented and tested.
1556 * @author knut st. osmundsen (knut.stange.osmundsen@mynd.no)
1557 * @remark The Ring-3 PeLdr is resposible for calling InitCommandLine before anyone
1558 * is able to call this function.
1559 */
1560LPCSTR WIN32API GetCommandLineA(VOID)
1561{
1562 /*
1563 * Check if the commandline is initiated.
1564 * If not we'll have to do it.
1565 * ASSUMES that if not inited this isn't a PE.EXE lauched process.
1566 */
1567 if (pszCmdLineA == NULL)
1568 {
1569 APIRET rc;
1570 rc = InitCommandLine(NULL);
1571 if (rc != NULL)
1572 SetLastError(rc);
1573 }
1574
1575 dprintf(("KERNEL32: GetCommandLineA: %s\n", pszCmdLineA));
1576 return pszCmdLineA;
1577}
1578
1579
1580/**
1581 * Gets the command line of the current process.
1582 * @returns On success:
1583 * Command line of the current process. One single string.
1584 * The first part of the command line string is the executable filename
1585 * of the current process. It might be in quotes if it contains spaces.
1586 * The rest of the string is arguments.
1587 *
1588 * On error:
1589 * NULL. Last error set. (does Win32 set last error this?)
1590 * @sketch IF not inited THEN
1591 * Init commandline assuming !PE.EXE
1592 * IF init failes THEN set last error.
1593 * ENDIF
1594 * return Unicode commandline.
1595 * @status Completely implemented and tested.
1596 * @author knut st. osmundsen (knut.stange.osmundsen@mynd.no)
1597 * @remark The Ring-3 PeLdr is resposible for calling InitCommandLine before anyone
1598 * is able to call this function.
1599 */
1600LPCWSTR WIN32API GetCommandLineW(void)
1601{
1602 /*
1603 * Check if the commandline is initiated.
1604 * If not we'll have to do it.
1605 * ASSUMES that if not inited this isn't a PE.EXE lauched process.
1606 */
1607 if (pszCmdLineW == NULL)
1608 {
1609 APIRET rc;
1610 rc = InitCommandLine(NULL);
1611 if (rc != NULL)
1612 SetLastError(rc);
1613 }
1614
1615 dprintf(("KERNEL32: GetCommandLineW: %ls\n", pszCmdLineW));
1616 return pszCmdLineW;
1617}
1618
1619
1620/**
1621 * GetModuleFileName gets the full path and file name for the specified module.
1622 * @returns Bytes written to the buffer (lpszPath). This count includes the
1623 * terminating '\0'.
1624 * On error 0 is returned. Last error is set.
1625 *
1626 * 2002-04-25 PH
1627 * Q - Do we set ERROR_BUFFER_OVERFLOW when cch > cchPath?
1628 * Q - Does NT really set the last error?
1629 * A > Win2k does not set LastError here, remains OK
1630 *
1631 * While GetModuleFileName does add a trailing termination zero
1632 * if there is enough room, the returned number of characters
1633 * *MUST NOT* include the zero character!
1634 * (Notes R6 Installer on Win2kSP6, verified Testcase)
1635 *
1636 * @param hModule Handle to the module you like to get the file name to.
1637 * @param lpszPath Output buffer for full path and file name.
1638 * @param cchPath Size of the lpszPath buffer.
1639 * @sketch Validate lpszPath.
1640 * Find the module object using handle.
1641 * If found Then
1642 * Get full path from module object.
1643 * If found path Then
1644 * Copy path to buffer and set the number of bytes written.
1645 * Else
1646 * IPE!
1647 * Else
1648 * Call Open32 GetModuleFileName. (kernel32 initterm needs/needed this)
1649 * Log result.
1650 * Return number of bytes written to the buffer.
1651 *
1652 * @status Completely implemented, Open32.
1653 * @author knut st. osmundsen (knut.stange.osmundsen@mynd.no)
1654 * Sander van Leeuwen (sandervl@xs4all.nl)
1655 * Patrick Haller (patrick.haller@innotek.de)
1656 * @remark - Do we still have to call Open32?
1657 */
1658DWORD WIN32API GetModuleFileNameA(HMODULE hModule, LPTSTR lpszPath, DWORD cchPath)
1659{
1660 Win32ImageBase * pMod; /* Pointer to the module object. */
1661 DWORD cch = 0; /* Length of the */
1662
1663 // PH 2002-04-24 Note:
1664 // WIN2k just crashes in NTDLL if lpszPath is invalid!
1665 if (!VALID_PSZ(lpszPath))
1666 {
1667 dprintf(("KERNEL32: GetModuleFileNameA(0x%x, 0x%x, 0x%x): invalid pointer lpszLibFile = 0x%x\n",
1668 hModule, lpszPath, cchPath, lpszPath));
1669 SetLastError(ERROR_INVALID_PARAMETER); //or maybe ERROR_ACCESS_DENIED is more appropriate?
1670 return 0;
1671 }
1672
1673 pMod = Win32ImageBase::findModule(hModule);
1674 if (pMod != NULL)
1675 {
1676 const char *pszFn = pMod->getFullPath();
1677 if (pszFn)
1678 {
1679 cch = strlen(pszFn);
1680 if (cch >= cchPath)
1681 cch = cchPath;
1682 else
1683 // if there is sufficient room for the zero termination,
1684 // write it additionally, uncounted
1685 lpszPath[cch] = '\0';
1686
1687 memcpy(lpszPath, pszFn, cch);
1688 }
1689 else
1690 {
1691 dprintf(("KERNEL32: GetModuleFileNameA(%x,...): IPE - getFullPath returned NULL or empty string\n"));
1692 DebugInt3();
1693 SetLastError(ERROR_INVALID_HANDLE);
1694 }
1695 }
1696 else
1697 {
1698 SetLastError(ERROR_INVALID_HANDLE);
1699 //only needed for call inside kernel32's initterm (profile init)
1700 //(console init only it seems...)
1701 cch = OSLibDosGetModuleFileName(hModule, lpszPath, cchPath);
1702 }
1703
1704 if (cch > 0)
1705 dprintf(("KERNEL32: GetModuleFileNameA(%x %x): %s %d\n", hModule, lpszPath, lpszPath, cch));
1706 else
1707 dprintf(("KERNEL32: WARNING: GetModuleFileNameA(%x,...) - not found!", hModule));
1708
1709 return cch;
1710}
1711
1712
1713/**
1714 * GetModuleFileName gets the full path and file name for the specified module.
1715 * @returns Bytes written to the buffer (lpszPath). This count includes the
1716 * terminating '\0'.
1717 * On error 0 is returned. Last error is set.
1718 * @param hModule Handle to the module you like to get the file name to.
1719 * @param lpszPath Output buffer for full path and file name.
1720 * @param cchPath Size of the lpszPath buffer.
1721 * @sketch Find the module object using handle.
1722 * If found Then
1723 * get full path from module object.
1724 * If found path Then
1725 * Determin path length.
1726 * Translate the path to into the buffer.
1727 * Else
1728 * IPE.
1729 * else
1730 * SetLastError to invalid handle.
1731 * Log result.
1732 * return number of bytes written to the buffer.
1733 *
1734 * @status Completely implemented.
1735 * @author knut st. osmundsen (knut.stange.osmundsen@mynd.no)
1736 * @remark - We do _NOT_ call Open32.
1737 * - Do we set ERROR_BUFFER_OVERFLOW when cch > cchPath?
1738 * - Does NT really set the last error?
1739 */
1740DWORD WIN32API GetModuleFileNameW(HMODULE hModule, LPWSTR lpszPath, DWORD cchPath)
1741{
1742 Win32ImageBase * pMod;
1743 DWORD cch = 0;
1744
1745 if (!VALID_PSZ(lpszPath))
1746 {
1747 dprintf(("KERNEL32: GetModuleFileNameW(0x%x, 0x%x, 0x%x): invalid pointer lpszLibFile = 0x%x\n",
1748 hModule, lpszPath, cchPath, lpszPath));
1749 SetLastError(ERROR_INVALID_PARAMETER); //or maybe ERROR_ACCESS_DENIED is more appropriate?
1750 return 0;
1751 }
1752
1753 pMod = Win32ImageBase::findModule(hModule);
1754 if (pMod != NULL)
1755 {
1756 const char *pszFn = pMod->getFullPath();
1757 if (pszFn || *pszFn != '\0')
1758 {
1759 cch = strlen(pszFn) + 1;
1760 if (cch > cchPath)
1761 cch = cchPath;
1762 AsciiToUnicodeN(pszFn, lpszPath, cch);
1763 }
1764 else
1765 {
1766 dprintf(("KERNEL32: GetModuleFileNameW(%x,...): IPE - getFullPath returned NULL or empty string\n"));
1767 DebugInt3();
1768 SetLastError(ERROR_INVALID_HANDLE);
1769 }
1770 }
1771 else
1772 SetLastError(ERROR_INVALID_HANDLE);
1773
1774 if (cch > 0)
1775 dprintf(("KERNEL32: GetModuleFileNameW(%x,...): %s %d\n", hModule, lpszPath, cch));
1776 else
1777 dprintf(("KERNEL32: WARNING: GetModuleFileNameW(%x,...) - not found!", hModule));
1778
1779 return cch;
1780}
1781
1782
1783//******************************************************************************
1784//NOTE: GetModuleHandleA does NOT support files with multiple dots (i.e.
1785// very.weird.exe)
1786//
1787// hinst = LoadLibrary("WINSPOOL.DRV"); -> succeeds
1788// hinst2 = GetModuleHandle("WINSPOOL.DRV"); -> succeeds
1789// hinst3 = GetModuleHandle("WINSPOOL."); -> fails
1790// hinst4 = GetModuleHandle("WINSPOOL"); -> fails
1791// hinst = LoadLibrary("KERNEL32.DLL"); -> succeeds
1792// hinst2 = GetModuleHandle("KERNEL32.DLL"); -> succeeds
1793// hinst3 = GetModuleHandle("KERNEL32."); -> fails
1794// hinst4 = GetModuleHandle("KERNEL32"); -> succeeds
1795// Same behaviour as observed in NT4, SP6
1796//******************************************************************************
1797HANDLE WIN32API GetModuleHandleA(LPCTSTR lpszModule)
1798{
1799 HANDLE hMod = 0;
1800 Win32DllBase *windll;
1801 char szModule[CCHMAXPATH];
1802 char *dot;
1803
1804 if(lpszModule == NULL)
1805 {
1806 if(WinExe)
1807 hMod = WinExe->getInstanceHandle();
1808 else
1809 {
1810 // // Just fail this API
1811 // hMod = 0;
1812 // SetLastError(ERROR_INVALID_HANDLE);
1813 // Wrong: in an ODIN32-LX environment, just
1814 // assume a fake handle
1815 hMod = -1;
1816 }
1817 }
1818 else
1819 {
1820 strcpy(szModule, OSLibStripPath((char *)lpszModule));
1821 strupr(szModule);
1822 dot = strchr(szModule, '.');
1823 if(dot == NULL) {
1824 //if no extension -> add .DLL (see SDK docs)
1825 strcat(szModule, DLL_EXTENSION);
1826 }
1827 else {
1828 if(dot[1] == 0) {
1829 //a trailing dot means the module has no extension (SDK docs)
1830 *dot = 0;
1831 }
1832 }
1833 if(WinExe && WinExe->matchModName(szModule)) {
1834 hMod = WinExe->getInstanceHandle();
1835 }
1836 else {
1837 windll = Win32DllBase::findModule(szModule);
1838 if(windll) {
1839 hMod = windll->getInstanceHandle();
1840 }
1841 }
1842 }
1843 dprintf(("KERNEL32: GetModuleHandle %s returned %X\n", lpszModule, hMod));
1844 return(hMod);
1845}
1846//******************************************************************************
1847//******************************************************************************
1848HMODULE WIN32API GetModuleHandleW(LPCWSTR lpwszModuleName)
1849{
1850 HMODULE rc;
1851 char *astring = NULL;
1852
1853 if (NULL != lpwszModuleName)
1854 astring = UnicodeToAsciiString((LPWSTR)lpwszModuleName);
1855
1856 rc = GetModuleHandleA(astring);
1857 dprintf(("KERNEL32: OS2GetModuleHandleW %s returned %X\n", astring, rc));
1858
1859 if (NULL != astring)
1860 FreeAsciiString(astring);
1861
1862 return(rc);
1863}
1864//******************************************************************************
1865//Checks whether program is LX or PE
1866//******************************************************************************
1867BOOL WIN32API ODIN_IsWin32App(LPSTR lpszProgramPath)
1868{
1869 DWORD Characteristics;
1870
1871 return Win32ImageBase::isPEImage(lpszProgramPath, &Characteristics, NULL) == NO_ERROR;
1872}
1873//******************************************************************************
1874//******************************************************************************
1875static char szPECmdLoader[260] = "";
1876static char szPEGUILoader[260] = "";
1877static char szNELoader[260] = "";
1878//******************************************************************************
1879//Set default paths for PE & NE loaders
1880//******************************************************************************
1881BOOL InitLoaders()
1882{
1883 sprintf(szPECmdLoader, "%s\\PEC.EXE", InternalGetSystemDirectoryA());
1884 sprintf(szPEGUILoader, "%s\\PE.EXE", InternalGetSystemDirectoryA());
1885 sprintf(szNELoader, "%s\\W16ODIN.EXE", InternalGetSystemDirectoryA());
1886
1887 return TRUE;
1888}
1889//******************************************************************************
1890//Override loader names (PEC, PE, W16ODIN)
1891//******************************************************************************
1892BOOL WIN32API ODIN_SetLoaders(LPCSTR pszPECmdLoader, LPCSTR pszPEGUILoader,
1893 LPCSTR pszNELoader)
1894{
1895 if(pszPECmdLoader) dprintf(("PE Cmd %s", pszPECmdLoader));
1896 if(pszPEGUILoader) dprintf(("PE GUI %s", pszPEGUILoader));
1897 if(pszNELoader) dprintf(("NE %s", pszNELoader));
1898 if(pszPECmdLoader) strcpy(szPECmdLoader, pszPECmdLoader);
1899 if(pszPEGUILoader) strcpy(szPEGUILoader, pszPEGUILoader);
1900 if(pszNELoader) strcpy(szNELoader, pszNELoader);
1901
1902 return TRUE;
1903}
1904//******************************************************************************
1905//******************************************************************************
1906BOOL WIN32API ODIN_QueryLoaders(LPSTR pszPECmdLoader, INT cchPECmdLoader,
1907 LPSTR pszPEGUILoader, INT cchPEGUILoader,
1908 LPSTR pszNELoader, INT cchNELoader)
1909{
1910 if(pszPECmdLoader) strncpy(pszPECmdLoader, szPECmdLoader, cchPECmdLoader);
1911 if(pszPEGUILoader) strncpy(pszPEGUILoader, szPEGUILoader, cchPEGUILoader);
1912 if(pszNELoader) strncpy(pszNELoader, szNELoader, cchNELoader);
1913
1914 return TRUE;
1915}
1916//******************************************************************************
1917//******************************************************************************
1918BOOL WINAPI CreateProcessA( LPCSTR lpApplicationName, LPSTR lpCommandLine,
1919 LPSECURITY_ATTRIBUTES lpProcessAttributes,
1920 LPSECURITY_ATTRIBUTES lpThreadAttributes,
1921 BOOL bInheritHandles, DWORD dwCreationFlags,
1922 LPVOID lpEnvironment, LPCSTR lpCurrentDirectory,
1923 LPSTARTUPINFOA lpStartupInfo,
1924 LPPROCESS_INFORMATION lpProcessInfo )
1925{
1926 STARTUPINFOA startinfo;
1927 TEB *pThreadDB = (TEB*)GetThreadTEB();
1928 char *cmdline = NULL, *newenv = NULL, *oldlibpath = NULL;
1929 BOOL rc;
1930
1931 dprintf(("KERNEL32: CreateProcessA %s cline:%s inherit:%d cFlags:%x Env:%x CurDir:%s StartupFlags:%x\n",
1932 lpApplicationName, lpCommandLine, bInheritHandles, dwCreationFlags,
1933 lpEnvironment, lpCurrentDirectory, lpStartupInfo));
1934
1935#ifdef DEBUG
1936 if(lpStartupInfo) {
1937 dprintf(("lpStartupInfo->lpReserved %x", lpStartupInfo->lpReserved));
1938 dprintf(("lpStartupInfo->lpDesktop %x", lpStartupInfo->lpDesktop));
1939 dprintf(("lpStartupInfo->lpTitle %s", lpStartupInfo->lpTitle));
1940 dprintf(("lpStartupInfo->dwX %x", lpStartupInfo->dwX));
1941 dprintf(("lpStartupInfo->dwY %x", lpStartupInfo->dwY));
1942 dprintf(("lpStartupInfo->dwXSize %x", lpStartupInfo->dwXSize));
1943 dprintf(("lpStartupInfo->dwYSize %x", lpStartupInfo->dwYSize));
1944 dprintf(("lpStartupInfo->dwXCountChars %x", lpStartupInfo->dwXCountChars));
1945 dprintf(("lpStartupInfo->dwYCountChars %x", lpStartupInfo->dwYCountChars));
1946 dprintf(("lpStartupInfo->dwFillAttribute %x", lpStartupInfo->dwFillAttribute));
1947 dprintf(("lpStartupInfo->dwFlags %x", lpStartupInfo->dwFlags));
1948 dprintf(("lpStartupInfo->wShowWindow %x", lpStartupInfo->wShowWindow));
1949 dprintf(("lpStartupInfo->hStdInput %x", lpStartupInfo->hStdInput));
1950 dprintf(("lpStartupInfo->hStdOutput %x", lpStartupInfo->hStdOutput));
1951 dprintf(("lpStartupInfo->hStdError %x", lpStartupInfo->hStdError));
1952 }
1953#endif
1954
1955 if(bInheritHandles && lpStartupInfo->dwFlags & STARTF_USESTDHANDLES)
1956 {
1957 //Translate standard handles if the child needs to inherit them
1958 int retcode = 0;
1959
1960 memcpy(&startinfo, lpStartupInfo, sizeof(startinfo));
1961 if(lpStartupInfo->hStdInput) {
1962 retcode |= HMHandleTranslateToOS2(lpStartupInfo->hStdInput, &startinfo.hStdInput);
1963 }
1964 if(lpStartupInfo->hStdOutput) {
1965 retcode |= HMHandleTranslateToOS2(lpStartupInfo->hStdOutput, &startinfo.hStdOutput);
1966 }
1967 if(lpStartupInfo->hStdError) {
1968 retcode |= HMHandleTranslateToOS2(lpStartupInfo->hStdError, &startinfo.hStdError);
1969 }
1970
1971 if(retcode) {
1972 SetLastError(ERROR_INVALID_HANDLE);
1973 rc = FALSE;
1974 goto finished;
1975 }
1976
1977 lpStartupInfo = &startinfo;
1978 }
1979
1980 if(lpApplicationName) {
1981 if(lpCommandLine) {
1982 //skip exe name in lpCommandLine
1983 //TODO: doesn't work for directories with spaces!
1984 while(*lpCommandLine != 0 && *lpCommandLine != ' ')
1985 lpCommandLine++;
1986
1987 if(*lpCommandLine != 0) {
1988 lpCommandLine++;
1989 }
1990 cmdline = (char *)malloc(strlen(lpApplicationName)+strlen(lpCommandLine) + 16);
1991 sprintf(cmdline, "%s %s", lpApplicationName, lpCommandLine);
1992 }
1993 else {
1994 cmdline = (char *)malloc(strlen(lpApplicationName) + 16);
1995 sprintf(cmdline, "%s", lpApplicationName);
1996 }
1997 }
1998 else {
1999 cmdline = (char *)malloc(strlen(lpCommandLine) + 16);
2000 sprintf(cmdline, "%s", lpCommandLine);
2001 }
2002
2003 char szAppName[MAX_PATH];
2004 char buffer[MAX_PATH];
2005 DWORD fileAttr;
2006 char *exename;
2007
2008 szAppName[0] = 0;
2009
2010 exename = buffer;
2011 strncpy(buffer, cmdline, sizeof(buffer));
2012 buffer[MAX_PATH-1] = 0;
2013 if(*exename == '"') {
2014 exename++;
2015 while(*exename != 0 && *exename != '"')
2016 exename++;
2017
2018 if(*exename != 0) {
2019 *exename = 0;
2020 }
2021 exename++;
2022 if (SearchPathA( NULL, &buffer[1], ".exe", sizeof(szAppName), szAppName, NULL ) ||
2023 SearchPathA( NULL, &buffer[1], NULL, sizeof(szAppName), szAppName, NULL ))
2024 {
2025 //
2026 }
2027 }
2028 else {
2029 BOOL fTerminate = FALSE;
2030 DWORD fileAttr;
2031
2032 while(*exename != 0) {
2033 while(*exename != 0 && *exename != ' ')
2034 exename++;
2035
2036 if(*exename != 0) {
2037 *exename = 0;
2038 fTerminate = TRUE;
2039 }
2040 dprintf(("Trying '%s'", buffer ));
2041 if (SearchPathA( NULL, buffer, ".exe", sizeof(szAppName), szAppName, NULL ) ||
2042 SearchPathA( NULL, buffer, NULL, sizeof(szAppName), szAppName, NULL ))
2043 {
2044 if(fTerminate) exename++;
2045 break;
2046 }
2047 else
2048 {//maybe it's a short name
2049 if(GetLongPathNameA(buffer, szAppName, sizeof(szAppName)))
2050 {
2051 if(fTerminate) exename++;
2052 break;
2053 }
2054 }
2055 if(fTerminate) {
2056 *exename = ' ';
2057 exename++;
2058 fTerminate = FALSE;
2059 }
2060 }
2061 }
2062 lpCommandLine = cmdline + (exename - buffer); //start of command line parameters
2063
2064 fileAttr = GetFileAttributesA(szAppName);
2065 if(fileAttr == -1 || (fileAttr & FILE_ATTRIBUTE_DIRECTORY)) {
2066 dprintf(("CreateProcess: can't find executable!"));
2067
2068 SetLastError(ERROR_FILE_NOT_FOUND);
2069
2070 rc = FALSE;
2071 goto finished;
2072 }
2073
2074 if(lpEnvironment) {
2075 newenv = CreateNewEnvironment((char *)lpEnvironment);
2076 if(newenv == NULL) {
2077 SetLastError(ERROR_NOT_ENOUGH_MEMORY);
2078 rc = FALSE;
2079 goto finished;
2080 }
2081 lpEnvironment = newenv;
2082 }
2083
2084 DWORD Characteristics, SubSystem, fNEExe, fPEExe;
2085
2086 fPEExe = Win32ImageBase::isPEImage(szAppName, &Characteristics, &SubSystem, &fNEExe) == 0;
2087
2088 // open32 does not support DEBUG_ONLY_THIS_PROCESS
2089 if(dwCreationFlags & DEBUG_ONLY_THIS_PROCESS)
2090 dwCreationFlags |= DEBUG_PROCESS;
2091
2092 //Only use WGSS to launch the app if it's not PE or PE & win32k loaded
2093 if(!fPEExe || (fPEExe && fWin32k))
2094 {
2095
2096 trylaunchagain:
2097 if(O32_CreateProcess(szAppName, lpCommandLine, lpProcessAttributes,
2098 lpThreadAttributes, bInheritHandles, dwCreationFlags,
2099 lpEnvironment, lpCurrentDirectory, lpStartupInfo,
2100 lpProcessInfo) == TRUE)
2101 {
2102 if (dwCreationFlags & DEBUG_PROCESS && pThreadDB != NULL)
2103 {
2104 if(pThreadDB->o.odin.pidDebuggee != 0)
2105 {
2106 // TODO: handle this
2107 dprintf(("KERNEL32: CreateProcess ERROR: This thread is already a debugger\n"));
2108 }
2109 else
2110 {
2111 pThreadDB->o.odin.pidDebuggee = lpProcessInfo->dwProcessId;
2112 OSLibStartDebugger((ULONG*)&pThreadDB->o.odin.pidDebuggee);
2113 }
2114 }
2115 else pThreadDB->o.odin.pidDebuggee = 0;
2116
2117 if(lpProcessInfo)
2118 {
2119 lpProcessInfo->dwThreadId = MAKE_THREADID(lpProcessInfo->dwProcessId, lpProcessInfo->dwThreadId);
2120 }
2121
2122 rc = TRUE;
2123 goto finished;
2124 }
2125 else
2126 if(!oldlibpath)
2127 {//might have failed because it wants to load dlls in its current directory
2128 // Add the application directory to the ENDLIBPATH, so dlls can be found there
2129 // Only necessary for OS/2 applications
2130 oldlibpath = (char *)calloc(4096, 1);
2131 if(oldlibpath)
2132 {
2133 OSLibQueryBeginLibpath(oldlibpath, 4096);
2134
2135 char *tmp = strrchr(szAppName, '\\');
2136 if(tmp) *tmp = 0;
2137
2138 OSLibSetBeginLibpath(szAppName);
2139 if(tmp) *tmp = '\\';
2140
2141 goto trylaunchagain;
2142 }
2143
2144 }
2145 // verify why O32_CreateProcess actually failed.
2146 // If GetLastError() == 191 (ERROR_INVALID_EXE_SIGNATURE)
2147 // we can continue to call "PE.EXE".
2148 // Note: Open32 does not translate ERROR_INVALID_EXE_SIGNATURE,
2149 // it is also valid in Win32.
2150 DWORD dwError = GetLastError();
2151 if (ERROR_INVALID_EXE_SIGNATURE != dwError && ERROR_FILE_NOT_FOUND != dwError && ERROR_ACCESS_DENIED != dwError)
2152 {
2153 dprintf(("CreateProcess: O32_CreateProcess failed with rc=%d, not PE-executable !", dwError));
2154
2155 // the current value of GetLastError() is still valid.
2156 rc = FALSE;
2157 goto finished;
2158 }
2159 }
2160
2161 // else ...
2162
2163 //probably a win32 exe, so run it in the pe loader
2164 dprintf(("KERNEL32: CreateProcess %s %s", szAppName, lpCommandLine));
2165
2166 if(fPEExe)
2167 {
2168 LPCSTR lpszExecutable;
2169 int iNewCommandLineLength;
2170
2171 // calculate base length for the new command line
2172 iNewCommandLineLength = strlen(szAppName) + strlen(lpCommandLine);
2173
2174 if(SubSystem == IMAGE_SUBSYSTEM_WINDOWS_CUI)
2175 lpszExecutable = szPECmdLoader;
2176 else
2177 lpszExecutable = szPEGUILoader;
2178
2179 // 2002-04-24 PH
2180 // set the ODIN32.DEBUG_CHILD environment variable to start new PE processes
2181 // under a new instance of the (IPMD) debugger.
2182 const char *pszDebugChildArg = "";
2183#ifdef DEBUG
2184 char szDebugChild[512];
2185 const char *pszChildDebugger = getenv("ODIN32.DEBUG_CHILD");
2186 if (pszChildDebugger)
2187 {
2188 /*
2189 * Change the executable to the debugger (icsdebug.exe) and
2190 * move the previous executable onto the commandline.
2191 */
2192 szDebugChild[0] = ' ';
2193 strcpy(&szDebugChild[1], lpszExecutable);
2194 iNewCommandLineLength += strlen(&szDebugChild[0]);
2195
2196 pszDebugChildArg = &szDebugChild[0];
2197 lpszExecutable = pszChildDebugger;
2198 }
2199#endif
2200
2201 //SvL: Allright. Before we call O32_CreateProcess, we must take care of
2202 // lpCurrentDirectory ourselves. (Open32 ignores it!)
2203 if(lpCurrentDirectory) {
2204 char *newcmdline;
2205
2206 newcmdline = (char *)malloc(strlen(lpCurrentDirectory) + iNewCommandLineLength + 64);
2207 sprintf(newcmdline, "%s /OPT:[CURDIR=%s] %s %s", pszDebugChildArg, lpCurrentDirectory, szAppName, lpCommandLine);
2208 free(cmdline);
2209 cmdline = newcmdline;
2210 }
2211 else {
2212 char *newcmdline;
2213
2214 newcmdline = (char *)malloc(iNewCommandLineLength + 16);
2215 sprintf(newcmdline, "%s %s %s", pszDebugChildArg, szAppName, lpCommandLine);
2216 free(cmdline);
2217 cmdline = newcmdline;
2218 }
2219
2220 dprintf(("KERNEL32: CreateProcess starting [%s],[%s]",
2221 lpszExecutable,
2222 cmdline));
2223
2224 rc = O32_CreateProcess(lpszExecutable, (LPCSTR)cmdline,lpProcessAttributes,
2225 lpThreadAttributes, bInheritHandles, dwCreationFlags,
2226 lpEnvironment, lpCurrentDirectory, lpStartupInfo,
2227 lpProcessInfo);
2228 }
2229 else
2230 if(fNEExe) {//16 bits windows app
2231 char *newcmdline;
2232
2233 newcmdline = (char *)malloc(strlen(szAppName) + strlen(cmdline) + strlen(szPEGUILoader) + strlen(lpCommandLine) + 32);
2234
2235 sprintf(newcmdline, " /PELDR=[%s] %s", szPEGUILoader, szAppName, lpCommandLine);
2236 free(cmdline);
2237 cmdline = newcmdline;
2238 //Force Open32 to use DosStartSession (DosExecPgm won't do)
2239 dwCreationFlags |= CREATE_NEW_PROCESS_GROUP;
2240
2241 dprintf(("KERNEL32: CreateProcess starting [%s],[%s]",
2242 szNELoader,
2243 cmdline));
2244 rc = O32_CreateProcess(szNELoader, (LPCSTR)cmdline, lpProcessAttributes,
2245 lpThreadAttributes, bInheritHandles, dwCreationFlags,
2246 lpEnvironment, lpCurrentDirectory, lpStartupInfo,
2247 lpProcessInfo);
2248 }
2249 else {//os/2 app??
2250 rc = O32_CreateProcess(szAppName, (LPCSTR)lpCommandLine, lpProcessAttributes,
2251 lpThreadAttributes, bInheritHandles, dwCreationFlags,
2252 lpEnvironment, lpCurrentDirectory, lpStartupInfo,
2253 lpProcessInfo);
2254 }
2255 if(!lpEnvironment) {
2256 // Restore old ENDLIBPATH variable
2257 // TODO:
2258 }
2259
2260 if(rc == TRUE)
2261 {
2262 if (dwCreationFlags & DEBUG_PROCESS && pThreadDB != NULL)
2263 {
2264 if(pThreadDB->o.odin.pidDebuggee != 0)
2265 {
2266 // TODO: handle this
2267 dprintf(("KERNEL32: CreateProcess ERROR: This thread is already a debugger\n"));
2268 }
2269 else
2270 {
2271 pThreadDB->o.odin.pidDebuggee = lpProcessInfo->dwProcessId;
2272 OSLibStartDebugger((ULONG*)&pThreadDB->o.odin.pidDebuggee);
2273 }
2274 }
2275 else
2276 pThreadDB->o.odin.pidDebuggee = 0;
2277 }
2278 if(lpProcessInfo)
2279 {
2280 lpProcessInfo->dwThreadId = MAKE_THREADID(lpProcessInfo->dwProcessId, lpProcessInfo->dwThreadId);
2281 dprintf(("KERNEL32: CreateProcess returned %d hPro:%x hThr:%x pid:%x tid:%x\n",
2282 rc, lpProcessInfo->hProcess, lpProcessInfo->hThread,
2283 lpProcessInfo->dwProcessId,lpProcessInfo->dwThreadId));
2284 }
2285 else
2286 dprintf(("KERNEL32: CreateProcess returned %d\n", rc));
2287
2288finished:
2289
2290 if(oldlibpath) {
2291 OSLibSetBeginLibpath(oldlibpath);
2292 free(oldlibpath);
2293 }
2294 if(cmdline) free(cmdline);
2295 if(newenv) free(newenv);
2296 return(rc);
2297}
2298//******************************************************************************
2299//******************************************************************************
2300BOOL WIN32API CreateProcessW(LPCWSTR lpApplicationName, LPWSTR lpCommandLine,
2301 PSECURITY_ATTRIBUTES lpProcessAttributes,
2302 PSECURITY_ATTRIBUTES lpThreadAttributes,
2303 BOOL bInheritHandles, DWORD dwCreationFlags,
2304 LPVOID lpEnvironment,
2305 LPCWSTR lpCurrentDirectory, LPSTARTUPINFOW lpStartupInfo,
2306 LPPROCESS_INFORMATION lpProcessInfo)
2307{
2308 BOOL rc;
2309 char *astring1 = 0, *astring2 = 0, *astring3 = 0;
2310
2311 dprintf(("KERNEL32: CreateProcessW"));
2312 if(lpApplicationName)
2313 astring1 = UnicodeToAsciiString((LPWSTR)lpApplicationName);
2314 if(lpCommandLine)
2315 astring2 = UnicodeToAsciiString(lpCommandLine);
2316 if(lpCurrentDirectory)
2317 astring3 = UnicodeToAsciiString((LPWSTR)lpCurrentDirectory);
2318 rc = CreateProcessA(astring1, astring2, lpProcessAttributes, lpThreadAttributes,
2319 bInheritHandles, dwCreationFlags, lpEnvironment,
2320 astring3, (LPSTARTUPINFOA)lpStartupInfo,
2321 lpProcessInfo);
2322 if(astring3) FreeAsciiString(astring3);
2323 if(astring2) FreeAsciiString(astring2);
2324 if(astring1) FreeAsciiString(astring1);
2325 return(rc);
2326}
2327//******************************************************************************
2328//******************************************************************************
2329HINSTANCE WIN32API WinExec(LPCSTR lpCmdLine, UINT nCmdShow)
2330{
2331 STARTUPINFOA startinfo = {0};
2332 PROCESS_INFORMATION procinfo;
2333 DWORD rc;
2334 HINSTANCE hInstance;
2335
2336 dprintf(("KERNEL32: WinExec lpCmdLine='%s' nCmdShow=%d\n", lpCmdLine));
2337 startinfo.cb = sizeof(startinfo);
2338 startinfo.dwFlags = STARTF_USESHOWWINDOW;
2339 startinfo.wShowWindow = nCmdShow;
2340 if(CreateProcessA(NULL, (LPSTR)lpCmdLine, NULL, NULL, FALSE, 0, NULL, NULL,
2341 &startinfo, &procinfo) == FALSE)
2342 {
2343 hInstance = (HINSTANCE)GetLastError();
2344 if(hInstance >= 32) {
2345 hInstance = 11;
2346 }
2347 dprintf(("KERNEL32: WinExec failed with rc %d", hInstance));
2348 return hInstance;
2349 }
2350 //block until the launched app waits for input (or a timeout of 15 seconds)
2351 //TODO: Shouldn't call Open32, but the api in user32..
2352 if(fVersionWarp3) {
2353 Sleep(1000); //WaitForInputIdle not available in Warp 3
2354 }
2355 else {
2356 dprintf(("Calling WaitForInputIdle %x %d", procinfo.hProcess, 15000));
2357 rc = WaitForInputIdle(procinfo.hProcess, 15000);
2358#ifdef DEBUG
2359 if(rc != 0) {
2360 dprintf(("WinExec: WaitForInputIdle %x returned %x", procinfo.hProcess, rc));
2361 }
2362 else dprintf(("WinExec: WaitForInputIdle successfull"));
2363#endif
2364 }
2365 CloseHandle(procinfo.hThread);
2366 CloseHandle(procinfo.hProcess);
2367 return 33;
2368}
2369//******************************************************************************
2370//******************************************************************************
2371DWORD WIN32API WaitForInputIdle(HANDLE hProcess, DWORD dwTimeOut)
2372{
2373 dprintf(("USER32: WaitForInputIdle %x %d\n", hProcess, dwTimeOut));
2374
2375 if(fVersionWarp3) {
2376 Sleep(1000);
2377 return 0;
2378 }
2379 else return O32_WaitForInputIdle(hProcess, dwTimeOut);
2380}
2381/**********************************************************************
2382 * LoadModule (KERNEL32.499)
2383 *
2384 * Wine: 20000909
2385 *
2386 * Copyright 1995 Alexandre Julliard
2387 */
2388HINSTANCE WINAPI LoadModule( LPCSTR name, LPVOID paramBlock )
2389{
2390 LOADPARAMS *params = (LOADPARAMS *)paramBlock;
2391 PROCESS_INFORMATION info;
2392 STARTUPINFOA startup;
2393 HINSTANCE hInstance;
2394 LPSTR cmdline, p;
2395 char filename[MAX_PATH];
2396 BYTE len;
2397
2398 dprintf(("LoadModule %s %x", name, paramBlock));
2399
2400 if (!name) return ERROR_FILE_NOT_FOUND;
2401
2402 if (!SearchPathA( NULL, name, ".exe", sizeof(filename), filename, NULL ) &&
2403 !SearchPathA( NULL, name, NULL, sizeof(filename), filename, NULL ))
2404 return GetLastError();
2405
2406 len = (BYTE)params->lpCmdLine[0];
2407 if (!(cmdline = (LPSTR)HeapAlloc( GetProcessHeap(), 0, strlen(filename) + len + 2 )))
2408 return ERROR_NOT_ENOUGH_MEMORY;
2409
2410 strcpy( cmdline, filename );
2411 p = cmdline + strlen(cmdline);
2412 *p++ = ' ';
2413 memcpy( p, params->lpCmdLine + 1, len );
2414 p[len] = 0;
2415
2416 memset( &startup, 0, sizeof(startup) );
2417 startup.cb = sizeof(startup);
2418 if (params->lpCmdShow)
2419 {
2420 startup.dwFlags = STARTF_USESHOWWINDOW;
2421 startup.wShowWindow = params->lpCmdShow[1];
2422 }
2423
2424 if (CreateProcessA( filename, cmdline, NULL, NULL, FALSE, 0,
2425 params->lpEnvAddress, NULL, &startup, &info ))
2426 {
2427 /* Give 15 seconds to the app to come up */
2428 if ( WaitForInputIdle ( info.hProcess, 15000 ) == 0xFFFFFFFF )
2429 dprintf(("ERROR: WaitForInputIdle failed: Error %ld\n", GetLastError() ));
2430 hInstance = 33;
2431 /* Close off the handles */
2432 CloseHandle( info.hThread );
2433 CloseHandle( info.hProcess );
2434 }
2435 else if ((hInstance = GetLastError()) >= 32)
2436 {
2437 dprintf(("ERROR: Strange error set by CreateProcess: %d\n", hInstance ));
2438 hInstance = 11;
2439 }
2440
2441 HeapFree( GetProcessHeap(), 0, cmdline );
2442 return hInstance;
2443}
2444//******************************************************************************
2445//******************************************************************************
2446FARPROC WIN32API GetProcAddress(HMODULE hModule, LPCSTR lpszProc)
2447{
2448 Win32ImageBase *winmod;
2449 FARPROC proc = 0;
2450 ULONG ulAPIOrdinal;
2451
2452 if(hModule == 0 || hModule == -1 || (WinExe && hModule == WinExe->getInstanceHandle())) {
2453 winmod = WinExe;
2454 }
2455 else winmod = (Win32ImageBase *)Win32DllBase::findModule((HINSTANCE)hModule);
2456
2457 if(winmod) {
2458 ulAPIOrdinal = (ULONG)lpszProc;
2459 if (ulAPIOrdinal <= 0x0000FFFF) {
2460 proc = (FARPROC)winmod->getApi((int)ulAPIOrdinal);
2461 }
2462 else
2463 if (lpszProc && *lpszProc) {
2464 proc = (FARPROC)winmod->getApi((char *)lpszProc);
2465 }
2466 if(proc == 0) {
2467#ifdef DEBUG
2468 if(ulAPIOrdinal <= 0x0000FFFF) {
2469 dprintf(("GetProcAddress %x %x not found!", hModule, ulAPIOrdinal));
2470 }
2471 else dprintf(("GetProcAddress %x %s not found!", hModule, lpszProc));
2472#endif
2473 SetLastError(ERROR_PROC_NOT_FOUND);
2474 return 0;
2475 }
2476 if(HIWORD(lpszProc))
2477 dprintf(("KERNEL32: GetProcAddress %s from %X returned %X\n", lpszProc, hModule, proc));
2478 else dprintf(("KERNEL32: GetProcAddress %x from %X returned %X\n", lpszProc, hModule, proc));
2479
2480 SetLastError(ERROR_SUCCESS);
2481 return proc;
2482 }
2483 proc = (FARPROC)OSLibDosGetProcAddress(hModule, lpszProc);
2484 if(HIWORD(lpszProc))
2485 dprintf(("KERNEL32: GetProcAddress %s from %X returned %X\n", lpszProc, hModule, proc));
2486 else dprintf(("KERNEL32: GetProcAddress %x from %X returned %X\n", lpszProc, hModule, proc));
2487 SetLastError(ERROR_SUCCESS);
2488 return(proc);
2489}
2490//******************************************************************************
2491// ODIN_SetProcAddress: Override a dll export
2492//
2493// Parameters:
2494// HMODULE hModule Module handle
2495// LPCSTR lpszProc Export name or ordinal
2496// FARPROC pfnNewProc New export function address
2497//
2498// Returns: Success -> old address of export
2499// Failure -> -1
2500//
2501//******************************************************************************
2502FARPROC WIN32API ODIN_SetProcAddress(HMODULE hModule, LPCSTR lpszProc,
2503 FARPROC pfnNewProc)
2504{
2505 Win32ImageBase *winmod;
2506 FARPROC proc;
2507 ULONG ulAPIOrdinal;
2508
2509 if(hModule == 0 || hModule == -1 || (WinExe && hModule == WinExe->getInstanceHandle())) {
2510 winmod = WinExe;
2511 }
2512 else winmod = (Win32ImageBase *)Win32DllBase::findModule((HINSTANCE)hModule);
2513
2514 if(winmod) {
2515 ulAPIOrdinal = (ULONG)lpszProc;
2516 if (ulAPIOrdinal <= 0x0000FFFF) {
2517 proc = (FARPROC)winmod->setApi((int)ulAPIOrdinal, (ULONG)pfnNewProc);
2518 }
2519 else proc = (FARPROC)winmod->setApi((char *)lpszProc, (ULONG)pfnNewProc);
2520 if(proc == 0) {
2521#ifdef DEBUG
2522 if(ulAPIOrdinal <= 0x0000FFFF) {
2523 dprintf(("ODIN_SetProcAddress %x %x not found!", hModule, ulAPIOrdinal));
2524 }
2525 else dprintf(("ODIN_SetProcAddress %x %s not found!", hModule, lpszProc));
2526#endif
2527 SetLastError(ERROR_PROC_NOT_FOUND);
2528 return (FARPROC)-1;
2529 }
2530 if(HIWORD(lpszProc))
2531 dprintf(("KERNEL32: ODIN_SetProcAddress %s from %X returned %X\n", lpszProc, hModule, proc));
2532 else dprintf(("KERNEL32: ODIN_SetProcAddress %x from %X returned %X\n", lpszProc, hModule, proc));
2533
2534 SetLastError(ERROR_SUCCESS);
2535 return proc;
2536 }
2537 SetLastError(ERROR_INVALID_HANDLE);
2538 return (FARPROC)-1;
2539}
2540//******************************************************************************
2541//******************************************************************************
2542UINT WIN32API GetProcModuleFileNameA(ULONG lpvAddress, LPSTR lpszFileName, UINT cchFileNameMax)
2543{
2544 LPSTR lpszModuleName;
2545 Win32ImageBase *image = NULL;
2546 int len;
2547
2548 dprintf(("GetProcModuleFileNameA %x %x %d", lpvAddress, lpszFileName, cchFileNameMax));
2549
2550 if(WinExe && WinExe->insideModule(lpvAddress) && WinExe->insideModuleCode(lpvAddress)) {
2551 image = WinExe;
2552 }
2553 else {
2554 Win32DllBase *dll = Win32DllBase::findModuleByAddr(lpvAddress);
2555 if(dll && dll->insideModuleCode(lpvAddress)) {
2556 image = dll;
2557 }
2558 }
2559 if(image == NULL) {
2560 dprintf(("GetProcModuleFileNameA: address not found!!"));
2561 return 0;
2562 }
2563 len = strlen(image->getFullPath());
2564 if(len < cchFileNameMax) {
2565 strcpy(lpszFileName, image->getFullPath());
2566 return len+1; //??
2567 }
2568 else {
2569 dprintf(("GetProcModuleFileNameA: destination string too small!!"));
2570 return 0;
2571 }
2572}
2573//******************************************************************************
2574//******************************************************************************
2575BOOL WIN32API DisableThreadLibraryCalls(HMODULE hModule)
2576{
2577 Win32DllBase *winmod;
2578 FARPROC proc;
2579 ULONG ulAPIOrdinal;
2580
2581 winmod = Win32DllBase::findModule((HINSTANCE)hModule);
2582 if(winmod)
2583 {
2584 // don't call ATTACH/DETACH thread functions in DLL
2585 winmod->disableThreadLibraryCalls();
2586 return TRUE;
2587 }
2588 else
2589 {
2590 // raise error condition
2591 SetLastError(ERROR_INVALID_HANDLE);
2592 return FALSE;
2593 }
2594}
2595//******************************************************************************
2596// Forwarder for PSAPI.DLL
2597//
2598// Returns the handles of all loaded modules
2599//
2600//******************************************************************************
2601BOOL WINAPI PSAPI_EnumProcessModules(HANDLE hProcess, HMODULE *lphModule,
2602 DWORD cb, LPDWORD lpcbNeeded)
2603{
2604 DWORD count;
2605 DWORD countMax;
2606 HMODULE hModule;
2607
2608 dprintf(("KERNEL32: EnumProcessModules %p, %ld, %p", lphModule, cb, lpcbNeeded));
2609
2610 if ( lphModule == NULL )
2611 cb = 0;
2612
2613 if ( lpcbNeeded != NULL )
2614 *lpcbNeeded = 0;
2615
2616 count = 0;
2617 countMax = cb / sizeof(HMODULE);
2618
2619 count = Win32DllBase::enumDlls(lphModule, countMax);
2620
2621 if ( lpcbNeeded != NULL )
2622 *lpcbNeeded = sizeof(HMODULE) * count;
2623
2624 return TRUE;
2625}
2626//******************************************************************************
2627// Forwarder for PSAPI.DLL
2628//
2629// Returns some information about the module identified by hModule
2630//
2631//******************************************************************************
2632BOOL WINAPI PSAPI_GetModuleInformation(HANDLE hProcess, HMODULE hModule,
2633 LPMODULEINFO lpmodinfo, DWORD cb)
2634{
2635 BOOL ret = FALSE;
2636 Win32DllBase *winmod = NULL;
2637
2638 dprintf(("KERNEL32: GetModuleInformation hModule=%x", hModule));
2639
2640 if (!lpmodinfo || cb < sizeof(MODULEINFO)) return FALSE;
2641
2642 winmod = Win32DllBase::findModule((HINSTANCE)hModule);
2643 if (!winmod) {
2644 dprintf(("GetModuleInformation failed to find module"));
2645 return FALSE;
2646 }
2647
2648 lpmodinfo->SizeOfImage = winmod->getImageSize();
2649 lpmodinfo->EntryPoint = winmod->getEntryPoint();
2650 lpmodinfo->lpBaseOfDll = (void*)hModule;
2651
2652 return TRUE;
2653}
2654//******************************************************************************
2655//******************************************************************************
2656/**
2657 * Gets the startup info which was passed to CreateProcess when
2658 * this process was created.
2659 *
2660 * @param lpStartupInfo Where to put the startup info.
2661 * Please don't change the strings :)
2662 * @status Partially Implemented.
2663 * @author knut st. osmundsen <bird@anduin.net>
2664 * @remark The three pointers of the structure is just fake.
2665 * @remark Pretty much identical to current wine code.
2666 */
2667void WIN32API GetStartupInfoA(LPSTARTUPINFOA lpStartupInfo)
2668{
2669 dprintf2(("KERNEL32: GetStartupInfoA %x\n", lpStartupInfo));
2670 *lpStartupInfo = StartupInfo;
2671}
2672
2673
2674/**
2675 * Gets the startup info which was passed to CreateProcess when
2676 * this process was created.
2677 *
2678 * @param lpStartupInfo Where to put the startup info.
2679 * Please don't change the strings :)
2680 * @status Partially Implemented.
2681 * @author knut st. osmundsen <bird@anduin.net>
2682 * @remark The three pointers of the structure is just fake.
2683 * @remark Similar to wine code, but they use RtlCreateUnicodeStringFromAsciiz
2684 * for creating the UNICODE strings and are doing so for each call.
2685 * As I don't wanna call NTDLL code from kernel32 I take the easy path.
2686 */
2687void WIN32API GetStartupInfoW(LPSTARTUPINFOW lpStartupInfo)
2688{
2689 /*
2690 * Converted once, this information shouldn't change...
2691 */
2692
2693 dprintf2(("KERNEL32: GetStartupInfoW %x\n", lpStartupInfo));
2694
2695 //assumes the structs are identical but for the strings pointed to.
2696 memcpy(lpStartupInfo, &StartupInfo, sizeof(STARTUPINFOA));
2697 lpStartupInfo->cb = sizeof(STARTUPINFOW); /* this really should be the same size else we're in for trouble.. :) */
2698
2699 /*
2700 * First time conversion only as this should be pretty static.
2701 * See remark!
2702 */
2703 static LPWSTR pwcReserved = NULL;
2704 static LPWSTR pwcDesktop = NULL;
2705 static LPWSTR pwcTitle = NULL;
2706
2707 if (lpStartupInfo->lpReserved && pwcReserved)
2708 pwcReserved = AsciiToUnicodeString((LPCSTR)lpStartupInfo->lpReserved);
2709 lpStartupInfo->lpReserved = pwcReserved;
2710
2711 if (lpStartupInfo->lpDesktop && pwcDesktop)
2712 pwcDesktop = AsciiToUnicodeString((LPCSTR)lpStartupInfo->lpDesktop);
2713 lpStartupInfo->lpDesktop = pwcDesktop;
2714
2715 if (lpStartupInfo->lpTitle && pwcTitle)
2716 pwcTitle = AsciiToUnicodeString((LPCSTR)lpStartupInfo->lpTitle);
2717 lpStartupInfo->lpTitle = pwcTitle;
2718}
2719
Note: See TracBrowser for help on using the repository browser.