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

Last change on this file since 21469 was 21469, checked in by dmik, 15 years ago

Fixed: argv[argc] must be NULL.

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