Porting fixes.
[wine/wine-kai.git] / dlls / kernel / process.c
blob23e51c94e6d71ebb7ba92a549325dbd8ce591dae
1 /*
2 * Win32 processes
4 * Copyright 1996, 1998 Alexandre Julliard
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
21 #include "config.h"
22 #include "wine/port.h"
24 #include <assert.h>
25 #include <ctype.h>
26 #include <errno.h>
27 #include <locale.h>
28 #include <signal.h>
29 #include <stdio.h>
31 #include "wine/winbase16.h"
32 #include "wine/winuser16.h"
33 #include "ntstatus.h"
34 #include "thread.h"
35 #include "drive.h"
36 #include "file.h"
37 #include "module.h"
38 #include "options.h"
39 #include "kernel_private.h"
40 #include "wine/exception.h"
41 #include "wine/server.h"
42 #include "wine/unicode.h"
43 #include "wine/debug.h"
45 WINE_DEFAULT_DEBUG_CHANNEL(process);
46 WINE_DECLARE_DEBUG_CHANNEL(server);
47 WINE_DECLARE_DEBUG_CHANNEL(relay);
49 typedef struct
51 LPSTR lpEnvAddress;
52 LPSTR lpCmdLine;
53 LPSTR lpCmdShow;
54 DWORD dwReserved;
55 } LOADPARMS32;
57 static UINT process_error_mode;
59 static HANDLE main_exe_file;
60 static DWORD shutdown_flags = 0;
61 static DWORD shutdown_priority = 0x280;
62 static DWORD process_dword;
63 static BOOL oem_file_apis;
65 static unsigned int server_startticks;
66 int main_create_flags = 0;
68 /* Process flags */
69 #define PDB32_DEBUGGED 0x0001 /* Process is being debugged */
70 #define PDB32_WIN16_PROC 0x0008 /* Win16 process */
71 #define PDB32_DOS_PROC 0x0010 /* Dos process */
72 #define PDB32_CONSOLE_PROC 0x0020 /* Console process */
73 #define PDB32_FILE_APIS_OEM 0x0040 /* File APIs are OEM */
74 #define PDB32_WIN32S_PROC 0x8000 /* Win32s process */
76 static const WCHAR comW[] = {'.','c','o','m',0};
77 static const WCHAR batW[] = {'.','b','a','t',0};
78 static const WCHAR winevdmW[] = {'w','i','n','e','v','d','m','.','e','x','e',0};
80 extern void SHELL_LoadRegistry(void);
81 extern void VERSION_Init( const WCHAR *appname );
82 extern void MODULE_InitLoadPath(void);
83 extern void LOCALE_Init(void);
85 /***********************************************************************
86 * contains_path
88 inline static int contains_path( LPCWSTR name )
90 return ((*name && (name[1] == ':')) || strchrW(name, '/') || strchrW(name, '\\'));
94 /***************************************************************************
95 * get_builtin_path
97 * Get the path of a builtin module when the native file does not exist.
99 static BOOL get_builtin_path( const WCHAR *libname, const WCHAR *ext, WCHAR *filename, UINT size )
101 WCHAR *file_part;
102 WCHAR sysdir[MAX_PATH];
103 UINT len = GetSystemDirectoryW( sysdir, MAX_PATH );
105 if (contains_path( libname ))
107 if (RtlGetFullPathName_U( libname, size * sizeof(WCHAR),
108 filename, &file_part ) > size * sizeof(WCHAR))
109 return FALSE; /* too long */
111 if (strncmpiW( filename, sysdir, len ) || filename[len] != '\\')
112 return FALSE;
113 while (filename[len] == '\\') len++;
114 if (filename + len != file_part) return FALSE;
116 else
118 if (strlenW(libname) + len + 2 >= size) return FALSE; /* too long */
119 memcpy( filename, sysdir, len * sizeof(WCHAR) );
120 file_part = filename + len;
121 if (file_part > filename && file_part[-1] != '\\') *file_part++ = '\\';
122 strcpyW( file_part, libname );
124 if (ext && !strchrW( file_part, '.' ))
126 if (file_part + strlenW(file_part) + strlenW(ext) + 1 > filename + size)
127 return FALSE; /* too long */
128 strcatW( file_part, ext );
130 return TRUE;
134 /***********************************************************************
135 * open_builtin_exe_file
137 * Open an exe file for a builtin exe.
139 static void *open_builtin_exe_file( const WCHAR *name, char *error, int error_size,
140 int test_only, int *file_exists )
142 char exename[MAX_PATH];
143 WCHAR *p;
144 UINT i, len;
146 if ((p = strrchrW( name, '/' ))) name = p + 1;
147 if ((p = strrchrW( name, '\\' ))) name = p + 1;
149 /* we don't want to depend on the current codepage here */
150 len = strlenW( name ) + 1;
151 if (len >= sizeof(exename)) return NULL;
152 for (i = 0; i < len; i++)
154 if (name[i] > 127) return NULL;
155 exename[i] = (char)name[i];
156 if (exename[i] >= 'A' && exename[i] <= 'Z') exename[i] += 'a' - 'A';
158 return wine_dll_load_main_exe( exename, error, error_size, test_only, file_exists );
162 /***********************************************************************
163 * open_exe_file
165 * Open a specific exe file, taking load order into account.
166 * Returns the file handle or 0 for a builtin exe.
168 static HANDLE open_exe_file( const WCHAR *name )
170 enum loadorder_type loadorder[LOADORDER_NTYPES];
171 WCHAR buffer[MAX_PATH];
172 HANDLE handle;
173 int i, file_exists;
175 TRACE("looking for %s\n", debugstr_w(name) );
177 if ((handle = CreateFileW( name, GENERIC_READ, FILE_SHARE_READ,
178 NULL, OPEN_EXISTING, 0, 0 )) == INVALID_HANDLE_VALUE)
180 /* file doesn't exist, check for builtin */
181 if (!contains_path( name )) goto error;
182 if (!get_builtin_path( name, NULL, buffer, sizeof(buffer) )) goto error;
183 name = buffer;
186 MODULE_GetLoadOrderW( loadorder, NULL, name );
188 for(i = 0; i < LOADORDER_NTYPES; i++)
190 if (loadorder[i] == LOADORDER_INVALID) break;
191 switch(loadorder[i])
193 case LOADORDER_DLL:
194 TRACE( "Trying native exe %s\n", debugstr_w(name) );
195 if (handle != INVALID_HANDLE_VALUE) return handle;
196 break;
197 case LOADORDER_BI:
198 TRACE( "Trying built-in exe %s\n", debugstr_w(name) );
199 open_builtin_exe_file( name, NULL, 0, 1, &file_exists );
200 if (file_exists)
202 if (handle != INVALID_HANDLE_VALUE) CloseHandle(handle);
203 return 0;
205 default:
206 break;
209 if (handle != INVALID_HANDLE_VALUE) CloseHandle(handle);
211 error:
212 SetLastError( ERROR_FILE_NOT_FOUND );
213 return INVALID_HANDLE_VALUE;
217 /***********************************************************************
218 * find_exe_file
220 * Open an exe file, and return the full name and file handle.
221 * Returns FALSE if file could not be found.
222 * If file exists but cannot be opened, returns TRUE and set handle to INVALID_HANDLE_VALUE.
223 * If file is a builtin exe, returns TRUE and sets handle to 0.
225 static BOOL find_exe_file( const WCHAR *name, WCHAR *buffer, int buflen, HANDLE *handle )
227 static const WCHAR exeW[] = {'.','e','x','e',0};
229 enum loadorder_type loadorder[LOADORDER_NTYPES];
230 int i, file_exists;
232 TRACE("looking for %s\n", debugstr_w(name) );
234 if (!SearchPathW( NULL, name, exeW, buflen, buffer, NULL ) &&
235 !get_builtin_path( name, exeW, buffer, buflen ))
237 /* no builtin found, try native without extension in case it is a Unix app */
239 if (SearchPathW( NULL, name, NULL, buflen, buffer, NULL ))
241 TRACE( "Trying native/Unix binary %s\n", debugstr_w(buffer) );
242 if ((*handle = CreateFileW( buffer, GENERIC_READ, FILE_SHARE_READ,
243 NULL, OPEN_EXISTING, 0, 0 )) != INVALID_HANDLE_VALUE)
244 return TRUE;
246 return FALSE;
249 MODULE_GetLoadOrderW( loadorder, NULL, buffer );
251 for(i = 0; i < LOADORDER_NTYPES; i++)
253 if (loadorder[i] == LOADORDER_INVALID) break;
254 switch(loadorder[i])
256 case LOADORDER_DLL:
257 TRACE( "Trying native exe %s\n", debugstr_w(buffer) );
258 if ((*handle = CreateFileW( buffer, GENERIC_READ, FILE_SHARE_READ,
259 NULL, OPEN_EXISTING, 0, 0 )) != INVALID_HANDLE_VALUE)
260 return TRUE;
261 if (GetLastError() != ERROR_FILE_NOT_FOUND) return TRUE;
262 break;
263 case LOADORDER_BI:
264 TRACE( "Trying built-in exe %s\n", debugstr_w(buffer) );
265 open_builtin_exe_file( buffer, NULL, 0, 1, &file_exists );
266 if (file_exists)
268 *handle = 0;
269 return TRUE;
271 break;
272 default:
273 break;
276 SetLastError( ERROR_FILE_NOT_FOUND );
277 return FALSE;
281 /**********************************************************************
282 * load_pe_exe
284 * Load a PE format EXE file.
286 static HMODULE load_pe_exe( const WCHAR *name, HANDLE file )
288 IMAGE_NT_HEADERS *nt;
289 HANDLE mapping;
290 void *module;
291 OBJECT_ATTRIBUTES attr;
292 LARGE_INTEGER size;
293 DWORD len = 0;
294 UINT drive_type;
296 attr.Length = sizeof(attr);
297 attr.RootDirectory = 0;
298 attr.ObjectName = NULL;
299 attr.Attributes = 0;
300 attr.SecurityDescriptor = NULL;
301 attr.SecurityQualityOfService = NULL;
302 size.QuadPart = 0;
304 if (NtCreateSection( &mapping, STANDARD_RIGHTS_REQUIRED | SECTION_QUERY | SECTION_MAP_READ,
305 &attr, &size, 0, SEC_IMAGE, file ) != STATUS_SUCCESS)
306 return NULL;
308 module = NULL;
309 if (NtMapViewOfSection( mapping, GetCurrentProcess(), &module, 0, 0, &size, &len,
310 ViewShare, 0, PAGE_READONLY ) != STATUS_SUCCESS)
311 return NULL;
313 NtClose( mapping );
315 /* virus check */
316 nt = RtlImageNtHeader( module );
317 if (nt->OptionalHeader.AddressOfEntryPoint)
319 if (!RtlImageRvaToSection( nt, module, nt->OptionalHeader.AddressOfEntryPoint ))
320 MESSAGE("VIRUS WARNING: PE module %s has an invalid entrypoint (0x%08lx) "
321 "outside all sections (possibly infected by Tchernobyl/SpaceFiller virus)!\n",
322 debugstr_w(name), nt->OptionalHeader.AddressOfEntryPoint );
325 drive_type = GetDriveTypeW( name );
326 /* don't keep the file handle open on removable media */
327 if (drive_type == DRIVE_REMOVABLE || drive_type == DRIVE_CDROM)
329 CloseHandle( main_exe_file );
330 main_exe_file = 0;
333 return module;
336 /***********************************************************************
337 * build_initial_environment
339 * Build the Win32 environment from the Unix environment
341 static BOOL build_initial_environment( char **environ )
343 ULONG size = 1;
344 char **e;
345 WCHAR *p, *endptr;
346 void *ptr;
348 /* Compute the total size of the Unix environment */
349 for (e = environ; *e; e++)
351 if (!memcmp(*e, "PATH=", 5)) continue;
352 size += MultiByteToWideChar( CP_UNIXCP, 0, *e, -1, NULL, 0 );
354 size *= sizeof(WCHAR);
356 /* Now allocate the environment */
357 if (NtAllocateVirtualMemory(NtCurrentProcess(), &ptr, 0, &size,
358 MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) != STATUS_SUCCESS)
359 return FALSE;
361 NtCurrentTeb()->Peb->ProcessParameters->Environment = p = ptr;
362 endptr = p + size / sizeof(WCHAR);
364 /* And fill it with the Unix environment */
365 for (e = environ; *e; e++)
367 char *str = *e;
368 /* skip Unix PATH and store WINEPATH as PATH */
369 if (!memcmp(str, "PATH=", 5)) continue;
370 if (!memcmp(str, "WINEPATH=", 9 )) str += 4;
371 MultiByteToWideChar( CP_UNIXCP, 0, str, -1, p, endptr - p );
372 p += strlenW(p) + 1;
374 *p = 0;
375 return TRUE;
379 /***********************************************************************
380 * set_library_wargv
382 * Set the Wine library Unicode argv global variables.
384 static void set_library_wargv( char **argv )
386 int argc;
387 WCHAR *p;
388 WCHAR **wargv;
389 DWORD total = 0;
391 for (argc = 0; argv[argc]; argc++)
392 total += MultiByteToWideChar( CP_UNIXCP, 0, argv[argc], -1, NULL, 0 );
394 wargv = RtlAllocateHeap( GetProcessHeap(), 0,
395 total * sizeof(WCHAR) + (argc + 1) * sizeof(*wargv) );
396 p = (WCHAR *)(wargv + argc + 1);
397 for (argc = 0; argv[argc]; argc++)
399 DWORD reslen = MultiByteToWideChar( CP_UNIXCP, 0, argv[argc], -1, p, total );
400 wargv[argc] = p;
401 p += reslen;
402 total -= reslen;
404 wargv[argc] = NULL;
405 __wine_main_wargv = wargv;
409 /***********************************************************************
410 * build_command_line
412 * Build the command line of a process from the argv array.
414 * Note that it does NOT necessarily include the file name.
415 * Sometimes we don't even have any command line options at all.
417 * We must quote and escape characters so that the argv array can be rebuilt
418 * from the command line:
419 * - spaces and tabs must be quoted
420 * 'a b' -> '"a b"'
421 * - quotes must be escaped
422 * '"' -> '\"'
423 * - if '\'s are followed by a '"', they must be doubled and followed by '\"',
424 * resulting in an odd number of '\' followed by a '"'
425 * '\"' -> '\\\"'
426 * '\\"' -> '\\\\\"'
427 * - '\'s that are not followed by a '"' can be left as is
428 * 'a\b' == 'a\b'
429 * 'a\\b' == 'a\\b'
431 static BOOL build_command_line( WCHAR **argv )
433 int len;
434 WCHAR **arg;
435 LPWSTR p;
436 RTL_USER_PROCESS_PARAMETERS* rupp = NtCurrentTeb()->Peb->ProcessParameters;
438 if (rupp->CommandLine.Buffer) return TRUE; /* already got it from the server */
440 len = 0;
441 for (arg = argv; *arg; arg++)
443 int has_space,bcount;
444 WCHAR* a;
446 has_space=0;
447 bcount=0;
448 a=*arg;
449 if( !*a ) has_space=1;
450 while (*a!='\0') {
451 if (*a=='\\') {
452 bcount++;
453 } else {
454 if (*a==' ' || *a=='\t') {
455 has_space=1;
456 } else if (*a=='"') {
457 /* doubling of '\' preceeding a '"',
458 * plus escaping of said '"'
460 len+=2*bcount+1;
462 bcount=0;
464 a++;
466 len+=(a-*arg)+1 /* for the separating space */;
467 if (has_space)
468 len+=2; /* for the quotes */
471 if (!(rupp->CommandLine.Buffer = RtlAllocateHeap( GetProcessHeap(), 0, len * sizeof(WCHAR))))
472 return FALSE;
474 p = rupp->CommandLine.Buffer;
475 rupp->CommandLine.Length = (len - 1) * sizeof(WCHAR);
476 rupp->CommandLine.MaximumLength = len * sizeof(WCHAR);
477 for (arg = argv; *arg; arg++)
479 int has_space,has_quote;
480 WCHAR* a;
482 /* Check for quotes and spaces in this argument */
483 has_space=has_quote=0;
484 a=*arg;
485 if( !*a ) has_space=1;
486 while (*a!='\0') {
487 if (*a==' ' || *a=='\t') {
488 has_space=1;
489 if (has_quote)
490 break;
491 } else if (*a=='"') {
492 has_quote=1;
493 if (has_space)
494 break;
496 a++;
499 /* Now transfer it to the command line */
500 if (has_space)
501 *p++='"';
502 if (has_quote) {
503 int bcount;
504 WCHAR* a;
506 bcount=0;
507 a=*arg;
508 while (*a!='\0') {
509 if (*a=='\\') {
510 *p++=*a;
511 bcount++;
512 } else {
513 if (*a=='"') {
514 int i;
516 /* Double all the '\\' preceeding this '"', plus one */
517 for (i=0;i<=bcount;i++)
518 *p++='\\';
519 *p++='"';
520 } else {
521 *p++=*a;
523 bcount=0;
525 a++;
527 } else {
528 WCHAR* x = *arg;
529 while ((*p=*x++)) p++;
531 if (has_space)
532 *p++='"';
533 *p++=' ';
535 if (p > rupp->CommandLine.Buffer)
536 p--; /* remove last space */
537 *p = '\0';
539 return TRUE;
543 /* make sure the unicode string doesn't point beyond the end pointer */
544 static inline void fix_unicode_string( UNICODE_STRING *str, char *end_ptr )
546 if ((char *)str->Buffer >= end_ptr)
548 str->Length = str->MaximumLength = 0;
549 str->Buffer = NULL;
550 return;
552 if ((char *)str->Buffer + str->MaximumLength > end_ptr)
554 str->MaximumLength = (end_ptr - (char *)str->Buffer) & ~(sizeof(WCHAR) - 1);
556 if (str->Length >= str->MaximumLength)
558 if (str->MaximumLength >= sizeof(WCHAR))
559 str->Length = str->MaximumLength - sizeof(WCHAR);
560 else
561 str->Length = str->MaximumLength = 0;
566 /***********************************************************************
567 * init_user_process_params
569 * Fill the RTL_USER_PROCESS_PARAMETERS structure from the server.
571 static RTL_USER_PROCESS_PARAMETERS *init_user_process_params( size_t info_size )
573 void *ptr;
574 DWORD size;
575 NTSTATUS status;
576 RTL_USER_PROCESS_PARAMETERS *params;
578 size = info_size;
579 if ((status = NtAllocateVirtualMemory( NtCurrentProcess(), &ptr, NULL, &size,
580 MEM_COMMIT, PAGE_READWRITE )) != STATUS_SUCCESS)
581 return NULL;
583 SERVER_START_REQ( get_startup_info )
585 wine_server_set_reply( req, ptr, info_size );
586 wine_server_call( req );
587 info_size = wine_server_reply_size( reply );
589 SERVER_END_REQ;
591 params = ptr;
592 params->Size = info_size;
593 params->AllocationSize = size;
595 /* make sure the strings are valid */
596 fix_unicode_string( &params->CurrentDirectoryName, (char *)info_size );
597 fix_unicode_string( &params->DllPath, (char *)info_size );
598 fix_unicode_string( &params->ImagePathName, (char *)info_size );
599 fix_unicode_string( &params->CommandLine, (char *)info_size );
600 fix_unicode_string( &params->WindowTitle, (char *)info_size );
601 fix_unicode_string( &params->Desktop, (char *)info_size );
602 fix_unicode_string( &params->ShellInfo, (char *)info_size );
603 fix_unicode_string( &params->RuntimeInfo, (char *)info_size );
605 return RtlNormalizeProcessParams( params );
609 /***********************************************************************
610 * process_init
612 * Main process initialisation code
614 static BOOL process_init( char *argv[], char **environ )
616 BOOL ret;
617 size_t info_size = 0;
618 RTL_USER_PROCESS_PARAMETERS *params;
619 PEB *peb = NtCurrentTeb()->Peb;
620 HANDLE hstdin, hstdout, hstderr;
622 setbuf(stdout,NULL);
623 setbuf(stderr,NULL);
624 setlocale(LC_CTYPE,"");
626 /* Retrieve startup info from the server */
627 SERVER_START_REQ( init_process )
629 req->peb = peb;
630 req->ldt_copy = &wine_ldt_copy;
631 if ((ret = !wine_server_call_err( req )))
633 main_exe_file = reply->exe_file;
634 main_create_flags = reply->create_flags;
635 info_size = reply->info_size;
636 server_startticks = reply->server_start;
637 hstdin = reply->hstdin;
638 hstdout = reply->hstdout;
639 hstderr = reply->hstderr;
642 SERVER_END_REQ;
643 if (!ret) return FALSE;
645 if (info_size == 0)
647 params = peb->ProcessParameters;
649 /* This is wine specific: we have no parent (we're started from unix)
650 * so, create a simple console with bare handles to unix stdio
651 * input & output streams (aka simple console)
653 wine_server_fd_to_handle( 0, GENERIC_READ|SYNCHRONIZE, TRUE, &params->hStdInput );
654 wine_server_fd_to_handle( 1, GENERIC_WRITE|SYNCHRONIZE, TRUE, &params->hStdOutput );
655 wine_server_fd_to_handle( 2, GENERIC_WRITE|SYNCHRONIZE, TRUE, &params->hStdError );
657 /* <hack: to be changed later on> */
658 params->CurrentDirectoryName.Length = 3 * sizeof(WCHAR);
659 params->CurrentDirectoryName.MaximumLength = RtlGetLongestNtPathLength() * sizeof(WCHAR);
660 params->CurrentDirectoryName.Buffer = RtlAllocateHeap( GetProcessHeap(), 0, params->CurrentDirectoryName.MaximumLength);
661 params->CurrentDirectoryName.Buffer[0] = 'C';
662 params->CurrentDirectoryName.Buffer[1] = ':';
663 params->CurrentDirectoryName.Buffer[2] = '\\';
664 params->CurrentDirectoryName.Buffer[3] = '\0';
665 /* </hack: to be changed later on> */
667 else
669 if (!(params = init_user_process_params( info_size ))) return FALSE;
670 peb->ProcessParameters = params;
672 /* convert value from server:
673 * + 0 => INVALID_HANDLE_VALUE
674 * + console handle need to be mapped
676 if (!hstdin)
677 hstdin = INVALID_HANDLE_VALUE;
678 else if (VerifyConsoleIoHandle(console_handle_map(hstdin)))
679 hstdin = console_handle_map(hstdin);
681 if (!hstdout)
682 hstdout = INVALID_HANDLE_VALUE;
683 else if (VerifyConsoleIoHandle(console_handle_map(hstdout)))
684 hstdout = console_handle_map(hstdout);
686 if (!hstderr)
687 hstderr = INVALID_HANDLE_VALUE;
688 else if (VerifyConsoleIoHandle(console_handle_map(hstderr)))
689 hstderr = console_handle_map(hstderr);
691 params->hStdInput = hstdin;
692 params->hStdOutput = hstdout;
693 params->hStdError = hstderr;
696 LOCALE_Init();
698 /* Copy the parent environment */
699 if (!build_initial_environment( environ )) return FALSE;
701 /* Parse command line arguments */
702 OPTIONS_ParseOptions( !info_size ? argv : NULL );
704 /* initialise DOS drives */
705 if (!DRIVE_Init()) return FALSE;
707 /* initialise DOS directories */
708 if (!DIR_Init()) return FALSE;
710 /* registry initialisation */
711 SHELL_LoadRegistry();
713 /* global boot finished, the rest is process-local */
714 SERVER_START_REQ( boot_done )
716 req->debug_level = TRACE_ON(server);
717 wine_server_call( req );
719 SERVER_END_REQ;
721 return TRUE;
725 /***********************************************************************
726 * start_process
728 * Startup routine of a new process. Runs on the new process stack.
730 static void start_process( void *arg )
732 __TRY
734 PEB *peb = NtCurrentTeb()->Peb;
735 IMAGE_NT_HEADERS *nt;
736 LPTHREAD_START_ROUTINE entry;
738 LdrInitializeThunk( main_exe_file, CreateFileW, 0, 0 );
740 nt = RtlImageNtHeader( peb->ImageBaseAddress );
741 entry = (LPTHREAD_START_ROUTINE)((char *)peb->ImageBaseAddress +
742 nt->OptionalHeader.AddressOfEntryPoint);
744 if (TRACE_ON(relay))
745 DPRINTF( "%04lx:Starting process %s (entryproc=%p)\n", GetCurrentThreadId(),
746 debugstr_w(peb->ProcessParameters->ImagePathName.Buffer), entry );
748 SetLastError( 0 ); /* clear error code */
749 if (peb->BeingDebugged) DbgBreakPoint();
750 ExitProcess( entry( peb ) );
752 __EXCEPT(UnhandledExceptionFilter)
754 TerminateThread( GetCurrentThread(), GetExceptionCode() );
756 __ENDTRY
760 /***********************************************************************
761 * __wine_kernel_init
763 * Wine initialisation: load and start the main exe file.
765 void __wine_kernel_init(void)
767 WCHAR *main_exe_name, *p;
768 char error[1024];
769 DWORD stack_size = 0;
770 int file_exists;
771 PEB *peb = NtCurrentTeb()->Peb;
773 /* Initialize everything */
774 if (!process_init( __wine_main_argv, __wine_main_environ )) exit(1);
775 /* update argc in case options have been removed */
776 for (__wine_main_argc = 0; __wine_main_argv[__wine_main_argc]; __wine_main_argc++) /*nothing*/;
778 __wine_main_argv++; /* remove argv[0] (wine itself) */
779 __wine_main_argc--;
781 if (!(main_exe_name = peb->ProcessParameters->ImagePathName.Buffer))
783 WCHAR buffer[MAX_PATH];
784 WCHAR exe_nameW[MAX_PATH];
786 if (!__wine_main_argv[0]) OPTIONS_Usage();
788 MultiByteToWideChar( CP_UNIXCP, 0, __wine_main_argv[0], -1, exe_nameW, MAX_PATH );
789 if (!find_exe_file( exe_nameW, buffer, MAX_PATH, &main_exe_file ))
791 MESSAGE( "wine: cannot find '%s'\n", __wine_main_argv[0] );
792 ExitProcess(1);
794 if (main_exe_file == INVALID_HANDLE_VALUE)
796 MESSAGE( "wine: cannot open %s\n", debugstr_w(main_exe_name) );
797 ExitProcess(1);
799 RtlCreateUnicodeString( &peb->ProcessParameters->ImagePathName, buffer );
800 main_exe_name = peb->ProcessParameters->ImagePathName.Buffer;
803 TRACE( "starting process name=%s file=%p argv[0]=%s\n",
804 debugstr_w(main_exe_name), main_exe_file, debugstr_a(__wine_main_argv[0]) );
806 MODULE_InitLoadPath();
807 VERSION_Init( main_exe_name );
809 if (!main_exe_file) /* no file handle -> Winelib app */
811 TRACE( "starting Winelib app %s\n", debugstr_w(main_exe_name) );
812 if (open_builtin_exe_file( main_exe_name, error, sizeof(error), 0, &file_exists ))
813 goto found;
814 MESSAGE( "wine: cannot open builtin library for %s: %s\n",
815 debugstr_w(main_exe_name), error );
816 ExitProcess(1);
819 switch( MODULE_GetBinaryType( main_exe_file ))
821 case BINARY_PE_EXE:
822 TRACE( "starting Win32 binary %s\n", debugstr_w(main_exe_name) );
823 if ((peb->ImageBaseAddress = load_pe_exe( main_exe_name, main_exe_file )))
824 goto found;
825 MESSAGE( "wine: could not load %s as Win32 binary\n", debugstr_w(main_exe_name) );
826 ExitProcess(1);
827 case BINARY_PE_DLL:
828 MESSAGE( "wine: %s is a DLL, not an executable\n", debugstr_w(main_exe_name) );
829 ExitProcess(1);
830 case BINARY_UNKNOWN:
831 /* check for .com extension */
832 if (!(p = strrchrW( main_exe_name, '.' )) || strcmpiW( p, comW ))
834 MESSAGE( "wine: cannot determine executable type for %s\n",
835 debugstr_w(main_exe_name) );
836 ExitProcess(1);
838 /* fall through */
839 case BINARY_WIN16:
840 case BINARY_DOS:
841 TRACE( "starting Win16/DOS binary %s\n", debugstr_w(main_exe_name) );
842 CloseHandle( main_exe_file );
843 main_exe_file = 0;
844 __wine_main_argv--;
845 __wine_main_argc++;
846 __wine_main_argv[0] = "winevdm.exe";
847 if (open_builtin_exe_file( winevdmW, error, sizeof(error), 0, &file_exists ))
848 goto found;
849 MESSAGE( "wine: trying to run %s, cannot open builtin library for 'winevdm.exe': %s\n",
850 debugstr_w(main_exe_name), error );
851 ExitProcess(1);
852 case BINARY_OS216:
853 MESSAGE( "wine: %s is an OS/2 binary, not supported\n", debugstr_w(main_exe_name) );
854 ExitProcess(1);
855 case BINARY_UNIX_EXE:
856 MESSAGE( "wine: %s is a Unix binary, not supported\n", debugstr_w(main_exe_name) );
857 ExitProcess(1);
858 case BINARY_UNIX_LIB:
860 DOS_FULL_NAME full_name;
862 TRACE( "starting Winelib app %s\n", debugstr_w(main_exe_name) );
863 CloseHandle( main_exe_file );
864 main_exe_file = 0;
865 if (DOSFS_GetFullName( main_exe_name, TRUE, &full_name ) &&
866 wine_dlopen( full_name.long_name, RTLD_NOW, error, sizeof(error) ))
868 static const WCHAR soW[] = {'.','s','o',0};
869 if ((p = strrchrW( main_exe_name, '.' )) && !strcmpW( p, soW ))
871 *p = 0;
872 /* update the unicode string */
873 RtlInitUnicodeString( &peb->ProcessParameters->ImagePathName, main_exe_name );
875 goto found;
877 MESSAGE( "wine: could not load %s: %s\n", debugstr_w(main_exe_name), error );
878 ExitProcess(1);
882 found:
883 wine_free_pe_load_area(); /* the main binary is loaded, we don't need this anymore */
885 /* build command line */
886 set_library_wargv( __wine_main_argv );
887 if (!build_command_line( __wine_main_wargv )) goto error;
889 stack_size = RtlImageNtHeader(peb->ImageBaseAddress)->OptionalHeader.SizeOfStackReserve;
891 /* allocate main thread stack */
892 if (!THREAD_InitStack( NtCurrentTeb(), stack_size )) goto error;
894 /* switch to the new stack */
895 wine_switch_to_stack( start_process, NULL, NtCurrentTeb()->Tib.StackBase );
897 error:
898 ExitProcess( GetLastError() );
902 /***********************************************************************
903 * build_argv
905 * Build an argv array from a command-line.
906 * 'reserved' is the number of args to reserve before the first one.
908 static char **build_argv( const WCHAR *cmdlineW, int reserved )
910 int argc;
911 char** argv;
912 char *arg,*s,*d,*cmdline;
913 int in_quotes,bcount,len;
915 len = WideCharToMultiByte( CP_UNIXCP, 0, cmdlineW, -1, NULL, 0, NULL, NULL );
916 if (!(cmdline = malloc(len))) return NULL;
917 WideCharToMultiByte( CP_UNIXCP, 0, cmdlineW, -1, cmdline, len, NULL, NULL );
919 argc=reserved+1;
920 bcount=0;
921 in_quotes=0;
922 s=cmdline;
923 while (1) {
924 if (*s=='\0' || ((*s==' ' || *s=='\t') && !in_quotes)) {
925 /* space */
926 argc++;
927 /* skip the remaining spaces */
928 while (*s==' ' || *s=='\t') {
929 s++;
931 if (*s=='\0')
932 break;
933 bcount=0;
934 continue;
935 } else if (*s=='\\') {
936 /* '\', count them */
937 bcount++;
938 } else if ((*s=='"') && ((bcount & 1)==0)) {
939 /* unescaped '"' */
940 in_quotes=!in_quotes;
941 bcount=0;
942 } else {
943 /* a regular character */
944 bcount=0;
946 s++;
948 argv=malloc(argc*sizeof(*argv));
949 if (!argv)
950 return NULL;
952 arg=d=s=cmdline;
953 bcount=0;
954 in_quotes=0;
955 argc=reserved;
956 while (*s) {
957 if ((*s==' ' || *s=='\t') && !in_quotes) {
958 /* Close the argument and copy it */
959 *d=0;
960 argv[argc++]=arg;
962 /* skip the remaining spaces */
963 do {
964 s++;
965 } while (*s==' ' || *s=='\t');
967 /* Start with a new argument */
968 arg=d=s;
969 bcount=0;
970 } else if (*s=='\\') {
971 /* '\\' */
972 *d++=*s++;
973 bcount++;
974 } else if (*s=='"') {
975 /* '"' */
976 if ((bcount & 1)==0) {
977 /* Preceeded by an even number of '\', this is half that
978 * number of '\', plus a '"' which we discard.
980 d-=bcount/2;
981 s++;
982 in_quotes=!in_quotes;
983 } else {
984 /* Preceeded by an odd number of '\', this is half that
985 * number of '\' followed by a '"'
987 d=d-bcount/2-1;
988 *d++='"';
989 s++;
991 bcount=0;
992 } else {
993 /* a regular character */
994 *d++=*s++;
995 bcount=0;
998 if (*arg) {
999 *d='\0';
1000 argv[argc++]=arg;
1002 argv[argc]=NULL;
1004 return argv;
1008 /***********************************************************************
1009 * alloc_env_string
1011 * Allocate an environment string; helper for build_envp
1013 static char *alloc_env_string( const char *name, const char *value )
1015 char *ret = malloc( strlen(name) + strlen(value) + 1 );
1016 strcpy( ret, name );
1017 strcat( ret, value );
1018 return ret;
1021 /***********************************************************************
1022 * build_envp
1024 * Build the environment of a new child process.
1026 static char **build_envp( const WCHAR *envW, const WCHAR *extra_envW )
1028 const WCHAR *p;
1029 char **envp;
1030 char *env, *extra_env = NULL;
1031 int count = 0, length;
1033 if (extra_envW)
1035 for (p = extra_envW; *p; count++) p += strlenW(p) + 1;
1036 p++;
1037 length = WideCharToMultiByte( CP_UNIXCP, 0, extra_envW, p - extra_envW,
1038 NULL, 0, NULL, NULL );
1039 if ((extra_env = malloc( length )))
1040 WideCharToMultiByte( CP_UNIXCP, 0, extra_envW, p - extra_envW,
1041 extra_env, length, NULL, NULL );
1043 for (p = envW; *p; count++) p += strlenW(p) + 1;
1044 p++;
1045 length = WideCharToMultiByte( CP_UNIXCP, 0, envW, p - envW, NULL, 0, NULL, NULL );
1046 if (!(env = malloc( length ))) return NULL;
1047 WideCharToMultiByte( CP_UNIXCP, 0, envW, p - envW, env, length, NULL, NULL );
1049 count += 4;
1051 if ((envp = malloc( count * sizeof(*envp) )))
1053 char **envptr = envp;
1054 char *p;
1056 /* first the extra strings */
1057 if (extra_env) for (p = extra_env; *p; p += strlen(p) + 1) *envptr++ = p;
1058 /* then put PATH, HOME and WINEPREFIX from the unix env */
1059 if ((p = getenv("PATH"))) *envptr++ = alloc_env_string( "PATH=", p );
1060 if ((p = getenv("HOME"))) *envptr++ = alloc_env_string( "HOME=", p );
1061 if ((p = getenv("WINEPREFIX"))) *envptr++ = alloc_env_string( "WINEPREFIX=", p );
1062 /* now put the Windows environment strings */
1063 for (p = env; *p; p += strlen(p) + 1)
1065 if (!memcmp( p, "PATH=", 5 )) /* store PATH as WINEPATH */
1066 *envptr++ = alloc_env_string( "WINEPATH=", p + 5 );
1067 else if (memcmp( p, "HOME=", 5 ) &&
1068 memcmp( p, "WINEPATH=", 9 ) &&
1069 memcmp( p, "WINEPREFIX=", 11 )) *envptr++ = p;
1071 *envptr = 0;
1073 return envp;
1077 /***********************************************************************
1078 * fork_and_exec
1080 * Fork and exec a new Unix binary, checking for errors.
1082 static int fork_and_exec( const char *filename, const WCHAR *cmdline,
1083 const WCHAR *env, const char *newdir )
1085 int fd[2];
1086 int pid, err;
1088 if (!env) env = GetEnvironmentStringsW();
1090 if (pipe(fd) == -1)
1092 FILE_SetDosError();
1093 return -1;
1095 fcntl( fd[1], F_SETFD, 1 ); /* set close on exec */
1096 if (!(pid = fork())) /* child */
1098 char **argv = build_argv( cmdline, 0 );
1099 char **envp = build_envp( env, NULL );
1100 close( fd[0] );
1102 /* Reset signals that we previously set to SIG_IGN */
1103 signal( SIGPIPE, SIG_DFL );
1104 signal( SIGCHLD, SIG_DFL );
1106 if (newdir) chdir(newdir);
1108 if (argv && envp) execve( filename, argv, envp );
1109 err = errno;
1110 write( fd[1], &err, sizeof(err) );
1111 _exit(1);
1113 close( fd[1] );
1114 if ((pid != -1) && (read( fd[0], &err, sizeof(err) ) > 0)) /* exec failed */
1116 errno = err;
1117 pid = -1;
1119 if (pid == -1) FILE_SetDosError();
1120 close( fd[0] );
1121 return pid;
1125 /***********************************************************************
1126 * create_user_params
1128 static RTL_USER_PROCESS_PARAMETERS *create_user_params( LPCWSTR filename, LPCWSTR cmdline,
1129 const STARTUPINFOW *startup )
1131 RTL_USER_PROCESS_PARAMETERS *params;
1132 UNICODE_STRING image_str, cmdline_str, desktop, title;
1133 NTSTATUS status;
1134 WCHAR buffer[MAX_PATH];
1136 if (GetLongPathNameW( filename, buffer, MAX_PATH ))
1137 RtlInitUnicodeString( &image_str, buffer );
1138 else
1139 RtlInitUnicodeString( &image_str, filename );
1141 RtlInitUnicodeString( &cmdline_str, cmdline );
1142 if (startup->lpDesktop) RtlInitUnicodeString( &desktop, startup->lpDesktop );
1143 if (startup->lpTitle) RtlInitUnicodeString( &title, startup->lpTitle );
1145 status = RtlCreateProcessParameters( &params, &image_str, NULL, NULL, &cmdline_str, NULL,
1146 startup->lpTitle ? &title : NULL,
1147 startup->lpDesktop ? &desktop : NULL,
1148 NULL, NULL );
1149 if (status != STATUS_SUCCESS)
1151 SetLastError( RtlNtStatusToDosError(status) );
1152 return NULL;
1155 params->Environment = NULL; /* we pass it through the Unix environment */
1156 params->hStdInput = startup->hStdInput;
1157 params->hStdOutput = startup->hStdOutput;
1158 params->hStdError = startup->hStdError;
1159 params->dwX = startup->dwX;
1160 params->dwY = startup->dwY;
1161 params->dwXSize = startup->dwXSize;
1162 params->dwYSize = startup->dwYSize;
1163 params->dwXCountChars = startup->dwXCountChars;
1164 params->dwYCountChars = startup->dwYCountChars;
1165 params->dwFillAttribute = startup->dwFillAttribute;
1166 params->dwFlags = startup->dwFlags;
1167 params->wShowWindow = startup->wShowWindow;
1168 return params;
1172 /***********************************************************************
1173 * create_process
1175 * Create a new process. If hFile is a valid handle we have an exe
1176 * file, otherwise it is a Winelib app.
1178 static BOOL create_process( HANDLE hFile, LPCWSTR filename, LPWSTR cmd_line, LPWSTR env,
1179 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1180 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
1181 LPPROCESS_INFORMATION info, LPCSTR unixdir )
1183 BOOL ret, success = FALSE;
1184 HANDLE process_info;
1185 RTL_USER_PROCESS_PARAMETERS *params;
1186 WCHAR *extra_env = NULL;
1187 int startfd[2];
1188 int execfd[2];
1189 pid_t pid;
1190 int err;
1191 char dummy = 0;
1193 if (!env)
1195 env = GetEnvironmentStringsW();
1196 extra_env = DRIVE_BuildEnv();
1199 if (!(params = create_user_params( filename, cmd_line, startup )))
1201 if (extra_env) HeapFree( GetProcessHeap(), 0, extra_env );
1202 return FALSE;
1205 /* create the synchronization pipes */
1207 if (pipe( startfd ) == -1)
1209 FILE_SetDosError();
1210 RtlDestroyProcessParameters( params );
1211 if (extra_env) HeapFree( GetProcessHeap(), 0, extra_env );
1212 return FALSE;
1214 if (pipe( execfd ) == -1)
1216 FILE_SetDosError();
1217 close( startfd[0] );
1218 close( startfd[1] );
1219 RtlDestroyProcessParameters( params );
1220 if (extra_env) HeapFree( GetProcessHeap(), 0, extra_env );
1221 return FALSE;
1223 fcntl( execfd[1], F_SETFD, 1 ); /* set close on exec */
1225 /* create the child process */
1227 if (!(pid = fork())) /* child */
1229 char **argv = build_argv( cmd_line, 1 );
1230 char **envp = build_envp( env, extra_env );
1232 close( startfd[1] );
1233 close( execfd[0] );
1235 /* wait for parent to tell us to start */
1236 if (read( startfd[0], &dummy, 1 ) != 1) _exit(1);
1238 close( startfd[0] );
1239 /* Reset signals that we previously set to SIG_IGN */
1240 signal( SIGPIPE, SIG_DFL );
1241 signal( SIGCHLD, SIG_DFL );
1243 if (unixdir) chdir(unixdir);
1245 if (argv && envp)
1247 /* first, try for a WINELOADER environment variable */
1248 argv[0] = getenv("WINELOADER");
1249 if (argv[0]) execve( argv[0], argv, envp );
1250 /* now use the standard search strategy */
1251 wine_exec_wine_binary( NULL, argv, envp );
1253 err = errno;
1254 write( execfd[1], &err, sizeof(err) );
1255 _exit(1);
1258 /* this is the parent */
1260 close( startfd[0] );
1261 close( execfd[1] );
1262 if (extra_env) HeapFree( GetProcessHeap(), 0, extra_env );
1263 if (pid == -1)
1265 close( startfd[1] );
1266 close( execfd[0] );
1267 FILE_SetDosError();
1268 RtlDestroyProcessParameters( params );
1269 return FALSE;
1272 /* create the process on the server side */
1274 SERVER_START_REQ( new_process )
1276 req->inherit_all = inherit;
1277 req->create_flags = flags;
1278 req->unix_pid = pid;
1279 req->exe_file = hFile;
1280 if (startup->dwFlags & STARTF_USESTDHANDLES)
1282 req->hstdin = startup->hStdInput;
1283 req->hstdout = startup->hStdOutput;
1284 req->hstderr = startup->hStdError;
1286 else
1288 req->hstdin = GetStdHandle( STD_INPUT_HANDLE );
1289 req->hstdout = GetStdHandle( STD_OUTPUT_HANDLE );
1290 req->hstderr = GetStdHandle( STD_ERROR_HANDLE );
1293 if ((flags & (CREATE_NEW_CONSOLE | DETACHED_PROCESS)) != 0)
1295 /* this is temporary (for console handles). We have no way to control that the handle is invalid in child process otherwise */
1296 if (is_console_handle(req->hstdin)) req->hstdin = INVALID_HANDLE_VALUE;
1297 if (is_console_handle(req->hstdout)) req->hstdout = INVALID_HANDLE_VALUE;
1298 if (is_console_handle(req->hstderr)) req->hstderr = INVALID_HANDLE_VALUE;
1300 else
1302 if (is_console_handle(req->hstdin)) req->hstdin = console_handle_unmap(req->hstdin);
1303 if (is_console_handle(req->hstdout)) req->hstdout = console_handle_unmap(req->hstdout);
1304 if (is_console_handle(req->hstderr)) req->hstderr = console_handle_unmap(req->hstderr);
1307 wine_server_add_data( req, params, params->Size );
1308 ret = !wine_server_call_err( req );
1309 process_info = reply->info;
1311 SERVER_END_REQ;
1313 RtlDestroyProcessParameters( params );
1314 if (!ret)
1316 close( startfd[1] );
1317 close( execfd[0] );
1318 return FALSE;
1321 /* tell child to start and wait for it to exec */
1323 write( startfd[1], &dummy, 1 );
1324 close( startfd[1] );
1326 if (read( execfd[0], &err, sizeof(err) ) > 0) /* exec failed */
1328 errno = err;
1329 FILE_SetDosError();
1330 close( execfd[0] );
1331 CloseHandle( process_info );
1332 return FALSE;
1335 /* wait for the new process info to be ready */
1337 WaitForSingleObject( process_info, INFINITE );
1338 SERVER_START_REQ( get_new_process_info )
1340 req->info = process_info;
1341 req->pinherit = (psa && (psa->nLength >= sizeof(*psa)) && psa->bInheritHandle);
1342 req->tinherit = (tsa && (tsa->nLength >= sizeof(*tsa)) && tsa->bInheritHandle);
1343 if ((ret = !wine_server_call_err( req )))
1345 info->dwProcessId = (DWORD)reply->pid;
1346 info->dwThreadId = (DWORD)reply->tid;
1347 info->hProcess = reply->phandle;
1348 info->hThread = reply->thandle;
1349 success = reply->success;
1352 SERVER_END_REQ;
1354 if (ret && !success) /* new process failed to start */
1356 DWORD exitcode;
1357 if (GetExitCodeProcess( info->hProcess, &exitcode )) SetLastError( exitcode );
1358 CloseHandle( info->hThread );
1359 CloseHandle( info->hProcess );
1360 ret = FALSE;
1362 CloseHandle( process_info );
1363 return ret;
1367 /***********************************************************************
1368 * create_vdm_process
1370 * Create a new VDM process for a 16-bit or DOS application.
1372 static BOOL create_vdm_process( LPCWSTR filename, LPWSTR cmd_line, LPWSTR env,
1373 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1374 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
1375 LPPROCESS_INFORMATION info, LPCSTR unixdir )
1377 static const WCHAR argsW[] = {'%','s',' ','-','-','a','p','p','-','n','a','m','e',' ','"','%','s','"',' ','%','s',0};
1379 BOOL ret;
1380 LPWSTR new_cmd_line = HeapAlloc( GetProcessHeap(), 0,
1381 (strlenW(filename) + strlenW(cmd_line) + 30) * sizeof(WCHAR) );
1383 if (!new_cmd_line)
1385 SetLastError( ERROR_OUTOFMEMORY );
1386 return FALSE;
1388 sprintfW( new_cmd_line, argsW, winevdmW, filename, cmd_line );
1389 ret = create_process( 0, winevdmW, new_cmd_line, env, psa, tsa, inherit,
1390 flags, startup, info, unixdir );
1391 HeapFree( GetProcessHeap(), 0, new_cmd_line );
1392 return ret;
1396 /***********************************************************************
1397 * create_cmd_process
1399 * Create a new cmd shell process for a .BAT file.
1401 static BOOL create_cmd_process( LPCWSTR filename, LPWSTR cmd_line, LPVOID env,
1402 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1403 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
1404 LPPROCESS_INFORMATION info, LPCWSTR cur_dir )
1407 static const WCHAR comspecW[] = {'C','O','M','S','P','E','C',0};
1408 static const WCHAR slashcW[] = {' ','/','c',' ',0};
1409 WCHAR comspec[MAX_PATH];
1410 WCHAR *newcmdline;
1411 BOOL ret;
1413 if (!GetEnvironmentVariableW( comspecW, comspec, sizeof(comspec)/sizeof(WCHAR) ))
1414 return FALSE;
1415 if (!(newcmdline = HeapAlloc( GetProcessHeap(), 0,
1416 (strlenW(comspec) + 4 + strlenW(cmd_line) + 1) * sizeof(WCHAR))))
1417 return FALSE;
1419 strcpyW( newcmdline, comspec );
1420 strcatW( newcmdline, slashcW );
1421 strcatW( newcmdline, cmd_line );
1422 ret = CreateProcessW( comspec, newcmdline, psa, tsa, inherit,
1423 flags, env, cur_dir, startup, info );
1424 HeapFree( GetProcessHeap(), 0, newcmdline );
1425 return ret;
1429 /*************************************************************************
1430 * get_file_name
1432 * Helper for CreateProcess: retrieve the file name to load from the
1433 * app name and command line. Store the file name in buffer, and
1434 * return a possibly modified command line.
1435 * Also returns a handle to the opened file if it's a Windows binary.
1437 static LPWSTR get_file_name( LPCWSTR appname, LPWSTR cmdline, LPWSTR buffer,
1438 int buflen, HANDLE *handle )
1440 static const WCHAR quotesW[] = {'"','%','s','"',0};
1442 WCHAR *name, *pos, *ret = NULL;
1443 const WCHAR *p;
1445 /* if we have an app name, everything is easy */
1447 if (appname)
1449 /* use the unmodified app name as file name */
1450 lstrcpynW( buffer, appname, buflen );
1451 *handle = open_exe_file( buffer );
1452 if (!(ret = cmdline) || !cmdline[0])
1454 /* no command-line, create one */
1455 if ((ret = HeapAlloc( GetProcessHeap(), 0, (strlenW(appname) + 3) * sizeof(WCHAR) )))
1456 sprintfW( ret, quotesW, appname );
1458 return ret;
1461 if (!cmdline)
1463 SetLastError( ERROR_INVALID_PARAMETER );
1464 return NULL;
1467 /* first check for a quoted file name */
1469 if ((cmdline[0] == '"') && ((p = strchrW( cmdline + 1, '"' ))))
1471 int len = p - cmdline - 1;
1472 /* extract the quoted portion as file name */
1473 if (!(name = HeapAlloc( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) ))) return NULL;
1474 memcpy( name, cmdline + 1, len * sizeof(WCHAR) );
1475 name[len] = 0;
1477 if (find_exe_file( name, buffer, buflen, handle ))
1478 ret = cmdline; /* no change necessary */
1479 goto done;
1482 /* now try the command-line word by word */
1484 if (!(name = HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline) + 1) * sizeof(WCHAR) )))
1485 return NULL;
1486 pos = name;
1487 p = cmdline;
1489 while (*p)
1491 do *pos++ = *p++; while (*p && *p != ' ');
1492 *pos = 0;
1493 if (find_exe_file( name, buffer, buflen, handle ))
1495 ret = cmdline;
1496 break;
1500 if (!ret || !strchrW( name, ' ' )) goto done; /* no change necessary */
1502 /* now build a new command-line with quotes */
1504 if (!(ret = HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline) + 3) * sizeof(WCHAR) )))
1505 goto done;
1506 sprintfW( ret, quotesW, name );
1507 strcatW( ret, p );
1509 done:
1510 HeapFree( GetProcessHeap(), 0, name );
1511 return ret;
1515 /**********************************************************************
1516 * CreateProcessA (KERNEL32.@)
1518 BOOL WINAPI CreateProcessA( LPCSTR app_name, LPSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
1519 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit,
1520 DWORD flags, LPVOID env, LPCSTR cur_dir,
1521 LPSTARTUPINFOA startup_info, LPPROCESS_INFORMATION info )
1523 BOOL ret;
1524 UNICODE_STRING app_nameW, cmd_lineW, cur_dirW, desktopW, titleW;
1525 STARTUPINFOW infoW;
1527 if (app_name) RtlCreateUnicodeStringFromAsciiz( &app_nameW, app_name );
1528 else app_nameW.Buffer = NULL;
1529 if (cmd_line) RtlCreateUnicodeStringFromAsciiz( &cmd_lineW, cmd_line );
1530 else cmd_lineW.Buffer = NULL;
1531 if (cur_dir) RtlCreateUnicodeStringFromAsciiz( &cur_dirW, cur_dir );
1532 else cur_dirW.Buffer = NULL;
1533 if (startup_info->lpDesktop) RtlCreateUnicodeStringFromAsciiz( &desktopW, startup_info->lpDesktop );
1534 else desktopW.Buffer = NULL;
1535 if (startup_info->lpTitle) RtlCreateUnicodeStringFromAsciiz( &titleW, startup_info->lpTitle );
1536 else titleW.Buffer = NULL;
1538 memcpy( &infoW, startup_info, sizeof(infoW) );
1539 infoW.lpDesktop = desktopW.Buffer;
1540 infoW.lpTitle = titleW.Buffer;
1542 if (startup_info->lpReserved)
1543 FIXME("StartupInfo.lpReserved is used, please report (%s)\n",
1544 debugstr_a(startup_info->lpReserved));
1546 ret = CreateProcessW( app_nameW.Buffer, cmd_lineW.Buffer, process_attr, thread_attr,
1547 inherit, flags, env, cur_dirW.Buffer, &infoW, info );
1549 RtlFreeUnicodeString( &app_nameW );
1550 RtlFreeUnicodeString( &cmd_lineW );
1551 RtlFreeUnicodeString( &cur_dirW );
1552 RtlFreeUnicodeString( &desktopW );
1553 RtlFreeUnicodeString( &titleW );
1554 return ret;
1558 /**********************************************************************
1559 * CreateProcessW (KERNEL32.@)
1561 BOOL WINAPI CreateProcessW( LPCWSTR app_name, LPWSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
1562 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit, DWORD flags,
1563 LPVOID env, LPCWSTR cur_dir, LPSTARTUPINFOW startup_info,
1564 LPPROCESS_INFORMATION info )
1566 BOOL retv = FALSE;
1567 HANDLE hFile = 0;
1568 const char *unixdir = NULL;
1569 DOS_FULL_NAME full_dir;
1570 WCHAR name[MAX_PATH];
1571 WCHAR *tidy_cmdline, *p, *envW = env;
1573 /* Process the AppName and/or CmdLine to get module name and path */
1575 TRACE("app %s cmdline %s\n", debugstr_w(app_name), debugstr_w(cmd_line) );
1577 if (!(tidy_cmdline = get_file_name( app_name, cmd_line, name, sizeof(name), &hFile )))
1578 return FALSE;
1579 if (hFile == INVALID_HANDLE_VALUE) goto done;
1581 /* Warn if unsupported features are used */
1583 if (flags & (IDLE_PRIORITY_CLASS | HIGH_PRIORITY_CLASS | REALTIME_PRIORITY_CLASS |
1584 CREATE_NEW_PROCESS_GROUP | CREATE_SEPARATE_WOW_VDM | CREATE_SHARED_WOW_VDM |
1585 CREATE_DEFAULT_ERROR_MODE | CREATE_NO_WINDOW |
1586 PROFILE_USER | PROFILE_KERNEL | PROFILE_SERVER))
1587 WARN("(%s,...): ignoring some flags in %lx\n", debugstr_w(name), flags);
1589 if (cur_dir)
1591 if (DOSFS_GetFullName( cur_dir, TRUE, &full_dir )) unixdir = full_dir.long_name;
1593 else
1595 WCHAR buf[MAX_PATH];
1596 if (GetCurrentDirectoryW(MAX_PATH, buf))
1598 if (DOSFS_GetFullName( buf, TRUE, &full_dir )) unixdir = full_dir.long_name;
1602 if (env && !(flags & CREATE_UNICODE_ENVIRONMENT)) /* convert environment to unicode */
1604 char *p = env;
1605 DWORD lenW;
1607 while (*p) p += strlen(p) + 1;
1608 p++; /* final null */
1609 lenW = MultiByteToWideChar( CP_ACP, 0, env, p - (char*)env, NULL, 0 );
1610 envW = HeapAlloc( GetProcessHeap(), 0, lenW * sizeof(WCHAR) );
1611 MultiByteToWideChar( CP_ACP, 0, env, p - (char*)env, envW, lenW );
1612 flags |= CREATE_UNICODE_ENVIRONMENT;
1615 info->hThread = info->hProcess = 0;
1616 info->dwProcessId = info->dwThreadId = 0;
1618 /* Determine executable type */
1620 if (!hFile) /* builtin exe */
1622 TRACE( "starting %s as Winelib app\n", debugstr_w(name) );
1623 retv = create_process( 0, name, tidy_cmdline, envW, process_attr, thread_attr,
1624 inherit, flags, startup_info, info, unixdir );
1625 goto done;
1628 switch( MODULE_GetBinaryType( hFile ))
1630 case BINARY_PE_EXE:
1631 TRACE( "starting %s as Win32 binary\n", debugstr_w(name) );
1632 retv = create_process( hFile, name, tidy_cmdline, envW, process_attr, thread_attr,
1633 inherit, flags, startup_info, info, unixdir );
1634 break;
1635 case BINARY_WIN16:
1636 case BINARY_DOS:
1637 TRACE( "starting %s as Win16/DOS binary\n", debugstr_w(name) );
1638 retv = create_vdm_process( name, tidy_cmdline, envW, process_attr, thread_attr,
1639 inherit, flags, startup_info, info, unixdir );
1640 break;
1641 case BINARY_OS216:
1642 FIXME( "%s is OS/2 binary, not supported\n", debugstr_w(name) );
1643 SetLastError( ERROR_BAD_EXE_FORMAT );
1644 break;
1645 case BINARY_PE_DLL:
1646 TRACE( "not starting %s since it is a dll\n", debugstr_w(name) );
1647 SetLastError( ERROR_BAD_EXE_FORMAT );
1648 break;
1649 case BINARY_UNIX_LIB:
1650 TRACE( "%s is a Unix library, starting as Winelib app\n", debugstr_w(name) );
1651 retv = create_process( hFile, name, tidy_cmdline, envW, process_attr, thread_attr,
1652 inherit, flags, startup_info, info, unixdir );
1653 break;
1654 case BINARY_UNKNOWN:
1655 /* check for .com or .bat extension */
1656 if ((p = strrchrW( name, '.' )))
1658 if (!strcmpiW( p, comW ))
1660 TRACE( "starting %s as DOS binary\n", debugstr_w(name) );
1661 retv = create_vdm_process( name, tidy_cmdline, envW, process_attr, thread_attr,
1662 inherit, flags, startup_info, info, unixdir );
1663 break;
1665 if (!strcmpiW( p, batW ))
1667 TRACE( "starting %s as batch binary\n", debugstr_w(name) );
1668 retv = create_cmd_process( name, tidy_cmdline, envW, process_attr, thread_attr,
1669 inherit, flags, startup_info, info, cur_dir );
1670 break;
1673 /* fall through */
1674 case BINARY_UNIX_EXE:
1676 /* unknown file, try as unix executable */
1677 DOS_FULL_NAME full_name;
1679 TRACE( "starting %s as Unix binary\n", debugstr_w(name) );
1681 if (DOSFS_GetFullName( name, TRUE, &full_name ))
1682 retv = (fork_and_exec( full_name.long_name, tidy_cmdline, envW, unixdir ) != -1);
1684 break;
1686 CloseHandle( hFile );
1688 done:
1689 if (tidy_cmdline != cmd_line) HeapFree( GetProcessHeap(), 0, tidy_cmdline );
1690 if (envW != env) HeapFree( GetProcessHeap(), 0, envW );
1691 return retv;
1695 /***********************************************************************
1696 * wait_input_idle
1698 * Wrapper to call WaitForInputIdle USER function
1700 typedef DWORD (WINAPI *WaitForInputIdle_ptr)( HANDLE hProcess, DWORD dwTimeOut );
1702 static DWORD wait_input_idle( HANDLE process, DWORD timeout )
1704 HMODULE mod = GetModuleHandleA( "user32.dll" );
1705 if (mod)
1707 WaitForInputIdle_ptr ptr = (WaitForInputIdle_ptr)GetProcAddress( mod, "WaitForInputIdle" );
1708 if (ptr) return ptr( process, timeout );
1710 return 0;
1714 /***********************************************************************
1715 * WinExec (KERNEL32.@)
1717 UINT WINAPI WinExec( LPCSTR lpCmdLine, UINT nCmdShow )
1719 PROCESS_INFORMATION info;
1720 STARTUPINFOA startup;
1721 char *cmdline;
1722 UINT ret;
1724 memset( &startup, 0, sizeof(startup) );
1725 startup.cb = sizeof(startup);
1726 startup.dwFlags = STARTF_USESHOWWINDOW;
1727 startup.wShowWindow = nCmdShow;
1729 /* cmdline needs to be writeable for CreateProcess */
1730 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(lpCmdLine)+1 ))) return 0;
1731 strcpy( cmdline, lpCmdLine );
1733 if (CreateProcessA( NULL, cmdline, NULL, NULL, FALSE,
1734 0, NULL, NULL, &startup, &info ))
1736 /* Give 30 seconds to the app to come up */
1737 if (wait_input_idle( info.hProcess, 30000 ) == WAIT_FAILED)
1738 WARN("WaitForInputIdle failed: Error %ld\n", GetLastError() );
1739 ret = 33;
1740 /* Close off the handles */
1741 CloseHandle( info.hThread );
1742 CloseHandle( info.hProcess );
1744 else if ((ret = GetLastError()) >= 32)
1746 FIXME("Strange error set by CreateProcess: %d\n", ret );
1747 ret = 11;
1749 HeapFree( GetProcessHeap(), 0, cmdline );
1750 return ret;
1754 /**********************************************************************
1755 * LoadModule (KERNEL32.@)
1757 HINSTANCE WINAPI LoadModule( LPCSTR name, LPVOID paramBlock )
1759 LOADPARMS32 *params = paramBlock;
1760 PROCESS_INFORMATION info;
1761 STARTUPINFOA startup;
1762 HINSTANCE hInstance;
1763 LPSTR cmdline, p;
1764 char filename[MAX_PATH];
1765 BYTE len;
1767 if (!name) return (HINSTANCE)ERROR_FILE_NOT_FOUND;
1769 if (!SearchPathA( NULL, name, ".exe", sizeof(filename), filename, NULL ) &&
1770 !SearchPathA( NULL, name, NULL, sizeof(filename), filename, NULL ))
1771 return (HINSTANCE)GetLastError();
1773 len = (BYTE)params->lpCmdLine[0];
1774 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(filename) + len + 2 )))
1775 return (HINSTANCE)ERROR_NOT_ENOUGH_MEMORY;
1777 strcpy( cmdline, filename );
1778 p = cmdline + strlen(cmdline);
1779 *p++ = ' ';
1780 memcpy( p, params->lpCmdLine + 1, len );
1781 p[len] = 0;
1783 memset( &startup, 0, sizeof(startup) );
1784 startup.cb = sizeof(startup);
1785 if (params->lpCmdShow)
1787 startup.dwFlags = STARTF_USESHOWWINDOW;
1788 startup.wShowWindow = ((WORD *)params->lpCmdShow)[1];
1791 if (CreateProcessA( filename, cmdline, NULL, NULL, FALSE, 0,
1792 params->lpEnvAddress, NULL, &startup, &info ))
1794 /* Give 30 seconds to the app to come up */
1795 if (wait_input_idle( info.hProcess, 30000 ) == WAIT_FAILED)
1796 WARN("WaitForInputIdle failed: Error %ld\n", GetLastError() );
1797 hInstance = (HINSTANCE)33;
1798 /* Close off the handles */
1799 CloseHandle( info.hThread );
1800 CloseHandle( info.hProcess );
1802 else if ((hInstance = (HINSTANCE)GetLastError()) >= (HINSTANCE)32)
1804 FIXME("Strange error set by CreateProcess: %p\n", hInstance );
1805 hInstance = (HINSTANCE)11;
1808 HeapFree( GetProcessHeap(), 0, cmdline );
1809 return hInstance;
1813 /******************************************************************************
1814 * TerminateProcess (KERNEL32.@)
1816 BOOL WINAPI TerminateProcess( HANDLE handle, DWORD exit_code )
1818 NTSTATUS status = NtTerminateProcess( handle, exit_code );
1819 if (status) SetLastError( RtlNtStatusToDosError(status) );
1820 return !status;
1824 /***********************************************************************
1825 * ExitProcess (KERNEL32.@)
1827 void WINAPI ExitProcess( DWORD status )
1829 LdrShutdownProcess();
1830 SERVER_START_REQ( terminate_process )
1832 /* send the exit code to the server */
1833 req->handle = GetCurrentProcess();
1834 req->exit_code = status;
1835 wine_server_call( req );
1837 SERVER_END_REQ;
1838 exit( status );
1842 /***********************************************************************
1843 * GetExitCodeProcess [KERNEL32.@]
1845 * Gets termination status of specified process
1847 * RETURNS
1848 * Success: TRUE
1849 * Failure: FALSE
1851 BOOL WINAPI GetExitCodeProcess(
1852 HANDLE hProcess, /* [in] handle to the process */
1853 LPDWORD lpExitCode) /* [out] address to receive termination status */
1855 BOOL ret;
1856 SERVER_START_REQ( get_process_info )
1858 req->handle = hProcess;
1859 ret = !wine_server_call_err( req );
1860 if (ret && lpExitCode) *lpExitCode = reply->exit_code;
1862 SERVER_END_REQ;
1863 return ret;
1867 /***********************************************************************
1868 * SetErrorMode (KERNEL32.@)
1870 UINT WINAPI SetErrorMode( UINT mode )
1872 UINT old = process_error_mode;
1873 process_error_mode = mode;
1874 return old;
1878 /**********************************************************************
1879 * TlsAlloc [KERNEL32.@] Allocates a TLS index.
1881 * Allocates a thread local storage index
1883 * RETURNS
1884 * Success: TLS Index
1885 * Failure: 0xFFFFFFFF
1887 DWORD WINAPI TlsAlloc( void )
1889 DWORD index;
1891 RtlAcquirePebLock();
1892 index = RtlFindClearBitsAndSet( NtCurrentTeb()->Peb->TlsBitmap, 1, 0 );
1893 if (index != ~0UL) NtCurrentTeb()->TlsSlots[index] = 0; /* clear the value */
1894 else SetLastError( ERROR_NO_MORE_ITEMS );
1895 RtlReleasePebLock();
1896 return index;
1900 /**********************************************************************
1901 * TlsFree [KERNEL32.@] Releases a TLS index.
1903 * Releases a thread local storage index, making it available for reuse
1905 * RETURNS
1906 * Success: TRUE
1907 * Failure: FALSE
1909 BOOL WINAPI TlsFree(
1910 DWORD index) /* [in] TLS Index to free */
1912 BOOL ret;
1914 RtlAcquirePebLock();
1915 ret = RtlAreBitsSet( NtCurrentTeb()->Peb->TlsBitmap, index, 1 );
1916 if (ret)
1918 RtlClearBits( NtCurrentTeb()->Peb->TlsBitmap, index, 1 );
1919 NtSetInformationThread( GetCurrentThread(), ThreadZeroTlsCell, &index, sizeof(index) );
1921 else SetLastError( ERROR_INVALID_PARAMETER );
1922 RtlReleasePebLock();
1923 return TRUE;
1927 /**********************************************************************
1928 * TlsGetValue [KERNEL32.@] Gets value in a thread's TLS slot
1930 * RETURNS
1931 * Success: Value stored in calling thread's TLS slot for index
1932 * Failure: 0 and GetLastError returns NO_ERROR
1934 LPVOID WINAPI TlsGetValue(
1935 DWORD index) /* [in] TLS index to retrieve value for */
1937 if (index >= NtCurrentTeb()->Peb->TlsBitmap->SizeOfBitMap)
1939 SetLastError( ERROR_INVALID_PARAMETER );
1940 return NULL;
1942 SetLastError( ERROR_SUCCESS );
1943 return NtCurrentTeb()->TlsSlots[index];
1947 /**********************************************************************
1948 * TlsSetValue [KERNEL32.@] Stores a value in the thread's TLS slot.
1950 * RETURNS
1951 * Success: TRUE
1952 * Failure: FALSE
1954 BOOL WINAPI TlsSetValue(
1955 DWORD index, /* [in] TLS index to set value for */
1956 LPVOID value) /* [in] Value to be stored */
1958 if (index >= NtCurrentTeb()->Peb->TlsBitmap->SizeOfBitMap)
1960 SetLastError( ERROR_INVALID_PARAMETER );
1961 return FALSE;
1963 NtCurrentTeb()->TlsSlots[index] = value;
1964 return TRUE;
1968 /***********************************************************************
1969 * GetProcessFlags (KERNEL32.@)
1971 DWORD WINAPI GetProcessFlags( DWORD processid )
1973 IMAGE_NT_HEADERS *nt;
1974 DWORD flags = 0;
1976 if (processid && processid != GetCurrentProcessId()) return 0;
1978 if ((nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress )))
1980 if (nt->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_CUI)
1981 flags |= PDB32_CONSOLE_PROC;
1983 if (!AreFileApisANSI()) flags |= PDB32_FILE_APIS_OEM;
1984 if (IsDebuggerPresent()) flags |= PDB32_DEBUGGED;
1985 return flags;
1989 /***********************************************************************
1990 * GetProcessDword (KERNEL.485)
1991 * GetProcessDword (KERNEL32.18)
1992 * 'Of course you cannot directly access Windows internal structures'
1994 DWORD WINAPI GetProcessDword( DWORD dwProcessID, INT offset )
1996 DWORD x, y;
1997 STARTUPINFOW siw;
1999 TRACE("(%ld, %d)\n", dwProcessID, offset );
2001 if (dwProcessID && dwProcessID != GetCurrentProcessId())
2003 ERR("%d: process %lx not accessible\n", offset, dwProcessID);
2004 return 0;
2007 switch ( offset )
2009 case GPD_APP_COMPAT_FLAGS:
2010 return GetAppCompatFlags16(0);
2011 case GPD_LOAD_DONE_EVENT:
2012 return 0;
2013 case GPD_HINSTANCE16:
2014 return GetTaskDS16();
2015 case GPD_WINDOWS_VERSION:
2016 return GetExeVersion16();
2017 case GPD_THDB:
2018 return (DWORD)NtCurrentTeb() - 0x10 /* FIXME */;
2019 case GPD_PDB:
2020 return (DWORD)NtCurrentTeb()->Peb;
2021 case GPD_STARTF_SHELLDATA: /* return stdoutput handle from startupinfo ??? */
2022 GetStartupInfoW(&siw);
2023 return (DWORD)siw.hStdOutput;
2024 case GPD_STARTF_HOTKEY: /* return stdinput handle from startupinfo ??? */
2025 GetStartupInfoW(&siw);
2026 return (DWORD)siw.hStdInput;
2027 case GPD_STARTF_SHOWWINDOW:
2028 GetStartupInfoW(&siw);
2029 return siw.wShowWindow;
2030 case GPD_STARTF_SIZE:
2031 GetStartupInfoW(&siw);
2032 x = siw.dwXSize;
2033 if ( (INT)x == CW_USEDEFAULT ) x = CW_USEDEFAULT16;
2034 y = siw.dwYSize;
2035 if ( (INT)y == CW_USEDEFAULT ) y = CW_USEDEFAULT16;
2036 return MAKELONG( x, y );
2037 case GPD_STARTF_POSITION:
2038 GetStartupInfoW(&siw);
2039 x = siw.dwX;
2040 if ( (INT)x == CW_USEDEFAULT ) x = CW_USEDEFAULT16;
2041 y = siw.dwY;
2042 if ( (INT)y == CW_USEDEFAULT ) y = CW_USEDEFAULT16;
2043 return MAKELONG( x, y );
2044 case GPD_STARTF_FLAGS:
2045 GetStartupInfoW(&siw);
2046 return siw.dwFlags;
2047 case GPD_PARENT:
2048 return 0;
2049 case GPD_FLAGS:
2050 return GetProcessFlags(0);
2051 case GPD_USERDATA:
2052 return process_dword;
2053 default:
2054 ERR("Unknown offset %d\n", offset );
2055 return 0;
2059 /***********************************************************************
2060 * SetProcessDword (KERNEL.484)
2061 * 'Of course you cannot directly access Windows internal structures'
2063 void WINAPI SetProcessDword( DWORD dwProcessID, INT offset, DWORD value )
2065 TRACE("(%ld, %d)\n", dwProcessID, offset );
2067 if (dwProcessID && dwProcessID != GetCurrentProcessId())
2069 ERR("%d: process %lx not accessible\n", offset, dwProcessID);
2070 return;
2073 switch ( offset )
2075 case GPD_APP_COMPAT_FLAGS:
2076 case GPD_LOAD_DONE_EVENT:
2077 case GPD_HINSTANCE16:
2078 case GPD_WINDOWS_VERSION:
2079 case GPD_THDB:
2080 case GPD_PDB:
2081 case GPD_STARTF_SHELLDATA:
2082 case GPD_STARTF_HOTKEY:
2083 case GPD_STARTF_SHOWWINDOW:
2084 case GPD_STARTF_SIZE:
2085 case GPD_STARTF_POSITION:
2086 case GPD_STARTF_FLAGS:
2087 case GPD_PARENT:
2088 case GPD_FLAGS:
2089 ERR("Not allowed to modify offset %d\n", offset );
2090 break;
2091 case GPD_USERDATA:
2092 process_dword = value;
2093 break;
2094 default:
2095 ERR("Unknown offset %d\n", offset );
2096 break;
2101 /***********************************************************************
2102 * ExitProcess (KERNEL.466)
2104 void WINAPI ExitProcess16( WORD status )
2106 DWORD count;
2107 ReleaseThunkLock( &count );
2108 ExitProcess( status );
2112 /*********************************************************************
2113 * OpenProcess (KERNEL32.@)
2115 HANDLE WINAPI OpenProcess( DWORD access, BOOL inherit, DWORD id )
2117 HANDLE ret = 0;
2118 SERVER_START_REQ( open_process )
2120 req->pid = id;
2121 req->access = access;
2122 req->inherit = inherit;
2123 if (!wine_server_call_err( req )) ret = reply->handle;
2125 SERVER_END_REQ;
2126 return ret;
2130 /*********************************************************************
2131 * MapProcessHandle (KERNEL.483)
2133 DWORD WINAPI MapProcessHandle( HANDLE handle )
2135 DWORD ret = 0;
2136 SERVER_START_REQ( get_process_info )
2138 req->handle = handle;
2139 if (!wine_server_call_err( req )) ret = reply->pid;
2141 SERVER_END_REQ;
2142 return ret;
2146 /*********************************************************************
2147 * CloseW32Handle (KERNEL.474)
2148 * CloseHandle (KERNEL32.@)
2150 BOOL WINAPI CloseHandle( HANDLE handle )
2152 NTSTATUS status;
2154 /* stdio handles need special treatment */
2155 if ((handle == (HANDLE)STD_INPUT_HANDLE) ||
2156 (handle == (HANDLE)STD_OUTPUT_HANDLE) ||
2157 (handle == (HANDLE)STD_ERROR_HANDLE))
2158 handle = GetStdHandle( (DWORD)handle );
2160 if (is_console_handle(handle))
2161 return CloseConsoleHandle(handle);
2163 status = NtClose( handle );
2164 if (status) SetLastError( RtlNtStatusToDosError(status) );
2165 return !status;
2169 /*********************************************************************
2170 * GetHandleInformation (KERNEL32.@)
2172 BOOL WINAPI GetHandleInformation( HANDLE handle, LPDWORD flags )
2174 BOOL ret;
2175 SERVER_START_REQ( set_handle_info )
2177 req->handle = handle;
2178 req->flags = 0;
2179 req->mask = 0;
2180 req->fd = -1;
2181 ret = !wine_server_call_err( req );
2182 if (ret && flags) *flags = reply->old_flags;
2184 SERVER_END_REQ;
2185 return ret;
2189 /*********************************************************************
2190 * SetHandleInformation (KERNEL32.@)
2192 BOOL WINAPI SetHandleInformation( HANDLE handle, DWORD mask, DWORD flags )
2194 BOOL ret;
2195 SERVER_START_REQ( set_handle_info )
2197 req->handle = handle;
2198 req->flags = flags;
2199 req->mask = mask;
2200 req->fd = -1;
2201 ret = !wine_server_call_err( req );
2203 SERVER_END_REQ;
2204 return ret;
2208 /*********************************************************************
2209 * DuplicateHandle (KERNEL32.@)
2211 BOOL WINAPI DuplicateHandle( HANDLE source_process, HANDLE source,
2212 HANDLE dest_process, HANDLE *dest,
2213 DWORD access, BOOL inherit, DWORD options )
2215 NTSTATUS status;
2217 if (is_console_handle(source))
2219 /* FIXME: this test is not sufficient, we need to test process ids, not handles */
2220 if (source_process != dest_process ||
2221 source_process != GetCurrentProcess())
2223 SetLastError(ERROR_INVALID_PARAMETER);
2224 return FALSE;
2226 *dest = DuplicateConsoleHandle( source, access, inherit, options );
2227 return (*dest != INVALID_HANDLE_VALUE);
2229 status = NtDuplicateObject( source_process, source, dest_process, dest,
2230 access, inherit ? OBJ_INHERIT : 0, options );
2231 if (status) SetLastError( RtlNtStatusToDosError(status) );
2232 return !status;
2236 /***********************************************************************
2237 * ConvertToGlobalHandle (KERNEL.476)
2238 * ConvertToGlobalHandle (KERNEL32.@)
2240 HANDLE WINAPI ConvertToGlobalHandle(HANDLE hSrc)
2242 HANDLE ret = INVALID_HANDLE_VALUE;
2243 DuplicateHandle( GetCurrentProcess(), hSrc, GetCurrentProcess(), &ret, 0, FALSE,
2244 DUP_HANDLE_MAKE_GLOBAL | DUP_HANDLE_SAME_ACCESS | DUP_HANDLE_CLOSE_SOURCE );
2245 return ret;
2249 /***********************************************************************
2250 * SetHandleContext (KERNEL32.@)
2252 BOOL WINAPI SetHandleContext(HANDLE hnd,DWORD context)
2254 FIXME("(%p,%ld), stub. In case this got called by WSOCK32/WS2_32: "
2255 "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd,context);
2256 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2257 return FALSE;
2261 /***********************************************************************
2262 * GetHandleContext (KERNEL32.@)
2264 DWORD WINAPI GetHandleContext(HANDLE hnd)
2266 FIXME("(%p), stub. In case this got called by WSOCK32/WS2_32: "
2267 "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd);
2268 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2269 return 0;
2273 /***********************************************************************
2274 * CreateSocketHandle (KERNEL32.@)
2276 HANDLE WINAPI CreateSocketHandle(void)
2278 FIXME("(), stub. In case this got called by WSOCK32/WS2_32: "
2279 "the external WINSOCK DLLs won't work with WINE, don't use them.\n");
2280 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2281 return INVALID_HANDLE_VALUE;
2285 /***********************************************************************
2286 * SetPriorityClass (KERNEL32.@)
2288 BOOL WINAPI SetPriorityClass( HANDLE hprocess, DWORD priorityclass )
2290 BOOL ret;
2291 SERVER_START_REQ( set_process_info )
2293 req->handle = hprocess;
2294 req->priority = priorityclass;
2295 req->mask = SET_PROCESS_INFO_PRIORITY;
2296 ret = !wine_server_call_err( req );
2298 SERVER_END_REQ;
2299 return ret;
2303 /***********************************************************************
2304 * GetPriorityClass (KERNEL32.@)
2306 DWORD WINAPI GetPriorityClass(HANDLE hprocess)
2308 DWORD ret = 0;
2309 SERVER_START_REQ( get_process_info )
2311 req->handle = hprocess;
2312 if (!wine_server_call_err( req )) ret = reply->priority;
2314 SERVER_END_REQ;
2315 return ret;
2319 /***********************************************************************
2320 * SetProcessAffinityMask (KERNEL32.@)
2322 BOOL WINAPI SetProcessAffinityMask( HANDLE hProcess, DWORD affmask )
2324 BOOL ret;
2325 SERVER_START_REQ( set_process_info )
2327 req->handle = hProcess;
2328 req->affinity = affmask;
2329 req->mask = SET_PROCESS_INFO_AFFINITY;
2330 ret = !wine_server_call_err( req );
2332 SERVER_END_REQ;
2333 return ret;
2337 /**********************************************************************
2338 * GetProcessAffinityMask (KERNEL32.@)
2340 BOOL WINAPI GetProcessAffinityMask( HANDLE hProcess,
2341 LPDWORD lpProcessAffinityMask,
2342 LPDWORD lpSystemAffinityMask )
2344 BOOL ret = FALSE;
2345 SERVER_START_REQ( get_process_info )
2347 req->handle = hProcess;
2348 if (!wine_server_call_err( req ))
2350 if (lpProcessAffinityMask) *lpProcessAffinityMask = reply->process_affinity;
2351 if (lpSystemAffinityMask) *lpSystemAffinityMask = reply->system_affinity;
2352 ret = TRUE;
2355 SERVER_END_REQ;
2356 return ret;
2360 /***********************************************************************
2361 * GetProcessVersion (KERNEL32.@)
2363 DWORD WINAPI GetProcessVersion( DWORD processid )
2365 IMAGE_NT_HEADERS *nt;
2367 if (processid && processid != GetCurrentProcessId())
2369 FIXME("should use ReadProcessMemory\n");
2370 return 0;
2372 if ((nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress )))
2373 return ((nt->OptionalHeader.MajorSubsystemVersion << 16) |
2374 nt->OptionalHeader.MinorSubsystemVersion);
2375 return 0;
2379 /***********************************************************************
2380 * SetProcessWorkingSetSize [KERNEL32.@]
2381 * Sets the min/max working set sizes for a specified process.
2383 * PARAMS
2384 * hProcess [I] Handle to the process of interest
2385 * minset [I] Specifies minimum working set size
2386 * maxset [I] Specifies maximum working set size
2388 * RETURNS STD
2390 BOOL WINAPI SetProcessWorkingSetSize(HANDLE hProcess, SIZE_T minset,
2391 SIZE_T maxset)
2393 FIXME("(%p,%ld,%ld): stub - harmless\n",hProcess,minset,maxset);
2394 if(( minset == (SIZE_T)-1) && (maxset == (SIZE_T)-1)) {
2395 /* Trim the working set to zero */
2396 /* Swap the process out of physical RAM */
2398 return TRUE;
2401 /***********************************************************************
2402 * GetProcessWorkingSetSize (KERNEL32.@)
2404 BOOL WINAPI GetProcessWorkingSetSize(HANDLE hProcess, PSIZE_T minset,
2405 PSIZE_T maxset)
2407 FIXME("(%p,%p,%p): stub\n",hProcess,minset,maxset);
2408 /* 32 MB working set size */
2409 if (minset) *minset = 32*1024*1024;
2410 if (maxset) *maxset = 32*1024*1024;
2411 return TRUE;
2415 /***********************************************************************
2416 * SetProcessShutdownParameters (KERNEL32.@)
2418 BOOL WINAPI SetProcessShutdownParameters(DWORD level, DWORD flags)
2420 FIXME("(%08lx, %08lx): partial stub.\n", level, flags);
2421 shutdown_flags = flags;
2422 shutdown_priority = level;
2423 return TRUE;
2427 /***********************************************************************
2428 * GetProcessShutdownParameters (KERNEL32.@)
2431 BOOL WINAPI GetProcessShutdownParameters( LPDWORD lpdwLevel, LPDWORD lpdwFlags )
2433 *lpdwLevel = shutdown_priority;
2434 *lpdwFlags = shutdown_flags;
2435 return TRUE;
2439 /***********************************************************************
2440 * GetProcessPriorityBoost (KERNEL32.@)
2442 BOOL WINAPI GetProcessPriorityBoost(HANDLE hprocess,PBOOL pDisablePriorityBoost)
2444 FIXME("(%p,%p): semi-stub\n", hprocess, pDisablePriorityBoost);
2446 /* Report that no boost is present.. */
2447 *pDisablePriorityBoost = FALSE;
2449 return TRUE;
2452 /***********************************************************************
2453 * SetProcessPriorityBoost (KERNEL32.@)
2455 BOOL WINAPI SetProcessPriorityBoost(HANDLE hprocess,BOOL disableboost)
2457 FIXME("(%p,%d): stub\n",hprocess,disableboost);
2458 /* Say we can do it. I doubt the program will notice that we don't. */
2459 return TRUE;
2463 /***********************************************************************
2464 * ReadProcessMemory (KERNEL32.@)
2466 BOOL WINAPI ReadProcessMemory( HANDLE process, LPCVOID addr, LPVOID buffer, SIZE_T size,
2467 SIZE_T *bytes_read )
2469 NTSTATUS status = NtReadVirtualMemory( process, addr, buffer, size, bytes_read );
2470 if (status) SetLastError( RtlNtStatusToDosError(status) );
2471 return !status;
2475 /***********************************************************************
2476 * WriteProcessMemory (KERNEL32.@)
2478 BOOL WINAPI WriteProcessMemory( HANDLE process, LPVOID addr, LPCVOID buffer, SIZE_T size,
2479 SIZE_T *bytes_written )
2481 NTSTATUS status = NtWriteVirtualMemory( process, addr, buffer, size, bytes_written );
2482 if (status) SetLastError( RtlNtStatusToDosError(status) );
2483 return !status;
2487 /****************************************************************************
2488 * FlushInstructionCache (KERNEL32.@)
2490 BOOL WINAPI FlushInstructionCache(HANDLE hProcess, LPCVOID lpBaseAddress, SIZE_T dwSize)
2492 if (GetVersion() & 0x80000000) return TRUE; /* not NT, always TRUE */
2493 FIXME("(%p,%p,0x%08lx): stub\n",hProcess, lpBaseAddress, dwSize);
2494 return TRUE;
2498 /******************************************************************
2499 * GetProcessIoCounters (KERNEL32.@)
2501 BOOL WINAPI GetProcessIoCounters(HANDLE hProcess, PIO_COUNTERS ioc)
2503 NTSTATUS status;
2505 status = NtQueryInformationProcess(hProcess, ProcessIoCounters,
2506 ioc, sizeof(*ioc), NULL);
2507 if (status) SetLastError( RtlNtStatusToDosError(status) );
2508 return !status;
2511 /***********************************************************************
2512 * ProcessIdToSessionId (KERNEL32.@)
2513 * This function is available on Terminal Server 4SP4 and Windows 2000
2515 BOOL WINAPI ProcessIdToSessionId( DWORD procid, DWORD *sessionid_ptr )
2517 /* According to MSDN, if the calling process is not in a terminal
2518 * services environment, then the sessionid returned is zero.
2520 *sessionid_ptr = 0;
2521 return TRUE;
2525 /***********************************************************************
2526 * RegisterServiceProcess (KERNEL.491)
2527 * RegisterServiceProcess (KERNEL32.@)
2529 * A service process calls this function to ensure that it continues to run
2530 * even after a user logged off.
2532 DWORD WINAPI RegisterServiceProcess(DWORD dwProcessId, DWORD dwType)
2534 /* I don't think that Wine needs to do anything in that function */
2535 return 1; /* success */
2539 /**************************************************************************
2540 * SetFileApisToOEM (KERNEL32.@)
2542 VOID WINAPI SetFileApisToOEM(void)
2544 oem_file_apis = TRUE;
2548 /**************************************************************************
2549 * SetFileApisToANSI (KERNEL32.@)
2551 VOID WINAPI SetFileApisToANSI(void)
2553 oem_file_apis = FALSE;
2557 /******************************************************************************
2558 * AreFileApisANSI [KERNEL32.@] Determines if file functions are using ANSI
2560 * RETURNS
2561 * TRUE: Set of file functions is using ANSI code page
2562 * FALSE: Set of file functions is using OEM code page
2564 BOOL WINAPI AreFileApisANSI(void)
2566 return !oem_file_apis;
2570 /***********************************************************************
2571 * GetTickCount (KERNEL32.@)
2573 * Returns the number of milliseconds, modulo 2^32, since the start
2574 * of the wineserver.
2576 DWORD WINAPI GetTickCount(void)
2578 struct timeval t;
2579 gettimeofday( &t, NULL );
2580 return ((t.tv_sec * 1000) + (t.tv_usec / 1000)) - server_startticks;
2584 /***********************************************************************
2585 * GetCurrentProcess (KERNEL32.@)
2587 #undef GetCurrentProcess
2588 HANDLE WINAPI GetCurrentProcess(void)
2590 return (HANDLE)0xffffffff;