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

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

PF: Corrected HFILE definition as it is in Wine and in Win2k

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