Moved most remaining file functions to dlls/kernel.
[wine/multimedia.git] / dlls / kernel / process.c
blobffca8f4cafa0ea4aa95d4ecc6d15d0e78f6563df
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>
30 #include <time.h>
31 #ifdef HAVE_SYS_TIME_H
32 # include <sys/time.h>
33 #endif
34 #include <sys/types.h>
36 #include "wine/winbase16.h"
37 #include "wine/winuser16.h"
38 #include "ntstatus.h"
39 #include "thread.h"
40 #include "module.h"
41 #include "options.h"
42 #include "kernel_private.h"
43 #include "wine/exception.h"
44 #include "wine/server.h"
45 #include "wine/unicode.h"
46 #include "wine/debug.h"
48 WINE_DEFAULT_DEBUG_CHANNEL(process);
49 WINE_DECLARE_DEBUG_CHANNEL(server);
50 WINE_DECLARE_DEBUG_CHANNEL(relay);
52 typedef struct
54 LPSTR lpEnvAddress;
55 LPSTR lpCmdLine;
56 LPSTR lpCmdShow;
57 DWORD dwReserved;
58 } LOADPARMS32;
60 static UINT process_error_mode;
62 static HANDLE main_exe_file;
63 static DWORD shutdown_flags = 0;
64 static DWORD shutdown_priority = 0x280;
65 static DWORD process_dword;
66 static BOOL oem_file_apis;
68 static unsigned int server_startticks;
69 int main_create_flags = 0;
70 HMODULE kernel32_handle = 0;
72 /* Process flags */
73 #define PDB32_DEBUGGED 0x0001 /* Process is being debugged */
74 #define PDB32_WIN16_PROC 0x0008 /* Win16 process */
75 #define PDB32_DOS_PROC 0x0010 /* Dos process */
76 #define PDB32_CONSOLE_PROC 0x0020 /* Console process */
77 #define PDB32_FILE_APIS_OEM 0x0040 /* File APIs are OEM */
78 #define PDB32_WIN32S_PROC 0x8000 /* Win32s process */
80 static const WCHAR comW[] = {'.','c','o','m',0};
81 static const WCHAR batW[] = {'.','b','a','t',0};
82 static const WCHAR winevdmW[] = {'w','i','n','e','v','d','m','.','e','x','e',0};
84 extern int DIR_Init(void);
85 extern void SHELL_LoadRegistry(void);
86 extern void VOLUME_CreateDevices(void);
87 extern void VERSION_Init( const WCHAR *appname );
88 extern void LOCALE_Init(void);
90 /***********************************************************************
91 * contains_path
93 inline static int contains_path( LPCWSTR name )
95 return ((*name && (name[1] == ':')) || strchrW(name, '/') || strchrW(name, '\\'));
99 /***********************************************************************
100 * is_special_env_var
102 * Check if an environment variable needs to be handled specially when
103 * passed through the Unix environment (i.e. prefixed with "WINE").
105 inline static int is_special_env_var( const char *var )
107 return (!strncmp( var, "PATH=", sizeof("PATH=")-1 ) ||
108 !strncmp( var, "TEMP=", sizeof("TEMP=")-1 ) ||
109 !strncmp( var, "TMP=", sizeof("TMP=")-1 ));
113 /***************************************************************************
114 * get_builtin_path
116 * Get the path of a builtin module when the native file does not exist.
118 static BOOL get_builtin_path( const WCHAR *libname, const WCHAR *ext, WCHAR *filename, UINT size )
120 WCHAR *file_part;
121 WCHAR sysdir[MAX_PATH];
122 UINT len = GetSystemDirectoryW( sysdir, MAX_PATH );
124 if (contains_path( libname ))
126 if (RtlGetFullPathName_U( libname, size * sizeof(WCHAR),
127 filename, &file_part ) > size * sizeof(WCHAR))
128 return FALSE; /* too long */
130 if (strncmpiW( filename, sysdir, len ) || filename[len] != '\\')
131 return FALSE;
132 while (filename[len] == '\\') len++;
133 if (filename + len != file_part) return FALSE;
135 else
137 if (strlenW(libname) + len + 2 >= size) return FALSE; /* too long */
138 memcpy( filename, sysdir, len * sizeof(WCHAR) );
139 file_part = filename + len;
140 if (file_part > filename && file_part[-1] != '\\') *file_part++ = '\\';
141 strcpyW( file_part, libname );
143 if (ext && !strchrW( file_part, '.' ))
145 if (file_part + strlenW(file_part) + strlenW(ext) + 1 > filename + size)
146 return FALSE; /* too long */
147 strcatW( file_part, ext );
149 return TRUE;
153 /***********************************************************************
154 * open_builtin_exe_file
156 * Open an exe file for a builtin exe.
158 static void *open_builtin_exe_file( const WCHAR *name, char *error, int error_size,
159 int test_only, int *file_exists )
161 char exename[MAX_PATH];
162 WCHAR *p;
163 UINT i, len;
165 if ((p = strrchrW( name, '/' ))) name = p + 1;
166 if ((p = strrchrW( name, '\\' ))) name = p + 1;
168 /* we don't want to depend on the current codepage here */
169 len = strlenW( name ) + 1;
170 if (len >= sizeof(exename)) return NULL;
171 for (i = 0; i < len; i++)
173 if (name[i] > 127) return NULL;
174 exename[i] = (char)name[i];
175 if (exename[i] >= 'A' && exename[i] <= 'Z') exename[i] += 'a' - 'A';
177 return wine_dll_load_main_exe( exename, error, error_size, test_only, file_exists );
181 /***********************************************************************
182 * open_exe_file
184 * Open a specific exe file, taking load order into account.
185 * Returns the file handle or 0 for a builtin exe.
187 static HANDLE open_exe_file( const WCHAR *name )
189 enum loadorder_type loadorder[LOADORDER_NTYPES];
190 WCHAR buffer[MAX_PATH];
191 HANDLE handle;
192 int i, file_exists;
194 TRACE("looking for %s\n", debugstr_w(name) );
196 if ((handle = CreateFileW( name, GENERIC_READ, FILE_SHARE_READ,
197 NULL, OPEN_EXISTING, 0, 0 )) == INVALID_HANDLE_VALUE)
199 /* file doesn't exist, check for builtin */
200 if (!contains_path( name )) goto error;
201 if (!get_builtin_path( name, NULL, buffer, sizeof(buffer) )) goto error;
202 name = buffer;
205 MODULE_GetLoadOrderW( loadorder, NULL, name );
207 for(i = 0; i < LOADORDER_NTYPES; i++)
209 if (loadorder[i] == LOADORDER_INVALID) break;
210 switch(loadorder[i])
212 case LOADORDER_DLL:
213 TRACE( "Trying native exe %s\n", debugstr_w(name) );
214 if (handle != INVALID_HANDLE_VALUE) return handle;
215 break;
216 case LOADORDER_BI:
217 TRACE( "Trying built-in exe %s\n", debugstr_w(name) );
218 open_builtin_exe_file( name, NULL, 0, 1, &file_exists );
219 if (file_exists)
221 if (handle != INVALID_HANDLE_VALUE) CloseHandle(handle);
222 return 0;
224 default:
225 break;
228 if (handle != INVALID_HANDLE_VALUE) CloseHandle(handle);
230 error:
231 SetLastError( ERROR_FILE_NOT_FOUND );
232 return INVALID_HANDLE_VALUE;
236 /***********************************************************************
237 * find_exe_file
239 * Open an exe file, and return the full name and file handle.
240 * Returns FALSE if file could not be found.
241 * If file exists but cannot be opened, returns TRUE and set handle to INVALID_HANDLE_VALUE.
242 * If file is a builtin exe, returns TRUE and sets handle to 0.
244 static BOOL find_exe_file( const WCHAR *name, WCHAR *buffer, int buflen, HANDLE *handle )
246 static const WCHAR exeW[] = {'.','e','x','e',0};
248 enum loadorder_type loadorder[LOADORDER_NTYPES];
249 int i, file_exists;
251 TRACE("looking for %s\n", debugstr_w(name) );
253 if (!SearchPathW( NULL, name, exeW, buflen, buffer, NULL ) &&
254 !get_builtin_path( name, exeW, buffer, buflen ))
256 /* no builtin found, try native without extension in case it is a Unix app */
258 if (SearchPathW( NULL, name, NULL, buflen, buffer, NULL ))
260 TRACE( "Trying native/Unix binary %s\n", debugstr_w(buffer) );
261 if ((*handle = CreateFileW( buffer, GENERIC_READ, FILE_SHARE_READ,
262 NULL, OPEN_EXISTING, 0, 0 )) != INVALID_HANDLE_VALUE)
263 return TRUE;
265 return FALSE;
268 MODULE_GetLoadOrderW( loadorder, NULL, buffer );
270 for(i = 0; i < LOADORDER_NTYPES; i++)
272 if (loadorder[i] == LOADORDER_INVALID) break;
273 switch(loadorder[i])
275 case LOADORDER_DLL:
276 TRACE( "Trying native exe %s\n", debugstr_w(buffer) );
277 if ((*handle = CreateFileW( buffer, GENERIC_READ, FILE_SHARE_READ,
278 NULL, OPEN_EXISTING, 0, 0 )) != INVALID_HANDLE_VALUE)
279 return TRUE;
280 if (GetLastError() != ERROR_FILE_NOT_FOUND) return TRUE;
281 break;
282 case LOADORDER_BI:
283 TRACE( "Trying built-in exe %s\n", debugstr_w(buffer) );
284 open_builtin_exe_file( buffer, NULL, 0, 1, &file_exists );
285 if (file_exists)
287 *handle = 0;
288 return TRUE;
290 break;
291 default:
292 break;
295 SetLastError( ERROR_FILE_NOT_FOUND );
296 return FALSE;
300 /**********************************************************************
301 * load_pe_exe
303 * Load a PE format EXE file.
305 static HMODULE load_pe_exe( const WCHAR *name, HANDLE file )
307 IMAGE_NT_HEADERS *nt;
308 HANDLE mapping;
309 void *module;
310 OBJECT_ATTRIBUTES attr;
311 LARGE_INTEGER size;
312 DWORD len = 0;
313 UINT drive_type;
315 attr.Length = sizeof(attr);
316 attr.RootDirectory = 0;
317 attr.ObjectName = NULL;
318 attr.Attributes = 0;
319 attr.SecurityDescriptor = NULL;
320 attr.SecurityQualityOfService = NULL;
321 size.QuadPart = 0;
323 if (NtCreateSection( &mapping, STANDARD_RIGHTS_REQUIRED | SECTION_QUERY | SECTION_MAP_READ,
324 &attr, &size, 0, SEC_IMAGE, file ) != STATUS_SUCCESS)
325 return NULL;
327 module = NULL;
328 if (NtMapViewOfSection( mapping, GetCurrentProcess(), &module, 0, 0, &size, &len,
329 ViewShare, 0, PAGE_READONLY ) != STATUS_SUCCESS)
330 return NULL;
332 NtClose( mapping );
334 /* virus check */
335 nt = RtlImageNtHeader( module );
336 if (nt->OptionalHeader.AddressOfEntryPoint)
338 if (!RtlImageRvaToSection( nt, module, nt->OptionalHeader.AddressOfEntryPoint ))
339 MESSAGE("VIRUS WARNING: PE module %s has an invalid entrypoint (0x%08lx) "
340 "outside all sections (possibly infected by Tchernobyl/SpaceFiller virus)!\n",
341 debugstr_w(name), nt->OptionalHeader.AddressOfEntryPoint );
344 drive_type = GetDriveTypeW( name );
345 /* don't keep the file handle open on removable media */
346 if (drive_type == DRIVE_REMOVABLE || drive_type == DRIVE_CDROM)
348 CloseHandle( main_exe_file );
349 main_exe_file = 0;
352 return module;
355 /***********************************************************************
356 * build_initial_environment
358 * Build the Win32 environment from the Unix environment
360 static BOOL build_initial_environment( char **environ )
362 ULONG size = 1;
363 char **e;
364 WCHAR *p, *endptr;
365 void *ptr;
367 /* Compute the total size of the Unix environment */
368 for (e = environ; *e; e++)
370 if (is_special_env_var( *e )) continue;
371 size += MultiByteToWideChar( CP_UNIXCP, 0, *e, -1, NULL, 0 );
373 size *= sizeof(WCHAR);
375 /* Now allocate the environment */
376 if (NtAllocateVirtualMemory(NtCurrentProcess(), &ptr, 0, &size,
377 MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) != STATUS_SUCCESS)
378 return FALSE;
380 NtCurrentTeb()->Peb->ProcessParameters->Environment = p = ptr;
381 endptr = p + size / sizeof(WCHAR);
383 /* And fill it with the Unix environment */
384 for (e = environ; *e; e++)
386 char *str = *e;
388 /* skip Unix special variables and use the Wine variants instead */
389 if (!strncmp( str, "WINE", 4 ))
391 if (is_special_env_var( str + 4 )) str += 4;
393 else if (is_special_env_var( str )) continue; /* skip it */
395 MultiByteToWideChar( CP_UNIXCP, 0, str, -1, p, endptr - p );
396 p += strlenW(p) + 1;
398 *p = 0;
399 return TRUE;
403 /***********************************************************************
404 * set_library_wargv
406 * Set the Wine library Unicode argv global variables.
408 static void set_library_wargv( char **argv )
410 int argc;
411 WCHAR *p;
412 WCHAR **wargv;
413 DWORD total = 0;
415 for (argc = 0; argv[argc]; argc++)
416 total += MultiByteToWideChar( CP_UNIXCP, 0, argv[argc], -1, NULL, 0 );
418 wargv = RtlAllocateHeap( GetProcessHeap(), 0,
419 total * sizeof(WCHAR) + (argc + 1) * sizeof(*wargv) );
420 p = (WCHAR *)(wargv + argc + 1);
421 for (argc = 0; argv[argc]; argc++)
423 DWORD reslen = MultiByteToWideChar( CP_UNIXCP, 0, argv[argc], -1, p, total );
424 wargv[argc] = p;
425 p += reslen;
426 total -= reslen;
428 wargv[argc] = NULL;
429 __wine_main_wargv = wargv;
433 /***********************************************************************
434 * build_command_line
436 * Build the command line of a process from the argv array.
438 * Note that it does NOT necessarily include the file name.
439 * Sometimes we don't even have any command line options at all.
441 * We must quote and escape characters so that the argv array can be rebuilt
442 * from the command line:
443 * - spaces and tabs must be quoted
444 * 'a b' -> '"a b"'
445 * - quotes must be escaped
446 * '"' -> '\"'
447 * - if '\'s are followed by a '"', they must be doubled and followed by '\"',
448 * resulting in an odd number of '\' followed by a '"'
449 * '\"' -> '\\\"'
450 * '\\"' -> '\\\\\"'
451 * - '\'s that are not followed by a '"' can be left as is
452 * 'a\b' == 'a\b'
453 * 'a\\b' == 'a\\b'
455 static BOOL build_command_line( WCHAR **argv )
457 int len;
458 WCHAR **arg;
459 LPWSTR p;
460 RTL_USER_PROCESS_PARAMETERS* rupp = NtCurrentTeb()->Peb->ProcessParameters;
462 if (rupp->CommandLine.Buffer) return TRUE; /* already got it from the server */
464 len = 0;
465 for (arg = argv; *arg; arg++)
467 int has_space,bcount;
468 WCHAR* a;
470 has_space=0;
471 bcount=0;
472 a=*arg;
473 if( !*a ) has_space=1;
474 while (*a!='\0') {
475 if (*a=='\\') {
476 bcount++;
477 } else {
478 if (*a==' ' || *a=='\t') {
479 has_space=1;
480 } else if (*a=='"') {
481 /* doubling of '\' preceeding a '"',
482 * plus escaping of said '"'
484 len+=2*bcount+1;
486 bcount=0;
488 a++;
490 len+=(a-*arg)+1 /* for the separating space */;
491 if (has_space)
492 len+=2; /* for the quotes */
495 if (!(rupp->CommandLine.Buffer = RtlAllocateHeap( GetProcessHeap(), 0, len * sizeof(WCHAR))))
496 return FALSE;
498 p = rupp->CommandLine.Buffer;
499 rupp->CommandLine.Length = (len - 1) * sizeof(WCHAR);
500 rupp->CommandLine.MaximumLength = len * sizeof(WCHAR);
501 for (arg = argv; *arg; arg++)
503 int has_space,has_quote;
504 WCHAR* a;
506 /* Check for quotes and spaces in this argument */
507 has_space=has_quote=0;
508 a=*arg;
509 if( !*a ) has_space=1;
510 while (*a!='\0') {
511 if (*a==' ' || *a=='\t') {
512 has_space=1;
513 if (has_quote)
514 break;
515 } else if (*a=='"') {
516 has_quote=1;
517 if (has_space)
518 break;
520 a++;
523 /* Now transfer it to the command line */
524 if (has_space)
525 *p++='"';
526 if (has_quote) {
527 int bcount;
528 WCHAR* a;
530 bcount=0;
531 a=*arg;
532 while (*a!='\0') {
533 if (*a=='\\') {
534 *p++=*a;
535 bcount++;
536 } else {
537 if (*a=='"') {
538 int i;
540 /* Double all the '\\' preceeding this '"', plus one */
541 for (i=0;i<=bcount;i++)
542 *p++='\\';
543 *p++='"';
544 } else {
545 *p++=*a;
547 bcount=0;
549 a++;
551 } else {
552 WCHAR* x = *arg;
553 while ((*p=*x++)) p++;
555 if (has_space)
556 *p++='"';
557 *p++=' ';
559 if (p > rupp->CommandLine.Buffer)
560 p--; /* remove last space */
561 *p = '\0';
563 return TRUE;
567 /* make sure the unicode string doesn't point beyond the end pointer */
568 static inline void fix_unicode_string( UNICODE_STRING *str, char *end_ptr )
570 if ((char *)str->Buffer >= end_ptr)
572 str->Length = str->MaximumLength = 0;
573 str->Buffer = NULL;
574 return;
576 if ((char *)str->Buffer + str->MaximumLength > end_ptr)
578 str->MaximumLength = (end_ptr - (char *)str->Buffer) & ~(sizeof(WCHAR) - 1);
580 if (str->Length >= str->MaximumLength)
582 if (str->MaximumLength >= sizeof(WCHAR))
583 str->Length = str->MaximumLength - sizeof(WCHAR);
584 else
585 str->Length = str->MaximumLength = 0;
590 /***********************************************************************
591 * init_user_process_params
593 * Fill the RTL_USER_PROCESS_PARAMETERS structure from the server.
595 static RTL_USER_PROCESS_PARAMETERS *init_user_process_params( size_t info_size )
597 void *ptr;
598 DWORD size;
599 NTSTATUS status;
600 RTL_USER_PROCESS_PARAMETERS *params;
602 size = info_size;
603 if ((status = NtAllocateVirtualMemory( NtCurrentProcess(), &ptr, NULL, &size,
604 MEM_COMMIT, PAGE_READWRITE )) != STATUS_SUCCESS)
605 return NULL;
607 SERVER_START_REQ( get_startup_info )
609 wine_server_set_reply( req, ptr, info_size );
610 wine_server_call( req );
611 info_size = wine_server_reply_size( reply );
613 SERVER_END_REQ;
615 params = ptr;
616 params->Size = info_size;
617 params->AllocationSize = size;
619 /* make sure the strings are valid */
620 fix_unicode_string( &params->CurrentDirectory.DosPath, (char *)info_size );
621 fix_unicode_string( &params->DllPath, (char *)info_size );
622 fix_unicode_string( &params->ImagePathName, (char *)info_size );
623 fix_unicode_string( &params->CommandLine, (char *)info_size );
624 fix_unicode_string( &params->WindowTitle, (char *)info_size );
625 fix_unicode_string( &params->Desktop, (char *)info_size );
626 fix_unicode_string( &params->ShellInfo, (char *)info_size );
627 fix_unicode_string( &params->RuntimeInfo, (char *)info_size );
629 return RtlNormalizeProcessParams( params );
633 /***********************************************************************
634 * process_init
636 * Main process initialisation code
638 static BOOL process_init( char *argv[], char **environ )
640 static const WCHAR kernel32W[] = {'k','e','r','n','e','l','3','2',0};
641 BOOL ret;
642 size_t info_size = 0;
643 RTL_USER_PROCESS_PARAMETERS *params;
644 PEB *peb = NtCurrentTeb()->Peb;
645 HANDLE hstdin, hstdout, hstderr;
646 extern void __wine_dbg_kernel32_init(void);
648 PTHREAD_Init();
650 __wine_dbg_kernel32_init(); /* hack: register debug channels early */
652 setbuf(stdout,NULL);
653 setbuf(stderr,NULL);
654 setlocale(LC_CTYPE,"");
656 /* Retrieve startup info from the server */
657 SERVER_START_REQ( init_process )
659 req->peb = peb;
660 req->ldt_copy = &wine_ldt_copy;
661 if ((ret = !wine_server_call_err( req )))
663 main_exe_file = reply->exe_file;
664 main_create_flags = reply->create_flags;
665 info_size = reply->info_size;
666 server_startticks = reply->server_start;
667 hstdin = reply->hstdin;
668 hstdout = reply->hstdout;
669 hstderr = reply->hstderr;
672 SERVER_END_REQ;
673 if (!ret) return FALSE;
675 if (info_size == 0)
677 params = peb->ProcessParameters;
679 /* This is wine specific: we have no parent (we're started from unix)
680 * so, create a simple console with bare handles to unix stdio
681 * input & output streams (aka simple console)
683 wine_server_fd_to_handle( 0, GENERIC_READ|SYNCHRONIZE, TRUE, &params->hStdInput );
684 wine_server_fd_to_handle( 1, GENERIC_WRITE|SYNCHRONIZE, TRUE, &params->hStdOutput );
685 wine_server_fd_to_handle( 2, GENERIC_WRITE|SYNCHRONIZE, TRUE, &params->hStdError );
687 /* <hack: to be changed later on> */
688 params->CurrentDirectory.DosPath.Length = 3 * sizeof(WCHAR);
689 params->CurrentDirectory.DosPath.MaximumLength = RtlGetLongestNtPathLength() * sizeof(WCHAR);
690 params->CurrentDirectory.DosPath.Buffer = RtlAllocateHeap( GetProcessHeap(), 0, params->CurrentDirectory.DosPath.MaximumLength);
691 params->CurrentDirectory.DosPath.Buffer[0] = 'C';
692 params->CurrentDirectory.DosPath.Buffer[1] = ':';
693 params->CurrentDirectory.DosPath.Buffer[2] = '\\';
694 params->CurrentDirectory.DosPath.Buffer[3] = '\0';
695 /* </hack: to be changed later on> */
697 else
699 if (!(params = init_user_process_params( info_size ))) return FALSE;
700 peb->ProcessParameters = params;
702 /* convert value from server:
703 * + 0 => INVALID_HANDLE_VALUE
704 * + console handle need to be mapped
706 if (!hstdin)
707 hstdin = INVALID_HANDLE_VALUE;
708 else if (VerifyConsoleIoHandle(console_handle_map(hstdin)))
709 hstdin = console_handle_map(hstdin);
711 if (!hstdout)
712 hstdout = INVALID_HANDLE_VALUE;
713 else if (VerifyConsoleIoHandle(console_handle_map(hstdout)))
714 hstdout = console_handle_map(hstdout);
716 if (!hstderr)
717 hstderr = INVALID_HANDLE_VALUE;
718 else if (VerifyConsoleIoHandle(console_handle_map(hstderr)))
719 hstderr = console_handle_map(hstderr);
721 params->hStdInput = hstdin;
722 params->hStdOutput = hstdout;
723 params->hStdError = hstderr;
726 kernel32_handle = GetModuleHandleW(kernel32W);
728 LOCALE_Init();
730 /* Copy the parent environment */
731 if (!build_initial_environment( environ )) return FALSE;
733 /* Parse command line arguments */
734 if (!info_size) OPTIONS_ParseOptions( argv );
736 /* Create device symlinks */
737 VOLUME_CreateDevices();
739 /* initialise DOS directories */
740 if (!DIR_Init()) return FALSE;
742 /* registry initialisation */
743 SHELL_LoadRegistry();
745 /* global boot finished, the rest is process-local */
746 SERVER_START_REQ( boot_done )
748 req->debug_level = TRACE_ON(server);
749 wine_server_call( req );
751 SERVER_END_REQ;
753 return TRUE;
757 /***********************************************************************
758 * start_process
760 * Startup routine of a new process. Runs on the new process stack.
762 static void start_process( void *arg )
764 __TRY
766 PEB *peb = NtCurrentTeb()->Peb;
767 IMAGE_NT_HEADERS *nt;
768 LPTHREAD_START_ROUTINE entry;
770 LdrInitializeThunk( main_exe_file, 0, 0, 0 );
772 nt = RtlImageNtHeader( peb->ImageBaseAddress );
773 entry = (LPTHREAD_START_ROUTINE)((char *)peb->ImageBaseAddress +
774 nt->OptionalHeader.AddressOfEntryPoint);
776 if (TRACE_ON(relay))
777 DPRINTF( "%04lx:Starting process %s (entryproc=%p)\n", GetCurrentThreadId(),
778 debugstr_w(peb->ProcessParameters->ImagePathName.Buffer), entry );
780 SetLastError( 0 ); /* clear error code */
781 if (peb->BeingDebugged) DbgBreakPoint();
782 ExitProcess( entry( peb ) );
784 __EXCEPT(UnhandledExceptionFilter)
786 TerminateThread( GetCurrentThread(), GetExceptionCode() );
788 __ENDTRY
792 /***********************************************************************
793 * __wine_kernel_init
795 * Wine initialisation: load and start the main exe file.
797 void __wine_kernel_init(void)
799 WCHAR *main_exe_name, *p;
800 char error[1024];
801 DWORD stack_size = 0;
802 int file_exists;
803 PEB *peb = NtCurrentTeb()->Peb;
805 /* Initialize everything */
806 if (!process_init( __wine_main_argv, __wine_main_environ )) exit(1);
807 /* update argc in case options have been removed */
808 for (__wine_main_argc = 0; __wine_main_argv[__wine_main_argc]; __wine_main_argc++) /*nothing*/;
810 __wine_main_argv++; /* remove argv[0] (wine itself) */
811 __wine_main_argc--;
813 if (!(main_exe_name = peb->ProcessParameters->ImagePathName.Buffer))
815 WCHAR buffer[MAX_PATH];
816 WCHAR exe_nameW[MAX_PATH];
818 if (!__wine_main_argv[0]) OPTIONS_Usage();
820 MultiByteToWideChar( CP_UNIXCP, 0, __wine_main_argv[0], -1, exe_nameW, MAX_PATH );
821 if (!find_exe_file( exe_nameW, buffer, MAX_PATH, &main_exe_file ))
823 MESSAGE( "wine: cannot find '%s'\n", __wine_main_argv[0] );
824 ExitProcess(1);
826 if (main_exe_file == INVALID_HANDLE_VALUE)
828 MESSAGE( "wine: cannot open %s\n", debugstr_w(main_exe_name) );
829 ExitProcess(1);
831 RtlCreateUnicodeString( &peb->ProcessParameters->ImagePathName, buffer );
832 main_exe_name = peb->ProcessParameters->ImagePathName.Buffer;
835 TRACE( "starting process name=%s file=%p argv[0]=%s\n",
836 debugstr_w(main_exe_name), main_exe_file, debugstr_a(__wine_main_argv[0]) );
838 RtlInitUnicodeString( &NtCurrentTeb()->Peb->ProcessParameters->DllPath,
839 MODULE_get_dll_load_path(NULL) );
840 VERSION_Init( main_exe_name );
842 if (!main_exe_file) /* no file handle -> Winelib app */
844 TRACE( "starting Winelib app %s\n", debugstr_w(main_exe_name) );
845 if (open_builtin_exe_file( main_exe_name, error, sizeof(error), 0, &file_exists ))
846 goto found;
847 MESSAGE( "wine: cannot open builtin library for %s: %s\n",
848 debugstr_w(main_exe_name), error );
849 ExitProcess(1);
852 switch( MODULE_GetBinaryType( main_exe_file ))
854 case BINARY_PE_EXE:
855 TRACE( "starting Win32 binary %s\n", debugstr_w(main_exe_name) );
856 if ((peb->ImageBaseAddress = load_pe_exe( main_exe_name, main_exe_file )))
857 goto found;
858 MESSAGE( "wine: could not load %s as Win32 binary\n", debugstr_w(main_exe_name) );
859 ExitProcess(1);
860 case BINARY_PE_DLL:
861 MESSAGE( "wine: %s is a DLL, not an executable\n", debugstr_w(main_exe_name) );
862 ExitProcess(1);
863 case BINARY_UNKNOWN:
864 /* check for .com extension */
865 if (!(p = strrchrW( main_exe_name, '.' )) || strcmpiW( p, comW ))
867 MESSAGE( "wine: cannot determine executable type for %s\n",
868 debugstr_w(main_exe_name) );
869 ExitProcess(1);
871 /* fall through */
872 case BINARY_WIN16:
873 case BINARY_DOS:
874 TRACE( "starting Win16/DOS binary %s\n", debugstr_w(main_exe_name) );
875 CloseHandle( main_exe_file );
876 main_exe_file = 0;
877 __wine_main_argv--;
878 __wine_main_argc++;
879 __wine_main_argv[0] = "winevdm.exe";
880 if (open_builtin_exe_file( winevdmW, error, sizeof(error), 0, &file_exists ))
881 goto found;
882 MESSAGE( "wine: trying to run %s, cannot open builtin library for 'winevdm.exe': %s\n",
883 debugstr_w(main_exe_name), error );
884 ExitProcess(1);
885 case BINARY_OS216:
886 MESSAGE( "wine: %s is an OS/2 binary, not supported\n", debugstr_w(main_exe_name) );
887 ExitProcess(1);
888 case BINARY_UNIX_EXE:
889 MESSAGE( "wine: %s is a Unix binary, not supported\n", debugstr_w(main_exe_name) );
890 ExitProcess(1);
891 case BINARY_UNIX_LIB:
893 char *unix_name;
895 TRACE( "starting Winelib app %s\n", debugstr_w(main_exe_name) );
896 CloseHandle( main_exe_file );
897 main_exe_file = 0;
898 if ((unix_name = wine_get_unix_file_name( main_exe_name )) &&
899 wine_dlopen( unix_name, RTLD_NOW, error, sizeof(error) ))
901 static const WCHAR soW[] = {'.','s','o',0};
902 if ((p = strrchrW( main_exe_name, '.' )) && !strcmpW( p, soW ))
904 *p = 0;
905 /* update the unicode string */
906 RtlInitUnicodeString( &peb->ProcessParameters->ImagePathName, main_exe_name );
908 HeapFree( GetProcessHeap(), 0, unix_name );
909 goto found;
911 MESSAGE( "wine: could not load %s: %s\n", debugstr_w(main_exe_name), error );
912 ExitProcess(1);
916 found:
917 wine_free_pe_load_area(); /* the main binary is loaded, we don't need this anymore */
919 /* build command line */
920 set_library_wargv( __wine_main_argv );
921 if (!build_command_line( __wine_main_wargv )) goto error;
923 stack_size = RtlImageNtHeader(peb->ImageBaseAddress)->OptionalHeader.SizeOfStackReserve;
925 /* allocate main thread stack */
926 if (!THREAD_InitStack( NtCurrentTeb(), stack_size )) goto error;
928 /* switch to the new stack */
929 wine_switch_to_stack( start_process, NULL, NtCurrentTeb()->Tib.StackBase );
931 error:
932 ExitProcess( GetLastError() );
936 /***********************************************************************
937 * build_argv
939 * Build an argv array from a command-line.
940 * 'reserved' is the number of args to reserve before the first one.
942 static char **build_argv( const WCHAR *cmdlineW, int reserved )
944 int argc;
945 char** argv;
946 char *arg,*s,*d,*cmdline;
947 int in_quotes,bcount,len;
949 len = WideCharToMultiByte( CP_UNIXCP, 0, cmdlineW, -1, NULL, 0, NULL, NULL );
950 if (!(cmdline = malloc(len))) return NULL;
951 WideCharToMultiByte( CP_UNIXCP, 0, cmdlineW, -1, cmdline, len, NULL, NULL );
953 argc=reserved+1;
954 bcount=0;
955 in_quotes=0;
956 s=cmdline;
957 while (1) {
958 if (*s=='\0' || ((*s==' ' || *s=='\t') && !in_quotes)) {
959 /* space */
960 argc++;
961 /* skip the remaining spaces */
962 while (*s==' ' || *s=='\t') {
963 s++;
965 if (*s=='\0')
966 break;
967 bcount=0;
968 continue;
969 } else if (*s=='\\') {
970 /* '\', count them */
971 bcount++;
972 } else if ((*s=='"') && ((bcount & 1)==0)) {
973 /* unescaped '"' */
974 in_quotes=!in_quotes;
975 bcount=0;
976 } else {
977 /* a regular character */
978 bcount=0;
980 s++;
982 argv=malloc(argc*sizeof(*argv));
983 if (!argv)
984 return NULL;
986 arg=d=s=cmdline;
987 bcount=0;
988 in_quotes=0;
989 argc=reserved;
990 while (*s) {
991 if ((*s==' ' || *s=='\t') && !in_quotes) {
992 /* Close the argument and copy it */
993 *d=0;
994 argv[argc++]=arg;
996 /* skip the remaining spaces */
997 do {
998 s++;
999 } while (*s==' ' || *s=='\t');
1001 /* Start with a new argument */
1002 arg=d=s;
1003 bcount=0;
1004 } else if (*s=='\\') {
1005 /* '\\' */
1006 *d++=*s++;
1007 bcount++;
1008 } else if (*s=='"') {
1009 /* '"' */
1010 if ((bcount & 1)==0) {
1011 /* Preceeded by an even number of '\', this is half that
1012 * number of '\', plus a '"' which we discard.
1014 d-=bcount/2;
1015 s++;
1016 in_quotes=!in_quotes;
1017 } else {
1018 /* Preceeded by an odd number of '\', this is half that
1019 * number of '\' followed by a '"'
1021 d=d-bcount/2-1;
1022 *d++='"';
1023 s++;
1025 bcount=0;
1026 } else {
1027 /* a regular character */
1028 *d++=*s++;
1029 bcount=0;
1032 if (*arg) {
1033 *d='\0';
1034 argv[argc++]=arg;
1036 argv[argc]=NULL;
1038 return argv;
1042 /***********************************************************************
1043 * alloc_env_string
1045 * Allocate an environment string; helper for build_envp
1047 static char *alloc_env_string( const char *name, const char *value )
1049 char *ret = malloc( strlen(name) + strlen(value) + 1 );
1050 strcpy( ret, name );
1051 strcat( ret, value );
1052 return ret;
1055 /***********************************************************************
1056 * build_envp
1058 * Build the environment of a new child process.
1060 static char **build_envp( const WCHAR *envW )
1062 const WCHAR *p;
1063 char **envp;
1064 char *env;
1065 int count = 0, length;
1067 for (p = envW; *p; count++) p += strlenW(p) + 1;
1068 p++;
1069 length = WideCharToMultiByte( CP_UNIXCP, 0, envW, p - envW, NULL, 0, NULL, NULL );
1070 if (!(env = malloc( length ))) return NULL;
1071 WideCharToMultiByte( CP_UNIXCP, 0, envW, p - envW, env, length, NULL, NULL );
1073 count += 4;
1075 if ((envp = malloc( count * sizeof(*envp) )))
1077 char **envptr = envp;
1078 char *p;
1080 /* then put PATH, TEMP, TMP, HOME and WINEPREFIX from the unix env */
1081 if ((p = getenv("PATH"))) *envptr++ = alloc_env_string( "PATH=", p );
1082 if ((p = getenv("TEMP"))) *envptr++ = alloc_env_string( "TEMP=", p );
1083 if ((p = getenv("TMP"))) *envptr++ = alloc_env_string( "TMP=", p );
1084 if ((p = getenv("HOME"))) *envptr++ = alloc_env_string( "HOME=", p );
1085 if ((p = getenv("WINEPREFIX"))) *envptr++ = alloc_env_string( "WINEPREFIX=", p );
1086 /* now put the Windows environment strings */
1087 for (p = env; *p; p += strlen(p) + 1)
1089 if (is_special_env_var( p )) /* prefix it with "WINE" */
1090 *envptr++ = alloc_env_string( "WINE", p );
1091 else if (strncmp( p, "HOME=", 5 ) &&
1092 strncmp( p, "WINEPREFIX=", 11 )) *envptr++ = p;
1094 *envptr = 0;
1096 return envp;
1100 /***********************************************************************
1101 * fork_and_exec
1103 * Fork and exec a new Unix binary, checking for errors.
1105 static int fork_and_exec( const char *filename, const WCHAR *cmdline,
1106 const WCHAR *env, const char *newdir )
1108 int fd[2];
1109 int pid, err;
1111 if (!env) env = GetEnvironmentStringsW();
1113 if (pipe(fd) == -1)
1115 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
1116 return -1;
1118 fcntl( fd[1], F_SETFD, 1 ); /* set close on exec */
1119 if (!(pid = fork())) /* child */
1121 char **argv = build_argv( cmdline, 0 );
1122 char **envp = build_envp( env );
1123 close( fd[0] );
1125 /* Reset signals that we previously set to SIG_IGN */
1126 signal( SIGPIPE, SIG_DFL );
1127 signal( SIGCHLD, SIG_DFL );
1129 if (newdir) chdir(newdir);
1131 if (argv && envp) execve( filename, argv, envp );
1132 err = errno;
1133 write( fd[1], &err, sizeof(err) );
1134 _exit(1);
1136 close( fd[1] );
1137 if ((pid != -1) && (read( fd[0], &err, sizeof(err) ) > 0)) /* exec failed */
1139 errno = err;
1140 pid = -1;
1142 if (pid == -1) FILE_SetDosError();
1143 close( fd[0] );
1144 return pid;
1148 /***********************************************************************
1149 * create_user_params
1151 static RTL_USER_PROCESS_PARAMETERS *create_user_params( LPCWSTR filename, LPCWSTR cmdline,
1152 const STARTUPINFOW *startup )
1154 RTL_USER_PROCESS_PARAMETERS *params;
1155 UNICODE_STRING image_str, cmdline_str, desktop, title;
1156 NTSTATUS status;
1157 WCHAR buffer[MAX_PATH];
1159 if(!GetLongPathNameW( filename, buffer, MAX_PATH ))
1160 lstrcpynW( buffer, filename, MAX_PATH );
1161 if(!GetFullPathNameW( buffer, MAX_PATH, buffer, NULL ))
1162 lstrcpynW( buffer, filename, MAX_PATH );
1163 RtlInitUnicodeString( &image_str, buffer );
1165 RtlInitUnicodeString( &cmdline_str, cmdline );
1166 if (startup->lpDesktop) RtlInitUnicodeString( &desktop, startup->lpDesktop );
1167 if (startup->lpTitle) RtlInitUnicodeString( &title, startup->lpTitle );
1169 status = RtlCreateProcessParameters( &params, &image_str, NULL, NULL, &cmdline_str, NULL,
1170 startup->lpTitle ? &title : NULL,
1171 startup->lpDesktop ? &desktop : NULL,
1172 NULL, NULL );
1173 if (status != STATUS_SUCCESS)
1175 SetLastError( RtlNtStatusToDosError(status) );
1176 return NULL;
1179 params->Environment = NULL; /* we pass it through the Unix environment */
1180 params->hStdInput = startup->hStdInput;
1181 params->hStdOutput = startup->hStdOutput;
1182 params->hStdError = startup->hStdError;
1183 params->dwX = startup->dwX;
1184 params->dwY = startup->dwY;
1185 params->dwXSize = startup->dwXSize;
1186 params->dwYSize = startup->dwYSize;
1187 params->dwXCountChars = startup->dwXCountChars;
1188 params->dwYCountChars = startup->dwYCountChars;
1189 params->dwFillAttribute = startup->dwFillAttribute;
1190 params->dwFlags = startup->dwFlags;
1191 params->wShowWindow = startup->wShowWindow;
1192 return params;
1196 /***********************************************************************
1197 * create_process
1199 * Create a new process. If hFile is a valid handle we have an exe
1200 * file, otherwise it is a Winelib app.
1202 static BOOL create_process( HANDLE hFile, LPCWSTR filename, LPWSTR cmd_line, LPWSTR env,
1203 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1204 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
1205 LPPROCESS_INFORMATION info, LPCSTR unixdir )
1207 BOOL ret, success = FALSE;
1208 HANDLE process_info;
1209 RTL_USER_PROCESS_PARAMETERS *params;
1210 int startfd[2];
1211 int execfd[2];
1212 pid_t pid;
1213 int err;
1214 char dummy = 0;
1216 if (!env) env = GetEnvironmentStringsW();
1218 if (!(params = create_user_params( filename, cmd_line, startup )))
1219 return FALSE;
1221 /* create the synchronization pipes */
1223 if (pipe( startfd ) == -1)
1225 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
1226 RtlDestroyProcessParameters( params );
1227 return FALSE;
1229 if (pipe( execfd ) == -1)
1231 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
1232 close( startfd[0] );
1233 close( startfd[1] );
1234 RtlDestroyProcessParameters( params );
1235 return FALSE;
1237 fcntl( execfd[1], F_SETFD, 1 ); /* set close on exec */
1239 /* create the child process */
1241 if (!(pid = fork())) /* child */
1243 char **argv = build_argv( cmd_line, 1 );
1244 char **envp = build_envp( env );
1246 close( startfd[1] );
1247 close( execfd[0] );
1249 /* wait for parent to tell us to start */
1250 if (read( startfd[0], &dummy, 1 ) != 1) _exit(1);
1252 close( startfd[0] );
1253 /* Reset signals that we previously set to SIG_IGN */
1254 signal( SIGPIPE, SIG_DFL );
1255 signal( SIGCHLD, SIG_DFL );
1257 if (unixdir) chdir(unixdir);
1259 if (argv && envp)
1261 /* first, try for a WINELOADER environment variable */
1262 argv[0] = getenv("WINELOADER");
1263 if (argv[0]) execve( argv[0], argv, envp );
1264 /* now use the standard search strategy */
1265 wine_exec_wine_binary( NULL, argv, envp );
1267 err = errno;
1268 write( execfd[1], &err, sizeof(err) );
1269 _exit(1);
1272 /* this is the parent */
1274 close( startfd[0] );
1275 close( execfd[1] );
1276 if (pid == -1)
1278 close( startfd[1] );
1279 close( execfd[0] );
1280 FILE_SetDosError();
1281 RtlDestroyProcessParameters( params );
1282 return FALSE;
1285 /* create the process on the server side */
1287 SERVER_START_REQ( new_process )
1289 req->inherit_all = inherit;
1290 req->create_flags = flags;
1291 req->unix_pid = pid;
1292 req->exe_file = hFile;
1293 if (startup->dwFlags & STARTF_USESTDHANDLES)
1295 req->hstdin = startup->hStdInput;
1296 req->hstdout = startup->hStdOutput;
1297 req->hstderr = startup->hStdError;
1299 else
1301 req->hstdin = GetStdHandle( STD_INPUT_HANDLE );
1302 req->hstdout = GetStdHandle( STD_OUTPUT_HANDLE );
1303 req->hstderr = GetStdHandle( STD_ERROR_HANDLE );
1306 if ((flags & (CREATE_NEW_CONSOLE | DETACHED_PROCESS)) != 0)
1308 /* this is temporary (for console handles). We have no way to control that the handle is invalid in child process otherwise */
1309 if (is_console_handle(req->hstdin)) req->hstdin = INVALID_HANDLE_VALUE;
1310 if (is_console_handle(req->hstdout)) req->hstdout = INVALID_HANDLE_VALUE;
1311 if (is_console_handle(req->hstderr)) req->hstderr = INVALID_HANDLE_VALUE;
1313 else
1315 if (is_console_handle(req->hstdin)) req->hstdin = console_handle_unmap(req->hstdin);
1316 if (is_console_handle(req->hstdout)) req->hstdout = console_handle_unmap(req->hstdout);
1317 if (is_console_handle(req->hstderr)) req->hstderr = console_handle_unmap(req->hstderr);
1320 wine_server_add_data( req, params, params->Size );
1321 ret = !wine_server_call_err( req );
1322 process_info = reply->info;
1324 SERVER_END_REQ;
1326 RtlDestroyProcessParameters( params );
1327 if (!ret)
1329 close( startfd[1] );
1330 close( execfd[0] );
1331 return FALSE;
1334 /* tell child to start and wait for it to exec */
1336 write( startfd[1], &dummy, 1 );
1337 close( startfd[1] );
1339 if (read( execfd[0], &err, sizeof(err) ) > 0) /* exec failed */
1341 errno = err;
1342 FILE_SetDosError();
1343 close( execfd[0] );
1344 CloseHandle( process_info );
1345 return FALSE;
1347 close( execfd[0] );
1349 /* wait for the new process info to be ready */
1351 WaitForSingleObject( process_info, INFINITE );
1352 SERVER_START_REQ( get_new_process_info )
1354 req->info = process_info;
1355 req->pinherit = (psa && (psa->nLength >= sizeof(*psa)) && psa->bInheritHandle);
1356 req->tinherit = (tsa && (tsa->nLength >= sizeof(*tsa)) && tsa->bInheritHandle);
1357 if ((ret = !wine_server_call_err( req )))
1359 info->dwProcessId = (DWORD)reply->pid;
1360 info->dwThreadId = (DWORD)reply->tid;
1361 info->hProcess = reply->phandle;
1362 info->hThread = reply->thandle;
1363 success = reply->success;
1366 SERVER_END_REQ;
1368 if (ret && !success) /* new process failed to start */
1370 DWORD exitcode;
1371 if (GetExitCodeProcess( info->hProcess, &exitcode )) SetLastError( exitcode );
1372 CloseHandle( info->hThread );
1373 CloseHandle( info->hProcess );
1374 ret = FALSE;
1376 CloseHandle( process_info );
1377 return ret;
1381 /***********************************************************************
1382 * create_vdm_process
1384 * Create a new VDM process for a 16-bit or DOS application.
1386 static BOOL create_vdm_process( LPCWSTR filename, LPWSTR cmd_line, LPWSTR env,
1387 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1388 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
1389 LPPROCESS_INFORMATION info, LPCSTR unixdir )
1391 static const WCHAR argsW[] = {'%','s',' ','-','-','a','p','p','-','n','a','m','e',' ','"','%','s','"',' ','%','s',0};
1393 BOOL ret;
1394 LPWSTR new_cmd_line = HeapAlloc( GetProcessHeap(), 0,
1395 (strlenW(filename) + strlenW(cmd_line) + 30) * sizeof(WCHAR) );
1397 if (!new_cmd_line)
1399 SetLastError( ERROR_OUTOFMEMORY );
1400 return FALSE;
1402 sprintfW( new_cmd_line, argsW, winevdmW, filename, cmd_line );
1403 ret = create_process( 0, winevdmW, new_cmd_line, env, psa, tsa, inherit,
1404 flags, startup, info, unixdir );
1405 HeapFree( GetProcessHeap(), 0, new_cmd_line );
1406 return ret;
1410 /***********************************************************************
1411 * create_cmd_process
1413 * Create a new cmd shell process for a .BAT file.
1415 static BOOL create_cmd_process( LPCWSTR filename, LPWSTR cmd_line, LPVOID env,
1416 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1417 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
1418 LPPROCESS_INFORMATION info, LPCWSTR cur_dir )
1421 static const WCHAR comspecW[] = {'C','O','M','S','P','E','C',0};
1422 static const WCHAR slashcW[] = {' ','/','c',' ',0};
1423 WCHAR comspec[MAX_PATH];
1424 WCHAR *newcmdline;
1425 BOOL ret;
1427 if (!GetEnvironmentVariableW( comspecW, comspec, sizeof(comspec)/sizeof(WCHAR) ))
1428 return FALSE;
1429 if (!(newcmdline = HeapAlloc( GetProcessHeap(), 0,
1430 (strlenW(comspec) + 4 + strlenW(cmd_line) + 1) * sizeof(WCHAR))))
1431 return FALSE;
1433 strcpyW( newcmdline, comspec );
1434 strcatW( newcmdline, slashcW );
1435 strcatW( newcmdline, cmd_line );
1436 ret = CreateProcessW( comspec, newcmdline, psa, tsa, inherit,
1437 flags, env, cur_dir, startup, info );
1438 HeapFree( GetProcessHeap(), 0, newcmdline );
1439 return ret;
1443 /*************************************************************************
1444 * get_file_name
1446 * Helper for CreateProcess: retrieve the file name to load from the
1447 * app name and command line. Store the file name in buffer, and
1448 * return a possibly modified command line.
1449 * Also returns a handle to the opened file if it's a Windows binary.
1451 static LPWSTR get_file_name( LPCWSTR appname, LPWSTR cmdline, LPWSTR buffer,
1452 int buflen, HANDLE *handle )
1454 static const WCHAR quotesW[] = {'"','%','s','"',0};
1456 WCHAR *name, *pos, *ret = NULL;
1457 const WCHAR *p;
1459 /* if we have an app name, everything is easy */
1461 if (appname)
1463 /* use the unmodified app name as file name */
1464 lstrcpynW( buffer, appname, buflen );
1465 *handle = open_exe_file( buffer );
1466 if (!(ret = cmdline) || !cmdline[0])
1468 /* no command-line, create one */
1469 if ((ret = HeapAlloc( GetProcessHeap(), 0, (strlenW(appname) + 3) * sizeof(WCHAR) )))
1470 sprintfW( ret, quotesW, appname );
1472 return ret;
1475 if (!cmdline)
1477 SetLastError( ERROR_INVALID_PARAMETER );
1478 return NULL;
1481 /* first check for a quoted file name */
1483 if ((cmdline[0] == '"') && ((p = strchrW( cmdline + 1, '"' ))))
1485 int len = p - cmdline - 1;
1486 /* extract the quoted portion as file name */
1487 if (!(name = HeapAlloc( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) ))) return NULL;
1488 memcpy( name, cmdline + 1, len * sizeof(WCHAR) );
1489 name[len] = 0;
1491 if (find_exe_file( name, buffer, buflen, handle ))
1492 ret = cmdline; /* no change necessary */
1493 goto done;
1496 /* now try the command-line word by word */
1498 if (!(name = HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline) + 1) * sizeof(WCHAR) )))
1499 return NULL;
1500 pos = name;
1501 p = cmdline;
1503 while (*p)
1505 do *pos++ = *p++; while (*p && *p != ' ');
1506 *pos = 0;
1507 if (find_exe_file( name, buffer, buflen, handle ))
1509 ret = cmdline;
1510 break;
1514 if (!ret || !strchrW( name, ' ' )) goto done; /* no change necessary */
1516 /* now build a new command-line with quotes */
1518 if (!(ret = HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline) + 3) * sizeof(WCHAR) )))
1519 goto done;
1520 sprintfW( ret, quotesW, name );
1521 strcatW( ret, p );
1523 done:
1524 HeapFree( GetProcessHeap(), 0, name );
1525 return ret;
1529 /**********************************************************************
1530 * CreateProcessA (KERNEL32.@)
1532 BOOL WINAPI CreateProcessA( LPCSTR app_name, LPSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
1533 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit,
1534 DWORD flags, LPVOID env, LPCSTR cur_dir,
1535 LPSTARTUPINFOA startup_info, LPPROCESS_INFORMATION info )
1537 BOOL ret;
1538 UNICODE_STRING app_nameW, cmd_lineW, cur_dirW, desktopW, titleW;
1539 STARTUPINFOW infoW;
1541 if (app_name) RtlCreateUnicodeStringFromAsciiz( &app_nameW, app_name );
1542 else app_nameW.Buffer = NULL;
1543 if (cmd_line) RtlCreateUnicodeStringFromAsciiz( &cmd_lineW, cmd_line );
1544 else cmd_lineW.Buffer = NULL;
1545 if (cur_dir) RtlCreateUnicodeStringFromAsciiz( &cur_dirW, cur_dir );
1546 else cur_dirW.Buffer = NULL;
1547 if (startup_info->lpDesktop) RtlCreateUnicodeStringFromAsciiz( &desktopW, startup_info->lpDesktop );
1548 else desktopW.Buffer = NULL;
1549 if (startup_info->lpTitle) RtlCreateUnicodeStringFromAsciiz( &titleW, startup_info->lpTitle );
1550 else titleW.Buffer = NULL;
1552 memcpy( &infoW, startup_info, sizeof(infoW) );
1553 infoW.lpDesktop = desktopW.Buffer;
1554 infoW.lpTitle = titleW.Buffer;
1556 if (startup_info->lpReserved)
1557 FIXME("StartupInfo.lpReserved is used, please report (%s)\n",
1558 debugstr_a(startup_info->lpReserved));
1560 ret = CreateProcessW( app_nameW.Buffer, cmd_lineW.Buffer, process_attr, thread_attr,
1561 inherit, flags, env, cur_dirW.Buffer, &infoW, info );
1563 RtlFreeUnicodeString( &app_nameW );
1564 RtlFreeUnicodeString( &cmd_lineW );
1565 RtlFreeUnicodeString( &cur_dirW );
1566 RtlFreeUnicodeString( &desktopW );
1567 RtlFreeUnicodeString( &titleW );
1568 return ret;
1572 /**********************************************************************
1573 * CreateProcessW (KERNEL32.@)
1575 BOOL WINAPI CreateProcessW( LPCWSTR app_name, LPWSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
1576 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit, DWORD flags,
1577 LPVOID env, LPCWSTR cur_dir, LPSTARTUPINFOW startup_info,
1578 LPPROCESS_INFORMATION info )
1580 BOOL retv = FALSE;
1581 HANDLE hFile = 0;
1582 char *unixdir = NULL;
1583 WCHAR name[MAX_PATH];
1584 WCHAR *tidy_cmdline, *p, *envW = env;
1586 /* Process the AppName and/or CmdLine to get module name and path */
1588 TRACE("app %s cmdline %s\n", debugstr_w(app_name), debugstr_w(cmd_line) );
1590 if (!(tidy_cmdline = get_file_name( app_name, cmd_line, name, sizeof(name), &hFile )))
1591 return FALSE;
1592 if (hFile == INVALID_HANDLE_VALUE) goto done;
1594 /* Warn if unsupported features are used */
1596 if (flags & (IDLE_PRIORITY_CLASS | HIGH_PRIORITY_CLASS | REALTIME_PRIORITY_CLASS |
1597 CREATE_NEW_PROCESS_GROUP | CREATE_SEPARATE_WOW_VDM | CREATE_SHARED_WOW_VDM |
1598 CREATE_DEFAULT_ERROR_MODE | CREATE_NO_WINDOW |
1599 PROFILE_USER | PROFILE_KERNEL | PROFILE_SERVER))
1600 WARN("(%s,...): ignoring some flags in %lx\n", debugstr_w(name), flags);
1602 if (cur_dir)
1604 unixdir = wine_get_unix_file_name( cur_dir );
1606 else
1608 WCHAR buf[MAX_PATH];
1609 if (GetCurrentDirectoryW(MAX_PATH, buf)) unixdir = wine_get_unix_file_name( buf );
1612 if (env && !(flags & CREATE_UNICODE_ENVIRONMENT)) /* convert environment to unicode */
1614 char *p = env;
1615 DWORD lenW;
1617 while (*p) p += strlen(p) + 1;
1618 p++; /* final null */
1619 lenW = MultiByteToWideChar( CP_ACP, 0, env, p - (char*)env, NULL, 0 );
1620 envW = HeapAlloc( GetProcessHeap(), 0, lenW * sizeof(WCHAR) );
1621 MultiByteToWideChar( CP_ACP, 0, env, p - (char*)env, envW, lenW );
1622 flags |= CREATE_UNICODE_ENVIRONMENT;
1625 info->hThread = info->hProcess = 0;
1626 info->dwProcessId = info->dwThreadId = 0;
1628 /* Determine executable type */
1630 if (!hFile) /* builtin exe */
1632 TRACE( "starting %s as Winelib app\n", debugstr_w(name) );
1633 retv = create_process( 0, name, tidy_cmdline, envW, process_attr, thread_attr,
1634 inherit, flags, startup_info, info, unixdir );
1635 goto done;
1638 switch( MODULE_GetBinaryType( hFile ))
1640 case BINARY_PE_EXE:
1641 TRACE( "starting %s as Win32 binary\n", debugstr_w(name) );
1642 retv = create_process( hFile, name, tidy_cmdline, envW, process_attr, thread_attr,
1643 inherit, flags, startup_info, info, unixdir );
1644 break;
1645 case BINARY_WIN16:
1646 case BINARY_DOS:
1647 TRACE( "starting %s as Win16/DOS binary\n", debugstr_w(name) );
1648 retv = create_vdm_process( name, tidy_cmdline, envW, process_attr, thread_attr,
1649 inherit, flags, startup_info, info, unixdir );
1650 break;
1651 case BINARY_OS216:
1652 FIXME( "%s is OS/2 binary, not supported\n", debugstr_w(name) );
1653 SetLastError( ERROR_BAD_EXE_FORMAT );
1654 break;
1655 case BINARY_PE_DLL:
1656 TRACE( "not starting %s since it is a dll\n", debugstr_w(name) );
1657 SetLastError( ERROR_BAD_EXE_FORMAT );
1658 break;
1659 case BINARY_UNIX_LIB:
1660 TRACE( "%s is a Unix library, starting as Winelib app\n", debugstr_w(name) );
1661 retv = create_process( hFile, name, tidy_cmdline, envW, process_attr, thread_attr,
1662 inherit, flags, startup_info, info, unixdir );
1663 break;
1664 case BINARY_UNKNOWN:
1665 /* check for .com or .bat extension */
1666 if ((p = strrchrW( name, '.' )))
1668 if (!strcmpiW( p, comW ))
1670 TRACE( "starting %s as DOS binary\n", debugstr_w(name) );
1671 retv = create_vdm_process( name, tidy_cmdline, envW, process_attr, thread_attr,
1672 inherit, flags, startup_info, info, unixdir );
1673 break;
1675 if (!strcmpiW( p, batW ))
1677 TRACE( "starting %s as batch binary\n", debugstr_w(name) );
1678 retv = create_cmd_process( name, tidy_cmdline, envW, process_attr, thread_attr,
1679 inherit, flags, startup_info, info, cur_dir );
1680 break;
1683 /* fall through */
1684 case BINARY_UNIX_EXE:
1686 /* unknown file, try as unix executable */
1687 char *unix_name;
1689 TRACE( "starting %s as Unix binary\n", debugstr_w(name) );
1691 if ((unix_name = wine_get_unix_file_name( name )))
1693 retv = (fork_and_exec( unix_name, tidy_cmdline, envW, unixdir ) != -1);
1694 HeapFree( GetProcessHeap(), 0, unix_name );
1697 break;
1699 CloseHandle( hFile );
1701 done:
1702 if (tidy_cmdline != cmd_line) HeapFree( GetProcessHeap(), 0, tidy_cmdline );
1703 if (envW != env) HeapFree( GetProcessHeap(), 0, envW );
1704 if (unixdir) HeapFree( GetProcessHeap(), 0, unixdir );
1705 return retv;
1709 /***********************************************************************
1710 * wait_input_idle
1712 * Wrapper to call WaitForInputIdle USER function
1714 typedef DWORD (WINAPI *WaitForInputIdle_ptr)( HANDLE hProcess, DWORD dwTimeOut );
1716 static DWORD wait_input_idle( HANDLE process, DWORD timeout )
1718 HMODULE mod = GetModuleHandleA( "user32.dll" );
1719 if (mod)
1721 WaitForInputIdle_ptr ptr = (WaitForInputIdle_ptr)GetProcAddress( mod, "WaitForInputIdle" );
1722 if (ptr) return ptr( process, timeout );
1724 return 0;
1728 /***********************************************************************
1729 * WinExec (KERNEL32.@)
1731 UINT WINAPI WinExec( LPCSTR lpCmdLine, UINT nCmdShow )
1733 PROCESS_INFORMATION info;
1734 STARTUPINFOA startup;
1735 char *cmdline;
1736 UINT ret;
1738 memset( &startup, 0, sizeof(startup) );
1739 startup.cb = sizeof(startup);
1740 startup.dwFlags = STARTF_USESHOWWINDOW;
1741 startup.wShowWindow = nCmdShow;
1743 /* cmdline needs to be writeable for CreateProcess */
1744 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(lpCmdLine)+1 ))) return 0;
1745 strcpy( cmdline, lpCmdLine );
1747 if (CreateProcessA( NULL, cmdline, NULL, NULL, FALSE,
1748 0, NULL, NULL, &startup, &info ))
1750 /* Give 30 seconds to the app to come up */
1751 if (wait_input_idle( info.hProcess, 30000 ) == WAIT_FAILED)
1752 WARN("WaitForInputIdle failed: Error %ld\n", GetLastError() );
1753 ret = 33;
1754 /* Close off the handles */
1755 CloseHandle( info.hThread );
1756 CloseHandle( info.hProcess );
1758 else if ((ret = GetLastError()) >= 32)
1760 FIXME("Strange error set by CreateProcess: %d\n", ret );
1761 ret = 11;
1763 HeapFree( GetProcessHeap(), 0, cmdline );
1764 return ret;
1768 /**********************************************************************
1769 * LoadModule (KERNEL32.@)
1771 HINSTANCE WINAPI LoadModule( LPCSTR name, LPVOID paramBlock )
1773 LOADPARMS32 *params = paramBlock;
1774 PROCESS_INFORMATION info;
1775 STARTUPINFOA startup;
1776 HINSTANCE hInstance;
1777 LPSTR cmdline, p;
1778 char filename[MAX_PATH];
1779 BYTE len;
1781 if (!name) return (HINSTANCE)ERROR_FILE_NOT_FOUND;
1783 if (!SearchPathA( NULL, name, ".exe", sizeof(filename), filename, NULL ) &&
1784 !SearchPathA( NULL, name, NULL, sizeof(filename), filename, NULL ))
1785 return (HINSTANCE)GetLastError();
1787 len = (BYTE)params->lpCmdLine[0];
1788 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(filename) + len + 2 )))
1789 return (HINSTANCE)ERROR_NOT_ENOUGH_MEMORY;
1791 strcpy( cmdline, filename );
1792 p = cmdline + strlen(cmdline);
1793 *p++ = ' ';
1794 memcpy( p, params->lpCmdLine + 1, len );
1795 p[len] = 0;
1797 memset( &startup, 0, sizeof(startup) );
1798 startup.cb = sizeof(startup);
1799 if (params->lpCmdShow)
1801 startup.dwFlags = STARTF_USESHOWWINDOW;
1802 startup.wShowWindow = ((WORD *)params->lpCmdShow)[1];
1805 if (CreateProcessA( filename, cmdline, NULL, NULL, FALSE, 0,
1806 params->lpEnvAddress, NULL, &startup, &info ))
1808 /* Give 30 seconds to the app to come up */
1809 if (wait_input_idle( info.hProcess, 30000 ) == WAIT_FAILED)
1810 WARN("WaitForInputIdle failed: Error %ld\n", GetLastError() );
1811 hInstance = (HINSTANCE)33;
1812 /* Close off the handles */
1813 CloseHandle( info.hThread );
1814 CloseHandle( info.hProcess );
1816 else if ((hInstance = (HINSTANCE)GetLastError()) >= (HINSTANCE)32)
1818 FIXME("Strange error set by CreateProcess: %p\n", hInstance );
1819 hInstance = (HINSTANCE)11;
1822 HeapFree( GetProcessHeap(), 0, cmdline );
1823 return hInstance;
1827 /******************************************************************************
1828 * TerminateProcess (KERNEL32.@)
1830 BOOL WINAPI TerminateProcess( HANDLE handle, DWORD exit_code )
1832 NTSTATUS status = NtTerminateProcess( handle, exit_code );
1833 if (status) SetLastError( RtlNtStatusToDosError(status) );
1834 return !status;
1838 /***********************************************************************
1839 * ExitProcess (KERNEL32.@)
1841 void WINAPI ExitProcess( DWORD status )
1843 LdrShutdownProcess();
1844 SERVER_START_REQ( terminate_process )
1846 /* send the exit code to the server */
1847 req->handle = GetCurrentProcess();
1848 req->exit_code = status;
1849 wine_server_call( req );
1851 SERVER_END_REQ;
1852 exit( status );
1856 /***********************************************************************
1857 * GetExitCodeProcess [KERNEL32.@]
1859 * Gets termination status of specified process
1861 * RETURNS
1862 * Success: TRUE
1863 * Failure: FALSE
1865 BOOL WINAPI GetExitCodeProcess(
1866 HANDLE hProcess, /* [in] handle to the process */
1867 LPDWORD lpExitCode) /* [out] address to receive termination status */
1869 BOOL ret;
1870 SERVER_START_REQ( get_process_info )
1872 req->handle = hProcess;
1873 ret = !wine_server_call_err( req );
1874 if (ret && lpExitCode) *lpExitCode = reply->exit_code;
1876 SERVER_END_REQ;
1877 return ret;
1881 /***********************************************************************
1882 * SetErrorMode (KERNEL32.@)
1884 UINT WINAPI SetErrorMode( UINT mode )
1886 UINT old = process_error_mode;
1887 process_error_mode = mode;
1888 return old;
1892 /**********************************************************************
1893 * TlsAlloc [KERNEL32.@] Allocates a TLS index.
1895 * Allocates a thread local storage index
1897 * RETURNS
1898 * Success: TLS Index
1899 * Failure: 0xFFFFFFFF
1901 DWORD WINAPI TlsAlloc( void )
1903 DWORD index;
1905 RtlAcquirePebLock();
1906 index = RtlFindClearBitsAndSet( NtCurrentTeb()->Peb->TlsBitmap, 1, 0 );
1907 if (index != ~0UL) NtCurrentTeb()->TlsSlots[index] = 0; /* clear the value */
1908 else SetLastError( ERROR_NO_MORE_ITEMS );
1909 RtlReleasePebLock();
1910 return index;
1914 /**********************************************************************
1915 * TlsFree [KERNEL32.@] Releases a TLS index.
1917 * Releases a thread local storage index, making it available for reuse
1919 * RETURNS
1920 * Success: TRUE
1921 * Failure: FALSE
1923 BOOL WINAPI TlsFree(
1924 DWORD index) /* [in] TLS Index to free */
1926 BOOL ret;
1928 RtlAcquirePebLock();
1929 ret = RtlAreBitsSet( NtCurrentTeb()->Peb->TlsBitmap, index, 1 );
1930 if (ret)
1932 RtlClearBits( NtCurrentTeb()->Peb->TlsBitmap, index, 1 );
1933 NtSetInformationThread( GetCurrentThread(), ThreadZeroTlsCell, &index, sizeof(index) );
1935 else SetLastError( ERROR_INVALID_PARAMETER );
1936 RtlReleasePebLock();
1937 return TRUE;
1941 /**********************************************************************
1942 * TlsGetValue [KERNEL32.@] Gets value in a thread's TLS slot
1944 * RETURNS
1945 * Success: Value stored in calling thread's TLS slot for index
1946 * Failure: 0 and GetLastError returns NO_ERROR
1948 LPVOID WINAPI TlsGetValue(
1949 DWORD index) /* [in] TLS index to retrieve value for */
1951 if (index >= NtCurrentTeb()->Peb->TlsBitmap->SizeOfBitMap)
1953 SetLastError( ERROR_INVALID_PARAMETER );
1954 return NULL;
1956 SetLastError( ERROR_SUCCESS );
1957 return NtCurrentTeb()->TlsSlots[index];
1961 /**********************************************************************
1962 * TlsSetValue [KERNEL32.@] Stores a value in the thread's TLS slot.
1964 * RETURNS
1965 * Success: TRUE
1966 * Failure: FALSE
1968 BOOL WINAPI TlsSetValue(
1969 DWORD index, /* [in] TLS index to set value for */
1970 LPVOID value) /* [in] Value to be stored */
1972 if (index >= NtCurrentTeb()->Peb->TlsBitmap->SizeOfBitMap)
1974 SetLastError( ERROR_INVALID_PARAMETER );
1975 return FALSE;
1977 NtCurrentTeb()->TlsSlots[index] = value;
1978 return TRUE;
1982 /***********************************************************************
1983 * GetProcessFlags (KERNEL32.@)
1985 DWORD WINAPI GetProcessFlags( DWORD processid )
1987 IMAGE_NT_HEADERS *nt;
1988 DWORD flags = 0;
1990 if (processid && processid != GetCurrentProcessId()) return 0;
1992 if ((nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress )))
1994 if (nt->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_CUI)
1995 flags |= PDB32_CONSOLE_PROC;
1997 if (!AreFileApisANSI()) flags |= PDB32_FILE_APIS_OEM;
1998 if (IsDebuggerPresent()) flags |= PDB32_DEBUGGED;
1999 return flags;
2003 /***********************************************************************
2004 * GetProcessDword (KERNEL.485)
2005 * GetProcessDword (KERNEL32.18)
2006 * 'Of course you cannot directly access Windows internal structures'
2008 DWORD WINAPI GetProcessDword( DWORD dwProcessID, INT offset )
2010 DWORD x, y;
2011 STARTUPINFOW siw;
2013 TRACE("(%ld, %d)\n", dwProcessID, offset );
2015 if (dwProcessID && dwProcessID != GetCurrentProcessId())
2017 ERR("%d: process %lx not accessible\n", offset, dwProcessID);
2018 return 0;
2021 switch ( offset )
2023 case GPD_APP_COMPAT_FLAGS:
2024 return GetAppCompatFlags16(0);
2025 case GPD_LOAD_DONE_EVENT:
2026 return 0;
2027 case GPD_HINSTANCE16:
2028 return GetTaskDS16();
2029 case GPD_WINDOWS_VERSION:
2030 return GetExeVersion16();
2031 case GPD_THDB:
2032 return (DWORD)NtCurrentTeb() - 0x10 /* FIXME */;
2033 case GPD_PDB:
2034 return (DWORD)NtCurrentTeb()->Peb;
2035 case GPD_STARTF_SHELLDATA: /* return stdoutput handle from startupinfo ??? */
2036 GetStartupInfoW(&siw);
2037 return (DWORD)siw.hStdOutput;
2038 case GPD_STARTF_HOTKEY: /* return stdinput handle from startupinfo ??? */
2039 GetStartupInfoW(&siw);
2040 return (DWORD)siw.hStdInput;
2041 case GPD_STARTF_SHOWWINDOW:
2042 GetStartupInfoW(&siw);
2043 return siw.wShowWindow;
2044 case GPD_STARTF_SIZE:
2045 GetStartupInfoW(&siw);
2046 x = siw.dwXSize;
2047 if ( (INT)x == CW_USEDEFAULT ) x = CW_USEDEFAULT16;
2048 y = siw.dwYSize;
2049 if ( (INT)y == CW_USEDEFAULT ) y = CW_USEDEFAULT16;
2050 return MAKELONG( x, y );
2051 case GPD_STARTF_POSITION:
2052 GetStartupInfoW(&siw);
2053 x = siw.dwX;
2054 if ( (INT)x == CW_USEDEFAULT ) x = CW_USEDEFAULT16;
2055 y = siw.dwY;
2056 if ( (INT)y == CW_USEDEFAULT ) y = CW_USEDEFAULT16;
2057 return MAKELONG( x, y );
2058 case GPD_STARTF_FLAGS:
2059 GetStartupInfoW(&siw);
2060 return siw.dwFlags;
2061 case GPD_PARENT:
2062 return 0;
2063 case GPD_FLAGS:
2064 return GetProcessFlags(0);
2065 case GPD_USERDATA:
2066 return process_dword;
2067 default:
2068 ERR("Unknown offset %d\n", offset );
2069 return 0;
2073 /***********************************************************************
2074 * SetProcessDword (KERNEL.484)
2075 * 'Of course you cannot directly access Windows internal structures'
2077 void WINAPI SetProcessDword( DWORD dwProcessID, INT offset, DWORD value )
2079 TRACE("(%ld, %d)\n", dwProcessID, offset );
2081 if (dwProcessID && dwProcessID != GetCurrentProcessId())
2083 ERR("%d: process %lx not accessible\n", offset, dwProcessID);
2084 return;
2087 switch ( offset )
2089 case GPD_APP_COMPAT_FLAGS:
2090 case GPD_LOAD_DONE_EVENT:
2091 case GPD_HINSTANCE16:
2092 case GPD_WINDOWS_VERSION:
2093 case GPD_THDB:
2094 case GPD_PDB:
2095 case GPD_STARTF_SHELLDATA:
2096 case GPD_STARTF_HOTKEY:
2097 case GPD_STARTF_SHOWWINDOW:
2098 case GPD_STARTF_SIZE:
2099 case GPD_STARTF_POSITION:
2100 case GPD_STARTF_FLAGS:
2101 case GPD_PARENT:
2102 case GPD_FLAGS:
2103 ERR("Not allowed to modify offset %d\n", offset );
2104 break;
2105 case GPD_USERDATA:
2106 process_dword = value;
2107 break;
2108 default:
2109 ERR("Unknown offset %d\n", offset );
2110 break;
2115 /***********************************************************************
2116 * ExitProcess (KERNEL.466)
2118 void WINAPI ExitProcess16( WORD status )
2120 DWORD count;
2121 ReleaseThunkLock( &count );
2122 ExitProcess( status );
2126 /*********************************************************************
2127 * OpenProcess (KERNEL32.@)
2129 HANDLE WINAPI OpenProcess( DWORD access, BOOL inherit, DWORD id )
2131 HANDLE ret = 0;
2132 SERVER_START_REQ( open_process )
2134 req->pid = id;
2135 req->access = access;
2136 req->inherit = inherit;
2137 if (!wine_server_call_err( req )) ret = reply->handle;
2139 SERVER_END_REQ;
2140 return ret;
2144 /*********************************************************************
2145 * MapProcessHandle (KERNEL.483)
2147 DWORD WINAPI MapProcessHandle( HANDLE handle )
2149 DWORD ret = 0;
2150 SERVER_START_REQ( get_process_info )
2152 req->handle = handle;
2153 if (!wine_server_call_err( req )) ret = reply->pid;
2155 SERVER_END_REQ;
2156 return ret;
2160 /*********************************************************************
2161 * CloseW32Handle (KERNEL.474)
2162 * CloseHandle (KERNEL32.@)
2164 BOOL WINAPI CloseHandle( HANDLE handle )
2166 NTSTATUS status;
2168 /* stdio handles need special treatment */
2169 if ((handle == (HANDLE)STD_INPUT_HANDLE) ||
2170 (handle == (HANDLE)STD_OUTPUT_HANDLE) ||
2171 (handle == (HANDLE)STD_ERROR_HANDLE))
2172 handle = GetStdHandle( (DWORD)handle );
2174 if (is_console_handle(handle))
2175 return CloseConsoleHandle(handle);
2177 status = NtClose( handle );
2178 if (status) SetLastError( RtlNtStatusToDosError(status) );
2179 return !status;
2183 /*********************************************************************
2184 * GetHandleInformation (KERNEL32.@)
2186 BOOL WINAPI GetHandleInformation( HANDLE handle, LPDWORD flags )
2188 BOOL ret;
2189 SERVER_START_REQ( set_handle_info )
2191 req->handle = handle;
2192 req->flags = 0;
2193 req->mask = 0;
2194 req->fd = -1;
2195 ret = !wine_server_call_err( req );
2196 if (ret && flags) *flags = reply->old_flags;
2198 SERVER_END_REQ;
2199 return ret;
2203 /*********************************************************************
2204 * SetHandleInformation (KERNEL32.@)
2206 BOOL WINAPI SetHandleInformation( HANDLE handle, DWORD mask, DWORD flags )
2208 BOOL ret;
2209 SERVER_START_REQ( set_handle_info )
2211 req->handle = handle;
2212 req->flags = flags;
2213 req->mask = mask;
2214 req->fd = -1;
2215 ret = !wine_server_call_err( req );
2217 SERVER_END_REQ;
2218 return ret;
2222 /*********************************************************************
2223 * DuplicateHandle (KERNEL32.@)
2225 BOOL WINAPI DuplicateHandle( HANDLE source_process, HANDLE source,
2226 HANDLE dest_process, HANDLE *dest,
2227 DWORD access, BOOL inherit, DWORD options )
2229 NTSTATUS status;
2231 if (is_console_handle(source))
2233 /* FIXME: this test is not sufficient, we need to test process ids, not handles */
2234 if (source_process != dest_process ||
2235 source_process != GetCurrentProcess())
2237 SetLastError(ERROR_INVALID_PARAMETER);
2238 return FALSE;
2240 *dest = DuplicateConsoleHandle( source, access, inherit, options );
2241 return (*dest != INVALID_HANDLE_VALUE);
2243 status = NtDuplicateObject( source_process, source, dest_process, dest,
2244 access, inherit ? OBJ_INHERIT : 0, options );
2245 if (status) SetLastError( RtlNtStatusToDosError(status) );
2246 return !status;
2250 /***********************************************************************
2251 * ConvertToGlobalHandle (KERNEL.476)
2252 * ConvertToGlobalHandle (KERNEL32.@)
2254 HANDLE WINAPI ConvertToGlobalHandle(HANDLE hSrc)
2256 HANDLE ret = INVALID_HANDLE_VALUE;
2257 DuplicateHandle( GetCurrentProcess(), hSrc, GetCurrentProcess(), &ret, 0, FALSE,
2258 DUP_HANDLE_MAKE_GLOBAL | DUP_HANDLE_SAME_ACCESS | DUP_HANDLE_CLOSE_SOURCE );
2259 return ret;
2263 /***********************************************************************
2264 * SetHandleContext (KERNEL32.@)
2266 BOOL WINAPI SetHandleContext(HANDLE hnd,DWORD context)
2268 FIXME("(%p,%ld), stub. In case this got called by WSOCK32/WS2_32: "
2269 "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd,context);
2270 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2271 return FALSE;
2275 /***********************************************************************
2276 * GetHandleContext (KERNEL32.@)
2278 DWORD WINAPI GetHandleContext(HANDLE hnd)
2280 FIXME("(%p), stub. In case this got called by WSOCK32/WS2_32: "
2281 "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd);
2282 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2283 return 0;
2287 /***********************************************************************
2288 * CreateSocketHandle (KERNEL32.@)
2290 HANDLE WINAPI CreateSocketHandle(void)
2292 FIXME("(), stub. In case this got called by WSOCK32/WS2_32: "
2293 "the external WINSOCK DLLs won't work with WINE, don't use them.\n");
2294 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2295 return INVALID_HANDLE_VALUE;
2299 /***********************************************************************
2300 * SetPriorityClass (KERNEL32.@)
2302 BOOL WINAPI SetPriorityClass( HANDLE hprocess, DWORD priorityclass )
2304 BOOL ret;
2305 SERVER_START_REQ( set_process_info )
2307 req->handle = hprocess;
2308 req->priority = priorityclass;
2309 req->mask = SET_PROCESS_INFO_PRIORITY;
2310 ret = !wine_server_call_err( req );
2312 SERVER_END_REQ;
2313 return ret;
2317 /***********************************************************************
2318 * GetPriorityClass (KERNEL32.@)
2320 DWORD WINAPI GetPriorityClass(HANDLE hprocess)
2322 DWORD ret = 0;
2323 SERVER_START_REQ( get_process_info )
2325 req->handle = hprocess;
2326 if (!wine_server_call_err( req )) ret = reply->priority;
2328 SERVER_END_REQ;
2329 return ret;
2333 /***********************************************************************
2334 * SetProcessAffinityMask (KERNEL32.@)
2336 BOOL WINAPI SetProcessAffinityMask( HANDLE hProcess, DWORD affmask )
2338 BOOL ret;
2339 SERVER_START_REQ( set_process_info )
2341 req->handle = hProcess;
2342 req->affinity = affmask;
2343 req->mask = SET_PROCESS_INFO_AFFINITY;
2344 ret = !wine_server_call_err( req );
2346 SERVER_END_REQ;
2347 return ret;
2351 /**********************************************************************
2352 * GetProcessAffinityMask (KERNEL32.@)
2354 BOOL WINAPI GetProcessAffinityMask( HANDLE hProcess,
2355 LPDWORD lpProcessAffinityMask,
2356 LPDWORD lpSystemAffinityMask )
2358 BOOL ret = FALSE;
2359 SERVER_START_REQ( get_process_info )
2361 req->handle = hProcess;
2362 if (!wine_server_call_err( req ))
2364 if (lpProcessAffinityMask) *lpProcessAffinityMask = reply->process_affinity;
2365 if (lpSystemAffinityMask) *lpSystemAffinityMask = reply->system_affinity;
2366 ret = TRUE;
2369 SERVER_END_REQ;
2370 return ret;
2374 /***********************************************************************
2375 * GetProcessVersion (KERNEL32.@)
2377 DWORD WINAPI GetProcessVersion( DWORD processid )
2379 IMAGE_NT_HEADERS *nt;
2381 if (processid && processid != GetCurrentProcessId())
2383 FIXME("should use ReadProcessMemory\n");
2384 return 0;
2386 if ((nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress )))
2387 return ((nt->OptionalHeader.MajorSubsystemVersion << 16) |
2388 nt->OptionalHeader.MinorSubsystemVersion);
2389 return 0;
2393 /***********************************************************************
2394 * SetProcessWorkingSetSize [KERNEL32.@]
2395 * Sets the min/max working set sizes for a specified process.
2397 * PARAMS
2398 * hProcess [I] Handle to the process of interest
2399 * minset [I] Specifies minimum working set size
2400 * maxset [I] Specifies maximum working set size
2402 * RETURNS STD
2404 BOOL WINAPI SetProcessWorkingSetSize(HANDLE hProcess, SIZE_T minset,
2405 SIZE_T maxset)
2407 FIXME("(%p,%ld,%ld): stub - harmless\n",hProcess,minset,maxset);
2408 if(( minset == (SIZE_T)-1) && (maxset == (SIZE_T)-1)) {
2409 /* Trim the working set to zero */
2410 /* Swap the process out of physical RAM */
2412 return TRUE;
2415 /***********************************************************************
2416 * GetProcessWorkingSetSize (KERNEL32.@)
2418 BOOL WINAPI GetProcessWorkingSetSize(HANDLE hProcess, PSIZE_T minset,
2419 PSIZE_T maxset)
2421 FIXME("(%p,%p,%p): stub\n",hProcess,minset,maxset);
2422 /* 32 MB working set size */
2423 if (minset) *minset = 32*1024*1024;
2424 if (maxset) *maxset = 32*1024*1024;
2425 return TRUE;
2429 /***********************************************************************
2430 * SetProcessShutdownParameters (KERNEL32.@)
2432 BOOL WINAPI SetProcessShutdownParameters(DWORD level, DWORD flags)
2434 FIXME("(%08lx, %08lx): partial stub.\n", level, flags);
2435 shutdown_flags = flags;
2436 shutdown_priority = level;
2437 return TRUE;
2441 /***********************************************************************
2442 * GetProcessShutdownParameters (KERNEL32.@)
2445 BOOL WINAPI GetProcessShutdownParameters( LPDWORD lpdwLevel, LPDWORD lpdwFlags )
2447 *lpdwLevel = shutdown_priority;
2448 *lpdwFlags = shutdown_flags;
2449 return TRUE;
2453 /***********************************************************************
2454 * GetProcessPriorityBoost (KERNEL32.@)
2456 BOOL WINAPI GetProcessPriorityBoost(HANDLE hprocess,PBOOL pDisablePriorityBoost)
2458 FIXME("(%p,%p): semi-stub\n", hprocess, pDisablePriorityBoost);
2460 /* Report that no boost is present.. */
2461 *pDisablePriorityBoost = FALSE;
2463 return TRUE;
2466 /***********************************************************************
2467 * SetProcessPriorityBoost (KERNEL32.@)
2469 BOOL WINAPI SetProcessPriorityBoost(HANDLE hprocess,BOOL disableboost)
2471 FIXME("(%p,%d): stub\n",hprocess,disableboost);
2472 /* Say we can do it. I doubt the program will notice that we don't. */
2473 return TRUE;
2477 /***********************************************************************
2478 * ReadProcessMemory (KERNEL32.@)
2480 BOOL WINAPI ReadProcessMemory( HANDLE process, LPCVOID addr, LPVOID buffer, SIZE_T size,
2481 SIZE_T *bytes_read )
2483 NTSTATUS status = NtReadVirtualMemory( process, addr, buffer, size, bytes_read );
2484 if (status) SetLastError( RtlNtStatusToDosError(status) );
2485 return !status;
2489 /***********************************************************************
2490 * WriteProcessMemory (KERNEL32.@)
2492 BOOL WINAPI WriteProcessMemory( HANDLE process, LPVOID addr, LPCVOID buffer, SIZE_T size,
2493 SIZE_T *bytes_written )
2495 NTSTATUS status = NtWriteVirtualMemory( process, addr, buffer, size, bytes_written );
2496 if (status) SetLastError( RtlNtStatusToDosError(status) );
2497 return !status;
2501 /****************************************************************************
2502 * FlushInstructionCache (KERNEL32.@)
2504 BOOL WINAPI FlushInstructionCache(HANDLE hProcess, LPCVOID lpBaseAddress, SIZE_T dwSize)
2506 if (GetVersion() & 0x80000000) return TRUE; /* not NT, always TRUE */
2507 FIXME("(%p,%p,0x%08lx): stub\n",hProcess, lpBaseAddress, dwSize);
2508 return TRUE;
2512 /******************************************************************
2513 * GetProcessIoCounters (KERNEL32.@)
2515 BOOL WINAPI GetProcessIoCounters(HANDLE hProcess, PIO_COUNTERS ioc)
2517 NTSTATUS status;
2519 status = NtQueryInformationProcess(hProcess, ProcessIoCounters,
2520 ioc, sizeof(*ioc), NULL);
2521 if (status) SetLastError( RtlNtStatusToDosError(status) );
2522 return !status;
2525 /***********************************************************************
2526 * ProcessIdToSessionId (KERNEL32.@)
2527 * This function is available on Terminal Server 4SP4 and Windows 2000
2529 BOOL WINAPI ProcessIdToSessionId( DWORD procid, DWORD *sessionid_ptr )
2531 /* According to MSDN, if the calling process is not in a terminal
2532 * services environment, then the sessionid returned is zero.
2534 *sessionid_ptr = 0;
2535 return TRUE;
2539 /***********************************************************************
2540 * RegisterServiceProcess (KERNEL.491)
2541 * RegisterServiceProcess (KERNEL32.@)
2543 * A service process calls this function to ensure that it continues to run
2544 * even after a user logged off.
2546 DWORD WINAPI RegisterServiceProcess(DWORD dwProcessId, DWORD dwType)
2548 /* I don't think that Wine needs to do anything in that function */
2549 return 1; /* success */
2553 /**************************************************************************
2554 * SetFileApisToOEM (KERNEL32.@)
2556 VOID WINAPI SetFileApisToOEM(void)
2558 oem_file_apis = TRUE;
2562 /**************************************************************************
2563 * SetFileApisToANSI (KERNEL32.@)
2565 VOID WINAPI SetFileApisToANSI(void)
2567 oem_file_apis = FALSE;
2571 /******************************************************************************
2572 * AreFileApisANSI [KERNEL32.@] Determines if file functions are using ANSI
2574 * RETURNS
2575 * TRUE: Set of file functions is using ANSI code page
2576 * FALSE: Set of file functions is using OEM code page
2578 BOOL WINAPI AreFileApisANSI(void)
2580 return !oem_file_apis;
2584 /***********************************************************************
2585 * GetSystemMSecCount (SYSTEM.6)
2586 * GetTickCount (KERNEL32.@)
2588 * Returns the number of milliseconds, modulo 2^32, since the start
2589 * of the wineserver.
2591 DWORD WINAPI GetTickCount(void)
2593 struct timeval t;
2594 gettimeofday( &t, NULL );
2595 return ((t.tv_sec * 1000) + (t.tv_usec / 1000)) - server_startticks;
2599 /***********************************************************************
2600 * GetCurrentProcess (KERNEL32.@)
2602 #undef GetCurrentProcess
2603 HANDLE WINAPI GetCurrentProcess(void)
2605 return (HANDLE)0xffffffff;