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

Last change on this file since 21673 was 21673, checked in by dmik, 14 years ago

CreateProcessA: Add support for CREATE_UNICODE_ENVIRONMENT.

This also fixes CreateProcessW calls which didn't handle the environment properly.

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