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

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

KSO: Implemented WM_COPYDATA

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