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

Last change on this file since 21999 was 21999, checked in by dmik, 13 years ago

kernel32: Make SEH work in OS/2 context.

See #82 for details.

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