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

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

KSO: GetStartupInfo changes

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