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

Last change on this file since 9882 was 9882, checked in by sandervl, 22 years ago

ExitProcess: don't remove our exception handler too early

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