Avoid duplicate '=C:' entries in the child process environment.
[wine/testsucceed.git] / dlls / kernel / process.c
blobad71131736cabab53fa9aaa334190686205c0489
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;
621 extern void __wine_dbg_kernel32_init(void);
623 PTHREAD_Init();
625 __wine_dbg_kernel32_init(); /* hack: register debug channels early */
627 setbuf(stdout,NULL);
628 setbuf(stderr,NULL);
629 setlocale(LC_CTYPE,"");
631 /* Retrieve startup info from the server */
632 SERVER_START_REQ( init_process )
634 req->peb = peb;
635 req->ldt_copy = &wine_ldt_copy;
636 if ((ret = !wine_server_call_err( req )))
638 main_exe_file = reply->exe_file;
639 main_create_flags = reply->create_flags;
640 info_size = reply->info_size;
641 server_startticks = reply->server_start;
642 hstdin = reply->hstdin;
643 hstdout = reply->hstdout;
644 hstderr = reply->hstderr;
647 SERVER_END_REQ;
648 if (!ret) return FALSE;
650 if (info_size == 0)
652 params = peb->ProcessParameters;
654 /* This is wine specific: we have no parent (we're started from unix)
655 * so, create a simple console with bare handles to unix stdio
656 * input & output streams (aka simple console)
658 wine_server_fd_to_handle( 0, GENERIC_READ|SYNCHRONIZE, TRUE, &params->hStdInput );
659 wine_server_fd_to_handle( 1, GENERIC_WRITE|SYNCHRONIZE, TRUE, &params->hStdOutput );
660 wine_server_fd_to_handle( 2, GENERIC_WRITE|SYNCHRONIZE, TRUE, &params->hStdError );
662 /* <hack: to be changed later on> */
663 params->CurrentDirectoryName.Length = 3 * sizeof(WCHAR);
664 params->CurrentDirectoryName.MaximumLength = RtlGetLongestNtPathLength() * sizeof(WCHAR);
665 params->CurrentDirectoryName.Buffer = RtlAllocateHeap( GetProcessHeap(), 0, params->CurrentDirectoryName.MaximumLength);
666 params->CurrentDirectoryName.Buffer[0] = 'C';
667 params->CurrentDirectoryName.Buffer[1] = ':';
668 params->CurrentDirectoryName.Buffer[2] = '\\';
669 params->CurrentDirectoryName.Buffer[3] = '\0';
670 /* </hack: to be changed later on> */
672 else
674 if (!(params = init_user_process_params( info_size ))) return FALSE;
675 peb->ProcessParameters = params;
677 /* convert value from server:
678 * + 0 => INVALID_HANDLE_VALUE
679 * + console handle need to be mapped
681 if (!hstdin)
682 hstdin = INVALID_HANDLE_VALUE;
683 else if (VerifyConsoleIoHandle(console_handle_map(hstdin)))
684 hstdin = console_handle_map(hstdin);
686 if (!hstdout)
687 hstdout = INVALID_HANDLE_VALUE;
688 else if (VerifyConsoleIoHandle(console_handle_map(hstdout)))
689 hstdout = console_handle_map(hstdout);
691 if (!hstderr)
692 hstderr = INVALID_HANDLE_VALUE;
693 else if (VerifyConsoleIoHandle(console_handle_map(hstderr)))
694 hstderr = console_handle_map(hstderr);
696 params->hStdInput = hstdin;
697 params->hStdOutput = hstdout;
698 params->hStdError = hstderr;
701 LOCALE_Init();
703 /* Copy the parent environment */
704 if (!build_initial_environment( environ )) return FALSE;
706 /* Parse command line arguments */
707 OPTIONS_ParseOptions( !info_size ? argv : NULL );
709 /* initialise DOS drives */
710 if (!DRIVE_Init()) return FALSE;
712 /* initialise DOS directories */
713 if (!DIR_Init()) return FALSE;
715 /* registry initialisation */
716 SHELL_LoadRegistry();
718 /* global boot finished, the rest is process-local */
719 SERVER_START_REQ( boot_done )
721 req->debug_level = TRACE_ON(server);
722 wine_server_call( req );
724 SERVER_END_REQ;
726 return TRUE;
730 /***********************************************************************
731 * start_process
733 * Startup routine of a new process. Runs on the new process stack.
735 static void start_process( void *arg )
737 __TRY
739 PEB *peb = NtCurrentTeb()->Peb;
740 IMAGE_NT_HEADERS *nt;
741 LPTHREAD_START_ROUTINE entry;
743 LdrInitializeThunk( main_exe_file, CreateFileW, 0, 0 );
745 nt = RtlImageNtHeader( peb->ImageBaseAddress );
746 entry = (LPTHREAD_START_ROUTINE)((char *)peb->ImageBaseAddress +
747 nt->OptionalHeader.AddressOfEntryPoint);
749 if (TRACE_ON(relay))
750 DPRINTF( "%04lx:Starting process %s (entryproc=%p)\n", GetCurrentThreadId(),
751 debugstr_w(peb->ProcessParameters->ImagePathName.Buffer), entry );
753 SetLastError( 0 ); /* clear error code */
754 if (peb->BeingDebugged) DbgBreakPoint();
755 ExitProcess( entry( peb ) );
757 __EXCEPT(UnhandledExceptionFilter)
759 TerminateThread( GetCurrentThread(), GetExceptionCode() );
761 __ENDTRY
765 /***********************************************************************
766 * __wine_kernel_init
768 * Wine initialisation: load and start the main exe file.
770 void __wine_kernel_init(void)
772 WCHAR *main_exe_name, *p;
773 char error[1024];
774 DWORD stack_size = 0;
775 int file_exists;
776 PEB *peb = NtCurrentTeb()->Peb;
778 /* Initialize everything */
779 if (!process_init( __wine_main_argv, __wine_main_environ )) exit(1);
780 /* update argc in case options have been removed */
781 for (__wine_main_argc = 0; __wine_main_argv[__wine_main_argc]; __wine_main_argc++) /*nothing*/;
783 __wine_main_argv++; /* remove argv[0] (wine itself) */
784 __wine_main_argc--;
786 if (!(main_exe_name = peb->ProcessParameters->ImagePathName.Buffer))
788 WCHAR buffer[MAX_PATH];
789 WCHAR exe_nameW[MAX_PATH];
791 if (!__wine_main_argv[0]) OPTIONS_Usage();
793 MultiByteToWideChar( CP_UNIXCP, 0, __wine_main_argv[0], -1, exe_nameW, MAX_PATH );
794 if (!find_exe_file( exe_nameW, buffer, MAX_PATH, &main_exe_file ))
796 MESSAGE( "wine: cannot find '%s'\n", __wine_main_argv[0] );
797 ExitProcess(1);
799 if (main_exe_file == INVALID_HANDLE_VALUE)
801 MESSAGE( "wine: cannot open %s\n", debugstr_w(main_exe_name) );
802 ExitProcess(1);
804 RtlCreateUnicodeString( &peb->ProcessParameters->ImagePathName, buffer );
805 main_exe_name = peb->ProcessParameters->ImagePathName.Buffer;
808 TRACE( "starting process name=%s file=%p argv[0]=%s\n",
809 debugstr_w(main_exe_name), main_exe_file, debugstr_a(__wine_main_argv[0]) );
811 MODULE_InitLoadPath();
812 VERSION_Init( main_exe_name );
814 if (!main_exe_file) /* no file handle -> Winelib app */
816 TRACE( "starting Winelib app %s\n", debugstr_w(main_exe_name) );
817 if (open_builtin_exe_file( main_exe_name, error, sizeof(error), 0, &file_exists ))
818 goto found;
819 MESSAGE( "wine: cannot open builtin library for %s: %s\n",
820 debugstr_w(main_exe_name), error );
821 ExitProcess(1);
824 switch( MODULE_GetBinaryType( main_exe_file ))
826 case BINARY_PE_EXE:
827 TRACE( "starting Win32 binary %s\n", debugstr_w(main_exe_name) );
828 if ((peb->ImageBaseAddress = load_pe_exe( main_exe_name, main_exe_file )))
829 goto found;
830 MESSAGE( "wine: could not load %s as Win32 binary\n", debugstr_w(main_exe_name) );
831 ExitProcess(1);
832 case BINARY_PE_DLL:
833 MESSAGE( "wine: %s is a DLL, not an executable\n", debugstr_w(main_exe_name) );
834 ExitProcess(1);
835 case BINARY_UNKNOWN:
836 /* check for .com extension */
837 if (!(p = strrchrW( main_exe_name, '.' )) || strcmpiW( p, comW ))
839 MESSAGE( "wine: cannot determine executable type for %s\n",
840 debugstr_w(main_exe_name) );
841 ExitProcess(1);
843 /* fall through */
844 case BINARY_WIN16:
845 case BINARY_DOS:
846 TRACE( "starting Win16/DOS binary %s\n", debugstr_w(main_exe_name) );
847 CloseHandle( main_exe_file );
848 main_exe_file = 0;
849 __wine_main_argv--;
850 __wine_main_argc++;
851 __wine_main_argv[0] = "winevdm.exe";
852 if (open_builtin_exe_file( winevdmW, error, sizeof(error), 0, &file_exists ))
853 goto found;
854 MESSAGE( "wine: trying to run %s, cannot open builtin library for 'winevdm.exe': %s\n",
855 debugstr_w(main_exe_name), error );
856 ExitProcess(1);
857 case BINARY_OS216:
858 MESSAGE( "wine: %s is an OS/2 binary, not supported\n", debugstr_w(main_exe_name) );
859 ExitProcess(1);
860 case BINARY_UNIX_EXE:
861 MESSAGE( "wine: %s is a Unix binary, not supported\n", debugstr_w(main_exe_name) );
862 ExitProcess(1);
863 case BINARY_UNIX_LIB:
865 DOS_FULL_NAME full_name;
867 TRACE( "starting Winelib app %s\n", debugstr_w(main_exe_name) );
868 CloseHandle( main_exe_file );
869 main_exe_file = 0;
870 if (DOSFS_GetFullName( main_exe_name, TRUE, &full_name ) &&
871 wine_dlopen( full_name.long_name, RTLD_NOW, error, sizeof(error) ))
873 static const WCHAR soW[] = {'.','s','o',0};
874 if ((p = strrchrW( main_exe_name, '.' )) && !strcmpW( p, soW ))
876 *p = 0;
877 /* update the unicode string */
878 RtlInitUnicodeString( &peb->ProcessParameters->ImagePathName, main_exe_name );
880 goto found;
882 MESSAGE( "wine: could not load %s: %s\n", debugstr_w(main_exe_name), error );
883 ExitProcess(1);
887 found:
888 wine_free_pe_load_area(); /* the main binary is loaded, we don't need this anymore */
890 /* build command line */
891 set_library_wargv( __wine_main_argv );
892 if (!build_command_line( __wine_main_wargv )) goto error;
894 stack_size = RtlImageNtHeader(peb->ImageBaseAddress)->OptionalHeader.SizeOfStackReserve;
896 /* allocate main thread stack */
897 if (!THREAD_InitStack( NtCurrentTeb(), stack_size )) goto error;
899 /* switch to the new stack */
900 wine_switch_to_stack( start_process, NULL, NtCurrentTeb()->Tib.StackBase );
902 error:
903 ExitProcess( GetLastError() );
907 /***********************************************************************
908 * build_argv
910 * Build an argv array from a command-line.
911 * 'reserved' is the number of args to reserve before the first one.
913 static char **build_argv( const WCHAR *cmdlineW, int reserved )
915 int argc;
916 char** argv;
917 char *arg,*s,*d,*cmdline;
918 int in_quotes,bcount,len;
920 len = WideCharToMultiByte( CP_UNIXCP, 0, cmdlineW, -1, NULL, 0, NULL, NULL );
921 if (!(cmdline = malloc(len))) return NULL;
922 WideCharToMultiByte( CP_UNIXCP, 0, cmdlineW, -1, cmdline, len, NULL, NULL );
924 argc=reserved+1;
925 bcount=0;
926 in_quotes=0;
927 s=cmdline;
928 while (1) {
929 if (*s=='\0' || ((*s==' ' || *s=='\t') && !in_quotes)) {
930 /* space */
931 argc++;
932 /* skip the remaining spaces */
933 while (*s==' ' || *s=='\t') {
934 s++;
936 if (*s=='\0')
937 break;
938 bcount=0;
939 continue;
940 } else if (*s=='\\') {
941 /* '\', count them */
942 bcount++;
943 } else if ((*s=='"') && ((bcount & 1)==0)) {
944 /* unescaped '"' */
945 in_quotes=!in_quotes;
946 bcount=0;
947 } else {
948 /* a regular character */
949 bcount=0;
951 s++;
953 argv=malloc(argc*sizeof(*argv));
954 if (!argv)
955 return NULL;
957 arg=d=s=cmdline;
958 bcount=0;
959 in_quotes=0;
960 argc=reserved;
961 while (*s) {
962 if ((*s==' ' || *s=='\t') && !in_quotes) {
963 /* Close the argument and copy it */
964 *d=0;
965 argv[argc++]=arg;
967 /* skip the remaining spaces */
968 do {
969 s++;
970 } while (*s==' ' || *s=='\t');
972 /* Start with a new argument */
973 arg=d=s;
974 bcount=0;
975 } else if (*s=='\\') {
976 /* '\\' */
977 *d++=*s++;
978 bcount++;
979 } else if (*s=='"') {
980 /* '"' */
981 if ((bcount & 1)==0) {
982 /* Preceeded by an even number of '\', this is half that
983 * number of '\', plus a '"' which we discard.
985 d-=bcount/2;
986 s++;
987 in_quotes=!in_quotes;
988 } else {
989 /* Preceeded by an odd number of '\', this is half that
990 * number of '\' followed by a '"'
992 d=d-bcount/2-1;
993 *d++='"';
994 s++;
996 bcount=0;
997 } else {
998 /* a regular character */
999 *d++=*s++;
1000 bcount=0;
1003 if (*arg) {
1004 *d='\0';
1005 argv[argc++]=arg;
1007 argv[argc]=NULL;
1009 return argv;
1013 /***********************************************************************
1014 * alloc_env_string
1016 * Allocate an environment string; helper for build_envp
1018 static char *alloc_env_string( const char *name, const char *value )
1020 char *ret = malloc( strlen(name) + strlen(value) + 1 );
1021 strcpy( ret, name );
1022 strcat( ret, value );
1023 return ret;
1026 /***********************************************************************
1027 * build_envp
1029 * Build the environment of a new child process.
1031 static char **build_envp( const WCHAR *envW, const WCHAR *extra_envW )
1033 const WCHAR *p;
1034 char **envp;
1035 char *env, *extra_env = NULL;
1036 int count = 0, length;
1038 if (extra_envW)
1040 for (p = extra_envW; *p; count++) p += strlenW(p) + 1;
1041 p++;
1042 length = WideCharToMultiByte( CP_UNIXCP, 0, extra_envW, p - extra_envW,
1043 NULL, 0, NULL, NULL );
1044 if ((extra_env = malloc( length )))
1045 WideCharToMultiByte( CP_UNIXCP, 0, extra_envW, p - extra_envW,
1046 extra_env, length, NULL, NULL );
1048 for (p = envW; *p; count++) p += strlenW(p) + 1;
1049 p++;
1050 length = WideCharToMultiByte( CP_UNIXCP, 0, envW, p - envW, NULL, 0, NULL, NULL );
1051 if (!(env = malloc( length ))) return NULL;
1052 WideCharToMultiByte( CP_UNIXCP, 0, envW, p - envW, env, length, NULL, NULL );
1054 count += 4;
1056 if ((envp = malloc( count * sizeof(*envp) )))
1058 char **envptr = envp;
1059 char *p;
1061 /* first the extra strings */
1062 if (extra_env) for (p = extra_env; *p; p += strlen(p) + 1) *envptr++ = p;
1063 /* then put PATH, HOME and WINEPREFIX from the unix env */
1064 if ((p = getenv("PATH"))) *envptr++ = alloc_env_string( "PATH=", p );
1065 if ((p = getenv("HOME"))) *envptr++ = alloc_env_string( "HOME=", p );
1066 if ((p = getenv("WINEPREFIX"))) *envptr++ = alloc_env_string( "WINEPREFIX=", p );
1067 /* now put the Windows environment strings */
1068 for (p = env; *p; p += strlen(p) + 1)
1070 if (extra_env && p[0]=='=' && 'A'<=p[1] && p[1]<='Z' && p[2]==':' && p[3]=='=')
1071 continue; /* skipped */
1072 if (!memcmp( p, "PATH=", 5 )) /* store PATH as WINEPATH */
1073 *envptr++ = alloc_env_string( "WINEPATH=", p + 5 );
1074 else if (memcmp( p, "HOME=", 5 ) &&
1075 memcmp( p, "WINEPATH=", 9 ) &&
1076 memcmp( p, "WINEPREFIX=", 11 )) *envptr++ = p;
1078 *envptr = 0;
1080 return envp;
1084 /***********************************************************************
1085 * fork_and_exec
1087 * Fork and exec a new Unix binary, checking for errors.
1089 static int fork_and_exec( const char *filename, const WCHAR *cmdline,
1090 const WCHAR *env, const char *newdir )
1092 int fd[2];
1093 int pid, err;
1095 if (!env) env = GetEnvironmentStringsW();
1097 if (pipe(fd) == -1)
1099 FILE_SetDosError();
1100 return -1;
1102 fcntl( fd[1], F_SETFD, 1 ); /* set close on exec */
1103 if (!(pid = fork())) /* child */
1105 char **argv = build_argv( cmdline, 0 );
1106 char **envp = build_envp( env, NULL );
1107 close( fd[0] );
1109 /* Reset signals that we previously set to SIG_IGN */
1110 signal( SIGPIPE, SIG_DFL );
1111 signal( SIGCHLD, SIG_DFL );
1113 if (newdir) chdir(newdir);
1115 if (argv && envp) execve( filename, argv, envp );
1116 err = errno;
1117 write( fd[1], &err, sizeof(err) );
1118 _exit(1);
1120 close( fd[1] );
1121 if ((pid != -1) && (read( fd[0], &err, sizeof(err) ) > 0)) /* exec failed */
1123 errno = err;
1124 pid = -1;
1126 if (pid == -1) FILE_SetDosError();
1127 close( fd[0] );
1128 return pid;
1132 /***********************************************************************
1133 * create_user_params
1135 static RTL_USER_PROCESS_PARAMETERS *create_user_params( LPCWSTR filename, LPCWSTR cmdline,
1136 const STARTUPINFOW *startup )
1138 RTL_USER_PROCESS_PARAMETERS *params;
1139 UNICODE_STRING image_str, cmdline_str, desktop, title;
1140 NTSTATUS status;
1141 WCHAR buffer[MAX_PATH];
1143 if (GetLongPathNameW( filename, buffer, MAX_PATH ))
1144 RtlInitUnicodeString( &image_str, buffer );
1145 else
1146 RtlInitUnicodeString( &image_str, filename );
1148 RtlInitUnicodeString( &cmdline_str, cmdline );
1149 if (startup->lpDesktop) RtlInitUnicodeString( &desktop, startup->lpDesktop );
1150 if (startup->lpTitle) RtlInitUnicodeString( &title, startup->lpTitle );
1152 status = RtlCreateProcessParameters( &params, &image_str, NULL, NULL, &cmdline_str, NULL,
1153 startup->lpTitle ? &title : NULL,
1154 startup->lpDesktop ? &desktop : NULL,
1155 NULL, NULL );
1156 if (status != STATUS_SUCCESS)
1158 SetLastError( RtlNtStatusToDosError(status) );
1159 return NULL;
1162 params->Environment = NULL; /* we pass it through the Unix environment */
1163 params->hStdInput = startup->hStdInput;
1164 params->hStdOutput = startup->hStdOutput;
1165 params->hStdError = startup->hStdError;
1166 params->dwX = startup->dwX;
1167 params->dwY = startup->dwY;
1168 params->dwXSize = startup->dwXSize;
1169 params->dwYSize = startup->dwYSize;
1170 params->dwXCountChars = startup->dwXCountChars;
1171 params->dwYCountChars = startup->dwYCountChars;
1172 params->dwFillAttribute = startup->dwFillAttribute;
1173 params->dwFlags = startup->dwFlags;
1174 params->wShowWindow = startup->wShowWindow;
1175 return params;
1179 /***********************************************************************
1180 * create_process
1182 * Create a new process. If hFile is a valid handle we have an exe
1183 * file, otherwise it is a Winelib app.
1185 static BOOL create_process( HANDLE hFile, LPCWSTR filename, LPWSTR cmd_line, LPWSTR env,
1186 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1187 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
1188 LPPROCESS_INFORMATION info, LPCSTR unixdir )
1190 BOOL ret, success = FALSE;
1191 HANDLE process_info;
1192 RTL_USER_PROCESS_PARAMETERS *params;
1193 WCHAR *extra_env = NULL;
1194 int startfd[2];
1195 int execfd[2];
1196 pid_t pid;
1197 int err;
1198 char dummy = 0;
1200 if (!env)
1202 env = GetEnvironmentStringsW();
1203 extra_env = DRIVE_BuildEnv();
1206 if (!(params = create_user_params( filename, cmd_line, startup )))
1208 if (extra_env) HeapFree( GetProcessHeap(), 0, extra_env );
1209 return FALSE;
1212 /* create the synchronization pipes */
1214 if (pipe( startfd ) == -1)
1216 FILE_SetDosError();
1217 RtlDestroyProcessParameters( params );
1218 if (extra_env) HeapFree( GetProcessHeap(), 0, extra_env );
1219 return FALSE;
1221 if (pipe( execfd ) == -1)
1223 FILE_SetDosError();
1224 close( startfd[0] );
1225 close( startfd[1] );
1226 RtlDestroyProcessParameters( params );
1227 if (extra_env) HeapFree( GetProcessHeap(), 0, extra_env );
1228 return FALSE;
1230 fcntl( execfd[1], F_SETFD, 1 ); /* set close on exec */
1232 /* create the child process */
1234 if (!(pid = fork())) /* child */
1236 char **argv = build_argv( cmd_line, 1 );
1237 char **envp = build_envp( env, extra_env );
1239 close( startfd[1] );
1240 close( execfd[0] );
1242 /* wait for parent to tell us to start */
1243 if (read( startfd[0], &dummy, 1 ) != 1) _exit(1);
1245 close( startfd[0] );
1246 /* Reset signals that we previously set to SIG_IGN */
1247 signal( SIGPIPE, SIG_DFL );
1248 signal( SIGCHLD, SIG_DFL );
1250 if (unixdir) chdir(unixdir);
1252 if (argv && envp)
1254 /* first, try for a WINELOADER environment variable */
1255 argv[0] = getenv("WINELOADER");
1256 if (argv[0]) execve( argv[0], argv, envp );
1257 /* now use the standard search strategy */
1258 wine_exec_wine_binary( NULL, argv, envp );
1260 err = errno;
1261 write( execfd[1], &err, sizeof(err) );
1262 _exit(1);
1265 /* this is the parent */
1267 close( startfd[0] );
1268 close( execfd[1] );
1269 if (extra_env) HeapFree( GetProcessHeap(), 0, extra_env );
1270 if (pid == -1)
1272 close( startfd[1] );
1273 close( execfd[0] );
1274 FILE_SetDosError();
1275 RtlDestroyProcessParameters( params );
1276 return FALSE;
1279 /* create the process on the server side */
1281 SERVER_START_REQ( new_process )
1283 req->inherit_all = inherit;
1284 req->create_flags = flags;
1285 req->unix_pid = pid;
1286 req->exe_file = hFile;
1287 if (startup->dwFlags & STARTF_USESTDHANDLES)
1289 req->hstdin = startup->hStdInput;
1290 req->hstdout = startup->hStdOutput;
1291 req->hstderr = startup->hStdError;
1293 else
1295 req->hstdin = GetStdHandle( STD_INPUT_HANDLE );
1296 req->hstdout = GetStdHandle( STD_OUTPUT_HANDLE );
1297 req->hstderr = GetStdHandle( STD_ERROR_HANDLE );
1300 if ((flags & (CREATE_NEW_CONSOLE | DETACHED_PROCESS)) != 0)
1302 /* this is temporary (for console handles). We have no way to control that the handle is invalid in child process otherwise */
1303 if (is_console_handle(req->hstdin)) req->hstdin = INVALID_HANDLE_VALUE;
1304 if (is_console_handle(req->hstdout)) req->hstdout = INVALID_HANDLE_VALUE;
1305 if (is_console_handle(req->hstderr)) req->hstderr = INVALID_HANDLE_VALUE;
1307 else
1309 if (is_console_handle(req->hstdin)) req->hstdin = console_handle_unmap(req->hstdin);
1310 if (is_console_handle(req->hstdout)) req->hstdout = console_handle_unmap(req->hstdout);
1311 if (is_console_handle(req->hstderr)) req->hstderr = console_handle_unmap(req->hstderr);
1314 wine_server_add_data( req, params, params->Size );
1315 ret = !wine_server_call_err( req );
1316 process_info = reply->info;
1318 SERVER_END_REQ;
1320 RtlDestroyProcessParameters( params );
1321 if (!ret)
1323 close( startfd[1] );
1324 close( execfd[0] );
1325 return FALSE;
1328 /* tell child to start and wait for it to exec */
1330 write( startfd[1], &dummy, 1 );
1331 close( startfd[1] );
1333 if (read( execfd[0], &err, sizeof(err) ) > 0) /* exec failed */
1335 errno = err;
1336 FILE_SetDosError();
1337 close( execfd[0] );
1338 CloseHandle( process_info );
1339 return FALSE;
1341 close( execfd[0] );
1343 /* wait for the new process info to be ready */
1345 WaitForSingleObject( process_info, INFINITE );
1346 SERVER_START_REQ( get_new_process_info )
1348 req->info = process_info;
1349 req->pinherit = (psa && (psa->nLength >= sizeof(*psa)) && psa->bInheritHandle);
1350 req->tinherit = (tsa && (tsa->nLength >= sizeof(*tsa)) && tsa->bInheritHandle);
1351 if ((ret = !wine_server_call_err( req )))
1353 info->dwProcessId = (DWORD)reply->pid;
1354 info->dwThreadId = (DWORD)reply->tid;
1355 info->hProcess = reply->phandle;
1356 info->hThread = reply->thandle;
1357 success = reply->success;
1360 SERVER_END_REQ;
1362 if (ret && !success) /* new process failed to start */
1364 DWORD exitcode;
1365 if (GetExitCodeProcess( info->hProcess, &exitcode )) SetLastError( exitcode );
1366 CloseHandle( info->hThread );
1367 CloseHandle( info->hProcess );
1368 ret = FALSE;
1370 CloseHandle( process_info );
1371 return ret;
1375 /***********************************************************************
1376 * create_vdm_process
1378 * Create a new VDM process for a 16-bit or DOS application.
1380 static BOOL create_vdm_process( LPCWSTR filename, LPWSTR cmd_line, LPWSTR env,
1381 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1382 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
1383 LPPROCESS_INFORMATION info, LPCSTR unixdir )
1385 static const WCHAR argsW[] = {'%','s',' ','-','-','a','p','p','-','n','a','m','e',' ','"','%','s','"',' ','%','s',0};
1387 BOOL ret;
1388 LPWSTR new_cmd_line = HeapAlloc( GetProcessHeap(), 0,
1389 (strlenW(filename) + strlenW(cmd_line) + 30) * sizeof(WCHAR) );
1391 if (!new_cmd_line)
1393 SetLastError( ERROR_OUTOFMEMORY );
1394 return FALSE;
1396 sprintfW( new_cmd_line, argsW, winevdmW, filename, cmd_line );
1397 ret = create_process( 0, winevdmW, new_cmd_line, env, psa, tsa, inherit,
1398 flags, startup, info, unixdir );
1399 HeapFree( GetProcessHeap(), 0, new_cmd_line );
1400 return ret;
1404 /***********************************************************************
1405 * create_cmd_process
1407 * Create a new cmd shell process for a .BAT file.
1409 static BOOL create_cmd_process( LPCWSTR filename, LPWSTR cmd_line, LPVOID env,
1410 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1411 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
1412 LPPROCESS_INFORMATION info, LPCWSTR cur_dir )
1415 static const WCHAR comspecW[] = {'C','O','M','S','P','E','C',0};
1416 static const WCHAR slashcW[] = {' ','/','c',' ',0};
1417 WCHAR comspec[MAX_PATH];
1418 WCHAR *newcmdline;
1419 BOOL ret;
1421 if (!GetEnvironmentVariableW( comspecW, comspec, sizeof(comspec)/sizeof(WCHAR) ))
1422 return FALSE;
1423 if (!(newcmdline = HeapAlloc( GetProcessHeap(), 0,
1424 (strlenW(comspec) + 4 + strlenW(cmd_line) + 1) * sizeof(WCHAR))))
1425 return FALSE;
1427 strcpyW( newcmdline, comspec );
1428 strcatW( newcmdline, slashcW );
1429 strcatW( newcmdline, cmd_line );
1430 ret = CreateProcessW( comspec, newcmdline, psa, tsa, inherit,
1431 flags, env, cur_dir, startup, info );
1432 HeapFree( GetProcessHeap(), 0, newcmdline );
1433 return ret;
1437 /*************************************************************************
1438 * get_file_name
1440 * Helper for CreateProcess: retrieve the file name to load from the
1441 * app name and command line. Store the file name in buffer, and
1442 * return a possibly modified command line.
1443 * Also returns a handle to the opened file if it's a Windows binary.
1445 static LPWSTR get_file_name( LPCWSTR appname, LPWSTR cmdline, LPWSTR buffer,
1446 int buflen, HANDLE *handle )
1448 static const WCHAR quotesW[] = {'"','%','s','"',0};
1450 WCHAR *name, *pos, *ret = NULL;
1451 const WCHAR *p;
1453 /* if we have an app name, everything is easy */
1455 if (appname)
1457 /* use the unmodified app name as file name */
1458 lstrcpynW( buffer, appname, buflen );
1459 *handle = open_exe_file( buffer );
1460 if (!(ret = cmdline) || !cmdline[0])
1462 /* no command-line, create one */
1463 if ((ret = HeapAlloc( GetProcessHeap(), 0, (strlenW(appname) + 3) * sizeof(WCHAR) )))
1464 sprintfW( ret, quotesW, appname );
1466 return ret;
1469 if (!cmdline)
1471 SetLastError( ERROR_INVALID_PARAMETER );
1472 return NULL;
1475 /* first check for a quoted file name */
1477 if ((cmdline[0] == '"') && ((p = strchrW( cmdline + 1, '"' ))))
1479 int len = p - cmdline - 1;
1480 /* extract the quoted portion as file name */
1481 if (!(name = HeapAlloc( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) ))) return NULL;
1482 memcpy( name, cmdline + 1, len * sizeof(WCHAR) );
1483 name[len] = 0;
1485 if (find_exe_file( name, buffer, buflen, handle ))
1486 ret = cmdline; /* no change necessary */
1487 goto done;
1490 /* now try the command-line word by word */
1492 if (!(name = HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline) + 1) * sizeof(WCHAR) )))
1493 return NULL;
1494 pos = name;
1495 p = cmdline;
1497 while (*p)
1499 do *pos++ = *p++; while (*p && *p != ' ');
1500 *pos = 0;
1501 if (find_exe_file( name, buffer, buflen, handle ))
1503 ret = cmdline;
1504 break;
1508 if (!ret || !strchrW( name, ' ' )) goto done; /* no change necessary */
1510 /* now build a new command-line with quotes */
1512 if (!(ret = HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline) + 3) * sizeof(WCHAR) )))
1513 goto done;
1514 sprintfW( ret, quotesW, name );
1515 strcatW( ret, p );
1517 done:
1518 HeapFree( GetProcessHeap(), 0, name );
1519 return ret;
1523 /**********************************************************************
1524 * CreateProcessA (KERNEL32.@)
1526 BOOL WINAPI CreateProcessA( LPCSTR app_name, LPSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
1527 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit,
1528 DWORD flags, LPVOID env, LPCSTR cur_dir,
1529 LPSTARTUPINFOA startup_info, LPPROCESS_INFORMATION info )
1531 BOOL ret;
1532 UNICODE_STRING app_nameW, cmd_lineW, cur_dirW, desktopW, titleW;
1533 STARTUPINFOW infoW;
1535 if (app_name) RtlCreateUnicodeStringFromAsciiz( &app_nameW, app_name );
1536 else app_nameW.Buffer = NULL;
1537 if (cmd_line) RtlCreateUnicodeStringFromAsciiz( &cmd_lineW, cmd_line );
1538 else cmd_lineW.Buffer = NULL;
1539 if (cur_dir) RtlCreateUnicodeStringFromAsciiz( &cur_dirW, cur_dir );
1540 else cur_dirW.Buffer = NULL;
1541 if (startup_info->lpDesktop) RtlCreateUnicodeStringFromAsciiz( &desktopW, startup_info->lpDesktop );
1542 else desktopW.Buffer = NULL;
1543 if (startup_info->lpTitle) RtlCreateUnicodeStringFromAsciiz( &titleW, startup_info->lpTitle );
1544 else titleW.Buffer = NULL;
1546 memcpy( &infoW, startup_info, sizeof(infoW) );
1547 infoW.lpDesktop = desktopW.Buffer;
1548 infoW.lpTitle = titleW.Buffer;
1550 if (startup_info->lpReserved)
1551 FIXME("StartupInfo.lpReserved is used, please report (%s)\n",
1552 debugstr_a(startup_info->lpReserved));
1554 ret = CreateProcessW( app_nameW.Buffer, cmd_lineW.Buffer, process_attr, thread_attr,
1555 inherit, flags, env, cur_dirW.Buffer, &infoW, info );
1557 RtlFreeUnicodeString( &app_nameW );
1558 RtlFreeUnicodeString( &cmd_lineW );
1559 RtlFreeUnicodeString( &cur_dirW );
1560 RtlFreeUnicodeString( &desktopW );
1561 RtlFreeUnicodeString( &titleW );
1562 return ret;
1566 /**********************************************************************
1567 * CreateProcessW (KERNEL32.@)
1569 BOOL WINAPI CreateProcessW( LPCWSTR app_name, LPWSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
1570 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit, DWORD flags,
1571 LPVOID env, LPCWSTR cur_dir, LPSTARTUPINFOW startup_info,
1572 LPPROCESS_INFORMATION info )
1574 BOOL retv = FALSE;
1575 HANDLE hFile = 0;
1576 const char *unixdir = NULL;
1577 DOS_FULL_NAME full_dir;
1578 WCHAR name[MAX_PATH];
1579 WCHAR *tidy_cmdline, *p, *envW = env;
1581 /* Process the AppName and/or CmdLine to get module name and path */
1583 TRACE("app %s cmdline %s\n", debugstr_w(app_name), debugstr_w(cmd_line) );
1585 if (!(tidy_cmdline = get_file_name( app_name, cmd_line, name, sizeof(name), &hFile )))
1586 return FALSE;
1587 if (hFile == INVALID_HANDLE_VALUE) goto done;
1589 /* Warn if unsupported features are used */
1591 if (flags & (IDLE_PRIORITY_CLASS | HIGH_PRIORITY_CLASS | REALTIME_PRIORITY_CLASS |
1592 CREATE_NEW_PROCESS_GROUP | CREATE_SEPARATE_WOW_VDM | CREATE_SHARED_WOW_VDM |
1593 CREATE_DEFAULT_ERROR_MODE | CREATE_NO_WINDOW |
1594 PROFILE_USER | PROFILE_KERNEL | PROFILE_SERVER))
1595 WARN("(%s,...): ignoring some flags in %lx\n", debugstr_w(name), flags);
1597 if (cur_dir)
1599 if (DOSFS_GetFullName( cur_dir, TRUE, &full_dir )) unixdir = full_dir.long_name;
1601 else
1603 WCHAR buf[MAX_PATH];
1604 if (GetCurrentDirectoryW(MAX_PATH, buf))
1606 if (DOSFS_GetFullName( buf, TRUE, &full_dir )) unixdir = full_dir.long_name;
1610 if (env && !(flags & CREATE_UNICODE_ENVIRONMENT)) /* convert environment to unicode */
1612 char *p = env;
1613 DWORD lenW;
1615 while (*p) p += strlen(p) + 1;
1616 p++; /* final null */
1617 lenW = MultiByteToWideChar( CP_ACP, 0, env, p - (char*)env, NULL, 0 );
1618 envW = HeapAlloc( GetProcessHeap(), 0, lenW * sizeof(WCHAR) );
1619 MultiByteToWideChar( CP_ACP, 0, env, p - (char*)env, envW, lenW );
1620 flags |= CREATE_UNICODE_ENVIRONMENT;
1623 info->hThread = info->hProcess = 0;
1624 info->dwProcessId = info->dwThreadId = 0;
1626 /* Determine executable type */
1628 if (!hFile) /* builtin exe */
1630 TRACE( "starting %s as Winelib app\n", debugstr_w(name) );
1631 retv = create_process( 0, name, tidy_cmdline, envW, process_attr, thread_attr,
1632 inherit, flags, startup_info, info, unixdir );
1633 goto done;
1636 switch( MODULE_GetBinaryType( hFile ))
1638 case BINARY_PE_EXE:
1639 TRACE( "starting %s as Win32 binary\n", debugstr_w(name) );
1640 retv = create_process( hFile, name, tidy_cmdline, envW, process_attr, thread_attr,
1641 inherit, flags, startup_info, info, unixdir );
1642 break;
1643 case BINARY_WIN16:
1644 case BINARY_DOS:
1645 TRACE( "starting %s as Win16/DOS binary\n", debugstr_w(name) );
1646 retv = create_vdm_process( name, tidy_cmdline, envW, process_attr, thread_attr,
1647 inherit, flags, startup_info, info, unixdir );
1648 break;
1649 case BINARY_OS216:
1650 FIXME( "%s is OS/2 binary, not supported\n", debugstr_w(name) );
1651 SetLastError( ERROR_BAD_EXE_FORMAT );
1652 break;
1653 case BINARY_PE_DLL:
1654 TRACE( "not starting %s since it is a dll\n", debugstr_w(name) );
1655 SetLastError( ERROR_BAD_EXE_FORMAT );
1656 break;
1657 case BINARY_UNIX_LIB:
1658 TRACE( "%s is a Unix library, starting as Winelib app\n", debugstr_w(name) );
1659 retv = create_process( hFile, name, tidy_cmdline, envW, process_attr, thread_attr,
1660 inherit, flags, startup_info, info, unixdir );
1661 break;
1662 case BINARY_UNKNOWN:
1663 /* check for .com or .bat extension */
1664 if ((p = strrchrW( name, '.' )))
1666 if (!strcmpiW( p, comW ))
1668 TRACE( "starting %s as DOS binary\n", debugstr_w(name) );
1669 retv = create_vdm_process( name, tidy_cmdline, envW, process_attr, thread_attr,
1670 inherit, flags, startup_info, info, unixdir );
1671 break;
1673 if (!strcmpiW( p, batW ))
1675 TRACE( "starting %s as batch binary\n", debugstr_w(name) );
1676 retv = create_cmd_process( name, tidy_cmdline, envW, process_attr, thread_attr,
1677 inherit, flags, startup_info, info, cur_dir );
1678 break;
1681 /* fall through */
1682 case BINARY_UNIX_EXE:
1684 /* unknown file, try as unix executable */
1685 DOS_FULL_NAME full_name;
1687 TRACE( "starting %s as Unix binary\n", debugstr_w(name) );
1689 if (DOSFS_GetFullName( name, TRUE, &full_name ))
1690 retv = (fork_and_exec( full_name.long_name, tidy_cmdline, envW, unixdir ) != -1);
1692 break;
1694 CloseHandle( hFile );
1696 done:
1697 if (tidy_cmdline != cmd_line) HeapFree( GetProcessHeap(), 0, tidy_cmdline );
1698 if (envW != env) HeapFree( GetProcessHeap(), 0, envW );
1699 return retv;
1703 /***********************************************************************
1704 * wait_input_idle
1706 * Wrapper to call WaitForInputIdle USER function
1708 typedef DWORD (WINAPI *WaitForInputIdle_ptr)( HANDLE hProcess, DWORD dwTimeOut );
1710 static DWORD wait_input_idle( HANDLE process, DWORD timeout )
1712 HMODULE mod = GetModuleHandleA( "user32.dll" );
1713 if (mod)
1715 WaitForInputIdle_ptr ptr = (WaitForInputIdle_ptr)GetProcAddress( mod, "WaitForInputIdle" );
1716 if (ptr) return ptr( process, timeout );
1718 return 0;
1722 /***********************************************************************
1723 * WinExec (KERNEL32.@)
1725 UINT WINAPI WinExec( LPCSTR lpCmdLine, UINT nCmdShow )
1727 PROCESS_INFORMATION info;
1728 STARTUPINFOA startup;
1729 char *cmdline;
1730 UINT ret;
1732 memset( &startup, 0, sizeof(startup) );
1733 startup.cb = sizeof(startup);
1734 startup.dwFlags = STARTF_USESHOWWINDOW;
1735 startup.wShowWindow = nCmdShow;
1737 /* cmdline needs to be writeable for CreateProcess */
1738 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(lpCmdLine)+1 ))) return 0;
1739 strcpy( cmdline, lpCmdLine );
1741 if (CreateProcessA( NULL, cmdline, NULL, NULL, FALSE,
1742 0, NULL, NULL, &startup, &info ))
1744 /* Give 30 seconds to the app to come up */
1745 if (wait_input_idle( info.hProcess, 30000 ) == WAIT_FAILED)
1746 WARN("WaitForInputIdle failed: Error %ld\n", GetLastError() );
1747 ret = 33;
1748 /* Close off the handles */
1749 CloseHandle( info.hThread );
1750 CloseHandle( info.hProcess );
1752 else if ((ret = GetLastError()) >= 32)
1754 FIXME("Strange error set by CreateProcess: %d\n", ret );
1755 ret = 11;
1757 HeapFree( GetProcessHeap(), 0, cmdline );
1758 return ret;
1762 /**********************************************************************
1763 * LoadModule (KERNEL32.@)
1765 HINSTANCE WINAPI LoadModule( LPCSTR name, LPVOID paramBlock )
1767 LOADPARMS32 *params = paramBlock;
1768 PROCESS_INFORMATION info;
1769 STARTUPINFOA startup;
1770 HINSTANCE hInstance;
1771 LPSTR cmdline, p;
1772 char filename[MAX_PATH];
1773 BYTE len;
1775 if (!name) return (HINSTANCE)ERROR_FILE_NOT_FOUND;
1777 if (!SearchPathA( NULL, name, ".exe", sizeof(filename), filename, NULL ) &&
1778 !SearchPathA( NULL, name, NULL, sizeof(filename), filename, NULL ))
1779 return (HINSTANCE)GetLastError();
1781 len = (BYTE)params->lpCmdLine[0];
1782 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(filename) + len + 2 )))
1783 return (HINSTANCE)ERROR_NOT_ENOUGH_MEMORY;
1785 strcpy( cmdline, filename );
1786 p = cmdline + strlen(cmdline);
1787 *p++ = ' ';
1788 memcpy( p, params->lpCmdLine + 1, len );
1789 p[len] = 0;
1791 memset( &startup, 0, sizeof(startup) );
1792 startup.cb = sizeof(startup);
1793 if (params->lpCmdShow)
1795 startup.dwFlags = STARTF_USESHOWWINDOW;
1796 startup.wShowWindow = ((WORD *)params->lpCmdShow)[1];
1799 if (CreateProcessA( filename, cmdline, NULL, NULL, FALSE, 0,
1800 params->lpEnvAddress, NULL, &startup, &info ))
1802 /* Give 30 seconds to the app to come up */
1803 if (wait_input_idle( info.hProcess, 30000 ) == WAIT_FAILED)
1804 WARN("WaitForInputIdle failed: Error %ld\n", GetLastError() );
1805 hInstance = (HINSTANCE)33;
1806 /* Close off the handles */
1807 CloseHandle( info.hThread );
1808 CloseHandle( info.hProcess );
1810 else if ((hInstance = (HINSTANCE)GetLastError()) >= (HINSTANCE)32)
1812 FIXME("Strange error set by CreateProcess: %p\n", hInstance );
1813 hInstance = (HINSTANCE)11;
1816 HeapFree( GetProcessHeap(), 0, cmdline );
1817 return hInstance;
1821 /******************************************************************************
1822 * TerminateProcess (KERNEL32.@)
1824 BOOL WINAPI TerminateProcess( HANDLE handle, DWORD exit_code )
1826 NTSTATUS status = NtTerminateProcess( handle, exit_code );
1827 if (status) SetLastError( RtlNtStatusToDosError(status) );
1828 return !status;
1832 /***********************************************************************
1833 * ExitProcess (KERNEL32.@)
1835 void WINAPI ExitProcess( DWORD status )
1837 LdrShutdownProcess();
1838 SERVER_START_REQ( terminate_process )
1840 /* send the exit code to the server */
1841 req->handle = GetCurrentProcess();
1842 req->exit_code = status;
1843 wine_server_call( req );
1845 SERVER_END_REQ;
1846 exit( status );
1850 /***********************************************************************
1851 * GetExitCodeProcess [KERNEL32.@]
1853 * Gets termination status of specified process
1855 * RETURNS
1856 * Success: TRUE
1857 * Failure: FALSE
1859 BOOL WINAPI GetExitCodeProcess(
1860 HANDLE hProcess, /* [in] handle to the process */
1861 LPDWORD lpExitCode) /* [out] address to receive termination status */
1863 BOOL ret;
1864 SERVER_START_REQ( get_process_info )
1866 req->handle = hProcess;
1867 ret = !wine_server_call_err( req );
1868 if (ret && lpExitCode) *lpExitCode = reply->exit_code;
1870 SERVER_END_REQ;
1871 return ret;
1875 /***********************************************************************
1876 * SetErrorMode (KERNEL32.@)
1878 UINT WINAPI SetErrorMode( UINT mode )
1880 UINT old = process_error_mode;
1881 process_error_mode = mode;
1882 return old;
1886 /**********************************************************************
1887 * TlsAlloc [KERNEL32.@] Allocates a TLS index.
1889 * Allocates a thread local storage index
1891 * RETURNS
1892 * Success: TLS Index
1893 * Failure: 0xFFFFFFFF
1895 DWORD WINAPI TlsAlloc( void )
1897 DWORD index;
1899 RtlAcquirePebLock();
1900 index = RtlFindClearBitsAndSet( NtCurrentTeb()->Peb->TlsBitmap, 1, 0 );
1901 if (index != ~0UL) NtCurrentTeb()->TlsSlots[index] = 0; /* clear the value */
1902 else SetLastError( ERROR_NO_MORE_ITEMS );
1903 RtlReleasePebLock();
1904 return index;
1908 /**********************************************************************
1909 * TlsFree [KERNEL32.@] Releases a TLS index.
1911 * Releases a thread local storage index, making it available for reuse
1913 * RETURNS
1914 * Success: TRUE
1915 * Failure: FALSE
1917 BOOL WINAPI TlsFree(
1918 DWORD index) /* [in] TLS Index to free */
1920 BOOL ret;
1922 RtlAcquirePebLock();
1923 ret = RtlAreBitsSet( NtCurrentTeb()->Peb->TlsBitmap, index, 1 );
1924 if (ret)
1926 RtlClearBits( NtCurrentTeb()->Peb->TlsBitmap, index, 1 );
1927 NtSetInformationThread( GetCurrentThread(), ThreadZeroTlsCell, &index, sizeof(index) );
1929 else SetLastError( ERROR_INVALID_PARAMETER );
1930 RtlReleasePebLock();
1931 return TRUE;
1935 /**********************************************************************
1936 * TlsGetValue [KERNEL32.@] Gets value in a thread's TLS slot
1938 * RETURNS
1939 * Success: Value stored in calling thread's TLS slot for index
1940 * Failure: 0 and GetLastError returns NO_ERROR
1942 LPVOID WINAPI TlsGetValue(
1943 DWORD index) /* [in] TLS index to retrieve value for */
1945 if (index >= NtCurrentTeb()->Peb->TlsBitmap->SizeOfBitMap)
1947 SetLastError( ERROR_INVALID_PARAMETER );
1948 return NULL;
1950 SetLastError( ERROR_SUCCESS );
1951 return NtCurrentTeb()->TlsSlots[index];
1955 /**********************************************************************
1956 * TlsSetValue [KERNEL32.@] Stores a value in the thread's TLS slot.
1958 * RETURNS
1959 * Success: TRUE
1960 * Failure: FALSE
1962 BOOL WINAPI TlsSetValue(
1963 DWORD index, /* [in] TLS index to set value for */
1964 LPVOID value) /* [in] Value to be stored */
1966 if (index >= NtCurrentTeb()->Peb->TlsBitmap->SizeOfBitMap)
1968 SetLastError( ERROR_INVALID_PARAMETER );
1969 return FALSE;
1971 NtCurrentTeb()->TlsSlots[index] = value;
1972 return TRUE;
1976 /***********************************************************************
1977 * GetProcessFlags (KERNEL32.@)
1979 DWORD WINAPI GetProcessFlags( DWORD processid )
1981 IMAGE_NT_HEADERS *nt;
1982 DWORD flags = 0;
1984 if (processid && processid != GetCurrentProcessId()) return 0;
1986 if ((nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress )))
1988 if (nt->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_CUI)
1989 flags |= PDB32_CONSOLE_PROC;
1991 if (!AreFileApisANSI()) flags |= PDB32_FILE_APIS_OEM;
1992 if (IsDebuggerPresent()) flags |= PDB32_DEBUGGED;
1993 return flags;
1997 /***********************************************************************
1998 * GetProcessDword (KERNEL.485)
1999 * GetProcessDword (KERNEL32.18)
2000 * 'Of course you cannot directly access Windows internal structures'
2002 DWORD WINAPI GetProcessDword( DWORD dwProcessID, INT offset )
2004 DWORD x, y;
2005 STARTUPINFOW siw;
2007 TRACE("(%ld, %d)\n", dwProcessID, offset );
2009 if (dwProcessID && dwProcessID != GetCurrentProcessId())
2011 ERR("%d: process %lx not accessible\n", offset, dwProcessID);
2012 return 0;
2015 switch ( offset )
2017 case GPD_APP_COMPAT_FLAGS:
2018 return GetAppCompatFlags16(0);
2019 case GPD_LOAD_DONE_EVENT:
2020 return 0;
2021 case GPD_HINSTANCE16:
2022 return GetTaskDS16();
2023 case GPD_WINDOWS_VERSION:
2024 return GetExeVersion16();
2025 case GPD_THDB:
2026 return (DWORD)NtCurrentTeb() - 0x10 /* FIXME */;
2027 case GPD_PDB:
2028 return (DWORD)NtCurrentTeb()->Peb;
2029 case GPD_STARTF_SHELLDATA: /* return stdoutput handle from startupinfo ??? */
2030 GetStartupInfoW(&siw);
2031 return (DWORD)siw.hStdOutput;
2032 case GPD_STARTF_HOTKEY: /* return stdinput handle from startupinfo ??? */
2033 GetStartupInfoW(&siw);
2034 return (DWORD)siw.hStdInput;
2035 case GPD_STARTF_SHOWWINDOW:
2036 GetStartupInfoW(&siw);
2037 return siw.wShowWindow;
2038 case GPD_STARTF_SIZE:
2039 GetStartupInfoW(&siw);
2040 x = siw.dwXSize;
2041 if ( (INT)x == CW_USEDEFAULT ) x = CW_USEDEFAULT16;
2042 y = siw.dwYSize;
2043 if ( (INT)y == CW_USEDEFAULT ) y = CW_USEDEFAULT16;
2044 return MAKELONG( x, y );
2045 case GPD_STARTF_POSITION:
2046 GetStartupInfoW(&siw);
2047 x = siw.dwX;
2048 if ( (INT)x == CW_USEDEFAULT ) x = CW_USEDEFAULT16;
2049 y = siw.dwY;
2050 if ( (INT)y == CW_USEDEFAULT ) y = CW_USEDEFAULT16;
2051 return MAKELONG( x, y );
2052 case GPD_STARTF_FLAGS:
2053 GetStartupInfoW(&siw);
2054 return siw.dwFlags;
2055 case GPD_PARENT:
2056 return 0;
2057 case GPD_FLAGS:
2058 return GetProcessFlags(0);
2059 case GPD_USERDATA:
2060 return process_dword;
2061 default:
2062 ERR("Unknown offset %d\n", offset );
2063 return 0;
2067 /***********************************************************************
2068 * SetProcessDword (KERNEL.484)
2069 * 'Of course you cannot directly access Windows internal structures'
2071 void WINAPI SetProcessDword( DWORD dwProcessID, INT offset, DWORD value )
2073 TRACE("(%ld, %d)\n", dwProcessID, offset );
2075 if (dwProcessID && dwProcessID != GetCurrentProcessId())
2077 ERR("%d: process %lx not accessible\n", offset, dwProcessID);
2078 return;
2081 switch ( offset )
2083 case GPD_APP_COMPAT_FLAGS:
2084 case GPD_LOAD_DONE_EVENT:
2085 case GPD_HINSTANCE16:
2086 case GPD_WINDOWS_VERSION:
2087 case GPD_THDB:
2088 case GPD_PDB:
2089 case GPD_STARTF_SHELLDATA:
2090 case GPD_STARTF_HOTKEY:
2091 case GPD_STARTF_SHOWWINDOW:
2092 case GPD_STARTF_SIZE:
2093 case GPD_STARTF_POSITION:
2094 case GPD_STARTF_FLAGS:
2095 case GPD_PARENT:
2096 case GPD_FLAGS:
2097 ERR("Not allowed to modify offset %d\n", offset );
2098 break;
2099 case GPD_USERDATA:
2100 process_dword = value;
2101 break;
2102 default:
2103 ERR("Unknown offset %d\n", offset );
2104 break;
2109 /***********************************************************************
2110 * ExitProcess (KERNEL.466)
2112 void WINAPI ExitProcess16( WORD status )
2114 DWORD count;
2115 ReleaseThunkLock( &count );
2116 ExitProcess( status );
2120 /*********************************************************************
2121 * OpenProcess (KERNEL32.@)
2123 HANDLE WINAPI OpenProcess( DWORD access, BOOL inherit, DWORD id )
2125 HANDLE ret = 0;
2126 SERVER_START_REQ( open_process )
2128 req->pid = id;
2129 req->access = access;
2130 req->inherit = inherit;
2131 if (!wine_server_call_err( req )) ret = reply->handle;
2133 SERVER_END_REQ;
2134 return ret;
2138 /*********************************************************************
2139 * MapProcessHandle (KERNEL.483)
2141 DWORD WINAPI MapProcessHandle( HANDLE handle )
2143 DWORD ret = 0;
2144 SERVER_START_REQ( get_process_info )
2146 req->handle = handle;
2147 if (!wine_server_call_err( req )) ret = reply->pid;
2149 SERVER_END_REQ;
2150 return ret;
2154 /*********************************************************************
2155 * CloseW32Handle (KERNEL.474)
2156 * CloseHandle (KERNEL32.@)
2158 BOOL WINAPI CloseHandle( HANDLE handle )
2160 NTSTATUS status;
2162 /* stdio handles need special treatment */
2163 if ((handle == (HANDLE)STD_INPUT_HANDLE) ||
2164 (handle == (HANDLE)STD_OUTPUT_HANDLE) ||
2165 (handle == (HANDLE)STD_ERROR_HANDLE))
2166 handle = GetStdHandle( (DWORD)handle );
2168 if (is_console_handle(handle))
2169 return CloseConsoleHandle(handle);
2171 status = NtClose( handle );
2172 if (status) SetLastError( RtlNtStatusToDosError(status) );
2173 return !status;
2177 /*********************************************************************
2178 * GetHandleInformation (KERNEL32.@)
2180 BOOL WINAPI GetHandleInformation( HANDLE handle, LPDWORD flags )
2182 BOOL ret;
2183 SERVER_START_REQ( set_handle_info )
2185 req->handle = handle;
2186 req->flags = 0;
2187 req->mask = 0;
2188 req->fd = -1;
2189 ret = !wine_server_call_err( req );
2190 if (ret && flags) *flags = reply->old_flags;
2192 SERVER_END_REQ;
2193 return ret;
2197 /*********************************************************************
2198 * SetHandleInformation (KERNEL32.@)
2200 BOOL WINAPI SetHandleInformation( HANDLE handle, DWORD mask, DWORD flags )
2202 BOOL ret;
2203 SERVER_START_REQ( set_handle_info )
2205 req->handle = handle;
2206 req->flags = flags;
2207 req->mask = mask;
2208 req->fd = -1;
2209 ret = !wine_server_call_err( req );
2211 SERVER_END_REQ;
2212 return ret;
2216 /*********************************************************************
2217 * DuplicateHandle (KERNEL32.@)
2219 BOOL WINAPI DuplicateHandle( HANDLE source_process, HANDLE source,
2220 HANDLE dest_process, HANDLE *dest,
2221 DWORD access, BOOL inherit, DWORD options )
2223 NTSTATUS status;
2225 if (is_console_handle(source))
2227 /* FIXME: this test is not sufficient, we need to test process ids, not handles */
2228 if (source_process != dest_process ||
2229 source_process != GetCurrentProcess())
2231 SetLastError(ERROR_INVALID_PARAMETER);
2232 return FALSE;
2234 *dest = DuplicateConsoleHandle( source, access, inherit, options );
2235 return (*dest != INVALID_HANDLE_VALUE);
2237 status = NtDuplicateObject( source_process, source, dest_process, dest,
2238 access, inherit ? OBJ_INHERIT : 0, options );
2239 if (status) SetLastError( RtlNtStatusToDosError(status) );
2240 return !status;
2244 /***********************************************************************
2245 * ConvertToGlobalHandle (KERNEL.476)
2246 * ConvertToGlobalHandle (KERNEL32.@)
2248 HANDLE WINAPI ConvertToGlobalHandle(HANDLE hSrc)
2250 HANDLE ret = INVALID_HANDLE_VALUE;
2251 DuplicateHandle( GetCurrentProcess(), hSrc, GetCurrentProcess(), &ret, 0, FALSE,
2252 DUP_HANDLE_MAKE_GLOBAL | DUP_HANDLE_SAME_ACCESS | DUP_HANDLE_CLOSE_SOURCE );
2253 return ret;
2257 /***********************************************************************
2258 * SetHandleContext (KERNEL32.@)
2260 BOOL WINAPI SetHandleContext(HANDLE hnd,DWORD context)
2262 FIXME("(%p,%ld), stub. In case this got called by WSOCK32/WS2_32: "
2263 "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd,context);
2264 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2265 return FALSE;
2269 /***********************************************************************
2270 * GetHandleContext (KERNEL32.@)
2272 DWORD WINAPI GetHandleContext(HANDLE hnd)
2274 FIXME("(%p), stub. In case this got called by WSOCK32/WS2_32: "
2275 "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd);
2276 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2277 return 0;
2281 /***********************************************************************
2282 * CreateSocketHandle (KERNEL32.@)
2284 HANDLE WINAPI CreateSocketHandle(void)
2286 FIXME("(), stub. In case this got called by WSOCK32/WS2_32: "
2287 "the external WINSOCK DLLs won't work with WINE, don't use them.\n");
2288 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2289 return INVALID_HANDLE_VALUE;
2293 /***********************************************************************
2294 * SetPriorityClass (KERNEL32.@)
2296 BOOL WINAPI SetPriorityClass( HANDLE hprocess, DWORD priorityclass )
2298 BOOL ret;
2299 SERVER_START_REQ( set_process_info )
2301 req->handle = hprocess;
2302 req->priority = priorityclass;
2303 req->mask = SET_PROCESS_INFO_PRIORITY;
2304 ret = !wine_server_call_err( req );
2306 SERVER_END_REQ;
2307 return ret;
2311 /***********************************************************************
2312 * GetPriorityClass (KERNEL32.@)
2314 DWORD WINAPI GetPriorityClass(HANDLE hprocess)
2316 DWORD ret = 0;
2317 SERVER_START_REQ( get_process_info )
2319 req->handle = hprocess;
2320 if (!wine_server_call_err( req )) ret = reply->priority;
2322 SERVER_END_REQ;
2323 return ret;
2327 /***********************************************************************
2328 * SetProcessAffinityMask (KERNEL32.@)
2330 BOOL WINAPI SetProcessAffinityMask( HANDLE hProcess, DWORD affmask )
2332 BOOL ret;
2333 SERVER_START_REQ( set_process_info )
2335 req->handle = hProcess;
2336 req->affinity = affmask;
2337 req->mask = SET_PROCESS_INFO_AFFINITY;
2338 ret = !wine_server_call_err( req );
2340 SERVER_END_REQ;
2341 return ret;
2345 /**********************************************************************
2346 * GetProcessAffinityMask (KERNEL32.@)
2348 BOOL WINAPI GetProcessAffinityMask( HANDLE hProcess,
2349 LPDWORD lpProcessAffinityMask,
2350 LPDWORD lpSystemAffinityMask )
2352 BOOL ret = FALSE;
2353 SERVER_START_REQ( get_process_info )
2355 req->handle = hProcess;
2356 if (!wine_server_call_err( req ))
2358 if (lpProcessAffinityMask) *lpProcessAffinityMask = reply->process_affinity;
2359 if (lpSystemAffinityMask) *lpSystemAffinityMask = reply->system_affinity;
2360 ret = TRUE;
2363 SERVER_END_REQ;
2364 return ret;
2368 /***********************************************************************
2369 * GetProcessVersion (KERNEL32.@)
2371 DWORD WINAPI GetProcessVersion( DWORD processid )
2373 IMAGE_NT_HEADERS *nt;
2375 if (processid && processid != GetCurrentProcessId())
2377 FIXME("should use ReadProcessMemory\n");
2378 return 0;
2380 if ((nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress )))
2381 return ((nt->OptionalHeader.MajorSubsystemVersion << 16) |
2382 nt->OptionalHeader.MinorSubsystemVersion);
2383 return 0;
2387 /***********************************************************************
2388 * SetProcessWorkingSetSize [KERNEL32.@]
2389 * Sets the min/max working set sizes for a specified process.
2391 * PARAMS
2392 * hProcess [I] Handle to the process of interest
2393 * minset [I] Specifies minimum working set size
2394 * maxset [I] Specifies maximum working set size
2396 * RETURNS STD
2398 BOOL WINAPI SetProcessWorkingSetSize(HANDLE hProcess, SIZE_T minset,
2399 SIZE_T maxset)
2401 FIXME("(%p,%ld,%ld): stub - harmless\n",hProcess,minset,maxset);
2402 if(( minset == (SIZE_T)-1) && (maxset == (SIZE_T)-1)) {
2403 /* Trim the working set to zero */
2404 /* Swap the process out of physical RAM */
2406 return TRUE;
2409 /***********************************************************************
2410 * GetProcessWorkingSetSize (KERNEL32.@)
2412 BOOL WINAPI GetProcessWorkingSetSize(HANDLE hProcess, PSIZE_T minset,
2413 PSIZE_T maxset)
2415 FIXME("(%p,%p,%p): stub\n",hProcess,minset,maxset);
2416 /* 32 MB working set size */
2417 if (minset) *minset = 32*1024*1024;
2418 if (maxset) *maxset = 32*1024*1024;
2419 return TRUE;
2423 /***********************************************************************
2424 * SetProcessShutdownParameters (KERNEL32.@)
2426 BOOL WINAPI SetProcessShutdownParameters(DWORD level, DWORD flags)
2428 FIXME("(%08lx, %08lx): partial stub.\n", level, flags);
2429 shutdown_flags = flags;
2430 shutdown_priority = level;
2431 return TRUE;
2435 /***********************************************************************
2436 * GetProcessShutdownParameters (KERNEL32.@)
2439 BOOL WINAPI GetProcessShutdownParameters( LPDWORD lpdwLevel, LPDWORD lpdwFlags )
2441 *lpdwLevel = shutdown_priority;
2442 *lpdwFlags = shutdown_flags;
2443 return TRUE;
2447 /***********************************************************************
2448 * GetProcessPriorityBoost (KERNEL32.@)
2450 BOOL WINAPI GetProcessPriorityBoost(HANDLE hprocess,PBOOL pDisablePriorityBoost)
2452 FIXME("(%p,%p): semi-stub\n", hprocess, pDisablePriorityBoost);
2454 /* Report that no boost is present.. */
2455 *pDisablePriorityBoost = FALSE;
2457 return TRUE;
2460 /***********************************************************************
2461 * SetProcessPriorityBoost (KERNEL32.@)
2463 BOOL WINAPI SetProcessPriorityBoost(HANDLE hprocess,BOOL disableboost)
2465 FIXME("(%p,%d): stub\n",hprocess,disableboost);
2466 /* Say we can do it. I doubt the program will notice that we don't. */
2467 return TRUE;
2471 /***********************************************************************
2472 * ReadProcessMemory (KERNEL32.@)
2474 BOOL WINAPI ReadProcessMemory( HANDLE process, LPCVOID addr, LPVOID buffer, SIZE_T size,
2475 SIZE_T *bytes_read )
2477 NTSTATUS status = NtReadVirtualMemory( process, addr, buffer, size, bytes_read );
2478 if (status) SetLastError( RtlNtStatusToDosError(status) );
2479 return !status;
2483 /***********************************************************************
2484 * WriteProcessMemory (KERNEL32.@)
2486 BOOL WINAPI WriteProcessMemory( HANDLE process, LPVOID addr, LPCVOID buffer, SIZE_T size,
2487 SIZE_T *bytes_written )
2489 NTSTATUS status = NtWriteVirtualMemory( process, addr, buffer, size, bytes_written );
2490 if (status) SetLastError( RtlNtStatusToDosError(status) );
2491 return !status;
2495 /****************************************************************************
2496 * FlushInstructionCache (KERNEL32.@)
2498 BOOL WINAPI FlushInstructionCache(HANDLE hProcess, LPCVOID lpBaseAddress, SIZE_T dwSize)
2500 if (GetVersion() & 0x80000000) return TRUE; /* not NT, always TRUE */
2501 FIXME("(%p,%p,0x%08lx): stub\n",hProcess, lpBaseAddress, dwSize);
2502 return TRUE;
2506 /******************************************************************
2507 * GetProcessIoCounters (KERNEL32.@)
2509 BOOL WINAPI GetProcessIoCounters(HANDLE hProcess, PIO_COUNTERS ioc)
2511 NTSTATUS status;
2513 status = NtQueryInformationProcess(hProcess, ProcessIoCounters,
2514 ioc, sizeof(*ioc), NULL);
2515 if (status) SetLastError( RtlNtStatusToDosError(status) );
2516 return !status;
2519 /***********************************************************************
2520 * ProcessIdToSessionId (KERNEL32.@)
2521 * This function is available on Terminal Server 4SP4 and Windows 2000
2523 BOOL WINAPI ProcessIdToSessionId( DWORD procid, DWORD *sessionid_ptr )
2525 /* According to MSDN, if the calling process is not in a terminal
2526 * services environment, then the sessionid returned is zero.
2528 *sessionid_ptr = 0;
2529 return TRUE;
2533 /***********************************************************************
2534 * RegisterServiceProcess (KERNEL.491)
2535 * RegisterServiceProcess (KERNEL32.@)
2537 * A service process calls this function to ensure that it continues to run
2538 * even after a user logged off.
2540 DWORD WINAPI RegisterServiceProcess(DWORD dwProcessId, DWORD dwType)
2542 /* I don't think that Wine needs to do anything in that function */
2543 return 1; /* success */
2547 /**************************************************************************
2548 * SetFileApisToOEM (KERNEL32.@)
2550 VOID WINAPI SetFileApisToOEM(void)
2552 oem_file_apis = TRUE;
2556 /**************************************************************************
2557 * SetFileApisToANSI (KERNEL32.@)
2559 VOID WINAPI SetFileApisToANSI(void)
2561 oem_file_apis = FALSE;
2565 /******************************************************************************
2566 * AreFileApisANSI [KERNEL32.@] Determines if file functions are using ANSI
2568 * RETURNS
2569 * TRUE: Set of file functions is using ANSI code page
2570 * FALSE: Set of file functions is using OEM code page
2572 BOOL WINAPI AreFileApisANSI(void)
2574 return !oem_file_apis;
2578 /***********************************************************************
2579 * GetTickCount (KERNEL32.@)
2581 * Returns the number of milliseconds, modulo 2^32, since the start
2582 * of the wineserver.
2584 DWORD WINAPI GetTickCount(void)
2586 struct timeval t;
2587 gettimeofday( &t, NULL );
2588 return ((t.tv_sec * 1000) + (t.tv_usec / 1000)) - server_startticks;
2592 /***********************************************************************
2593 * GetCurrentProcess (KERNEL32.@)
2595 #undef GetCurrentProcess
2596 HANDLE WINAPI GetCurrentProcess(void)
2598 return (HANDLE)0xffffffff;