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

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

Added ODIN_IsWin32App export to determine whether an app is a win32 or os2 binary

File size: 93.8 KB
Line 
1/* $Id: wprocess.cpp,v 1.182 2003-02-24 17:02:17 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 SetOS2ExceptionChain(-1);
513
514 HMDeviceCommClass::CloseOverlappedIOHandlers();
515
516 //detach all dlls (LIFO order) before really unloading them; this
517 //should take care of circular dependencies (crash while accessing
518 //memory of a dll that has just been freed)
519 dprintf(("********************************************"));
520 dprintf(("**** Detach process from all dlls -- START"));
521 Win32DllBase::detachProcessFromAllDlls();
522 dprintf(("**** Detach process from all dlls -- END"));
523 dprintf(("********************************************"));
524
525 if(WinExe) {
526 delete(WinExe);
527 WinExe = NULL;
528 }
529
530 //Note: Needs to be done after deleting WinExe (destruction of exe + dll objects)
531 //Flush and delete all open memory mapped files
532 Win32MemMap::deleteAll();
533
534 //SvL: We must make sure no threads are still suspended (with SuspendThread)
535 // OS/2 seems to be unable to terminate the process otherwise (exitlist hang)
536 threadListMutex.enter();
537 teb = threadList;
538 while(teb) {
539 dprintf(("Active thread id %d, handle %x", LOWORD(teb->o.odin.threadId), teb->o.odin.hThread));
540 if(teb->o.odin.hThread != hThread && teb->o.odin.dwSuspend > 0) {
541 //kill any threads that are suspended; dangerous, but so is calling
542 //SuspendThread; we assume the app knew what it was doing
543 TerminateThread(teb->o.odin.hThread, 0);
544 ResumeThread(teb->o.odin.hThread);
545 }
546 teb = teb->o.odin.next;
547 }
548 threadListMutex.leave();
549
550#ifdef DEBUG_HEAPSTATE
551 pszHeapDumpStart = pszHeapDump = (char *)malloc(10*1024*1024);
552 _heap_walk(callback_function);
553 dprintf((pszHeapDumpStart));
554 free(pszHeapDumpStart);
555#endif
556
557#ifdef PROFILE
558 // Note: after this point we do not expect any more Win32-API calls,
559 // so this is probably the best time to dump the gathered profiling
560 // information
561 PerfView_Write();
562 ProfilerWrite();
563 ProfilerTerminate();
564#endif /* PROFILE */
565
566 //Restore original OS/2 TIB selector
567 teb = GetThreadTEB();
568 if(teb) DestroyTEB(teb);
569 SetExceptionChain((ULONG)-1);
570
571 //avoid crashes since win32 & OS/2 exception handler aren't identical
572 //(terminate process generates two exceptions)
573 /* @@@PH 1998/02/12 Added Console Support */
574 if (iConsoleIsActive())
575 iConsoleWaitClose();
576
577 dprintf(("KERNEL32: ExitProcess done (time %x)", GetCurrentTime()));
578 O32_ExitProcess(exitcode);
579}
580//******************************************************************************
581//******************************************************************************
582BOOL WIN32API FreeLibrary(HINSTANCE hinstance)
583{
584 Win32DllBase *winmod;
585 BOOL rc;
586
587 SetLastError(ERROR_SUCCESS);
588 //SvL: Ignore FreeLibary for executable
589 if(WinExe && hinstance == WinExe->getInstanceHandle()) {
590 return TRUE;
591 }
592
593 winmod = Win32DllBase::findModule(hinstance);
594 if(winmod) {
595 dprintf(("FreeLibrary %s", winmod->getName()));
596 //Only free it when the nrDynamicLibRef != 0
597 //This prevent problems after ExitProcess:
598 //i.e. dll A is referenced by our exe and loaded with LoadLibrary by dll B
599 // During ExitProcess it's unloaded once (before dll B), dll B calls
600 // FreeLibrary, but our exe also has a reference -> unloaded too many times
601 if(winmod->isDynamicLib()) {
602 winmod->decDynamicLib();
603 winmod->Release();
604 }
605 else {
606 dprintf(("Skipping dynamic unload as nrDynamicLibRef == 0"));
607 }
608 return(TRUE);
609 }
610 dprintf(("WARNING: KERNEL32: FreeLibrary %s %x NOT FOUND!", OSLibGetDllName(hinstance), hinstance));
611 return(TRUE);
612}
613/*****************************************************************************
614 * Name : VOID WIN32API FreeLibraryAndExitThread
615 * Purpose : The FreeLibraryAndExitThread function decrements the reference
616 * count of a loaded dynamic-link library (DLL) by one, and then
617 * calls ExitThread to terminate the calling thread.
618 * The function does not return.
619 *
620 * The FreeLibraryAndExitThread function gives threads that are
621 * created and executed within a dynamic-link library an opportunity
622 * to safely unload the DLL and terminate themselves.
623 * Parameters:
624 * Variables :
625 * Result :
626 * Remark :
627 *****************************************************************************/
628VOID WIN32API FreeLibraryAndExitThread( HMODULE hLibModule, DWORD dwExitCode)
629{
630
631 dprintf(("KERNEL32: FreeLibraryAndExitThread(%08x,%08x)", hLibModule, dwExitCode));
632 FreeLibrary(hLibModule);
633 ExitThread(dwExitCode);
634}
635/******************************************************************************/
636/******************************************************************************/
637/**
638 * LoadLibraryA can be used to map a DLL module into the calling process's
639 * addressspace. It returns a handle that can be used with GetProcAddress to
640 * get addresses of exported entry points (functions and variables).
641 *
642 * LoadLibraryA can also be used to map executable (.exe) modules into the
643 * address to access resources in the module. However, LoadLibrary can't be
644 * used to run an executable (.exe) module.
645 *
646 * @returns Handle to the library which was loaded.
647 * @param lpszLibFile Pointer to zero ASCII string giving the name of the
648 * executable image (either a Dll or an Exe) which is to be
649 * loaded.
650 *
651 * If no extention is specified the default .DLL extention is
652 * appended to the name. End the filename with an '.' if the
653 * file does not have an extention (and don't want the .DLL
654 * appended).
655 *
656 * If no path is specified, this API will use the Odin32
657 * standard search strategy to find the file. This strategy
658 * is described in the method Win32ImageBase::findDLL.
659 *
660 * This API likes to have backslashes (\), but will probably
661 * accept forward slashes too. Win32 SDK docs says that it
662 * should not contain forward slashes.
663 *
664 * Win32 SDK docs adds:
665 * "The name specified is the file name of the module and
666 * is not related to the name stored in the library module
667 * itself, as specified by the LIBRARY keyword in the
668 * module-definition (.def) file."
669 *
670 * @sketch Call LoadLibraryExA with flags set to 0.
671 * @status Odin32 Completely Implemented.
672 * @author Sander van Leeuwen (sandervl@xs4all.nl)
673 * knut st. osmundsen (knut.stange.osmundsen@pmsc.no)
674 * @remark Forwards to LoadLibraryExA.
675 */
676HINSTANCE WIN32API LoadLibraryA(LPCTSTR lpszLibFile)
677{
678 HINSTANCE hDll;
679
680 dprintf(("KERNEL32: LoadLibraryA(%s) --> LoadLibraryExA(lpszLibFile, 0, 0)",
681 lpszLibFile));
682 hDll = LoadLibraryExA(lpszLibFile, 0, 0);
683 dprintf(("KERNEL32: LoadLibraryA(%s) returns 0x%x",
684 lpszLibFile, hDll));
685 return hDll;
686}
687
688
689/**
690 * LoadLibraryW can be used to map a DLL module into the calling process's
691 * addressspace. It returns a handle that can be used with GetProcAddress to
692 * get addresses of exported entry points (functions and variables).
693 *
694 * LoadLibraryW can also be used to map executable (.exe) modules into the
695 * address to access resources in the module. However, LoadLibrary can't be
696 * used to run an executable (.exe) module.
697 *
698 * @returns Handle to the library which was loaded.
699 * @param lpszLibFile Pointer to Unicode string giving the name of
700 * the executable image (either a Dll or an Exe) which is to
701 * be loaded.
702 *
703 * If no extention is specified the default .DLL extention is
704 * appended to the name. End the filename with an '.' if the
705 * file does not have an extention (and don't want the .DLL
706 * appended).
707 *
708 * If no path is specified, this API will use the Odin32
709 * standard search strategy to find the file. This strategy
710 * is described in the method Win32ImageBase::findDLL.
711 *
712 * This API likes to have backslashes (\), but will probably
713 * accept forward slashes too. Win32 SDK docs says that it
714 * should not contain forward slashes.
715 *
716 * Win32 SDK docs adds:
717 * "The name specified is the file name of the module and
718 * is not related to the name stored in the library module
719 * itself, as specified by the LIBRARY keyword in the
720 * module-definition (.def) file."
721 *
722 * @sketch Convert Unicode name to ascii.
723 * Call LoadLibraryExA with flags set to 0.
724 * free ascii string.
725 * @status Odin32 Completely Implemented.
726 * @author Sander van Leeuwen (sandervl@xs4all.nl)
727 * knut st. osmundsen (knut.stange.osmundsen@pmsc.no)
728 * @remark Forwards to LoadLibraryExA.
729 */
730HINSTANCE WIN32API LoadLibraryW(LPCWSTR lpszLibFile)
731{
732 char * pszAsciiLibFile;
733 HINSTANCE hDll;
734
735 pszAsciiLibFile = UnicodeToAsciiString(lpszLibFile);
736 dprintf(("KERNEL32: LoadLibraryW(%s) --> LoadLibraryExA(lpszLibFile, 0, 0)",
737 pszAsciiLibFile));
738 hDll = LoadLibraryExA(pszAsciiLibFile, NULL, 0);
739 dprintf(("KERNEL32: LoadLibraryW(%s) returns 0x%x",
740 pszAsciiLibFile, hDll));
741 FreeAsciiString(pszAsciiLibFile);
742
743 return hDll;
744}
745
746//******************************************************************************
747//Custom build function to disable loading of LX dlls
748static BOOL fDisableLXDllLoading = FALSE;
749//******************************************************************************
750void WIN32API ODIN_DisableLXDllLoading()
751{
752 fDisableLXDllLoading = TRUE;
753}
754
755
756/**
757 * Custombuild API for registering a callback for LX Dll loading thru LoadLibrary*().
758 * @returns Success indicator.
759 * @param pfn Pointer to callback.
760 * NULL if callback is deregistered.
761 */
762BOOL WIN32API ODIN_SetLxDllLoadCallback(PFNLXDLLLOAD pfn)
763{
764 pfnLxDllLoadCallback = pfn;
765 return TRUE;
766}
767
768
769/**
770 * LoadLibraryExA can be used to map a DLL module into the calling process's
771 * addressspace. It returns a handle that can be used with GetProcAddress to
772 * get addresses of exported entry points (functions and variables).
773 *
774 * LoadLibraryExA can also be used to map executable (.exe) modules into the
775 * address to access resources in the module. However, LoadLibrary can't be
776 * used to run an executable (.exe) module.
777 *
778 * @returns Handle to the library which was loaded.
779 * @param lpszLibFile Pointer to Unicode string giving the name of
780 * the executable image (either a Dll or an Exe) which is to
781 * be loaded.
782 *
783 * If no extention is specified the default .DLL extention is
784 * appended to the name. End the filename with an '.' if the
785 * file does not have an extention (and don't want the .DLL
786 * appended).
787 *
788 * If no path is specified, this API will use the Odin32
789 * standard search strategy to find the file. This strategy
790 * is described in the method Win32ImageBase::findDLL.
791 * This may be alterned by the LOAD_WITH_ALTERED_SEARCH_PATH
792 * flag, see below.
793 *
794 * This API likes to have backslashes (\), but will probably
795 * accept forward slashes too. Win32 SDK docs says that it
796 * should not contain forward slashes.
797 *
798 * Win32 SDK docs adds:
799 * "The name specified is the file name of the module and
800 * is not related to the name stored in the library module
801 * itself, as specified by the LIBRARY keyword in the
802 * module-definition (.def) file."
803 *
804 * @param hFile Reserved. Must be 0.
805 *
806 * @param dwFlags Flags which specifies the taken when loading the module.
807 * The value 0 makes it identical to LoadLibraryA/W.
808 *
809 * Flags:
810 *
811 * DONT_RESOLVE_DLL_REFERENCES
812 * (WinNT/2K feature): Don't load imported modules and
813 * hence don't resolve imported symbols.
814 * DllMain isn't called either. (Which is obvious since
815 * it may use one of the importe symbols.)
816 *
817 * On the other hand, if this flag is NOT set, the system
818 * load imported modules, resolves imported symbols, calls
819 * DllMain for process and thread init and term (if wished
820 * by the module).
821 *
822 *
823 * LOAD_LIBRARY_AS_DATAFILE
824 * If this flag is set, the module is mapped into the
825 * address space but is not prepared for execution. Though
826 * it's preparted for resource API. Hence, you'll use this
827 * flag when you want to load a DLL for extracting
828 * messages or resources from it.
829 *
830 * The resulting handle can be used with any Odin32 API
831 * which operates on resources.
832 * (WinNt/2k supports all resource APIs while Win9x don't
833 * support the specialized resource APIs: LoadBitmap,
834 * LoadCursor, LoadIcon, LoadImage, LoadMenu.)
835 *
836 *
837 * LOAD_WITH_ALTERED_SEARCH_PATH
838 * If this flag is set and lpszLibFile specifies a path
839 * we'll use an alternative file search strategy to find
840 * imported modules. This stratgy is simply to use the
841 * path of the module being loaded instead of the path
842 * of the executable module as the first location
843 * to search for imported modules.
844 *
845 * If this flag is clear, the standard Odin32 standard
846 * search strategy. See Win32ImageBase::findDll for
847 * further information.
848 *
849 * not implemented yet.
850 *
851 * @status Open32 Partially Implemented.
852 * @author Sander van Leeuwen (sandervl@xs4all.nl)
853 * knut st. osmundsen (knut.stange.osmundsen@pmsc.no)
854 * @remark Forwards to LoadLibraryExA.
855 */
856HINSTANCE WIN32API LoadLibraryExA(LPCTSTR lpszLibFile, HANDLE hFile, DWORD dwFlags)
857{
858 HINSTANCE hDll;
859 Win32DllBase * pModule;
860 char szModname[CCHMAXPATH];
861 BOOL fPath; /* Flags which is set if the */
862 /* lpszLibFile contains a path. */
863 ULONG fPE; /* isPEImage return value. */
864 DWORD Characteristics; //file header's Characteristics
865 char *dot;
866
867 /** @sketch
868 * Some parameter validations is probably useful.
869 */
870 if (!VALID_PSZ(lpszLibFile))
871 {
872 dprintf(("KERNEL32: LoadLibraryExA(0x%x, 0x%x, 0x%x): invalid pointer lpszLibFile = 0x%x\n",
873 lpszLibFile, hFile, dwFlags, lpszLibFile));
874 SetLastError(ERROR_INVALID_PARAMETER); //or maybe ERROR_ACCESS_DENIED is more appropriate?
875 return NULL;
876 }
877 if (!VALID_PSZMAXSIZE(lpszLibFile, CCHMAXPATH))
878 {
879 dprintf(("KERNEL32: LoadLibraryExA(%s, 0x%x, 0x%x): lpszLibFile string too long, %d\n",
880 lpszLibFile, hFile, dwFlags, strlen(lpszLibFile)));
881 SetLastError(ERROR_INVALID_PARAMETER);
882 return NULL;
883 }
884 if ((dwFlags & ~(DONT_RESOLVE_DLL_REFERENCES | LOAD_WITH_ALTERED_SEARCH_PATH | LOAD_LIBRARY_AS_DATAFILE)) != 0)
885 {
886 dprintf(("KERNEL32: LoadLibraryExA(%s, 0x%x, 0x%x): dwFlags have invalid or unsupported flags\n",
887 lpszLibFile, hFile, dwFlags));
888 SetLastError(ERROR_INVALID_PARAMETER);
889 return NULL;
890 }
891
892 /** @sketch
893 * First we'll see if the module is allready loaded - either as the EXE or as DLL.
894 * IF Executable present AND libfile matches the modname of the executable THEN
895 * RETURN instance handle of executable.
896 * Endif
897 * IF allready loaded THEN
898 * IF it's a LX dll which isn't loaded and we're using the PeLoader THEN
899 * Set Load library.
900 * Endif
901 * Inc dynamic reference count.
902 * Inc reference count.
903 * RETURN instance handle.
904 * Endif
905 */
906 strcpy(szModname, lpszLibFile);
907 strupr(szModname);
908 dot = strchr(szModname, '.');
909 if(dot == NULL) {
910 //if there's no extension or trainling dot, we
911 //assume it's a dll (see Win32 SDK docs)
912 strcat(szModname, DLL_EXTENSION);
913 }
914 else {
915 if(dot[1] == 0) {
916 //a trailing dot means the module has no extension (SDK docs)
917 *dot = 0;
918 }
919 }
920 if (WinExe != NULL && WinExe->matchModName(szModname))
921 return WinExe->getInstanceHandle();
922
923 pModule = Win32DllBase::findModule((LPSTR)szModname);
924 if (pModule)
925 {
926 pModule->incDynamicLib();
927 pModule->AddRef();
928 dprintf(("KERNEL32: LoadLibraryExA(%s, 0x%x, 0x%x): returns 0x%x. Dll found %s",
929 szModname, hFile, dwFlags, pModule->getInstanceHandle(), pModule->getFullPath()));
930 return pModule->getInstanceHandle();
931 }
932
933
934 /** @sketch
935 * Test if lpszLibFile has a path or not.
936 * Copy the lpszLibFile to szModname, rename the dll and uppercase the name.
937 * IF it hasn't a path THEN
938 * Issue a findDll to find the dll/executable to be loaded.
939 * IF the Dll isn't found THEN
940 * Set last error and RETURN.
941 * Endif.
942 * Endif
943 */
944 fPath = strchr(szModname, '\\') || strchr(szModname, '/');
945 Win32DllBase::renameDll(szModname);
946
947 if (!fPath)
948 {
949 char szModName2[CCHMAXPATH];
950 strcpy(szModName2, szModname);
951 if (!Win32ImageBase::findDll(szModName2, szModname, sizeof(szModname)))
952 {
953 dprintf(("KERNEL32: LoadLibraryExA(%s, 0x%x, 0x%x): module wasn't found. returns NULL",
954 lpszLibFile, hFile, dwFlags));
955 SetLastError(ERROR_FILE_NOT_FOUND);
956 return NULL;
957 }
958 }
959
960 //test if dll is in PE or LX format
961 fPE = Win32ImageBase::isPEImage(szModname, &Characteristics, NULL);
962
963 /** @sketch
964 * IF (fDisableLXDllLoading && (!fPeLoader || fPE == failure)) THEN
965 * Try load the executable using LoadLibrary
966 * IF successfully loaded THEN
967 * Try find registered/pe2lx object.
968 * IF callback Then
969 * If callback give green light Then
970 * Find registered lx object.
971 * Else
972 * Unload it if loaded.
973 * Endif
974 * Endif
975 * IF module object found Then
976 * IF LX dll and is using the PE Loader THEN
977 * Set Load library.
978 * Inc reference count.
979 * Endif
980 * Inc dynamic reference count.
981 * RETURN successfully.
982 * Else
983 * fail.
984 * Endif
985 * Endif
986 * Endif
987 */
988 //only call OS/2 if LX binary or win32k process
989 if (!fDisableLXDllLoading && (!fPeLoader || fPE != ERROR_SUCCESS))
990 {
991 hDll = OSLibDosLoadModule(szModname);
992 if (hDll)
993 {
994 /* OS/2 dll, system dll, converted dll or win32k took care of it. */
995 pModule = Win32DllBase::findModuleByOS2Handle(hDll);
996 /* Custombuild customizing may take care of it too. */
997 if (pfnLxDllLoadCallback)
998 {
999 /* If callback says yes, continue load it, else fail. */
1000 if (pfnLxDllLoadCallback(hDll, pModule ? pModule->getInstanceHandle() : NULL))
1001 pModule = Win32DllBase::findModuleByOS2Handle(hDll);
1002 else if (pModule)
1003 {
1004 pModule->Release();
1005 pModule = NULL;
1006 }
1007 }
1008 if (pModule)
1009 {
1010 if (pModule->isLxDll())
1011 {
1012 ((Win32LxDll *)pModule)->setDllHandleOS2(hDll);
1013 if (fPeLoader && pModule->AddRef() == -1)
1014 { //-1 -> load failed (attachProcess)
1015 delete pModule;
1016 SetLastError(ERROR_INVALID_EXE_SIGNATURE);
1017 dprintf(("Dll %s refused to be loaded; aborting", szModname));
1018 return 0;
1019 }
1020
1021 }
1022 pModule->incDynamicLib();
1023 }
1024 else if (fExeStarted && !fIsOS2Image) {
1025 OSLibDosFreeModule(hDll);
1026 SetLastError(ERROR_INVALID_EXE_SIGNATURE);
1027 dprintf(("Dll %s is not an Odin dll; unload & return failure", szModname));
1028 return 0;
1029 }
1030 else {
1031 /* bird 2001-07-10:
1032 * let's fail right away instead of hitting DebugInt3s and fail other places.
1033 * This is very annoying when running Opera on a debug build with netscape/2
1034 * plugins present. We'll make this conditional for the time being.
1035 */
1036 static BOOL fFailIfUnregisteredLX = -1;
1037 if (fFailIfUnregisteredLX == -1)
1038 fFailIfUnregisteredLX = getenv("ODIN32.FAIL_IF_UNREGISTEREDLX") != NULL;
1039 if (fExeStarted && fFailIfUnregisteredLX)
1040 {
1041 dprintf(("KERNEL32: LoadLibraryExA(%s, 0x%x, 0x%x): returns 0x%x. Loaded OS/2 dll %s using DosLoadModule. returns NULL.",
1042 lpszLibFile, hFile, dwFlags, hDll, szModname));
1043 SetLastError(ERROR_INVALID_EXE_SIGNATURE);
1044 return NULL;
1045 }
1046 dprintf(("KERNEL32: LoadLibraryExA(%s, 0x%x, 0x%x): returns 0x%x. Loaded OS/2 dll %s using DosLoadModule.",
1047 lpszLibFile, hFile, dwFlags, hDll, szModname));
1048 return hDll; //happens when LoadLibrary is called in kernel32's initterm (nor harmful)
1049 }
1050 dprintf(("KERNEL32: LoadLibraryExA(%s, 0x%x, 0x%x): returns 0x%x. Loaded %s using DosLoadModule.",
1051 lpszLibFile, hFile, dwFlags, hDll, szModname));
1052 return pModule->getInstanceHandle();
1053 }
1054 dprintf(("KERNEL32: LoadLibraryExA(%s, 0x%x, 0x%x): DosLoadModule (%s) failed. LastError=%d",
1055 lpszLibFile, hFile, dwFlags, szModname, GetLastError()));
1056 }
1057 else
1058 hDll = NULL;
1059
1060
1061 /** @sketch
1062 * If PE image THEN
1063 * IF LOAD_LIBRARY_AS_DATAFILE or Executable THEN
1064 *
1065 *
1066 * Try load the file using the Win32PeLdrDll class.
1067 * <sketch continued further down>
1068 * Else
1069 * Set last error.
1070 * (hDll is NULL)
1071 * Endif
1072 * return hDll.
1073 */
1074 if(fPE == ERROR_SUCCESS)
1075 {
1076 Win32PeLdrDll *peldrDll;
1077
1078 //SvL: If executable -> load as data file (only resources)
1079 if(!(Characteristics & IMAGE_FILE_DLL))
1080 {
1081 dwFlags |= (LOAD_LIBRARY_AS_DATAFILE | DONT_RESOLVE_DLL_REFERENCES);
1082 }
1083
1084 peldrDll = new Win32PeLdrDll(szModname);
1085 if (peldrDll == NULL)
1086 {
1087 dprintf(("KERNEL32: LoadLibraryExA(%s, 0x%x, 0x%x): Failed to created instance of Win32PeLdrDll. returns NULL.",
1088 lpszLibFile, hFile, dwFlags));
1089 SetLastError(ERROR_NOT_ENOUGH_MEMORY);
1090 return NULL;
1091 }
1092
1093 /** @sketch
1094 * Process dwFlags
1095 */
1096 if (dwFlags & LOAD_LIBRARY_AS_DATAFILE)
1097 {
1098 dprintf(("KERNEL32: LoadLibraryExA(%s, 0x%x, 0x%x): LOAD_LIBRARY_AS_DATAFILE",
1099 lpszLibFile, hFile, dwFlags));
1100 peldrDll->setLoadAsDataFile();
1101 peldrDll->disableLibraryCalls();
1102 }
1103 if (dwFlags & DONT_RESOLVE_DLL_REFERENCES)
1104 {
1105 dprintf(("KERNEL32: LoadLibraryExA(%s, 0x%x, 0x%x): DONT_RESOLVE_DLL_REFERENCES",
1106 lpszLibFile, hFile, dwFlags));
1107 peldrDll->disableLibraryCalls();
1108 peldrDll->disableImportHandling();
1109 }
1110 if (dwFlags & LOAD_WITH_ALTERED_SEARCH_PATH)
1111 {
1112 dprintf(("KERNEL32: LoadLibraryExA(%s, 0x%x, 0x%x): Warning dwFlags LOAD_WITH_ALTERED_SEARCH_PATH is not implemented.",
1113 lpszLibFile, hFile, dwFlags));
1114 //peldrDll->setLoadWithAlteredSearchPath();
1115 }
1116
1117 /** @sketch
1118 * Initiate the peldr DLL.
1119 * IF successful init THEN
1120 * Inc dynamic ref count.
1121 * Inc ref count.
1122 * Attach to process
1123 * IF successful THEN
1124 * hDLL <- instance handle.
1125 * ELSE
1126 * set last error
1127 * delete Win32PeLdrDll instance.
1128 * Endif
1129 * ELSE
1130 * set last error
1131 * delete Win32PeLdrDll instance.
1132 * Endif.
1133 */
1134 if(peldrDll->init(0) == LDRERROR_SUCCESS)
1135 {
1136 peldrDll->AddRef();
1137 if (peldrDll->attachProcess())
1138 {
1139 hDll = peldrDll->getInstanceHandle();
1140 //Must be called *after* attachprocess, since attachprocess may also
1141 //trigger LoadLibrary calls
1142 //Those dlls must not be put in front of this dll in the dynamic
1143 //dll list; or else the unload order is wrong:
1144 //i.e. RPAP3260 loads PNRS3260 in DLL_PROCESS_ATTACH
1145 // this means that in ExitProcess, PNRS3260 needs to be removed
1146 // first since RPAP3260 depends on it
1147 peldrDll->incDynamicLib();
1148 }
1149 else
1150 {
1151 dprintf(("KERNEL32: LoadLibraryExA(%s, 0x%x, 0x%x): attachProcess call to Win32PeLdrDll instance failed. returns NULL.",
1152 lpszLibFile, hFile, dwFlags));
1153 SetLastError(ERROR_DLL_INIT_FAILED);
1154 delete peldrDll;
1155 return NULL;
1156 }
1157 }
1158 else
1159 {
1160 dprintf(("KERNEL32: LoadLibraryExA(%s, 0x%x, 0x%x): Failed to init Win32PeLdrDll instance. error=%d returns NULL.",
1161 lpszLibFile, hFile, dwFlags, peldrDll->getError()));
1162 SetLastError(ERROR_INVALID_EXE_SIGNATURE);
1163 delete peldrDll;
1164 return NULL;
1165 }
1166 }
1167 else
1168 {
1169 dprintf(("KERNEL32: LoadLibraryExA(%s, 0x%x, 0x%x) library wasn't found (%s) or isn't loadable; err %x",
1170 lpszLibFile, hFile, dwFlags, szModname, fPE));
1171 SetLastError(fPE);
1172 return NULL;
1173 }
1174
1175 return hDll;
1176}
1177
1178
1179/**
1180 * LoadLibraryExW can be used to map a DLL module into the calling process's
1181 * addressspace. It returns a handle that can be used with GetProcAddress to
1182 * get addresses of exported entry points (functions and variables).
1183 *
1184 * LoadLibraryExW can also be used to map executable (.exe) modules into the
1185 * address to access resources in the module. However, LoadLibrary can't be
1186 * used to run an executable (.exe) module.
1187 *
1188 * @returns Handle to the library which was loaded.
1189 * @param lpszLibFile Pointer to Unicode string giving the name of
1190 * the executable image (either a Dll or an Exe) which is to
1191 * be loaded.
1192 *
1193 * If no extention is specified the default .DLL extention is
1194 * appended to the name. End the filename with an '.' if the
1195 * file does not have an extention (and don't want the .DLL
1196 * appended).
1197 *
1198 * If no path is specified, this API will use the Odin32
1199 * standard search strategy to find the file. This strategy
1200 * is described in the method Win32ImageBase::findDLL.
1201 * This may be alterned by the LOAD_WITH_ALTERED_SEARCH_PATH
1202 * flag, see below.
1203 *
1204 * This API likes to have backslashes (\), but will probably
1205 * accept forward slashes too. Win32 SDK docs says that it
1206 * should not contain forward slashes.
1207 *
1208 * Win32 SDK docs adds:
1209 * "The name specified is the file name of the module and
1210 * is not related to the name stored in the library module
1211 * itself, as specified by the LIBRARY keyword in the
1212 * module-definition (.def) file."
1213 *
1214 * @param hFile Reserved. Must be 0.
1215 *
1216 * @param dwFlags Flags which specifies the taken when loading the module.
1217 * The value 0 makes it identical to LoadLibraryA/W.
1218 *
1219 * Flags:
1220 *
1221 * DONT_RESOLVE_DLL_REFERENCES
1222 * (WinNT/2K feature): Don't load imported modules and
1223 * hence don't resolve imported symbols.
1224 * DllMain isn't called either. (Which is obvious since
1225 * it may use one of the importe symbols.)
1226 *
1227 * On the other hand, if this flag is NOT set, the system
1228 * load imported modules, resolves imported symbols, calls
1229 * DllMain for process and thread init and term (if wished
1230 * by the module).
1231 *
1232 * LOAD_LIBRARY_AS_DATAFILE
1233 * If this flag is set, the module is mapped into the
1234 * address space but is not prepared for execution. Though
1235 * it's preparted for resource API. Hence, you'll use this
1236 * flag when you want to load a DLL for extracting
1237 * messages or resources from it.
1238 *
1239 * The resulting handle can be used with any Odin32 API
1240 * which operates on resources.
1241 * (WinNt/2k supports all resource APIs while Win9x don't
1242 * support the specialized resource APIs: LoadBitmap,
1243 * LoadCursor, LoadIcon, LoadImage, LoadMenu.)
1244 *
1245 * LOAD_WITH_ALTERED_SEARCH_PATH
1246 * If this flag is set and lpszLibFile specifies a path
1247 * we'll use an alternative file search strategy to find
1248 * imported modules. This stratgy is simply to use the
1249 * path of the module being loaded instead of the path
1250 * of the executable module as the first location
1251 * to search for imported modules.
1252 *
1253 * If this flag is clear, the standard Odin32 standard
1254 * search strategy. See Win32ImageBase::findDll for
1255 * further information.
1256 *
1257 * @sketch Convert Unicode name to ascii.
1258 * Call LoadLibraryExA.
1259 * Free ascii string.
1260 * return handle from LoadLibraryExA.
1261 * @status Open32 Partially Implemented.
1262 * @author Sander van Leeuwen (sandervl@xs4all.nl)
1263 * knut st. osmundsen (knut.stange.osmundsen@pmsc.no)
1264 * @remark Forwards to LoadLibraryExA.
1265 */
1266HINSTANCE WIN32API LoadLibraryExW(LPCWSTR lpszLibFile, HANDLE hFile, DWORD dwFlags)
1267{
1268 char * pszAsciiLibFile;
1269 HINSTANCE hDll;
1270
1271 pszAsciiLibFile = UnicodeToAsciiString(lpszLibFile);
1272 dprintf(("KERNEL32: LoadLibraryExW(%s, 0x%x, 0x%x) --> LoadLibraryExA",
1273 pszAsciiLibFile, hFile, dwFlags));
1274 hDll = LoadLibraryExA(pszAsciiLibFile, hFile, dwFlags);
1275 dprintf(("KERNEL32: LoadLibraryExW(%s, 0x%x, 0x%x) returns 0x%x",
1276 pszAsciiLibFile, hFile, dwFlags, hDll));
1277 FreeAsciiString(pszAsciiLibFile);
1278
1279 return hDll;
1280}
1281//******************************************************************************
1282//******************************************************************************
1283HINSTANCE16 WIN32API LoadLibrary16(LPCTSTR lpszLibFile)
1284{
1285 dprintf(("ERROR: LoadLibrary16 %s, not implemented", lpszLibFile));
1286 return 0;
1287}
1288//******************************************************************************
1289//******************************************************************************
1290VOID WIN32API FreeLibrary16(HINSTANCE16 hinstance)
1291{
1292 dprintf(("ERROR: FreeLibrary16 %x, not implemented", hinstance));
1293}
1294//******************************************************************************
1295//******************************************************************************
1296FARPROC WIN32API GetProcAddress16(HMODULE hModule, LPCSTR lpszProc)
1297{
1298 dprintf(("ERROR: GetProcAddress16 %x %x, not implemented", hModule, lpszProc));
1299 return 0;
1300}
1301
1302
1303/**
1304 * Internal function which gets the commandline (string) used to start the current process.
1305 * @returns OS/2 / Windows return code
1306 * On successful return (NO_ERROR) the global variables
1307 * pszCmdLineA and pszCmdLineW are set.
1308 *
1309 * @param pszPeExe Pass in the name of the PE exe of this process. We'll
1310 * us this as exename and skip the first argument (ie. argv[1]).
1311 * If NULL we'll use the commandline from OS/2 as it is.
1312 * @status Completely implemented and tested.
1313 * @author knut st. osmundsen (knut.stange.osmundsen@mynd.no)
1314 */
1315ULONG InitCommandLine(const char *pszPeExe)
1316{
1317 PCHAR pib_pchcmd; /* PIB pointer to commandline. */
1318 CHAR szFilename[CCHMAXPATH]; /* Filename buffer used to get the exe filename in. */
1319 ULONG cch; /* Commandline string length. (including terminator) */
1320 PSZ psz; /* Temporary string pointer. */
1321 PSZ psz2; /* Temporary string pointer. */
1322 APIRET rc; /* OS/2 return code. */
1323 BOOL fQuotes; /* Flag used to remember if the exe filename should be in quotes. */
1324
1325 /** @sketch
1326 * Get commandline from the PIB.
1327 */
1328 pib_pchcmd = (PCHAR)OSLibGetPIB(PIB_PCHCMD);
1329
1330 /** @sketch
1331 * Two methods of making the commandline:
1332 * (1) The first argument is skipped and the second is used as exe filname.
1333 * This applies to PE.EXE launched processes only.
1334 * (2) No skipping. First argument is the exe filename.
1335 * This applies to all but PE.EXE launched processes.
1336 *
1337 * Note: We could do some code size optimization here. Much of the code for
1338 * the two methods are nearly identical.
1339 *
1340 */
1341 if(pszPeExe)
1342 {
1343 /** @sketch
1344 * Allocate memory for the commandline.
1345 * Build commandline:
1346 * Copy exe filename.
1347 * Add arguments.
1348 */
1349 cch = strlen(pszPeExe)+1;
1350
1351 // PH 2002-04-11
1352 // Note: intentional memory leak, pszCmdLineW will not be freed
1353 // or allocated after process startup
1354 pszCmdLineA = psz = (PSZ)malloc(cch);
1355 if (psz == NULL)
1356 {
1357 dprintf(("KERNEL32: InitCommandLine(%p): malloc(%d) failed\n", pszPeExe, cch));
1358 return ERROR_NOT_ENOUGH_MEMORY;
1359 }
1360 strcpy((char *)pszCmdLineA, pszPeExe);
1361
1362 rc = NO_ERROR;
1363 }
1364 else
1365 {
1366 /** @sketch Method (2):
1367 * First we'll have to determin the size of the commandline.
1368 *
1369 * As we don't assume that OS/2 allways puts a fully qualified EXE name
1370 * as the first string, we'll check if it's empty - and get the modulename
1371 * in that case - and allways get the fully qualified filename.
1372 */
1373 if (pib_pchcmd == NULL || pib_pchcmd[0] == '\0')
1374 {
1375 rc = OSLibDosQueryModuleName(OSLibGetPIB(PIB_HMTE), sizeof(szFilename), szFilename);
1376 if (rc != NO_ERROR)
1377 {
1378 dprintf(("KERNEL32: InitCommandLine(%p): OSLibQueryModuleName(0x%x,...) failed with rc=%d\n",
1379 pszPeExe, OSLibGetPIB(PIB_HMTE), rc));
1380 return rc;
1381 }
1382 }
1383 else
1384 {
1385 rc = OSLibDosQueryPathInfo(pib_pchcmd, FIL_QUERYFULLNAME, szFilename, sizeof(szFilename));
1386 if (rc != NO_ERROR)
1387 {
1388 dprintf(("KERNEL32: InitCommandLine(%p): (info) OSLibDosQueryPathInfo failed with rc=%d\n", pszPeExe, rc));
1389 strcpy(szFilename, pib_pchcmd);
1390 rc = NO_ERROR;
1391 }
1392 }
1393
1394 /** @sketch
1395 * We're still measuring the size of the commandline:
1396 * Check if we have to quote the exe filename.
1397 * Determin the length of the executable name including quotes and '\0'-terminator.
1398 * Count the length of the arguments. (We here count's all argument strings.)
1399 */
1400 fQuotes = strchr(szFilename, ' ') != NULL;
1401 cch = strlen(szFilename) + fQuotes*2 + 1;
1402 if (pib_pchcmd != NULL)
1403 {
1404 psz2 = pib_pchcmd + strlen(pib_pchcmd) + 1;
1405 while (*psz2 != '\0')
1406 {
1407 register int cchTmp = strlen(psz2) + 1; /* + 1 is for terminator (psz2) and space (cch). */
1408 psz2 += cchTmp;
1409 cch += cchTmp;
1410 }
1411 }
1412
1413 /** @sketch
1414 * Allocate memory for the commandline.
1415 * Build commandline:
1416 * Copy exe filename.
1417 * Add arguments.
1418 */
1419 pszCmdLineA = psz = (PSZ)malloc(cch);
1420 if (psz == NULL)
1421 {
1422 dprintf(("KERNEL32: InitCommandLine(%p): malloc(%d) failed\n", pszPeExe, cch));
1423 return ERROR_NOT_ENOUGH_MEMORY;
1424 }
1425
1426 if (fQuotes)
1427 *psz++ = '"';
1428 strcpy(psz, szFilename);
1429 psz += strlen(psz);
1430 if (fQuotes)
1431 {
1432 *psz++ = '"';
1433 *psz = '\0';
1434 }
1435
1436 if (pib_pchcmd != NULL)
1437 {
1438 psz2 = pib_pchcmd + strlen(pib_pchcmd) + 1;
1439 while (*psz2 != '\0')
1440 {
1441 register int cchTmp = strlen(psz2) + 1; /* + 1 is for terminator (psz). */
1442 *psz++ = ' '; /* add space */
1443 memcpy(psz, psz2, cchTmp);
1444 psz2 += cchTmp;
1445 psz += cchTmp - 1;
1446 }
1447 }
1448 }
1449
1450 /** @sketch
1451 * If successfully build ASCII commandline then convert it to UniCode.
1452 */
1453 if (rc == NO_ERROR)
1454 {
1455 // PH 2002-04-11
1456 // Note: intentional memory leak, pszCmdLineW will not be freed
1457 // or allocated after process startup
1458 cch = strlen(pszCmdLineA) + 1;
1459
1460 pszCmdLineW = (WCHAR*)malloc(cch * 2);
1461 if (pszCmdLineW != NULL) {
1462 //Translate from OS/2 to Windows codepage & ascii to unicode
1463 MultiByteToWideChar(CP_OEMCP, 0, pszCmdLineA, -1, (LPWSTR)pszCmdLineW, cch-1);
1464 ((LPWSTR)pszCmdLineW)[cch-1] = 0;
1465
1466 //ascii command line is still in OS/2 codepage, so convert it
1467 WideCharToMultiByte(CP_ACP, 0, pszCmdLineW, -1, (LPSTR)pszCmdLineA, cch-1, 0, NULL);
1468 ((LPSTR)pszCmdLineA)[cch-1] = 0;
1469 }
1470 else
1471 {
1472 DebugInt3();
1473 dprintf(("KERNEL32: InitCommandLine(%p): malloc(%d) failed (2)\n", pszPeExe, cch));
1474 rc = ERROR_NOT_ENOUGH_MEMORY;
1475 }
1476 }
1477
1478 return rc;
1479}
1480
1481/**
1482 * Gets the command line of the current process.
1483 * @returns On success:
1484 * Command line of the current process. One single string.
1485 * The first part of the command line string is the executable filename
1486 * of the current process. It might be in quotes if it contains spaces.
1487 * The rest of the string is arguments.
1488 *
1489 * On error:
1490 * NULL. Last error set. (does Win32 set last error this?)
1491 * @sketch IF not inited THEN
1492 * Init commandline assuming !PE.EXE
1493 * IF init failes THEN set last error.
1494 * ENDIF
1495 * return ASCII/ANSI commandline.
1496 * @status Completely implemented and tested.
1497 * @author knut st. osmundsen (knut.stange.osmundsen@mynd.no)
1498 * @remark The Ring-3 PeLdr is resposible for calling InitCommandLine before anyone
1499 * is able to call this function.
1500 */
1501LPCSTR WIN32API GetCommandLineA(VOID)
1502{
1503 /*
1504 * Check if the commandline is initiated.
1505 * If not we'll have to do it.
1506 * ASSUMES that if not inited this isn't a PE.EXE lauched process.
1507 */
1508 if (pszCmdLineA == NULL)
1509 {
1510 APIRET rc;
1511 rc = InitCommandLine(NULL);
1512 if (rc != NULL)
1513 SetLastError(rc);
1514 }
1515
1516 dprintf(("KERNEL32: GetCommandLineA: %s\n", pszCmdLineA));
1517 return pszCmdLineA;
1518}
1519
1520
1521/**
1522 * Gets the command line of the current process.
1523 * @returns On success:
1524 * Command line of the current process. One single string.
1525 * The first part of the command line string is the executable filename
1526 * of the current process. It might be in quotes if it contains spaces.
1527 * The rest of the string is arguments.
1528 *
1529 * On error:
1530 * NULL. Last error set. (does Win32 set last error this?)
1531 * @sketch IF not inited THEN
1532 * Init commandline assuming !PE.EXE
1533 * IF init failes THEN set last error.
1534 * ENDIF
1535 * return Unicode commandline.
1536 * @status Completely implemented and tested.
1537 * @author knut st. osmundsen (knut.stange.osmundsen@mynd.no)
1538 * @remark The Ring-3 PeLdr is resposible for calling InitCommandLine before anyone
1539 * is able to call this function.
1540 */
1541LPCWSTR WIN32API GetCommandLineW(void)
1542{
1543 /*
1544 * Check if the commandline is initiated.
1545 * If not we'll have to do it.
1546 * ASSUMES that if not inited this isn't a PE.EXE lauched process.
1547 */
1548 if (pszCmdLineW == NULL)
1549 {
1550 APIRET rc;
1551 rc = InitCommandLine(NULL);
1552 if (rc != NULL)
1553 SetLastError(rc);
1554 }
1555
1556 dprintf(("KERNEL32: GetCommandLineW: %s\n", pszCmdLineA));
1557 return pszCmdLineW;
1558}
1559
1560
1561/**
1562 * GetModuleFileName gets the full path and file name for the specified module.
1563 * @returns Bytes written to the buffer (lpszPath). This count includes the
1564 * terminating '\0'.
1565 * On error 0 is returned. Last error is set.
1566 *
1567 * 2002-04-25 PH
1568 * Q - Do we set ERROR_BUFFER_OVERFLOW when cch > cchPath?
1569 * Q - Does NT really set the last error?
1570 * A > Win2k does not set LastError here, remains OK
1571 *
1572 * While GetModuleFileName does add a trailing termination zero
1573 * if there is enough room, the returned number of characters
1574 * *MUST NOT* include the zero character!
1575 * (Notes R6 Installer on Win2kSP6, verified Testcase)
1576 *
1577 * @param hModule Handle to the module you like to get the file name to.
1578 * @param lpszPath Output buffer for full path and file name.
1579 * @param cchPath Size of the lpszPath buffer.
1580 * @sketch Validate lpszPath.
1581 * Find the module object using handle.
1582 * If found Then
1583 * Get full path from module object.
1584 * If found path Then
1585 * Copy path to buffer and set the number of bytes written.
1586 * Else
1587 * IPE!
1588 * Else
1589 * Call Open32 GetModuleFileName. (kernel32 initterm needs/needed this)
1590 * Log result.
1591 * Return number of bytes written to the buffer.
1592 *
1593 * @status Completely implemented, Open32.
1594 * @author knut st. osmundsen (knut.stange.osmundsen@mynd.no)
1595 * Sander van Leeuwen (sandervl@xs4all.nl)
1596 * Patrick Haller (patrick.haller@innotek.de)
1597 * @remark - Do we still have to call Open32?
1598 */
1599DWORD WIN32API GetModuleFileNameA(HMODULE hModule, LPTSTR lpszPath, DWORD cchPath)
1600{
1601 Win32ImageBase * pMod; /* Pointer to the module object. */
1602 DWORD cch = 0; /* Length of the */
1603
1604 // PH 2002-04-24 Note:
1605 // WIN2k just crashes in NTDLL if lpszPath is invalid!
1606 if (!VALID_PSZ(lpszPath))
1607 {
1608 dprintf(("KERNEL32: GetModuleFileNameA(0x%x, 0x%x, 0x%x): invalid pointer lpszLibFile = 0x%x\n",
1609 hModule, lpszPath, cchPath, lpszPath));
1610 SetLastError(ERROR_INVALID_PARAMETER); //or maybe ERROR_ACCESS_DENIED is more appropriate?
1611 return 0;
1612 }
1613
1614 pMod = Win32ImageBase::findModule(hModule);
1615 if (pMod != NULL)
1616 {
1617 const char *pszFn = pMod->getFullPath();
1618 if (pszFn)
1619 {
1620 cch = strlen(pszFn);
1621 if (cch >= cchPath)
1622 cch = cchPath;
1623 else
1624 // if there is sufficient room for the zero termination,
1625 // write it additionally, uncounted
1626 lpszPath[cch] = '\0';
1627
1628 memcpy(lpszPath, pszFn, cch);
1629 }
1630 else
1631 {
1632 dprintf(("KERNEL32: GetModuleFileNameA(%x,...): IPE - getFullPath returned NULL or empty string\n"));
1633 DebugInt3();
1634 SetLastError(ERROR_INVALID_HANDLE);
1635 }
1636 }
1637 else
1638 {
1639 SetLastError(ERROR_INVALID_HANDLE);
1640 //only needed for call inside kernel32's initterm (profile init)
1641 //(console init only it seems...)
1642 cch = OSLibDosGetModuleFileName(hModule, lpszPath, cchPath);
1643 }
1644
1645 if (cch > 0)
1646 dprintf(("KERNEL32: GetModuleFileNameA(%x %x): %s %d\n", hModule, lpszPath, lpszPath, cch));
1647 else
1648 dprintf(("KERNEL32: WARNING: GetModuleFileNameA(%x,...) - not found!", hModule));
1649
1650 return cch;
1651}
1652
1653
1654/**
1655 * GetModuleFileName gets the full path and file name for the specified module.
1656 * @returns Bytes written to the buffer (lpszPath). This count includes the
1657 * terminating '\0'.
1658 * On error 0 is returned. Last error is set.
1659 * @param hModule Handle to the module you like to get the file name to.
1660 * @param lpszPath Output buffer for full path and file name.
1661 * @param cchPath Size of the lpszPath buffer.
1662 * @sketch Find the module object using handle.
1663 * If found Then
1664 * get full path from module object.
1665 * If found path Then
1666 * Determin path length.
1667 * Translate the path to into the buffer.
1668 * Else
1669 * IPE.
1670 * else
1671 * SetLastError to invalid handle.
1672 * Log result.
1673 * return number of bytes written to the buffer.
1674 *
1675 * @status Completely implemented.
1676 * @author knut st. osmundsen (knut.stange.osmundsen@mynd.no)
1677 * @remark - We do _NOT_ call Open32.
1678 * - Do we set ERROR_BUFFER_OVERFLOW when cch > cchPath?
1679 * - Does NT really set the last error?
1680 */
1681DWORD WIN32API GetModuleFileNameW(HMODULE hModule, LPWSTR lpszPath, DWORD cchPath)
1682{
1683 Win32ImageBase * pMod;
1684 DWORD cch = 0;
1685
1686 if (!VALID_PSZ(lpszPath))
1687 {
1688 dprintf(("KERNEL32: GetModuleFileNameW(0x%x, 0x%x, 0x%x): invalid pointer lpszLibFile = 0x%x\n",
1689 hModule, lpszPath, cchPath, lpszPath));
1690 SetLastError(ERROR_INVALID_PARAMETER); //or maybe ERROR_ACCESS_DENIED is more appropriate?
1691 return 0;
1692 }
1693
1694 pMod = Win32ImageBase::findModule(hModule);
1695 if (pMod != NULL)
1696 {
1697 const char *pszFn = pMod->getFullPath();
1698 if (pszFn || *pszFn != '\0')
1699 {
1700 cch = strlen(pszFn) + 1;
1701 if (cch > cchPath)
1702 cch = cchPath;
1703 AsciiToUnicodeN(pszFn, lpszPath, cch);
1704 }
1705 else
1706 {
1707 dprintf(("KERNEL32: GetModuleFileNameW(%x,...): IPE - getFullPath returned NULL or empty string\n"));
1708 DebugInt3();
1709 SetLastError(ERROR_INVALID_HANDLE);
1710 }
1711 }
1712 else
1713 SetLastError(ERROR_INVALID_HANDLE);
1714
1715 if (cch > 0)
1716 dprintf(("KERNEL32: GetModuleFileNameW(%x,...): %s %d\n", hModule, lpszPath, cch));
1717 else
1718 dprintf(("KERNEL32: WARNING: GetModuleFileNameW(%x,...) - not found!", hModule));
1719
1720 return cch;
1721}
1722
1723
1724//******************************************************************************
1725//NOTE: GetModuleHandleA does NOT support files with multiple dots (i.e.
1726// very.weird.exe)
1727//
1728// hinst = LoadLibrary("WINSPOOL.DRV"); -> succeeds
1729// hinst2 = GetModuleHandle("WINSPOOL.DRV"); -> succeeds
1730// hinst3 = GetModuleHandle("WINSPOOL."); -> fails
1731// hinst4 = GetModuleHandle("WINSPOOL"); -> fails
1732// hinst = LoadLibrary("KERNEL32.DLL"); -> succeeds
1733// hinst2 = GetModuleHandle("KERNEL32.DLL"); -> succeeds
1734// hinst3 = GetModuleHandle("KERNEL32."); -> fails
1735// hinst4 = GetModuleHandle("KERNEL32"); -> succeeds
1736// Same behaviour as observed in NT4, SP6
1737//******************************************************************************
1738HANDLE WIN32API GetModuleHandleA(LPCTSTR lpszModule)
1739{
1740 HANDLE hMod = 0;
1741 Win32DllBase *windll;
1742 char szModule[CCHMAXPATH];
1743 char *dot;
1744
1745 if(lpszModule == NULL)
1746 {
1747 if(WinExe)
1748 hMod = WinExe->getInstanceHandle();
1749 else
1750 {
1751 // // Just fail this API
1752 // hMod = 0;
1753 // SetLastError(ERROR_INVALID_HANDLE);
1754 // Wrong: in an ODIN32-LX environment, just
1755 // assume a fake handle
1756 hMod = -1;
1757 }
1758 }
1759 else
1760 {
1761 strcpy(szModule, OSLibStripPath((char *)lpszModule));
1762 strupr(szModule);
1763 dot = strchr(szModule, '.');
1764 if(dot == NULL) {
1765 //if no extension -> add .DLL (see SDK docs)
1766 strcat(szModule, DLL_EXTENSION);
1767 }
1768 else {
1769 if(dot[1] == 0) {
1770 //a trailing dot means the module has no extension (SDK docs)
1771 *dot = 0;
1772 }
1773 }
1774 if(WinExe && WinExe->matchModName(szModule)) {
1775 hMod = WinExe->getInstanceHandle();
1776 }
1777 else {
1778 windll = Win32DllBase::findModule(szModule);
1779 if(windll) {
1780 hMod = windll->getInstanceHandle();
1781 }
1782 }
1783 }
1784 dprintf(("KERNEL32: GetModuleHandle %s returned %X\n", lpszModule, hMod));
1785 return(hMod);
1786}
1787//******************************************************************************
1788//******************************************************************************
1789HMODULE WIN32API GetModuleHandleW(LPCWSTR lpwszModuleName)
1790{
1791 HMODULE rc;
1792 char *astring = NULL;
1793
1794 if (NULL != lpwszModuleName)
1795 astring = UnicodeToAsciiString((LPWSTR)lpwszModuleName);
1796
1797 rc = GetModuleHandleA(astring);
1798 dprintf(("KERNEL32: OS2GetModuleHandleW %s returned %X\n", astring, rc));
1799
1800 if (NULL != astring)
1801 FreeAsciiString(astring);
1802
1803 return(rc);
1804}
1805//******************************************************************************
1806//Checks whether program is LX or PE
1807//******************************************************************************
1808BOOL WIN32API ODIN_IsWin32App(LPSTR lpszProgramPath)
1809{
1810 DWORD Characteristics;
1811
1812 return Win32ImageBase::isPEImage(lpszProgramPath, &Characteristics, NULL) == NO_ERROR;
1813}
1814//******************************************************************************
1815//******************************************************************************
1816static char szPECmdLoader[260] = "";
1817static char szPEGUILoader[260] = "";
1818static char szNELoader[260] = "";
1819//******************************************************************************
1820//Set default paths for PE & NE loaders
1821//******************************************************************************
1822BOOL InitLoaders()
1823{
1824 sprintf(szPECmdLoader, "%s\\PEC.EXE", InternalGetSystemDirectoryA());
1825 sprintf(szPEGUILoader, "%s\\PE.EXE", InternalGetSystemDirectoryA());
1826 sprintf(szNELoader, "%s\\W16ODIN.EXE", InternalGetSystemDirectoryA());
1827
1828 return TRUE;
1829}
1830//******************************************************************************
1831//Override loader names (PEC, PE, W16ODIN)
1832//******************************************************************************
1833BOOL WIN32API ODIN_SetLoaders(LPCSTR pszPECmdLoader, LPCSTR pszPEGUILoader,
1834 LPCSTR pszNELoader)
1835{
1836 if(pszPECmdLoader) strcpy(szPECmdLoader, pszPECmdLoader);
1837 if(pszPEGUILoader) strcpy(szPEGUILoader, pszPEGUILoader);
1838 if(pszNELoader) strcpy(szNELoader, pszNELoader);
1839
1840 return TRUE;
1841}
1842//******************************************************************************
1843//******************************************************************************
1844BOOL WIN32API ODIN_QueryLoaders(LPSTR pszPECmdLoader, INT cchPECmdLoader,
1845 LPSTR pszPEGUILoader, INT cchPEGUILoader,
1846 LPSTR pszNELoader, INT cchNELoader)
1847{
1848 if(pszPECmdLoader) strncpy(pszPECmdLoader, szPECmdLoader, cchPECmdLoader);
1849 if(pszPEGUILoader) strncpy(pszPEGUILoader, szPEGUILoader, cchPEGUILoader);
1850 if(pszNELoader) strncpy(pszNELoader, szNELoader, cchNELoader);
1851
1852 return TRUE;
1853}
1854//******************************************************************************
1855//******************************************************************************
1856BOOL WINAPI CreateProcessA( LPCSTR lpApplicationName, LPSTR lpCommandLine,
1857 LPSECURITY_ATTRIBUTES lpProcessAttributes,
1858 LPSECURITY_ATTRIBUTES lpThreadAttributes,
1859 BOOL bInheritHandles, DWORD dwCreationFlags,
1860 LPVOID lpEnvironment, LPCSTR lpCurrentDirectory,
1861 LPSTARTUPINFOA lpStartupInfo,
1862 LPPROCESS_INFORMATION lpProcessInfo )
1863{
1864 STARTUPINFOA startinfo;
1865 TEB *pThreadDB = (TEB*)GetThreadTEB();
1866 char *cmdline = NULL;
1867 BOOL rc;
1868
1869 dprintf(("KERNEL32: CreateProcessA %s cline:%s inherit:%d cFlags:%x Env:%x CurDir:%s StartupFlags:%x\n",
1870 lpApplicationName, lpCommandLine, bInheritHandles, dwCreationFlags,
1871 lpEnvironment, lpCurrentDirectory, lpStartupInfo));
1872
1873#ifdef DEBUG
1874 if(lpStartupInfo) {
1875 dprintf(("lpStartupInfo->lpReserved %x", lpStartupInfo->lpReserved));
1876 dprintf(("lpStartupInfo->lpDesktop %x", lpStartupInfo->lpDesktop));
1877 dprintf(("lpStartupInfo->lpTitle %s", lpStartupInfo->lpTitle));
1878 dprintf(("lpStartupInfo->dwX %x", lpStartupInfo->dwX));
1879 dprintf(("lpStartupInfo->dwY %x", lpStartupInfo->dwY));
1880 dprintf(("lpStartupInfo->dwXSize %x", lpStartupInfo->dwXSize));
1881 dprintf(("lpStartupInfo->dwYSize %x", lpStartupInfo->dwYSize));
1882 dprintf(("lpStartupInfo->dwXCountChars %x", lpStartupInfo->dwXCountChars));
1883 dprintf(("lpStartupInfo->dwYCountChars %x", lpStartupInfo->dwYCountChars));
1884 dprintf(("lpStartupInfo->dwFillAttribute %x", lpStartupInfo->dwFillAttribute));
1885 dprintf(("lpStartupInfo->dwFlags %x", lpStartupInfo->dwFlags));
1886 dprintf(("lpStartupInfo->wShowWindow %x", lpStartupInfo->wShowWindow));
1887 dprintf(("lpStartupInfo->hStdInput %x", lpStartupInfo->hStdInput));
1888 dprintf(("lpStartupInfo->hStdOutput %x", lpStartupInfo->hStdOutput));
1889 dprintf(("lpStartupInfo->hStdError %x", lpStartupInfo->hStdError));
1890 }
1891#endif
1892
1893 if(bInheritHandles && lpStartupInfo->dwFlags & STARTF_USESTDHANDLES)
1894 {
1895 //Translate standard handles if the child needs to inherit them
1896 int retcode = 0;
1897
1898 memcpy(&startinfo, lpStartupInfo, sizeof(startinfo));
1899 retcode |= HMHandleTranslateToOS2(lpStartupInfo->hStdInput, &startinfo.hStdInput);
1900 retcode |= HMHandleTranslateToOS2(lpStartupInfo->hStdOutput, &startinfo.hStdOutput);
1901 retcode |= HMHandleTranslateToOS2(lpStartupInfo->hStdError, &startinfo.hStdError);
1902
1903 if(retcode) {
1904 SetLastError(ERROR_INVALID_HANDLE);
1905 return FALSE;
1906 }
1907
1908 lpStartupInfo = &startinfo;
1909 }
1910
1911 if(lpApplicationName) {
1912 if(lpCommandLine) {
1913 //skip exe name in lpCommandLine
1914 //TODO: doesn't work for directories with spaces!
1915 while(*lpCommandLine != 0 && *lpCommandLine != ' ')
1916 lpCommandLine++;
1917
1918 if(*lpCommandLine != 0) {
1919 lpCommandLine++;
1920 }
1921 cmdline = (char *)malloc(strlen(lpApplicationName)+strlen(lpCommandLine) + 16);
1922 sprintf(cmdline, "%s %s", lpApplicationName, lpCommandLine);
1923 }
1924 else {
1925 cmdline = (char *)malloc(strlen(lpApplicationName) + 16);
1926 sprintf(cmdline, "%s", lpApplicationName);
1927 }
1928 }
1929 else {
1930 cmdline = (char *)malloc(strlen(lpCommandLine) + 16);
1931 sprintf(cmdline, "%s", lpCommandLine);
1932 }
1933
1934 char szAppName[MAX_PATH];
1935 char buffer[MAX_PATH];
1936 DWORD fileAttr;
1937 char *exename;
1938
1939 exename = buffer;
1940 strncpy(buffer, cmdline, sizeof(buffer));
1941 buffer[MAX_PATH-1] = 0;
1942 if(*exename == '"') {
1943 exename++;
1944 while(*exename != 0 && *exename != '"')
1945 exename++;
1946
1947 if(*exename != 0) {
1948 *exename = 0;
1949 }
1950 exename++;
1951 if (SearchPathA( NULL, &buffer[1], ".exe", sizeof(szAppName), szAppName, NULL ) ||
1952 SearchPathA( NULL, &buffer[1], NULL, sizeof(szAppName), szAppName, NULL ))
1953 {
1954 //
1955 }
1956 }
1957 else {
1958 BOOL fTerminate = FALSE;
1959 DWORD fileAttr;
1960
1961 while(*exename != 0) {
1962 while(*exename != 0 && *exename != ' ')
1963 exename++;
1964
1965 if(*exename != 0) {
1966 *exename = 0;
1967 fTerminate = TRUE;
1968 }
1969 dprintf(("Trying '%s'", buffer ));
1970 if (SearchPathA( NULL, buffer, ".exe", sizeof(szAppName), szAppName, NULL ) ||
1971 SearchPathA( NULL, buffer, NULL, sizeof(szAppName), szAppName, NULL ))
1972 {
1973 if(fTerminate) exename++;
1974 break;
1975 }
1976
1977 if(fTerminate) {
1978 *exename = ' ';
1979 exename++;
1980 fTerminate = FALSE;
1981 }
1982 }
1983 }
1984 lpCommandLine = cmdline + (exename - buffer); //start of command line parameters
1985
1986 fileAttr = GetFileAttributesA(szAppName);
1987 if(fileAttr == -1 || (fileAttr & FILE_ATTRIBUTE_DIRECTORY)) {
1988 dprintf(("CreateProcess: can't find executable!"));
1989
1990 if(cmdline)
1991 free(cmdline);
1992
1993 SetLastError(ERROR_FILE_NOT_FOUND);
1994 return FALSE;
1995 }
1996
1997 // open32 does not support DEBUG_ONLY_THIS_PROCESS
1998 if(dwCreationFlags & DEBUG_ONLY_THIS_PROCESS)
1999 dwCreationFlags |= DEBUG_PROCESS;
2000
2001 if(O32_CreateProcess(szAppName, lpCommandLine, lpProcessAttributes,
2002 lpThreadAttributes, bInheritHandles, dwCreationFlags,
2003 lpEnvironment, lpCurrentDirectory, lpStartupInfo,
2004 lpProcessInfo) == TRUE)
2005 {
2006 if (dwCreationFlags & DEBUG_PROCESS && pThreadDB != NULL)
2007 {
2008 if(pThreadDB->o.odin.pidDebuggee != 0)
2009 {
2010 // TODO: handle this
2011 dprintf(("KERNEL32: CreateProcess ERROR: This thread is already a debugger\n"));
2012 }
2013 else
2014 {
2015 pThreadDB->o.odin.pidDebuggee = lpProcessInfo->dwProcessId;
2016 OSLibStartDebugger((ULONG*)&pThreadDB->o.odin.pidDebuggee);
2017 }
2018 }
2019 else pThreadDB->o.odin.pidDebuggee = 0;
2020
2021 if(lpProcessInfo)
2022 {
2023 lpProcessInfo->dwThreadId = MAKE_THREADID(lpProcessInfo->dwProcessId, lpProcessInfo->dwThreadId);
2024 }
2025
2026 if(cmdline)
2027 free(cmdline);
2028 return(TRUE);
2029 }
2030
2031 // PH 2001-05-07
2032 // verify why O32_CreateProcess actually failed.
2033 // If GetLastError() == 191 (ERROR_INVALID_EXE_SIGNATURE)
2034 // we can continue to call "PE.EXE".
2035 // Note: Open32 does not translate ERROR_INVALID_EXE_SIGNATURE,
2036 // it is also valid in Win32.
2037 DWORD dwError = GetLastError();
2038 if (ERROR_INVALID_EXE_SIGNATURE != dwError && ERROR_FILE_NOT_FOUND != dwError && ERROR_ACCESS_DENIED != dwError)
2039 {
2040 dprintf(("CreateProcess: O32_CreateProcess failed with rc=%d, not PE-executable !",
2041 dwError));
2042
2043 // the current value of GetLastError() is still valid.
2044
2045 if(cmdline)
2046 free(cmdline);
2047
2048 return FALSE;
2049 }
2050
2051 // else ...
2052
2053 //probably a win32 exe, so run it in the pe loader
2054 dprintf(("KERNEL32: CreateProcess %s %s", szAppName, lpCommandLine));
2055
2056 DWORD Characteristics, SubSystem, fNEExe;
2057 if(Win32ImageBase::isPEImage(szAppName, &Characteristics, &SubSystem, &fNEExe) == 0)
2058 {
2059 char *lpszPE;
2060 char *lpszExecutable;
2061 int iNewCommandLineLength;
2062
2063 // calculate base length for the new command line
2064 iNewCommandLineLength = strlen(szAppName) + strlen(lpCommandLine);
2065
2066 if(SubSystem == IMAGE_SUBSYSTEM_WINDOWS_CUI)
2067 lpszExecutable = (LPSTR)szPECmdLoader;
2068 else
2069 lpszExecutable = (LPSTR)szPEGUILoader;
2070
2071 lpszPE = lpszExecutable;
2072
2073 // 2002-04-24 PH
2074 // set the ODIN32.DEBUG_CHILD environment variable to start new PE processes
2075 // under a new instance of the (IPMD) debugger.
2076#ifdef DEBUG
2077 CHAR debug_szPE[ 512 ];
2078 PSZ debug_pszOS2Debugger = getenv("ODIN32.DEBUG_CHILD");
2079 if (NULL != debug_pszOS2Debugger)
2080 {
2081 // build new start command
2082 strcpy(debug_szPE, debug_pszOS2Debugger);
2083 strcat(debug_szPE, " ");
2084 strcat(debug_szPE, lpszExecutable);
2085
2086 // we require more space in the new command line
2087 iNewCommandLineLength += strlen( debug_szPE );
2088
2089 // only launch the specified executable (ICSDEBUG.EXE)
2090 lpszPE = debug_szPE;
2091 lpszExecutable = debug_pszOS2Debugger;
2092 }
2093#endif
2094
2095 //SvL: Allright. Before we call O32_CreateProcess, we must take care of
2096 // lpCurrentDirectory ourselves. (Open32 ignores it!)
2097 if(lpCurrentDirectory) {
2098 char *newcmdline;
2099
2100 newcmdline = (char *)malloc(strlen(lpCurrentDirectory) + iNewCommandLineLength + strlen(lpszPE) + 64);
2101 sprintf(newcmdline, "%s /OPT:[CURDIR=%s] %s %s", lpszPE, lpCurrentDirectory, szAppName, lpCommandLine);
2102 free(cmdline);
2103 cmdline = newcmdline;
2104 }
2105 else {
2106 char *newcmdline;
2107
2108 newcmdline = (char *)malloc(iNewCommandLineLength + strlen(lpszPE) + 16);
2109 sprintf(newcmdline, "%s %s %s", lpszPE, szAppName, lpCommandLine);
2110 free(cmdline);
2111 cmdline = newcmdline;
2112 }
2113
2114 dprintf(("KERNEL32: CreateProcess starting [%s],[%s]",
2115 lpszExecutable,
2116 cmdline));
2117
2118 rc = O32_CreateProcess(lpszExecutable, (LPCSTR)cmdline,lpProcessAttributes,
2119 lpThreadAttributes, bInheritHandles, dwCreationFlags,
2120 lpEnvironment, lpCurrentDirectory, lpStartupInfo,
2121 lpProcessInfo);
2122 }
2123 else
2124 if(fNEExe) {//16 bits windows app
2125 char *newcmdline;
2126
2127 newcmdline = (char *)malloc(strlen(szAppName) + strlen(cmdline) + strlen(szNELoader) + strlen(szPEGUILoader) + strlen(lpCommandLine) + 32);
2128
2129 sprintf(newcmdline, "%s /PELDR=[%s] %s", szNELoader, szPEGUILoader, szAppName, lpCommandLine);
2130 free(cmdline);
2131 cmdline = newcmdline;
2132 //Force Open32 to use DosStartSession (DosExecPgm won't do)
2133 dwCreationFlags |= CREATE_NEW_PROCESS_GROUP;
2134
2135 dprintf(("KERNEL32: CreateProcess starting [%s],[%s]",
2136 szNELoader,
2137 cmdline));
2138 rc = O32_CreateProcess(szNELoader, (LPCSTR)cmdline, lpProcessAttributes,
2139 lpThreadAttributes, bInheritHandles, dwCreationFlags,
2140 lpEnvironment, lpCurrentDirectory, lpStartupInfo,
2141 lpProcessInfo);
2142 }
2143 else {//os/2 app??
2144 rc = O32_CreateProcess(szAppName, (LPCSTR)lpCommandLine, lpProcessAttributes,
2145 lpThreadAttributes, bInheritHandles, dwCreationFlags,
2146 lpEnvironment, lpCurrentDirectory, lpStartupInfo,
2147 lpProcessInfo);
2148 }
2149 if(rc == TRUE)
2150 {
2151 if (dwCreationFlags & DEBUG_PROCESS && pThreadDB != NULL)
2152 {
2153 if(pThreadDB->o.odin.pidDebuggee != 0)
2154 {
2155 // TODO: handle this
2156 dprintf(("KERNEL32: CreateProcess ERROR: This thread is already a debugger\n"));
2157 }
2158 else
2159 {
2160 pThreadDB->o.odin.pidDebuggee = lpProcessInfo->dwProcessId;
2161 OSLibStartDebugger((ULONG*)&pThreadDB->o.odin.pidDebuggee);
2162 }
2163 }
2164 else
2165 pThreadDB->o.odin.pidDebuggee = 0;
2166 }
2167 if(cmdline)
2168 free(cmdline);
2169
2170 if(lpProcessInfo)
2171 {
2172 lpProcessInfo->dwThreadId = MAKE_THREADID(lpProcessInfo->dwProcessId, lpProcessInfo->dwThreadId);
2173 dprintf(("KERNEL32: CreateProcess returned %d hPro:%x hThr:%x pid:%x tid:%x\n",
2174 rc, lpProcessInfo->hProcess, lpProcessInfo->hThread,
2175 lpProcessInfo->dwProcessId,lpProcessInfo->dwThreadId));
2176 }
2177 else
2178 dprintf(("KERNEL32: CreateProcess returned %d\n", rc));
2179 return(rc);
2180}
2181//******************************************************************************
2182//******************************************************************************
2183BOOL WIN32API CreateProcessW(LPCWSTR lpApplicationName, LPWSTR lpCommandLine,
2184 PSECURITY_ATTRIBUTES lpProcessAttributes,
2185 PSECURITY_ATTRIBUTES lpThreadAttributes,
2186 BOOL bInheritHandles, DWORD dwCreationFlags,
2187 LPVOID lpEnvironment,
2188 LPCWSTR lpCurrentDirectory, LPSTARTUPINFOW lpStartupInfo,
2189 LPPROCESS_INFORMATION lpProcessInfo)
2190{
2191 BOOL rc;
2192 char *astring1 = 0, *astring2 = 0, *astring3 = 0;
2193
2194 dprintf(("KERNEL32: CreateProcessW"));
2195 if(lpApplicationName)
2196 astring1 = UnicodeToAsciiString((LPWSTR)lpApplicationName);
2197 if(lpCommandLine)
2198 astring2 = UnicodeToAsciiString(lpCommandLine);
2199 if(lpCurrentDirectory)
2200 astring3 = UnicodeToAsciiString((LPWSTR)lpCurrentDirectory);
2201 rc = CreateProcessA(astring1, astring2, lpProcessAttributes, lpThreadAttributes,
2202 bInheritHandles, dwCreationFlags, lpEnvironment,
2203 astring3, (LPSTARTUPINFOA)lpStartupInfo,
2204 lpProcessInfo);
2205 if(astring3) FreeAsciiString(astring3);
2206 if(astring2) FreeAsciiString(astring2);
2207 if(astring1) FreeAsciiString(astring1);
2208 return(rc);
2209}
2210//******************************************************************************
2211//******************************************************************************
2212HINSTANCE WIN32API WinExec(LPCSTR lpCmdLine, UINT nCmdShow)
2213{
2214 STARTUPINFOA startinfo = {0};
2215 PROCESS_INFORMATION procinfo;
2216 DWORD rc;
2217 HINSTANCE hInstance;
2218
2219 dprintf(("KERNEL32: WinExec %s\n", lpCmdLine));
2220 startinfo.dwFlags = nCmdShow;
2221 if(CreateProcessA(NULL, (LPSTR)lpCmdLine, NULL, NULL, FALSE, 0, NULL, NULL,
2222 &startinfo, &procinfo) == FALSE)
2223 {
2224 hInstance = (HINSTANCE)GetLastError();
2225 if(hInstance >= 32) {
2226 hInstance = 11;
2227 }
2228 dprintf(("KERNEL32: WinExec failed with rc %d", hInstance));
2229 return hInstance;
2230 }
2231 //block until the launched app waits for input (or a timeout of 15 seconds)
2232 //TODO: Shouldn't call Open32, but the api in user32..
2233 if(fVersionWarp3) {
2234 Sleep(1000); //WaitForInputIdle not available in Warp 3
2235 }
2236 else {
2237 dprintf(("Calling WaitForInputIdle %x %d", procinfo.hProcess, 15000));
2238 rc = WaitForInputIdle(procinfo.hProcess, 15000);
2239#ifdef DEBUG
2240 if(rc != 0) {
2241 dprintf(("WinExec: WaitForInputIdle %x returned %x", procinfo.hProcess, rc));
2242 }
2243 else dprintf(("WinExec: WaitForInputIdle successfull"));
2244#endif
2245 }
2246 CloseHandle(procinfo.hThread);
2247 CloseHandle(procinfo.hProcess);
2248 return 33;
2249}
2250//******************************************************************************
2251//DWORD idAttach; /* thread to attach */
2252//DWORD idAttachTo; /* thread to attach to */
2253//BOOL fAttach; /* attach or detach */
2254//******************************************************************************
2255BOOL WIN32API AttachThreadInput(DWORD idAttach, DWORD idAttachTo, BOOL fAttach)
2256{
2257 dprintf(("USER32: AttachThreadInput, not implemented\n"));
2258 return(TRUE);
2259}
2260//******************************************************************************
2261//******************************************************************************
2262DWORD WIN32API WaitForInputIdle(HANDLE hProcess, DWORD dwTimeOut)
2263{
2264 dprintf(("USER32: WaitForInputIdle %x %d\n", hProcess, dwTimeOut));
2265
2266 if(fVersionWarp3) {
2267 Sleep(1000);
2268 return 0;
2269 }
2270 else return O32_WaitForInputIdle(hProcess, dwTimeOut);
2271}
2272/**********************************************************************
2273 * LoadModule (KERNEL32.499)
2274 *
2275 * Wine: 20000909
2276 *
2277 * Copyright 1995 Alexandre Julliard
2278 */
2279HINSTANCE WINAPI LoadModule( LPCSTR name, LPVOID paramBlock )
2280{
2281 LOADPARAMS *params = (LOADPARAMS *)paramBlock;
2282 PROCESS_INFORMATION info;
2283 STARTUPINFOA startup;
2284 HINSTANCE hInstance;
2285 LPSTR cmdline, p;
2286 char filename[MAX_PATH];
2287 BYTE len;
2288
2289 dprintf(("LoadModule %s %x", name, paramBlock));
2290
2291 if (!name) return ERROR_FILE_NOT_FOUND;
2292
2293 if (!SearchPathA( NULL, name, ".exe", sizeof(filename), filename, NULL ) &&
2294 !SearchPathA( NULL, name, NULL, sizeof(filename), filename, NULL ))
2295 return GetLastError();
2296
2297 len = (BYTE)params->lpCmdLine[0];
2298 if (!(cmdline = (LPSTR)HeapAlloc( GetProcessHeap(), 0, strlen(filename) + len + 2 )))
2299 return ERROR_NOT_ENOUGH_MEMORY;
2300
2301 strcpy( cmdline, filename );
2302 p = cmdline + strlen(cmdline);
2303 *p++ = ' ';
2304 memcpy( p, params->lpCmdLine + 1, len );
2305 p[len] = 0;
2306
2307 memset( &startup, 0, sizeof(startup) );
2308 startup.cb = sizeof(startup);
2309 if (params->lpCmdShow)
2310 {
2311 startup.dwFlags = STARTF_USESHOWWINDOW;
2312 startup.wShowWindow = params->lpCmdShow[1];
2313 }
2314
2315 if (CreateProcessA( filename, cmdline, NULL, NULL, FALSE, 0,
2316 params->lpEnvAddress, NULL, &startup, &info ))
2317 {
2318 /* Give 15 seconds to the app to come up */
2319 if ( WaitForInputIdle ( info.hProcess, 15000 ) == 0xFFFFFFFF )
2320 dprintf(("ERROR: WaitForInputIdle failed: Error %ld\n", GetLastError() ));
2321 hInstance = 33;
2322 /* Close off the handles */
2323 CloseHandle( info.hThread );
2324 CloseHandle( info.hProcess );
2325 }
2326 else if ((hInstance = GetLastError()) >= 32)
2327 {
2328 dprintf(("ERROR: Strange error set by CreateProcess: %d\n", hInstance ));
2329 hInstance = 11;
2330 }
2331
2332 HeapFree( GetProcessHeap(), 0, cmdline );
2333 return hInstance;
2334}
2335//******************************************************************************
2336//******************************************************************************
2337FARPROC WIN32API GetProcAddress(HMODULE hModule, LPCSTR lpszProc)
2338{
2339 Win32ImageBase *winmod;
2340 FARPROC proc;
2341 ULONG ulAPIOrdinal;
2342
2343 if(hModule == 0 || hModule == -1 || (WinExe && hModule == WinExe->getInstanceHandle())) {
2344 winmod = WinExe;
2345 }
2346 else winmod = (Win32ImageBase *)Win32DllBase::findModule((HINSTANCE)hModule);
2347
2348 if(winmod) {
2349 ulAPIOrdinal = (ULONG)lpszProc;
2350 if (ulAPIOrdinal <= 0x0000FFFF) {
2351 proc = (FARPROC)winmod->getApi((int)ulAPIOrdinal);
2352 }
2353 else proc = (FARPROC)winmod->getApi((char *)lpszProc);
2354 if(proc == 0) {
2355#ifdef DEBUG
2356 if(ulAPIOrdinal <= 0x0000FFFF) {
2357 dprintf(("GetProcAddress %x %x not found!", hModule, ulAPIOrdinal));
2358 }
2359 else dprintf(("GetProcAddress %x %s not found!", hModule, lpszProc));
2360#endif
2361 SetLastError(ERROR_PROC_NOT_FOUND);
2362 }
2363 if(HIWORD(lpszProc))
2364 dprintf(("KERNEL32: GetProcAddress %s from %X returned %X\n", lpszProc, hModule, proc));
2365 else dprintf(("KERNEL32: GetProcAddress %x from %X returned %X\n", lpszProc, hModule, proc));
2366
2367 SetLastError(ERROR_SUCCESS);
2368 return proc;
2369 }
2370 proc = (FARPROC)OSLibDosGetProcAddress(hModule, lpszProc);
2371 if(HIWORD(lpszProc))
2372 dprintf(("KERNEL32: GetProcAddress %s from %X returned %X\n", lpszProc, hModule, proc));
2373 else dprintf(("KERNEL32: GetProcAddress %x from %X returned %X\n", lpszProc, hModule, proc));
2374 SetLastError(ERROR_SUCCESS);
2375 return(proc);
2376}
2377//******************************************************************************
2378// ODIN_SetProcAddress: Override a dll export
2379//
2380// Parameters:
2381// HMODULE hModule Module handle
2382// LPCSTR lpszProc Export name or ordinal
2383// FARPROC pfnNewProc New export function address
2384//
2385// Returns: Success -> old address of export
2386// Failure -> -1
2387//
2388//******************************************************************************
2389FARPROC WIN32API ODIN_SetProcAddress(HMODULE hModule, LPCSTR lpszProc,
2390 FARPROC pfnNewProc)
2391{
2392 Win32ImageBase *winmod;
2393 FARPROC proc;
2394 ULONG ulAPIOrdinal;
2395
2396 if(hModule == 0 || hModule == -1 || (WinExe && hModule == WinExe->getInstanceHandle())) {
2397 winmod = WinExe;
2398 }
2399 else winmod = (Win32ImageBase *)Win32DllBase::findModule((HINSTANCE)hModule);
2400
2401 if(winmod) {
2402 ulAPIOrdinal = (ULONG)lpszProc;
2403 if (ulAPIOrdinal <= 0x0000FFFF) {
2404 proc = (FARPROC)winmod->setApi((int)ulAPIOrdinal, (ULONG)pfnNewProc);
2405 }
2406 else proc = (FARPROC)winmod->setApi((char *)lpszProc, (ULONG)pfnNewProc);
2407 if(proc == 0) {
2408#ifdef DEBUG
2409 if(ulAPIOrdinal <= 0x0000FFFF) {
2410 dprintf(("ODIN_SetProcAddress %x %x not found!", hModule, ulAPIOrdinal));
2411 }
2412 else dprintf(("ODIN_SetProcAddress %x %s not found!", hModule, lpszProc));
2413#endif
2414 SetLastError(ERROR_PROC_NOT_FOUND);
2415 }
2416 if(HIWORD(lpszProc))
2417 dprintf(("KERNEL32: ODIN_SetProcAddress %s from %X returned %X\n", lpszProc, hModule, proc));
2418 else dprintf(("KERNEL32: ODIN_SetProcAddress %x from %X returned %X\n", lpszProc, hModule, proc));
2419
2420 SetLastError(ERROR_SUCCESS);
2421 return proc;
2422 }
2423 SetLastError(ERROR_INVALID_HANDLE);
2424 return (FARPROC)-1;
2425}
2426//******************************************************************************
2427//Retrieve the version
2428//******************************************************************************
2429BOOL SYSTEM GetVersionStruct(char *lpszModName, char *verstruct, ULONG bufLength)
2430{
2431 Win32ImageBase *winimage;
2432 HINSTANCE hDll;
2433 BOOL rc = FALSE;
2434
2435 dprintf(("GetVersionStruct of module %s %x %d", lpszModName, verstruct, bufLength));
2436 if(verstruct == NULL) {
2437 SetLastError(ERROR_INVALID_PARAMETER);
2438 return FALSE;
2439 }
2440 if (WinExe != NULL && WinExe->matchModName(lpszModName)) {
2441 return WinExe->getVersionStruct(verstruct, bufLength);
2442 }
2443 hDll = LoadLibraryExA(lpszModName, 0, LOAD_LIBRARY_AS_DATAFILE);
2444 if(hDll == 0) {
2445 dprintf(("ERROR: GetVersionStruct: Unable to load module!!"));
2446 return 0;
2447 }
2448 winimage = (Win32ImageBase *)Win32DllBase::findModule(hDll);
2449 if(winimage != NULL) {
2450 rc = winimage->getVersionStruct(verstruct, bufLength);
2451 }
2452 else {
2453 dprintf(("GetVersionStruct; just loaded dll %s, but can't find it now!", lpszModName));
2454//// DebugInt3();
2455 }
2456 FreeLibrary(hDll);
2457 return rc;
2458}
2459//******************************************************************************
2460//******************************************************************************
2461ULONG SYSTEM GetVersionSize(char *lpszModName)
2462{
2463 Win32ImageBase *winimage;
2464 HINSTANCE hDll;
2465 ULONG size = 0;
2466
2467 dprintf(("GetVersionSize of %s", lpszModName));
2468 if (WinExe != NULL && WinExe->matchModName(lpszModName)) {
2469 return WinExe->getVersionSize();
2470 }
2471
2472 hDll = LoadLibraryExA(lpszModName, 0, LOAD_LIBRARY_AS_DATAFILE);
2473 if(hDll == 0) {
2474 dprintf(("ERROR: GetVersionStruct: Unable to load module!!"));
2475 return 0;
2476 }
2477 winimage = (Win32ImageBase *)Win32DllBase::findModule(hDll);
2478 if(winimage != NULL) {
2479 size = winimage->getVersionSize();
2480 }
2481 else {
2482 dprintf(("GetVersionSize; just loaded dll %s, but can't find it now!", lpszModName));
2483//// DebugInt3();
2484 }
2485 FreeLibrary(hDll);
2486 return size;
2487}
2488//******************************************************************************
2489//******************************************************************************
2490BOOL WIN32API DisableThreadLibraryCalls(HMODULE hModule)
2491{
2492 Win32DllBase *winmod;
2493 FARPROC proc;
2494 ULONG ulAPIOrdinal;
2495
2496 winmod = Win32DllBase::findModule((HINSTANCE)hModule);
2497 if(winmod)
2498 {
2499 // don't call ATTACH/DETACH thread functions in DLL
2500 winmod->disableThreadLibraryCalls();
2501 return TRUE;
2502 }
2503 else
2504 {
2505 // raise error condition
2506 SetLastError(ERROR_INVALID_HANDLE);
2507 return FALSE;
2508 }
2509}
2510//******************************************************************************
2511//******************************************************************************
Note: See TracBrowser for help on using the repository browser.