Removed some unnecessary inclusions of thread.h
[wine/wine-kai.git] / dlls / kernel / process.c
blob59da5743fb44fc055462f009fb3704b92a35e572
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 "winioctl.h"
40 #include "winreg.h"
41 #include "winternl.h"
42 #include "module.h"
43 #include "kernel_private.h"
44 #include "wine/exception.h"
45 #include "wine/server.h"
46 #include "wine/unicode.h"
47 #include "wine/debug.h"
49 WINE_DEFAULT_DEBUG_CHANNEL(process);
50 WINE_DECLARE_DEBUG_CHANNEL(file);
51 WINE_DECLARE_DEBUG_CHANNEL(server);
52 WINE_DECLARE_DEBUG_CHANNEL(relay);
54 typedef struct
56 LPSTR lpEnvAddress;
57 LPSTR lpCmdLine;
58 LPSTR lpCmdShow;
59 DWORD dwReserved;
60 } LOADPARMS32;
62 static UINT process_error_mode;
64 static HANDLE main_exe_file;
65 static DWORD shutdown_flags = 0;
66 static DWORD shutdown_priority = 0x280;
67 static DWORD process_dword;
69 static unsigned int server_startticks;
70 int main_create_flags = 0;
71 HMODULE kernel32_handle = 0;
73 const WCHAR *DIR_Windows = NULL;
74 const WCHAR *DIR_System = NULL;
76 /* Process flags */
77 #define PDB32_DEBUGGED 0x0001 /* Process is being debugged */
78 #define PDB32_WIN16_PROC 0x0008 /* Win16 process */
79 #define PDB32_DOS_PROC 0x0010 /* Dos process */
80 #define PDB32_CONSOLE_PROC 0x0020 /* Console process */
81 #define PDB32_FILE_APIS_OEM 0x0040 /* File APIs are OEM */
82 #define PDB32_WIN32S_PROC 0x8000 /* Win32s process */
84 static const WCHAR comW[] = {'.','c','o','m',0};
85 static const WCHAR batW[] = {'.','b','a','t',0};
86 static const WCHAR pifW[] = {'.','p','i','f',0};
87 static const WCHAR winevdmW[] = {'w','i','n','e','v','d','m','.','e','x','e',0};
89 extern void SHELL_LoadRegistry(void);
90 extern void convert_old_config(void);
91 extern void VERSION_Init( const WCHAR *appname );
92 extern void LOCALE_Init(void);
94 /***********************************************************************
95 * contains_path
97 inline static int contains_path( LPCWSTR name )
99 return ((*name && (name[1] == ':')) || strchrW(name, '/') || strchrW(name, '\\'));
103 /***********************************************************************
104 * is_special_env_var
106 * Check if an environment variable needs to be handled specially when
107 * passed through the Unix environment (i.e. prefixed with "WINE").
109 inline static int is_special_env_var( const char *var )
111 return (!strncmp( var, "PATH=", sizeof("PATH=")-1 ) ||
112 !strncmp( var, "HOME=", sizeof("HOME=")-1 ) ||
113 !strncmp( var, "TEMP=", sizeof("TEMP=")-1 ) ||
114 !strncmp( var, "TMP=", sizeof("TMP=")-1 ));
118 /***************************************************************************
119 * get_builtin_path
121 * Get the path of a builtin module when the native file does not exist.
123 static BOOL get_builtin_path( const WCHAR *libname, const WCHAR *ext, WCHAR *filename, UINT size )
125 WCHAR *file_part;
126 UINT len = strlenW( DIR_System );
128 if (contains_path( libname ))
130 if (RtlGetFullPathName_U( libname, size * sizeof(WCHAR),
131 filename, &file_part ) > size * sizeof(WCHAR))
132 return FALSE; /* too long */
134 if (strncmpiW( filename, DIR_System, len ) || filename[len] != '\\')
135 return FALSE;
136 while (filename[len] == '\\') len++;
137 if (filename + len != file_part) return FALSE;
139 else
141 if (strlenW(libname) + len + 2 >= size) return FALSE; /* too long */
142 memcpy( filename, DIR_System, len * sizeof(WCHAR) );
143 file_part = filename + len;
144 if (file_part > filename && file_part[-1] != '\\') *file_part++ = '\\';
145 strcpyW( file_part, libname );
147 if (ext && !strchrW( file_part, '.' ))
149 if (file_part + strlenW(file_part) + strlenW(ext) + 1 > filename + size)
150 return FALSE; /* too long */
151 strcatW( file_part, ext );
153 return TRUE;
157 /***********************************************************************
158 * open_builtin_exe_file
160 * Open an exe file for a builtin exe.
162 static void *open_builtin_exe_file( const WCHAR *name, char *error, int error_size,
163 int test_only, int *file_exists )
165 char exename[MAX_PATH];
166 WCHAR *p;
167 UINT i, len;
169 if ((p = strrchrW( name, '/' ))) name = p + 1;
170 if ((p = strrchrW( name, '\\' ))) name = p + 1;
172 /* we don't want to depend on the current codepage here */
173 len = strlenW( name ) + 1;
174 if (len >= sizeof(exename)) return NULL;
175 for (i = 0; i < len; i++)
177 if (name[i] > 127) return NULL;
178 exename[i] = (char)name[i];
179 if (exename[i] >= 'A' && exename[i] <= 'Z') exename[i] += 'a' - 'A';
181 return wine_dll_load_main_exe( exename, error, error_size, test_only, file_exists );
185 /***********************************************************************
186 * open_exe_file
188 * Open a specific exe file, taking load order into account.
189 * Returns the file handle or 0 for a builtin exe.
191 static HANDLE open_exe_file( const WCHAR *name )
193 enum loadorder_type loadorder[LOADORDER_NTYPES];
194 WCHAR buffer[MAX_PATH];
195 HANDLE handle;
196 int i, file_exists;
198 TRACE("looking for %s\n", debugstr_w(name) );
200 if ((handle = CreateFileW( name, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_DELETE,
201 NULL, OPEN_EXISTING, 0, 0 )) == INVALID_HANDLE_VALUE)
203 /* file doesn't exist, check for builtin */
204 if (!contains_path( name )) goto error;
205 if (!get_builtin_path( name, NULL, buffer, sizeof(buffer) )) goto error;
206 name = buffer;
209 MODULE_GetLoadOrderW( loadorder, NULL, name );
211 for(i = 0; i < LOADORDER_NTYPES; i++)
213 if (loadorder[i] == LOADORDER_INVALID) break;
214 switch(loadorder[i])
216 case LOADORDER_DLL:
217 TRACE( "Trying native exe %s\n", debugstr_w(name) );
218 if (handle != INVALID_HANDLE_VALUE) return handle;
219 break;
220 case LOADORDER_BI:
221 TRACE( "Trying built-in exe %s\n", debugstr_w(name) );
222 open_builtin_exe_file( name, NULL, 0, 1, &file_exists );
223 if (file_exists)
225 if (handle != INVALID_HANDLE_VALUE) CloseHandle(handle);
226 return 0;
228 default:
229 break;
232 if (handle != INVALID_HANDLE_VALUE) CloseHandle(handle);
234 error:
235 SetLastError( ERROR_FILE_NOT_FOUND );
236 return INVALID_HANDLE_VALUE;
240 /***********************************************************************
241 * find_exe_file
243 * Open an exe file, and return the full name and file handle.
244 * Returns FALSE if file could not be found.
245 * If file exists but cannot be opened, returns TRUE and set handle to INVALID_HANDLE_VALUE.
246 * If file is a builtin exe, returns TRUE and sets handle to 0.
248 static BOOL find_exe_file( const WCHAR *name, WCHAR *buffer, int buflen, HANDLE *handle )
250 static const WCHAR exeW[] = {'.','e','x','e',0};
252 enum loadorder_type loadorder[LOADORDER_NTYPES];
253 int i, file_exists;
255 TRACE("looking for %s\n", debugstr_w(name) );
257 if (!SearchPathW( NULL, name, exeW, buflen, buffer, NULL ) &&
258 !get_builtin_path( name, exeW, buffer, buflen ))
260 /* no builtin found, try native without extension in case it is a Unix app */
262 if (SearchPathW( NULL, name, NULL, buflen, buffer, NULL ))
264 TRACE( "Trying native/Unix binary %s\n", debugstr_w(buffer) );
265 if ((*handle = CreateFileW( buffer, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_DELETE,
266 NULL, OPEN_EXISTING, 0, 0 )) != INVALID_HANDLE_VALUE)
267 return TRUE;
269 return FALSE;
272 MODULE_GetLoadOrderW( loadorder, NULL, buffer );
274 for(i = 0; i < LOADORDER_NTYPES; i++)
276 if (loadorder[i] == LOADORDER_INVALID) break;
277 switch(loadorder[i])
279 case LOADORDER_DLL:
280 TRACE( "Trying native exe %s\n", debugstr_w(buffer) );
281 if ((*handle = CreateFileW( buffer, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_DELETE,
282 NULL, OPEN_EXISTING, 0, 0 )) != INVALID_HANDLE_VALUE)
283 return TRUE;
284 if (GetLastError() != ERROR_FILE_NOT_FOUND) return TRUE;
285 break;
286 case LOADORDER_BI:
287 TRACE( "Trying built-in exe %s\n", debugstr_w(buffer) );
288 open_builtin_exe_file( buffer, NULL, 0, 1, &file_exists );
289 if (file_exists)
291 *handle = 0;
292 return TRUE;
294 break;
295 default:
296 break;
299 SetLastError( ERROR_FILE_NOT_FOUND );
300 return FALSE;
304 /**********************************************************************
305 * load_pe_exe
307 * Load a PE format EXE file.
309 static HMODULE load_pe_exe( const WCHAR *name, HANDLE file )
311 IO_STATUS_BLOCK io;
312 FILE_FS_DEVICE_INFORMATION device_info;
313 IMAGE_NT_HEADERS *nt;
314 HANDLE mapping;
315 void *module;
316 OBJECT_ATTRIBUTES attr;
317 LARGE_INTEGER size;
318 DWORD len = 0;
320 attr.Length = sizeof(attr);
321 attr.RootDirectory = 0;
322 attr.ObjectName = NULL;
323 attr.Attributes = 0;
324 attr.SecurityDescriptor = NULL;
325 attr.SecurityQualityOfService = NULL;
326 size.QuadPart = 0;
328 if (NtCreateSection( &mapping, STANDARD_RIGHTS_REQUIRED | SECTION_QUERY | SECTION_MAP_READ,
329 &attr, &size, 0, SEC_IMAGE, file ) != STATUS_SUCCESS)
330 return NULL;
332 module = NULL;
333 if (NtMapViewOfSection( mapping, GetCurrentProcess(), &module, 0, 0, &size, &len,
334 ViewShare, 0, PAGE_READONLY ) != STATUS_SUCCESS)
335 return NULL;
337 NtClose( mapping );
339 /* virus check */
340 nt = RtlImageNtHeader( module );
341 if (nt->OptionalHeader.AddressOfEntryPoint)
343 if (!RtlImageRvaToSection( nt, module, nt->OptionalHeader.AddressOfEntryPoint ))
344 MESSAGE("VIRUS WARNING: PE module %s has an invalid entrypoint (0x%08lx) "
345 "outside all sections (possibly infected by Tchernobyl/SpaceFiller virus)!\n",
346 debugstr_w(name), nt->OptionalHeader.AddressOfEntryPoint );
349 if (NtQueryVolumeInformationFile( file, &io, &device_info, sizeof(device_info),
350 FileFsDeviceInformation ) == STATUS_SUCCESS)
352 /* don't keep the file handle open on removable media */
353 if (device_info.Characteristics & FILE_REMOVABLE_MEDIA)
355 CloseHandle( main_exe_file );
356 main_exe_file = 0;
360 return module;
363 /***********************************************************************
364 * build_initial_environment
366 * Build the Win32 environment from the Unix environment
368 static BOOL build_initial_environment( char **environ )
370 ULONG size = 1;
371 char **e;
372 WCHAR *p, *endptr;
373 void *ptr;
375 /* Compute the total size of the Unix environment */
376 for (e = environ; *e; e++)
378 if (is_special_env_var( *e )) continue;
379 size += MultiByteToWideChar( CP_UNIXCP, 0, *e, -1, NULL, 0 );
381 size *= sizeof(WCHAR);
383 /* Now allocate the environment */
384 ptr = NULL;
385 if (NtAllocateVirtualMemory(NtCurrentProcess(), &ptr, 0, &size,
386 MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) != STATUS_SUCCESS)
387 return FALSE;
389 NtCurrentTeb()->Peb->ProcessParameters->Environment = p = ptr;
390 endptr = p + size / sizeof(WCHAR);
392 /* And fill it with the Unix environment */
393 for (e = environ; *e; e++)
395 char *str = *e;
397 /* skip Unix special variables and use the Wine variants instead */
398 if (!strncmp( str, "WINE", 4 ))
400 if (is_special_env_var( str + 4 )) str += 4;
401 else if (!strncmp( str, "WINEPRELOADRESERVE=", 19 )) continue; /* skip it */
403 else if (is_special_env_var( str )) continue; /* skip it */
405 MultiByteToWideChar( CP_UNIXCP, 0, str, -1, p, endptr - p );
406 p += strlenW(p) + 1;
408 *p = 0;
409 return TRUE;
413 /***********************************************************************
414 * set_registry_variables
416 * Set environment variables by enumerating the values of a key;
417 * helper for set_registry_environment().
418 * Note that Windows happily truncates the value if it's too big.
420 static void set_registry_variables( HKEY hkey, ULONG type )
422 UNICODE_STRING env_name, env_value;
423 NTSTATUS status;
424 DWORD size;
425 int index;
426 char buffer[1024*sizeof(WCHAR) + sizeof(KEY_VALUE_FULL_INFORMATION)];
427 KEY_VALUE_FULL_INFORMATION *info = (KEY_VALUE_FULL_INFORMATION *)buffer;
429 for (index = 0; ; index++)
431 status = NtEnumerateValueKey( hkey, index, KeyValueFullInformation,
432 buffer, sizeof(buffer), &size );
433 if (status != STATUS_SUCCESS && status != STATUS_BUFFER_OVERFLOW)
434 break;
435 if (info->Type != type)
436 continue;
437 env_name.Buffer = info->Name;
438 env_name.Length = env_name.MaximumLength = info->NameLength;
439 env_value.Buffer = (WCHAR *)(buffer + info->DataOffset);
440 env_value.Length = env_value.MaximumLength = info->DataLength;
441 if (env_value.Length && !env_value.Buffer[env_value.Length/sizeof(WCHAR)-1])
442 env_value.Length--; /* don't count terminating null if any */
443 if (info->Type == REG_EXPAND_SZ)
445 WCHAR buf_expanded[1024];
446 UNICODE_STRING env_expanded;
447 env_expanded.Length = env_expanded.MaximumLength = sizeof(buf_expanded);
448 env_expanded.Buffer=buf_expanded;
449 status = RtlExpandEnvironmentStrings_U(NULL, &env_value, &env_expanded, NULL);
450 if (status == STATUS_SUCCESS || status == STATUS_BUFFER_OVERFLOW)
451 RtlSetEnvironmentVariable( NULL, &env_name, &env_expanded );
453 else
455 RtlSetEnvironmentVariable( NULL, &env_name, &env_value );
461 /***********************************************************************
462 * set_registry_environment
464 * Set the environment variables specified in the registry.
466 * Note: Windows handles REG_SZ and REG_EXPAND_SZ in one pass with the
467 * consequence that REG_EXPAND_SZ cannot be used reliably as it depends
468 * on the order in which the variables are processed. But on Windows it
469 * does not really matter since they only use %SystemDrive% and
470 * %SystemRoot% which are predefined. But Wine defines these in the
471 * registry, so we need two passes.
473 static void set_registry_environment(void)
475 static const WCHAR env_keyW[] = {'M','a','c','h','i','n','e','\\',
476 'S','y','s','t','e','m','\\',
477 'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
478 'C','o','n','t','r','o','l','\\',
479 'S','e','s','s','i','o','n',' ','M','a','n','a','g','e','r','\\',
480 'E','n','v','i','r','o','n','m','e','n','t',0};
481 static const WCHAR envW[] = {'E','n','v','i','r','o','n','m','e','n','t',0};
483 OBJECT_ATTRIBUTES attr;
484 UNICODE_STRING nameW;
485 HKEY hkey;
487 attr.Length = sizeof(attr);
488 attr.RootDirectory = 0;
489 attr.ObjectName = &nameW;
490 attr.Attributes = 0;
491 attr.SecurityDescriptor = NULL;
492 attr.SecurityQualityOfService = NULL;
494 /* first the system environment variables */
495 RtlInitUnicodeString( &nameW, env_keyW );
496 if (NtOpenKey( &hkey, KEY_ALL_ACCESS, &attr ) == STATUS_SUCCESS)
498 set_registry_variables( hkey, REG_SZ );
499 set_registry_variables( hkey, REG_EXPAND_SZ );
500 NtClose( hkey );
503 /* then the ones for the current user */
504 if (RtlOpenCurrentUser( KEY_ALL_ACCESS, (HKEY *)&attr.RootDirectory ) != STATUS_SUCCESS) return;
505 RtlInitUnicodeString( &nameW, envW );
506 if (NtOpenKey( &hkey, KEY_ALL_ACCESS, &attr ) == STATUS_SUCCESS)
508 set_registry_variables( hkey, REG_SZ );
509 set_registry_variables( hkey, REG_EXPAND_SZ );
510 NtClose( hkey );
512 NtClose( attr.RootDirectory );
516 /***********************************************************************
517 * set_library_wargv
519 * Set the Wine library Unicode argv global variables.
521 static void set_library_wargv( char **argv )
523 int argc;
524 char *q;
525 WCHAR *p;
526 WCHAR **wargv;
527 DWORD total = 0;
529 for (argc = 0; argv[argc]; argc++)
530 total += MultiByteToWideChar( CP_UNIXCP, 0, argv[argc], -1, NULL, 0 );
532 wargv = RtlAllocateHeap( GetProcessHeap(), 0,
533 total * sizeof(WCHAR) + (argc + 1) * sizeof(*wargv) );
534 p = (WCHAR *)(wargv + argc + 1);
535 for (argc = 0; argv[argc]; argc++)
537 DWORD reslen = MultiByteToWideChar( CP_UNIXCP, 0, argv[argc], -1, p, total );
538 wargv[argc] = p;
539 p += reslen;
540 total -= reslen;
542 wargv[argc] = NULL;
544 /* convert argv back from Unicode since it has to be in the Ansi codepage not the Unix one */
546 for (argc = 0; wargv[argc]; argc++)
547 total += WideCharToMultiByte( CP_ACP, 0, wargv[argc], -1, NULL, 0, NULL, NULL );
549 argv = RtlAllocateHeap( GetProcessHeap(), 0, total + (argc + 1) * sizeof(*argv) );
550 q = (char *)(argv + argc + 1);
551 for (argc = 0; wargv[argc]; argc++)
553 DWORD reslen = WideCharToMultiByte( CP_ACP, 0, wargv[argc], -1, q, total, NULL, NULL );
554 argv[argc] = q;
555 q += reslen;
556 total -= reslen;
558 argv[argc] = NULL;
560 __wine_main_argv = argv;
561 __wine_main_wargv = wargv;
565 /***********************************************************************
566 * build_command_line
568 * Build the command line of a process from the argv array.
570 * Note that it does NOT necessarily include the file name.
571 * Sometimes we don't even have any command line options at all.
573 * We must quote and escape characters so that the argv array can be rebuilt
574 * from the command line:
575 * - spaces and tabs must be quoted
576 * 'a b' -> '"a b"'
577 * - quotes must be escaped
578 * '"' -> '\"'
579 * - if '\'s are followed by a '"', they must be doubled and followed by '\"',
580 * resulting in an odd number of '\' followed by a '"'
581 * '\"' -> '\\\"'
582 * '\\"' -> '\\\\\"'
583 * - '\'s that are not followed by a '"' can be left as is
584 * 'a\b' == 'a\b'
585 * 'a\\b' == 'a\\b'
587 static BOOL build_command_line( WCHAR **argv )
589 int len;
590 WCHAR **arg;
591 LPWSTR p;
592 RTL_USER_PROCESS_PARAMETERS* rupp = NtCurrentTeb()->Peb->ProcessParameters;
594 if (rupp->CommandLine.Buffer) return TRUE; /* already got it from the server */
596 len = 0;
597 for (arg = argv; *arg; arg++)
599 int has_space,bcount;
600 WCHAR* a;
602 has_space=0;
603 bcount=0;
604 a=*arg;
605 if( !*a ) has_space=1;
606 while (*a!='\0') {
607 if (*a=='\\') {
608 bcount++;
609 } else {
610 if (*a==' ' || *a=='\t') {
611 has_space=1;
612 } else if (*a=='"') {
613 /* doubling of '\' preceding a '"',
614 * plus escaping of said '"'
616 len+=2*bcount+1;
618 bcount=0;
620 a++;
622 len+=(a-*arg)+1 /* for the separating space */;
623 if (has_space)
624 len+=2; /* for the quotes */
627 if (!(rupp->CommandLine.Buffer = RtlAllocateHeap( GetProcessHeap(), 0, len * sizeof(WCHAR))))
628 return FALSE;
630 p = rupp->CommandLine.Buffer;
631 rupp->CommandLine.Length = (len - 1) * sizeof(WCHAR);
632 rupp->CommandLine.MaximumLength = len * sizeof(WCHAR);
633 for (arg = argv; *arg; arg++)
635 int has_space,has_quote;
636 WCHAR* a;
638 /* Check for quotes and spaces in this argument */
639 has_space=has_quote=0;
640 a=*arg;
641 if( !*a ) has_space=1;
642 while (*a!='\0') {
643 if (*a==' ' || *a=='\t') {
644 has_space=1;
645 if (has_quote)
646 break;
647 } else if (*a=='"') {
648 has_quote=1;
649 if (has_space)
650 break;
652 a++;
655 /* Now transfer it to the command line */
656 if (has_space)
657 *p++='"';
658 if (has_quote) {
659 int bcount;
660 WCHAR* a;
662 bcount=0;
663 a=*arg;
664 while (*a!='\0') {
665 if (*a=='\\') {
666 *p++=*a;
667 bcount++;
668 } else {
669 if (*a=='"') {
670 int i;
672 /* Double all the '\\' preceding this '"', plus one */
673 for (i=0;i<=bcount;i++)
674 *p++='\\';
675 *p++='"';
676 } else {
677 *p++=*a;
679 bcount=0;
681 a++;
683 } else {
684 WCHAR* x = *arg;
685 while ((*p=*x++)) p++;
687 if (has_space)
688 *p++='"';
689 *p++=' ';
691 if (p > rupp->CommandLine.Buffer)
692 p--; /* remove last space */
693 *p = '\0';
695 return TRUE;
699 /* make sure the unicode string doesn't point beyond the end pointer */
700 static inline void fix_unicode_string( UNICODE_STRING *str, char *end_ptr )
702 if ((char *)str->Buffer >= end_ptr)
704 str->Length = str->MaximumLength = 0;
705 str->Buffer = NULL;
706 return;
708 if ((char *)str->Buffer + str->MaximumLength > end_ptr)
710 str->MaximumLength = (end_ptr - (char *)str->Buffer) & ~(sizeof(WCHAR) - 1);
712 if (str->Length >= str->MaximumLength)
714 if (str->MaximumLength >= sizeof(WCHAR))
715 str->Length = str->MaximumLength - sizeof(WCHAR);
716 else
717 str->Length = str->MaximumLength = 0;
721 static void version(void)
723 MESSAGE( "%s\n", PACKAGE_STRING );
724 ExitProcess(0);
727 static void usage(void)
729 MESSAGE( "%s\n", PACKAGE_STRING );
730 MESSAGE( "Usage: wine PROGRAM [ARGUMENTS...] Run the specified program\n" );
731 MESSAGE( " wine --help Display this help and exit\n");
732 MESSAGE( " wine --version Output version information and exit\n");
733 ExitProcess(0);
737 /***********************************************************************
738 * init_user_process_params
740 * Fill the RTL_USER_PROCESS_PARAMETERS structure from the server.
742 static RTL_USER_PROCESS_PARAMETERS *init_user_process_params( size_t info_size )
744 void *ptr;
745 DWORD size, env_size;
746 RTL_USER_PROCESS_PARAMETERS *params;
748 size = info_size;
749 ptr = NULL;
750 if (NtAllocateVirtualMemory( NtCurrentProcess(), &ptr, 0, &size,
751 MEM_COMMIT, PAGE_READWRITE ) != STATUS_SUCCESS)
752 return NULL;
754 SERVER_START_REQ( get_startup_info )
756 wine_server_set_reply( req, ptr, info_size );
757 wine_server_call( req );
758 info_size = wine_server_reply_size( reply );
760 SERVER_END_REQ;
762 params = ptr;
763 params->AllocationSize = size;
764 if (params->Size > info_size) params->Size = info_size;
766 /* make sure the strings are valid */
767 fix_unicode_string( &params->CurrentDirectory.DosPath, (char *)info_size );
768 fix_unicode_string( &params->DllPath, (char *)info_size );
769 fix_unicode_string( &params->ImagePathName, (char *)info_size );
770 fix_unicode_string( &params->CommandLine, (char *)info_size );
771 fix_unicode_string( &params->WindowTitle, (char *)info_size );
772 fix_unicode_string( &params->Desktop, (char *)info_size );
773 fix_unicode_string( &params->ShellInfo, (char *)info_size );
774 fix_unicode_string( &params->RuntimeInfo, (char *)info_size );
776 /* environment needs to be a separate memory block */
777 env_size = info_size - params->Size;
778 if (!env_size) env_size = 1;
779 ptr = NULL;
780 if (NtAllocateVirtualMemory( NtCurrentProcess(), &ptr, 0, &env_size,
781 MEM_COMMIT, PAGE_READWRITE ) != STATUS_SUCCESS)
782 return NULL;
783 memcpy( ptr, (char *)params + params->Size, info_size - params->Size );
784 params->Environment = ptr;
786 return RtlNormalizeProcessParams( params );
790 /***********************************************************************
791 * init_current_directory
793 * Initialize the current directory from the Unix cwd or the parent info.
795 static void init_current_directory( CURDIR *cur_dir )
797 UNICODE_STRING dir_str;
798 char *cwd;
799 int size;
801 /* if we received a cur dir from the parent, try this first */
803 if (cur_dir->DosPath.Length)
805 if (RtlSetCurrentDirectory_U( &cur_dir->DosPath ) == STATUS_SUCCESS) goto done;
808 /* now try to get it from the Unix cwd */
810 for (size = 256; ; size *= 2)
812 if (!(cwd = HeapAlloc( GetProcessHeap(), 0, size ))) break;
813 if (getcwd( cwd, size )) break;
814 HeapFree( GetProcessHeap(), 0, cwd );
815 if (errno == ERANGE) continue;
816 cwd = NULL;
817 break;
820 if (cwd)
822 WCHAR *dirW;
823 int lenW = MultiByteToWideChar( CP_UNIXCP, 0, cwd, -1, NULL, 0 );
824 if ((dirW = HeapAlloc( GetProcessHeap(), 0, lenW * sizeof(WCHAR) )))
826 MultiByteToWideChar( CP_UNIXCP, 0, cwd, -1, dirW, lenW );
827 RtlInitUnicodeString( &dir_str, dirW );
828 RtlSetCurrentDirectory_U( &dir_str );
829 RtlFreeUnicodeString( &dir_str );
833 if (!cur_dir->DosPath.Length) /* still not initialized */
835 MESSAGE("Warning: could not find DOS drive for current working directory '%s', "
836 "starting in the Windows directory.\n", cwd ? cwd : "" );
837 RtlInitUnicodeString( &dir_str, DIR_Windows );
838 RtlSetCurrentDirectory_U( &dir_str );
840 HeapFree( GetProcessHeap(), 0, cwd );
842 done:
843 if (!cur_dir->Handle) chdir("/"); /* change to root directory so as not to lock cdroms */
844 TRACE( "starting in %s %p\n", debugstr_w( cur_dir->DosPath.Buffer ), cur_dir->Handle );
848 /***********************************************************************
849 * init_windows_dirs
851 * Initialize the windows and system directories from the environment.
853 static void init_windows_dirs(void)
855 extern void __wine_init_windows_dir( const WCHAR *windir, const WCHAR *sysdir );
857 static const WCHAR windirW[] = {'w','i','n','d','i','r',0};
858 static const WCHAR winsysdirW[] = {'w','i','n','s','y','s','d','i','r',0};
859 static const WCHAR default_windirW[] = {'c',':','\\','w','i','n','d','o','w','s',0};
860 static const WCHAR default_sysdirW[] = {'\\','s','y','s','t','e','m',0};
862 DWORD len;
863 WCHAR *buffer;
865 if ((len = GetEnvironmentVariableW( windirW, NULL, 0 )))
867 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
868 GetEnvironmentVariableW( windirW, buffer, len );
869 DIR_Windows = buffer;
871 else DIR_Windows = default_windirW;
873 if ((len = GetEnvironmentVariableW( winsysdirW, NULL, 0 )))
875 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
876 GetEnvironmentVariableW( winsysdirW, buffer, len );
877 DIR_System = buffer;
879 else
881 len = strlenW( DIR_Windows );
882 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) + sizeof(default_sysdirW) );
883 memcpy( buffer, DIR_Windows, len * sizeof(WCHAR) );
884 memcpy( buffer + len, default_sysdirW, sizeof(default_sysdirW) );
885 DIR_System = buffer;
888 if (GetFileAttributesW( DIR_Windows ) == INVALID_FILE_ATTRIBUTES)
889 MESSAGE( "Warning: the specified Windows directory %s is not accessible.\n",
890 debugstr_w(DIR_Windows) );
891 if (GetFileAttributesW( DIR_System ) == INVALID_FILE_ATTRIBUTES)
892 MESSAGE( "Warning: the specified System directory %s is not accessible.\n",
893 debugstr_w(DIR_System) );
895 TRACE_(file)( "WindowsDir = %s\n", debugstr_w(DIR_Windows) );
896 TRACE_(file)( "SystemDir = %s\n", debugstr_w(DIR_System) );
898 /* set the directories in ntdll too */
899 __wine_init_windows_dir( DIR_Windows, DIR_System );
903 /***********************************************************************
904 * process_init
906 * Main process initialisation code
908 static BOOL process_init(void)
910 static const WCHAR kernel32W[] = {'k','e','r','n','e','l','3','2',0};
911 BOOL ret;
912 size_t info_size = 0;
913 RTL_USER_PROCESS_PARAMETERS *params;
914 PEB *peb = NtCurrentTeb()->Peb;
915 HANDLE hstdin, hstdout, hstderr;
916 extern void __wine_dbg_kernel32_init(void);
918 PTHREAD_Init();
920 __wine_dbg_kernel32_init(); /* hack: register debug channels early */
922 setbuf(stdout,NULL);
923 setbuf(stderr,NULL);
924 setlocale(LC_CTYPE,"");
926 /* Retrieve startup info from the server */
927 SERVER_START_REQ( init_process )
929 req->peb = peb;
930 req->ldt_copy = &wine_ldt_copy;
931 if ((ret = !wine_server_call_err( req )))
933 main_exe_file = reply->exe_file;
934 main_create_flags = reply->create_flags;
935 info_size = reply->info_size;
936 server_startticks = reply->server_start;
937 hstdin = reply->hstdin;
938 hstdout = reply->hstdout;
939 hstderr = reply->hstderr;
942 SERVER_END_REQ;
943 if (!ret) return FALSE;
945 if (info_size == 0)
947 params = peb->ProcessParameters;
949 /* This is wine specific: we have no parent (we're started from unix)
950 * so, create a simple console with bare handles to unix stdio
951 * input & output streams (aka simple console)
953 wine_server_fd_to_handle( 0, GENERIC_READ|SYNCHRONIZE, TRUE, &params->hStdInput );
954 wine_server_fd_to_handle( 1, GENERIC_WRITE|SYNCHRONIZE, TRUE, &params->hStdOutput );
955 wine_server_fd_to_handle( 2, GENERIC_WRITE|SYNCHRONIZE, TRUE, &params->hStdError );
957 params->CurrentDirectory.DosPath.Length = 0;
958 params->CurrentDirectory.DosPath.MaximumLength = RtlGetLongestNtPathLength() * sizeof(WCHAR);
959 params->CurrentDirectory.DosPath.Buffer = RtlAllocateHeap( GetProcessHeap(), 0, params->CurrentDirectory.DosPath.MaximumLength);
961 else
963 if (!(params = init_user_process_params( info_size ))) return FALSE;
964 peb->ProcessParameters = params;
966 /* convert value from server:
967 * + 0 => INVALID_HANDLE_VALUE
968 * + console handle need to be mapped
970 if (!hstdin)
971 hstdin = INVALID_HANDLE_VALUE;
972 else if (VerifyConsoleIoHandle(console_handle_map(hstdin)))
973 hstdin = console_handle_map(hstdin);
975 if (!hstdout)
976 hstdout = INVALID_HANDLE_VALUE;
977 else if (VerifyConsoleIoHandle(console_handle_map(hstdout)))
978 hstdout = console_handle_map(hstdout);
980 if (!hstderr)
981 hstderr = INVALID_HANDLE_VALUE;
982 else if (VerifyConsoleIoHandle(console_handle_map(hstderr)))
983 hstderr = console_handle_map(hstderr);
985 params->hStdInput = hstdin;
986 params->hStdOutput = hstdout;
987 params->hStdError = hstderr;
990 kernel32_handle = GetModuleHandleW(kernel32W);
992 LOCALE_Init();
994 if (!info_size)
996 /* Copy the parent environment */
997 if (!build_initial_environment( __wine_main_environ )) return FALSE;
999 /* convert old configuration to new format */
1000 convert_old_config();
1002 /* global boot finished, the rest is process-local */
1003 SERVER_START_REQ( boot_done )
1005 req->debug_level = TRACE_ON(server);
1006 wine_server_call( req );
1008 SERVER_END_REQ;
1010 set_registry_environment();
1013 init_windows_dirs();
1014 init_current_directory( &params->CurrentDirectory );
1016 return TRUE;
1020 /***********************************************************************
1021 * start_process
1023 * Startup routine of a new process. Runs on the new process stack.
1025 static void start_process( void *arg )
1027 __TRY
1029 PEB *peb = NtCurrentTeb()->Peb;
1030 IMAGE_NT_HEADERS *nt;
1031 LPTHREAD_START_ROUTINE entry;
1033 LdrInitializeThunk( main_exe_file, 0, 0, 0 );
1035 nt = RtlImageNtHeader( peb->ImageBaseAddress );
1036 entry = (LPTHREAD_START_ROUTINE)((char *)peb->ImageBaseAddress +
1037 nt->OptionalHeader.AddressOfEntryPoint);
1039 if (TRACE_ON(relay))
1040 DPRINTF( "%04lx:Starting process %s (entryproc=%p)\n", GetCurrentThreadId(),
1041 debugstr_w(peb->ProcessParameters->ImagePathName.Buffer), entry );
1043 SetLastError( 0 ); /* clear error code */
1044 if (peb->BeingDebugged) DbgBreakPoint();
1045 ExitProcess( entry( peb ) );
1047 __EXCEPT(UnhandledExceptionFilter)
1049 TerminateThread( GetCurrentThread(), GetExceptionCode() );
1051 __ENDTRY
1055 /***********************************************************************
1056 * __wine_kernel_init
1058 * Wine initialisation: load and start the main exe file.
1060 void __wine_kernel_init(void)
1062 WCHAR *main_exe_name, *p;
1063 char error[1024];
1064 DWORD stack_size = 0;
1065 int file_exists;
1066 PEB *peb = NtCurrentTeb()->Peb;
1068 /* Initialize everything */
1069 if (!process_init()) exit(1);
1071 __wine_main_argv++; /* remove argv[0] (wine itself) */
1072 __wine_main_argc--;
1074 if (!(main_exe_name = peb->ProcessParameters->ImagePathName.Buffer))
1076 WCHAR buffer[MAX_PATH];
1077 WCHAR exe_nameW[MAX_PATH];
1079 if (!__wine_main_argv[0]) usage();
1080 if (__wine_main_argc == 1)
1082 if (strcmp(__wine_main_argv[0], "--help") == 0) usage();
1083 if (strcmp(__wine_main_argv[0], "--version") == 0) version();
1086 MultiByteToWideChar( CP_UNIXCP, 0, __wine_main_argv[0], -1, exe_nameW, MAX_PATH );
1087 if (!find_exe_file( exe_nameW, buffer, MAX_PATH, &main_exe_file ))
1089 MESSAGE( "wine: cannot find '%s'\n", __wine_main_argv[0] );
1090 ExitProcess(1);
1092 if (main_exe_file == INVALID_HANDLE_VALUE)
1094 MESSAGE( "wine: cannot open %s\n", debugstr_w(main_exe_name) );
1095 ExitProcess(1);
1097 RtlCreateUnicodeString( &peb->ProcessParameters->ImagePathName, buffer );
1098 main_exe_name = peb->ProcessParameters->ImagePathName.Buffer;
1101 TRACE( "starting process name=%s file=%p argv[0]=%s\n",
1102 debugstr_w(main_exe_name), main_exe_file, debugstr_a(__wine_main_argv[0]) );
1104 RtlInitUnicodeString( &NtCurrentTeb()->Peb->ProcessParameters->DllPath,
1105 MODULE_get_dll_load_path(NULL) );
1106 VERSION_Init( main_exe_name );
1108 if (!main_exe_file) /* no file handle -> Winelib app */
1110 TRACE( "starting Winelib app %s\n", debugstr_w(main_exe_name) );
1111 if (open_builtin_exe_file( main_exe_name, error, sizeof(error), 0, &file_exists ))
1112 goto found;
1113 MESSAGE( "wine: cannot open builtin library for %s: %s\n",
1114 debugstr_w(main_exe_name), error );
1115 ExitProcess(1);
1118 switch( MODULE_GetBinaryType( main_exe_file, NULL, NULL ))
1120 case BINARY_PE_EXE:
1121 TRACE( "starting Win32 binary %s\n", debugstr_w(main_exe_name) );
1122 if ((peb->ImageBaseAddress = load_pe_exe( main_exe_name, main_exe_file )))
1123 goto found;
1124 MESSAGE( "wine: could not load %s as Win32 binary\n", debugstr_w(main_exe_name) );
1125 ExitProcess(1);
1126 case BINARY_PE_DLL:
1127 MESSAGE( "wine: %s is a DLL, not an executable\n", debugstr_w(main_exe_name) );
1128 ExitProcess(1);
1129 case BINARY_UNKNOWN:
1130 /* check for .com extension */
1131 if (!(p = strrchrW( main_exe_name, '.' )) || strcmpiW( p, comW ))
1133 MESSAGE( "wine: cannot determine executable type for %s\n",
1134 debugstr_w(main_exe_name) );
1135 ExitProcess(1);
1137 /* fall through */
1138 case BINARY_OS216:
1139 case BINARY_WIN16:
1140 case BINARY_DOS:
1141 TRACE( "starting Win16/DOS binary %s\n", debugstr_w(main_exe_name) );
1142 CloseHandle( main_exe_file );
1143 main_exe_file = 0;
1144 __wine_main_argv--;
1145 __wine_main_argc++;
1146 __wine_main_argv[0] = "winevdm.exe";
1147 if (open_builtin_exe_file( winevdmW, error, sizeof(error), 0, &file_exists ))
1148 goto found;
1149 MESSAGE( "wine: trying to run %s, cannot open builtin library for 'winevdm.exe': %s\n",
1150 debugstr_w(main_exe_name), error );
1151 ExitProcess(1);
1152 case BINARY_UNIX_EXE:
1153 MESSAGE( "wine: %s is a Unix binary, not supported\n", debugstr_w(main_exe_name) );
1154 ExitProcess(1);
1155 case BINARY_UNIX_LIB:
1157 char *unix_name;
1159 TRACE( "starting Winelib app %s\n", debugstr_w(main_exe_name) );
1160 CloseHandle( main_exe_file );
1161 main_exe_file = 0;
1162 if ((unix_name = wine_get_unix_file_name( main_exe_name )) &&
1163 wine_dlopen( unix_name, RTLD_NOW, error, sizeof(error) ))
1165 static const WCHAR soW[] = {'.','s','o',0};
1166 if ((p = strrchrW( main_exe_name, '.' )) && !strcmpW( p, soW ))
1168 *p = 0;
1169 /* update the unicode string */
1170 RtlInitUnicodeString( &peb->ProcessParameters->ImagePathName, main_exe_name );
1172 HeapFree( GetProcessHeap(), 0, unix_name );
1173 goto found;
1175 MESSAGE( "wine: could not load %s: %s\n", debugstr_w(main_exe_name), error );
1176 ExitProcess(1);
1180 found:
1181 /* build command line */
1182 set_library_wargv( __wine_main_argv );
1183 if (!build_command_line( __wine_main_wargv )) goto error;
1185 stack_size = RtlImageNtHeader(peb->ImageBaseAddress)->OptionalHeader.SizeOfStackReserve;
1187 /* allocate main thread stack */
1188 if (!THREAD_InitStack( NtCurrentTeb(), stack_size )) goto error;
1190 /* switch to the new stack */
1191 wine_switch_to_stack( start_process, NULL, NtCurrentTeb()->Tib.StackBase );
1193 error:
1194 ExitProcess( GetLastError() );
1198 /***********************************************************************
1199 * build_argv
1201 * Build an argv array from a command-line.
1202 * 'reserved' is the number of args to reserve before the first one.
1204 static char **build_argv( const WCHAR *cmdlineW, int reserved )
1206 int argc;
1207 char** argv;
1208 char *arg,*s,*d,*cmdline;
1209 int in_quotes,bcount,len;
1211 len = WideCharToMultiByte( CP_UNIXCP, 0, cmdlineW, -1, NULL, 0, NULL, NULL );
1212 if (!(cmdline = malloc(len))) return NULL;
1213 WideCharToMultiByte( CP_UNIXCP, 0, cmdlineW, -1, cmdline, len, NULL, NULL );
1215 argc=reserved+1;
1216 bcount=0;
1217 in_quotes=0;
1218 s=cmdline;
1219 while (1) {
1220 if (*s=='\0' || ((*s==' ' || *s=='\t') && !in_quotes)) {
1221 /* space */
1222 argc++;
1223 /* skip the remaining spaces */
1224 while (*s==' ' || *s=='\t') {
1225 s++;
1227 if (*s=='\0')
1228 break;
1229 bcount=0;
1230 continue;
1231 } else if (*s=='\\') {
1232 /* '\', count them */
1233 bcount++;
1234 } else if ((*s=='"') && ((bcount & 1)==0)) {
1235 /* unescaped '"' */
1236 in_quotes=!in_quotes;
1237 bcount=0;
1238 } else {
1239 /* a regular character */
1240 bcount=0;
1242 s++;
1244 argv=malloc(argc*sizeof(*argv));
1245 if (!argv)
1246 return NULL;
1248 arg=d=s=cmdline;
1249 bcount=0;
1250 in_quotes=0;
1251 argc=reserved;
1252 while (*s) {
1253 if ((*s==' ' || *s=='\t') && !in_quotes) {
1254 /* Close the argument and copy it */
1255 *d=0;
1256 argv[argc++]=arg;
1258 /* skip the remaining spaces */
1259 do {
1260 s++;
1261 } while (*s==' ' || *s=='\t');
1263 /* Start with a new argument */
1264 arg=d=s;
1265 bcount=0;
1266 } else if (*s=='\\') {
1267 /* '\\' */
1268 *d++=*s++;
1269 bcount++;
1270 } else if (*s=='"') {
1271 /* '"' */
1272 if ((bcount & 1)==0) {
1273 /* Preceded by an even number of '\', this is half that
1274 * number of '\', plus a '"' which we discard.
1276 d-=bcount/2;
1277 s++;
1278 in_quotes=!in_quotes;
1279 } else {
1280 /* Preceded by an odd number of '\', this is half that
1281 * number of '\' followed by a '"'
1283 d=d-bcount/2-1;
1284 *d++='"';
1285 s++;
1287 bcount=0;
1288 } else {
1289 /* a regular character */
1290 *d++=*s++;
1291 bcount=0;
1294 if (*arg) {
1295 *d='\0';
1296 argv[argc++]=arg;
1298 argv[argc]=NULL;
1300 return argv;
1304 /***********************************************************************
1305 * alloc_env_string
1307 * Allocate an environment string; helper for build_envp
1309 static char *alloc_env_string( const char *name, const char *value )
1311 char *ret = malloc( strlen(name) + strlen(value) + 1 );
1312 strcpy( ret, name );
1313 strcat( ret, value );
1314 return ret;
1317 /***********************************************************************
1318 * build_envp
1320 * Build the environment of a new child process.
1322 static char **build_envp( const WCHAR *envW )
1324 const WCHAR *end;
1325 char **envp;
1326 char *env, *p;
1327 int count = 0, length;
1329 for (end = envW; *end; count++) end += strlenW(end) + 1;
1330 end++;
1331 length = WideCharToMultiByte( CP_UNIXCP, 0, envW, end - envW, NULL, 0, NULL, NULL );
1332 if (!(env = malloc( length ))) return NULL;
1333 WideCharToMultiByte( CP_UNIXCP, 0, envW, end - envW, env, length, NULL, NULL );
1335 count += 4;
1337 if ((envp = malloc( count * sizeof(*envp) )))
1339 char **envptr = envp;
1341 /* some variables must not be modified, so we get them directly from the unix env */
1342 if ((p = getenv("PATH"))) *envptr++ = alloc_env_string( "PATH=", p );
1343 if ((p = getenv("TEMP"))) *envptr++ = alloc_env_string( "TEMP=", p );
1344 if ((p = getenv("TMP"))) *envptr++ = alloc_env_string( "TMP=", p );
1345 if ((p = getenv("HOME"))) *envptr++ = alloc_env_string( "HOME=", p );
1346 /* now put the Windows environment strings */
1347 for (p = env; *p; p += strlen(p) + 1)
1349 if (*p == '=') continue; /* skip drive curdirs, this crashes some unix apps */
1350 if (!strncmp( p, "WINEPRELOADRESERVE=", sizeof("WINEPRELOADRESERVE=")-1 )) continue;
1351 if (is_special_env_var( p )) /* prefix it with "WINE" */
1352 *envptr++ = alloc_env_string( "WINE", p );
1353 else
1354 *envptr++ = p;
1356 *envptr = 0;
1358 return envp;
1362 /***********************************************************************
1363 * fork_and_exec
1365 * Fork and exec a new Unix binary, checking for errors.
1367 static int fork_and_exec( const char *filename, const WCHAR *cmdline,
1368 const WCHAR *env, const char *newdir )
1370 int fd[2];
1371 int pid, err;
1373 if (!env) env = GetEnvironmentStringsW();
1375 if (pipe(fd) == -1)
1377 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
1378 return -1;
1380 fcntl( fd[1], F_SETFD, 1 ); /* set close on exec */
1381 if (!(pid = fork())) /* child */
1383 char **argv = build_argv( cmdline, 0 );
1384 char **envp = build_envp( env );
1385 close( fd[0] );
1387 /* Reset signals that we previously set to SIG_IGN */
1388 signal( SIGPIPE, SIG_DFL );
1389 signal( SIGCHLD, SIG_DFL );
1391 if (newdir) chdir(newdir);
1393 if (argv && envp) execve( filename, argv, envp );
1394 err = errno;
1395 write( fd[1], &err, sizeof(err) );
1396 _exit(1);
1398 close( fd[1] );
1399 if ((pid != -1) && (read( fd[0], &err, sizeof(err) ) > 0)) /* exec failed */
1401 errno = err;
1402 pid = -1;
1404 if (pid == -1) FILE_SetDosError();
1405 close( fd[0] );
1406 return pid;
1410 /***********************************************************************
1411 * create_user_params
1413 static RTL_USER_PROCESS_PARAMETERS *create_user_params( LPCWSTR filename, LPCWSTR cmdline,
1414 LPCWSTR cur_dir, LPWSTR env,
1415 const STARTUPINFOW *startup )
1417 RTL_USER_PROCESS_PARAMETERS *params;
1418 UNICODE_STRING image_str, cmdline_str, curdir_str, desktop, title, runtime;
1419 NTSTATUS status;
1420 WCHAR buffer[MAX_PATH];
1422 if(!GetLongPathNameW( filename, buffer, MAX_PATH ))
1423 lstrcpynW( buffer, filename, MAX_PATH );
1424 if(!GetFullPathNameW( buffer, MAX_PATH, buffer, NULL ))
1425 lstrcpynW( buffer, filename, MAX_PATH );
1426 RtlInitUnicodeString( &image_str, buffer );
1428 RtlInitUnicodeString( &cmdline_str, cmdline );
1429 if (cur_dir) RtlInitUnicodeString( &curdir_str, cur_dir );
1430 if (startup->lpDesktop) RtlInitUnicodeString( &desktop, startup->lpDesktop );
1431 if (startup->lpTitle) RtlInitUnicodeString( &title, startup->lpTitle );
1432 if (startup->lpReserved2 && startup->cbReserved2)
1434 runtime.Length = 0;
1435 runtime.MaximumLength = startup->cbReserved2;
1436 runtime.Buffer = (WCHAR*)startup->lpReserved2;
1439 status = RtlCreateProcessParameters( &params, &image_str, NULL,
1440 cur_dir ? &curdir_str : NULL,
1441 &cmdline_str, env,
1442 startup->lpTitle ? &title : NULL,
1443 startup->lpDesktop ? &desktop : NULL,
1444 NULL,
1445 (startup->lpReserved2 && startup->cbReserved2) ? &runtime : NULL );
1446 if (status != STATUS_SUCCESS)
1448 SetLastError( RtlNtStatusToDosError(status) );
1449 return NULL;
1452 params->hStdInput = startup->hStdInput;
1453 params->hStdOutput = startup->hStdOutput;
1454 params->hStdError = startup->hStdError;
1455 params->dwX = startup->dwX;
1456 params->dwY = startup->dwY;
1457 params->dwXSize = startup->dwXSize;
1458 params->dwYSize = startup->dwYSize;
1459 params->dwXCountChars = startup->dwXCountChars;
1460 params->dwYCountChars = startup->dwYCountChars;
1461 params->dwFillAttribute = startup->dwFillAttribute;
1462 params->dwFlags = startup->dwFlags;
1463 params->wShowWindow = startup->wShowWindow;
1464 return params;
1468 /***********************************************************************
1469 * create_process
1471 * Create a new process. If hFile is a valid handle we have an exe
1472 * file, otherwise it is a Winelib app.
1474 static BOOL create_process( HANDLE hFile, LPCWSTR filename, LPWSTR cmd_line, LPWSTR env,
1475 LPCWSTR cur_dir, LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1476 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
1477 LPPROCESS_INFORMATION info, LPCSTR unixdir,
1478 void *res_start, void *res_end )
1480 BOOL ret, success = FALSE;
1481 HANDLE process_info;
1482 WCHAR *env_end;
1483 RTL_USER_PROCESS_PARAMETERS *params;
1484 int startfd[2];
1485 int execfd[2];
1486 pid_t pid;
1487 int err;
1488 char dummy = 0;
1489 char preloader_reserve[64];
1491 if (!env) RtlAcquirePebLock();
1493 if (!(params = create_user_params( filename, cmd_line, cur_dir, env, startup )))
1495 if (!env) RtlReleasePebLock();
1496 return FALSE;
1498 env_end = params->Environment;
1499 while (*env_end) env_end += strlenW(env_end) + 1;
1500 env_end++;
1502 sprintf( preloader_reserve, "WINEPRELOADRESERVE=%lx-%lx%c",
1503 (unsigned long)res_start, (unsigned long)res_end, 0 );
1505 /* create the synchronization pipes */
1507 if (pipe( startfd ) == -1)
1509 if (!env) RtlReleasePebLock();
1510 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
1511 RtlDestroyProcessParameters( params );
1512 return FALSE;
1514 if (pipe( execfd ) == -1)
1516 if (!env) RtlReleasePebLock();
1517 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
1518 close( startfd[0] );
1519 close( startfd[1] );
1520 RtlDestroyProcessParameters( params );
1521 return FALSE;
1523 fcntl( execfd[1], F_SETFD, 1 ); /* set close on exec */
1525 /* create the child process */
1527 if (!(pid = fork())) /* child */
1529 char **argv = build_argv( cmd_line, 1 );
1531 close( startfd[1] );
1532 close( execfd[0] );
1534 /* wait for parent to tell us to start */
1535 if (read( startfd[0], &dummy, 1 ) != 1) _exit(1);
1537 close( startfd[0] );
1538 /* Reset signals that we previously set to SIG_IGN */
1539 signal( SIGPIPE, SIG_DFL );
1540 signal( SIGCHLD, SIG_DFL );
1542 putenv( preloader_reserve );
1543 if (unixdir) chdir(unixdir);
1545 if (argv)
1547 /* first, try for a WINELOADER environment variable */
1548 const char *loader = getenv("WINELOADER");
1549 if (loader) wine_exec_wine_binary( loader, argv, NULL, TRUE );
1550 /* now use the standard search strategy */
1551 wine_exec_wine_binary( NULL, argv, NULL, TRUE );
1553 err = errno;
1554 write( execfd[1], &err, sizeof(err) );
1555 _exit(1);
1558 /* this is the parent */
1560 close( startfd[0] );
1561 close( execfd[1] );
1562 if (pid == -1)
1564 if (!env) RtlReleasePebLock();
1565 close( startfd[1] );
1566 close( execfd[0] );
1567 FILE_SetDosError();
1568 RtlDestroyProcessParameters( params );
1569 return FALSE;
1572 /* create the process on the server side */
1574 SERVER_START_REQ( new_process )
1576 req->inherit_all = inherit;
1577 req->create_flags = flags;
1578 req->unix_pid = pid;
1579 req->exe_file = hFile;
1580 if (startup->dwFlags & STARTF_USESTDHANDLES)
1582 req->hstdin = startup->hStdInput;
1583 req->hstdout = startup->hStdOutput;
1584 req->hstderr = startup->hStdError;
1586 else
1588 req->hstdin = GetStdHandle( STD_INPUT_HANDLE );
1589 req->hstdout = GetStdHandle( STD_OUTPUT_HANDLE );
1590 req->hstderr = GetStdHandle( STD_ERROR_HANDLE );
1593 if ((flags & (CREATE_NEW_CONSOLE | DETACHED_PROCESS)) != 0)
1595 /* this is temporary (for console handles). We have no way to control that the handle is invalid in child process otherwise */
1596 if (is_console_handle(req->hstdin)) req->hstdin = INVALID_HANDLE_VALUE;
1597 if (is_console_handle(req->hstdout)) req->hstdout = INVALID_HANDLE_VALUE;
1598 if (is_console_handle(req->hstderr)) req->hstderr = INVALID_HANDLE_VALUE;
1600 else
1602 if (is_console_handle(req->hstdin)) req->hstdin = console_handle_unmap(req->hstdin);
1603 if (is_console_handle(req->hstdout)) req->hstdout = console_handle_unmap(req->hstdout);
1604 if (is_console_handle(req->hstderr)) req->hstderr = console_handle_unmap(req->hstderr);
1607 wine_server_add_data( req, params, params->Size );
1608 wine_server_add_data( req, params->Environment, (env_end-params->Environment)*sizeof(WCHAR) );
1609 ret = !wine_server_call_err( req );
1610 process_info = reply->info;
1612 SERVER_END_REQ;
1614 if (!env) RtlReleasePebLock();
1615 RtlDestroyProcessParameters( params );
1616 if (!ret)
1618 close( startfd[1] );
1619 close( execfd[0] );
1620 return FALSE;
1623 /* tell child to start and wait for it to exec */
1625 write( startfd[1], &dummy, 1 );
1626 close( startfd[1] );
1628 if (read( execfd[0], &err, sizeof(err) ) > 0) /* exec failed */
1630 errno = err;
1631 FILE_SetDosError();
1632 close( execfd[0] );
1633 CloseHandle( process_info );
1634 return FALSE;
1636 close( execfd[0] );
1638 /* wait for the new process info to be ready */
1640 WaitForSingleObject( process_info, INFINITE );
1641 SERVER_START_REQ( get_new_process_info )
1643 req->info = process_info;
1644 req->pinherit = (psa && (psa->nLength >= sizeof(*psa)) && psa->bInheritHandle);
1645 req->tinherit = (tsa && (tsa->nLength >= sizeof(*tsa)) && tsa->bInheritHandle);
1646 if ((ret = !wine_server_call_err( req )))
1648 info->dwProcessId = (DWORD)reply->pid;
1649 info->dwThreadId = (DWORD)reply->tid;
1650 info->hProcess = reply->phandle;
1651 info->hThread = reply->thandle;
1652 success = reply->success;
1655 SERVER_END_REQ;
1657 if (ret && !success) /* new process failed to start */
1659 DWORD exitcode;
1660 if (GetExitCodeProcess( info->hProcess, &exitcode )) SetLastError( exitcode );
1661 CloseHandle( info->hThread );
1662 CloseHandle( info->hProcess );
1663 ret = FALSE;
1665 CloseHandle( process_info );
1666 return ret;
1670 /***********************************************************************
1671 * create_vdm_process
1673 * Create a new VDM process for a 16-bit or DOS application.
1675 static BOOL create_vdm_process( LPCWSTR filename, LPWSTR cmd_line, LPWSTR env, LPCWSTR cur_dir,
1676 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1677 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
1678 LPPROCESS_INFORMATION info, LPCSTR unixdir )
1680 static const WCHAR argsW[] = {'%','s',' ','-','-','a','p','p','-','n','a','m','e',' ','"','%','s','"',' ','%','s',0};
1682 BOOL ret;
1683 LPWSTR new_cmd_line = HeapAlloc( GetProcessHeap(), 0,
1684 (strlenW(filename) + strlenW(cmd_line) + 30) * sizeof(WCHAR) );
1686 if (!new_cmd_line)
1688 SetLastError( ERROR_OUTOFMEMORY );
1689 return FALSE;
1691 sprintfW( new_cmd_line, argsW, winevdmW, filename, cmd_line );
1692 ret = create_process( 0, winevdmW, new_cmd_line, env, cur_dir, psa, tsa, inherit,
1693 flags, startup, info, unixdir, NULL, NULL );
1694 HeapFree( GetProcessHeap(), 0, new_cmd_line );
1695 return ret;
1699 /***********************************************************************
1700 * create_cmd_process
1702 * Create a new cmd shell process for a .BAT file.
1704 static BOOL create_cmd_process( LPCWSTR filename, LPWSTR cmd_line, LPVOID env, LPCWSTR cur_dir,
1705 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1706 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
1707 LPPROCESS_INFORMATION info )
1710 static const WCHAR comspecW[] = {'C','O','M','S','P','E','C',0};
1711 static const WCHAR slashcW[] = {' ','/','c',' ',0};
1712 WCHAR comspec[MAX_PATH];
1713 WCHAR *newcmdline;
1714 BOOL ret;
1716 if (!GetEnvironmentVariableW( comspecW, comspec, sizeof(comspec)/sizeof(WCHAR) ))
1717 return FALSE;
1718 if (!(newcmdline = HeapAlloc( GetProcessHeap(), 0,
1719 (strlenW(comspec) + 4 + strlenW(cmd_line) + 1) * sizeof(WCHAR))))
1720 return FALSE;
1722 strcpyW( newcmdline, comspec );
1723 strcatW( newcmdline, slashcW );
1724 strcatW( newcmdline, cmd_line );
1725 ret = CreateProcessW( comspec, newcmdline, psa, tsa, inherit,
1726 flags, env, cur_dir, startup, info );
1727 HeapFree( GetProcessHeap(), 0, newcmdline );
1728 return ret;
1732 /*************************************************************************
1733 * get_file_name
1735 * Helper for CreateProcess: retrieve the file name to load from the
1736 * app name and command line. Store the file name in buffer, and
1737 * return a possibly modified command line.
1738 * Also returns a handle to the opened file if it's a Windows binary.
1740 static LPWSTR get_file_name( LPCWSTR appname, LPWSTR cmdline, LPWSTR buffer,
1741 int buflen, HANDLE *handle )
1743 static const WCHAR quotesW[] = {'"','%','s','"',0};
1745 WCHAR *name, *pos, *ret = NULL;
1746 const WCHAR *p;
1748 /* if we have an app name, everything is easy */
1750 if (appname)
1752 /* use the unmodified app name as file name */
1753 lstrcpynW( buffer, appname, buflen );
1754 *handle = open_exe_file( buffer );
1755 if (!(ret = cmdline) || !cmdline[0])
1757 /* no command-line, create one */
1758 if ((ret = HeapAlloc( GetProcessHeap(), 0, (strlenW(appname) + 3) * sizeof(WCHAR) )))
1759 sprintfW( ret, quotesW, appname );
1761 return ret;
1764 if (!cmdline)
1766 SetLastError( ERROR_INVALID_PARAMETER );
1767 return NULL;
1770 /* first check for a quoted file name */
1772 if ((cmdline[0] == '"') && ((p = strchrW( cmdline + 1, '"' ))))
1774 int len = p - cmdline - 1;
1775 /* extract the quoted portion as file name */
1776 if (!(name = HeapAlloc( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) ))) return NULL;
1777 memcpy( name, cmdline + 1, len * sizeof(WCHAR) );
1778 name[len] = 0;
1780 if (find_exe_file( name, buffer, buflen, handle ))
1781 ret = cmdline; /* no change necessary */
1782 goto done;
1785 /* now try the command-line word by word */
1787 if (!(name = HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline) + 1) * sizeof(WCHAR) )))
1788 return NULL;
1789 pos = name;
1790 p = cmdline;
1792 while (*p)
1794 do *pos++ = *p++; while (*p && *p != ' ');
1795 *pos = 0;
1796 if (find_exe_file( name, buffer, buflen, handle ))
1798 ret = cmdline;
1799 break;
1803 if (!ret || !strchrW( name, ' ' )) goto done; /* no change necessary */
1805 /* now build a new command-line with quotes */
1807 if (!(ret = HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline) + 3) * sizeof(WCHAR) )))
1808 goto done;
1809 sprintfW( ret, quotesW, name );
1810 strcatW( ret, p );
1812 done:
1813 HeapFree( GetProcessHeap(), 0, name );
1814 return ret;
1818 /**********************************************************************
1819 * CreateProcessA (KERNEL32.@)
1821 BOOL WINAPI CreateProcessA( LPCSTR app_name, LPSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
1822 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit,
1823 DWORD flags, LPVOID env, LPCSTR cur_dir,
1824 LPSTARTUPINFOA startup_info, LPPROCESS_INFORMATION info )
1826 BOOL ret = FALSE;
1827 WCHAR *app_nameW = NULL, *cmd_lineW = NULL, *cur_dirW = NULL;
1828 UNICODE_STRING desktopW, titleW;
1829 STARTUPINFOW infoW;
1831 desktopW.Buffer = NULL;
1832 titleW.Buffer = NULL;
1833 if (app_name && !(app_nameW = FILE_name_AtoW( app_name, TRUE ))) goto done;
1834 if (cmd_line && !(cmd_lineW = FILE_name_AtoW( cmd_line, TRUE ))) goto done;
1835 if (cur_dir && !(cur_dirW = FILE_name_AtoW( cur_dir, TRUE ))) goto done;
1837 if (startup_info->lpDesktop) RtlCreateUnicodeStringFromAsciiz( &desktopW, startup_info->lpDesktop );
1838 if (startup_info->lpTitle) RtlCreateUnicodeStringFromAsciiz( &titleW, startup_info->lpTitle );
1840 memcpy( &infoW, startup_info, sizeof(infoW) );
1841 infoW.lpDesktop = desktopW.Buffer;
1842 infoW.lpTitle = titleW.Buffer;
1844 if (startup_info->lpReserved)
1845 FIXME("StartupInfo.lpReserved is used, please report (%s)\n",
1846 debugstr_a(startup_info->lpReserved));
1848 ret = CreateProcessW( app_nameW, cmd_lineW, process_attr, thread_attr,
1849 inherit, flags, env, cur_dirW, &infoW, info );
1850 done:
1851 HeapFree( GetProcessHeap(), 0, app_nameW );
1852 HeapFree( GetProcessHeap(), 0, cmd_lineW );
1853 HeapFree( GetProcessHeap(), 0, cur_dirW );
1854 RtlFreeUnicodeString( &desktopW );
1855 RtlFreeUnicodeString( &titleW );
1856 return ret;
1860 /**********************************************************************
1861 * CreateProcessW (KERNEL32.@)
1863 BOOL WINAPI CreateProcessW( LPCWSTR app_name, LPWSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
1864 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit, DWORD flags,
1865 LPVOID env, LPCWSTR cur_dir, LPSTARTUPINFOW startup_info,
1866 LPPROCESS_INFORMATION info )
1868 BOOL retv = FALSE;
1869 HANDLE hFile = 0;
1870 char *unixdir = NULL;
1871 WCHAR name[MAX_PATH];
1872 WCHAR *tidy_cmdline, *p, *envW = env;
1873 void *res_start, *res_end;
1875 /* Process the AppName and/or CmdLine to get module name and path */
1877 TRACE("app %s cmdline %s\n", debugstr_w(app_name), debugstr_w(cmd_line) );
1879 if (!(tidy_cmdline = get_file_name( app_name, cmd_line, name, sizeof(name), &hFile )))
1880 return FALSE;
1881 if (hFile == INVALID_HANDLE_VALUE) goto done;
1883 /* Warn if unsupported features are used */
1885 if (flags & (IDLE_PRIORITY_CLASS | HIGH_PRIORITY_CLASS | REALTIME_PRIORITY_CLASS |
1886 CREATE_NEW_PROCESS_GROUP | CREATE_SEPARATE_WOW_VDM | CREATE_SHARED_WOW_VDM |
1887 CREATE_DEFAULT_ERROR_MODE | CREATE_NO_WINDOW |
1888 PROFILE_USER | PROFILE_KERNEL | PROFILE_SERVER))
1889 WARN("(%s,...): ignoring some flags in %lx\n", debugstr_w(name), flags);
1891 if (cur_dir)
1893 unixdir = wine_get_unix_file_name( cur_dir );
1895 else
1897 WCHAR buf[MAX_PATH];
1898 if (GetCurrentDirectoryW(MAX_PATH, buf)) unixdir = wine_get_unix_file_name( buf );
1901 if (env && !(flags & CREATE_UNICODE_ENVIRONMENT)) /* convert environment to unicode */
1903 char *p = env;
1904 DWORD lenW;
1906 while (*p) p += strlen(p) + 1;
1907 p++; /* final null */
1908 lenW = MultiByteToWideChar( CP_ACP, 0, env, p - (char*)env, NULL, 0 );
1909 envW = HeapAlloc( GetProcessHeap(), 0, lenW * sizeof(WCHAR) );
1910 MultiByteToWideChar( CP_ACP, 0, env, p - (char*)env, envW, lenW );
1911 flags |= CREATE_UNICODE_ENVIRONMENT;
1914 info->hThread = info->hProcess = 0;
1915 info->dwProcessId = info->dwThreadId = 0;
1917 /* Determine executable type */
1919 if (!hFile) /* builtin exe */
1921 TRACE( "starting %s as Winelib app\n", debugstr_w(name) );
1922 retv = create_process( 0, name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1923 inherit, flags, startup_info, info, unixdir, NULL, NULL );
1924 goto done;
1927 switch( MODULE_GetBinaryType( hFile, &res_start, &res_end ))
1929 case BINARY_PE_EXE:
1930 TRACE( "starting %s as Win32 binary (%p-%p)\n", debugstr_w(name), res_start, res_end );
1931 retv = create_process( hFile, name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1932 inherit, flags, startup_info, info, unixdir, res_start, res_end );
1933 break;
1934 case BINARY_OS216:
1935 case BINARY_WIN16:
1936 case BINARY_DOS:
1937 TRACE( "starting %s as Win16/DOS binary\n", debugstr_w(name) );
1938 retv = create_vdm_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1939 inherit, flags, startup_info, info, unixdir );
1940 break;
1941 case BINARY_PE_DLL:
1942 TRACE( "not starting %s since it is a dll\n", debugstr_w(name) );
1943 SetLastError( ERROR_BAD_EXE_FORMAT );
1944 break;
1945 case BINARY_UNIX_LIB:
1946 TRACE( "%s is a Unix library, starting as Winelib app\n", debugstr_w(name) );
1947 retv = create_process( hFile, name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1948 inherit, flags, startup_info, info, unixdir, NULL, NULL );
1949 break;
1950 case BINARY_UNKNOWN:
1951 /* check for .com or .bat extension */
1952 if ((p = strrchrW( name, '.' )))
1954 if (!strcmpiW( p, comW ) || !strcmpiW( p, pifW ))
1956 TRACE( "starting %s as DOS binary\n", debugstr_w(name) );
1957 retv = create_vdm_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1958 inherit, flags, startup_info, info, unixdir );
1959 break;
1961 if (!strcmpiW( p, batW ))
1963 TRACE( "starting %s as batch binary\n", debugstr_w(name) );
1964 retv = create_cmd_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1965 inherit, flags, startup_info, info );
1966 break;
1969 /* fall through */
1970 case BINARY_UNIX_EXE:
1972 /* unknown file, try as unix executable */
1973 char *unix_name;
1975 TRACE( "starting %s as Unix binary\n", debugstr_w(name) );
1977 if ((unix_name = wine_get_unix_file_name( name )))
1979 retv = (fork_and_exec( unix_name, tidy_cmdline, envW, unixdir ) != -1);
1980 HeapFree( GetProcessHeap(), 0, unix_name );
1983 break;
1985 CloseHandle( hFile );
1987 done:
1988 if (tidy_cmdline != cmd_line) HeapFree( GetProcessHeap(), 0, tidy_cmdline );
1989 if (envW != env) HeapFree( GetProcessHeap(), 0, envW );
1990 HeapFree( GetProcessHeap(), 0, unixdir );
1991 return retv;
1995 /***********************************************************************
1996 * wait_input_idle
1998 * Wrapper to call WaitForInputIdle USER function
2000 typedef DWORD (WINAPI *WaitForInputIdle_ptr)( HANDLE hProcess, DWORD dwTimeOut );
2002 static DWORD wait_input_idle( HANDLE process, DWORD timeout )
2004 HMODULE mod = GetModuleHandleA( "user32.dll" );
2005 if (mod)
2007 WaitForInputIdle_ptr ptr = (WaitForInputIdle_ptr)GetProcAddress( mod, "WaitForInputIdle" );
2008 if (ptr) return ptr( process, timeout );
2010 return 0;
2014 /***********************************************************************
2015 * WinExec (KERNEL32.@)
2017 UINT WINAPI WinExec( LPCSTR lpCmdLine, UINT nCmdShow )
2019 PROCESS_INFORMATION info;
2020 STARTUPINFOA startup;
2021 char *cmdline;
2022 UINT ret;
2024 memset( &startup, 0, sizeof(startup) );
2025 startup.cb = sizeof(startup);
2026 startup.dwFlags = STARTF_USESHOWWINDOW;
2027 startup.wShowWindow = nCmdShow;
2029 /* cmdline needs to be writeable for CreateProcess */
2030 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(lpCmdLine)+1 ))) return 0;
2031 strcpy( cmdline, lpCmdLine );
2033 if (CreateProcessA( NULL, cmdline, NULL, NULL, FALSE,
2034 0, NULL, NULL, &startup, &info ))
2036 /* Give 30 seconds to the app to come up */
2037 if (wait_input_idle( info.hProcess, 30000 ) == WAIT_FAILED)
2038 WARN("WaitForInputIdle failed: Error %ld\n", GetLastError() );
2039 ret = 33;
2040 /* Close off the handles */
2041 CloseHandle( info.hThread );
2042 CloseHandle( info.hProcess );
2044 else if ((ret = GetLastError()) >= 32)
2046 FIXME("Strange error set by CreateProcess: %d\n", ret );
2047 ret = 11;
2049 HeapFree( GetProcessHeap(), 0, cmdline );
2050 return ret;
2054 /**********************************************************************
2055 * LoadModule (KERNEL32.@)
2057 HINSTANCE WINAPI LoadModule( LPCSTR name, LPVOID paramBlock )
2059 LOADPARMS32 *params = paramBlock;
2060 PROCESS_INFORMATION info;
2061 STARTUPINFOA startup;
2062 HINSTANCE hInstance;
2063 LPSTR cmdline, p;
2064 char filename[MAX_PATH];
2065 BYTE len;
2067 if (!name) return (HINSTANCE)ERROR_FILE_NOT_FOUND;
2069 if (!SearchPathA( NULL, name, ".exe", sizeof(filename), filename, NULL ) &&
2070 !SearchPathA( NULL, name, NULL, sizeof(filename), filename, NULL ))
2071 return (HINSTANCE)GetLastError();
2073 len = (BYTE)params->lpCmdLine[0];
2074 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(filename) + len + 2 )))
2075 return (HINSTANCE)ERROR_NOT_ENOUGH_MEMORY;
2077 strcpy( cmdline, filename );
2078 p = cmdline + strlen(cmdline);
2079 *p++ = ' ';
2080 memcpy( p, params->lpCmdLine + 1, len );
2081 p[len] = 0;
2083 memset( &startup, 0, sizeof(startup) );
2084 startup.cb = sizeof(startup);
2085 if (params->lpCmdShow)
2087 startup.dwFlags = STARTF_USESHOWWINDOW;
2088 startup.wShowWindow = ((WORD *)params->lpCmdShow)[1];
2091 if (CreateProcessA( filename, cmdline, NULL, NULL, FALSE, 0,
2092 params->lpEnvAddress, NULL, &startup, &info ))
2094 /* Give 30 seconds to the app to come up */
2095 if (wait_input_idle( info.hProcess, 30000 ) == WAIT_FAILED)
2096 WARN("WaitForInputIdle failed: Error %ld\n", GetLastError() );
2097 hInstance = (HINSTANCE)33;
2098 /* Close off the handles */
2099 CloseHandle( info.hThread );
2100 CloseHandle( info.hProcess );
2102 else if ((hInstance = (HINSTANCE)GetLastError()) >= (HINSTANCE)32)
2104 FIXME("Strange error set by CreateProcess: %p\n", hInstance );
2105 hInstance = (HINSTANCE)11;
2108 HeapFree( GetProcessHeap(), 0, cmdline );
2109 return hInstance;
2113 /******************************************************************************
2114 * TerminateProcess (KERNEL32.@)
2116 BOOL WINAPI TerminateProcess( HANDLE handle, DWORD exit_code )
2118 NTSTATUS status = NtTerminateProcess( handle, exit_code );
2119 if (status) SetLastError( RtlNtStatusToDosError(status) );
2120 return !status;
2124 /***********************************************************************
2125 * ExitProcess (KERNEL32.@)
2127 void WINAPI ExitProcess( DWORD status )
2129 LdrShutdownProcess();
2130 SERVER_START_REQ( terminate_process )
2132 /* send the exit code to the server */
2133 req->handle = GetCurrentProcess();
2134 req->exit_code = status;
2135 wine_server_call( req );
2137 SERVER_END_REQ;
2138 exit( status );
2142 /***********************************************************************
2143 * GetExitCodeProcess [KERNEL32.@]
2145 * Gets termination status of specified process
2147 * RETURNS
2148 * Success: TRUE
2149 * Failure: FALSE
2151 BOOL WINAPI GetExitCodeProcess(
2152 HANDLE hProcess, /* [in] handle to the process */
2153 LPDWORD lpExitCode) /* [out] address to receive termination status */
2155 NTSTATUS status;
2156 PROCESS_BASIC_INFORMATION pbi;
2158 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
2159 sizeof(pbi), NULL);
2160 if (status == STATUS_SUCCESS)
2162 if (lpExitCode) *lpExitCode = pbi.ExitStatus;
2163 return TRUE;
2165 SetLastError( RtlNtStatusToDosError(status) );
2166 return FALSE;
2170 /***********************************************************************
2171 * SetErrorMode (KERNEL32.@)
2173 UINT WINAPI SetErrorMode( UINT mode )
2175 UINT old = process_error_mode;
2176 process_error_mode = mode;
2177 return old;
2181 /**********************************************************************
2182 * TlsAlloc [KERNEL32.@] Allocates a TLS index.
2184 * Allocates a thread local storage index
2186 * RETURNS
2187 * Success: TLS Index
2188 * Failure: 0xFFFFFFFF
2190 DWORD WINAPI TlsAlloc( void )
2192 DWORD index;
2193 PEB * const peb = NtCurrentTeb()->Peb;
2195 RtlAcquirePebLock();
2196 index = RtlFindClearBitsAndSet( peb->TlsBitmap, 1, 0 );
2197 if (index != ~0UL) NtCurrentTeb()->TlsSlots[index] = 0; /* clear the value */
2198 else
2200 index = RtlFindClearBitsAndSet( peb->TlsExpansionBitmap, 1, 0 );
2201 if (index != ~0UL)
2203 if (!NtCurrentTeb()->TlsExpansionSlots &&
2204 !(NtCurrentTeb()->TlsExpansionSlots = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY,
2205 8 * sizeof(peb->TlsExpansionBitmapBits) * sizeof(void*) )))
2207 RtlClearBits( peb->TlsExpansionBitmap, index, 1 );
2208 index = ~0UL;
2209 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
2211 else
2213 NtCurrentTeb()->TlsExpansionSlots[index] = 0; /* clear the value */
2214 index += TLS_MINIMUM_AVAILABLE;
2217 else SetLastError( ERROR_NO_MORE_ITEMS );
2219 RtlReleasePebLock();
2220 return index;
2224 /**********************************************************************
2225 * TlsFree [KERNEL32.@] Releases a TLS index.
2227 * Releases a thread local storage index, making it available for reuse
2229 * RETURNS
2230 * Success: TRUE
2231 * Failure: FALSE
2233 BOOL WINAPI TlsFree(
2234 DWORD index) /* [in] TLS Index to free */
2236 BOOL ret;
2238 RtlAcquirePebLock();
2239 if (index >= TLS_MINIMUM_AVAILABLE)
2241 ret = RtlAreBitsSet( NtCurrentTeb()->Peb->TlsExpansionBitmap, index - TLS_MINIMUM_AVAILABLE, 1 );
2242 if (ret) RtlClearBits( NtCurrentTeb()->Peb->TlsExpansionBitmap, index - TLS_MINIMUM_AVAILABLE, 1 );
2244 else
2246 ret = RtlAreBitsSet( NtCurrentTeb()->Peb->TlsBitmap, index, 1 );
2247 if (ret) RtlClearBits( NtCurrentTeb()->Peb->TlsBitmap, index, 1 );
2249 if (ret) NtSetInformationThread( GetCurrentThread(), ThreadZeroTlsCell, &index, sizeof(index) );
2250 else SetLastError( ERROR_INVALID_PARAMETER );
2251 RtlReleasePebLock();
2252 return TRUE;
2256 /**********************************************************************
2257 * TlsGetValue [KERNEL32.@] Gets value in a thread's TLS slot
2259 * RETURNS
2260 * Success: Value stored in calling thread's TLS slot for index
2261 * Failure: 0 and GetLastError() returns NO_ERROR
2263 LPVOID WINAPI TlsGetValue(
2264 DWORD index) /* [in] TLS index to retrieve value for */
2266 LPVOID ret;
2268 if (index < TLS_MINIMUM_AVAILABLE)
2270 ret = NtCurrentTeb()->TlsSlots[index];
2272 else
2274 index -= TLS_MINIMUM_AVAILABLE;
2275 if (index >= 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits))
2277 SetLastError( ERROR_INVALID_PARAMETER );
2278 return NULL;
2280 if (!NtCurrentTeb()->TlsExpansionSlots) ret = NULL;
2281 else ret = NtCurrentTeb()->TlsExpansionSlots[index];
2283 SetLastError( ERROR_SUCCESS );
2284 return ret;
2288 /**********************************************************************
2289 * TlsSetValue [KERNEL32.@] Stores a value in the thread's TLS slot.
2291 * RETURNS
2292 * Success: TRUE
2293 * Failure: FALSE
2295 BOOL WINAPI TlsSetValue(
2296 DWORD index, /* [in] TLS index to set value for */
2297 LPVOID value) /* [in] Value to be stored */
2299 if (index < TLS_MINIMUM_AVAILABLE)
2301 NtCurrentTeb()->TlsSlots[index] = value;
2303 else
2305 index -= TLS_MINIMUM_AVAILABLE;
2306 if (index >= 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits))
2308 SetLastError( ERROR_INVALID_PARAMETER );
2309 return FALSE;
2311 if (!NtCurrentTeb()->TlsExpansionSlots &&
2312 !(NtCurrentTeb()->TlsExpansionSlots = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY,
2313 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits) * sizeof(void*) )))
2315 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
2316 return FALSE;
2318 NtCurrentTeb()->TlsExpansionSlots[index] = value;
2320 return TRUE;
2324 /***********************************************************************
2325 * GetProcessFlags (KERNEL32.@)
2327 DWORD WINAPI GetProcessFlags( DWORD processid )
2329 IMAGE_NT_HEADERS *nt;
2330 DWORD flags = 0;
2332 if (processid && processid != GetCurrentProcessId()) return 0;
2334 if ((nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress )))
2336 if (nt->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_CUI)
2337 flags |= PDB32_CONSOLE_PROC;
2339 if (!AreFileApisANSI()) flags |= PDB32_FILE_APIS_OEM;
2340 if (IsDebuggerPresent()) flags |= PDB32_DEBUGGED;
2341 return flags;
2345 /***********************************************************************
2346 * GetProcessDword (KERNEL.485)
2347 * GetProcessDword (KERNEL32.18)
2348 * 'Of course you cannot directly access Windows internal structures'
2350 DWORD WINAPI GetProcessDword( DWORD dwProcessID, INT offset )
2352 DWORD x, y;
2353 STARTUPINFOW siw;
2355 TRACE("(%ld, %d)\n", dwProcessID, offset );
2357 if (dwProcessID && dwProcessID != GetCurrentProcessId())
2359 ERR("%d: process %lx not accessible\n", offset, dwProcessID);
2360 return 0;
2363 switch ( offset )
2365 case GPD_APP_COMPAT_FLAGS:
2366 return GetAppCompatFlags16(0);
2367 case GPD_LOAD_DONE_EVENT:
2368 return 0;
2369 case GPD_HINSTANCE16:
2370 return GetTaskDS16();
2371 case GPD_WINDOWS_VERSION:
2372 return GetExeVersion16();
2373 case GPD_THDB:
2374 return (DWORD)NtCurrentTeb() - 0x10 /* FIXME */;
2375 case GPD_PDB:
2376 return (DWORD)NtCurrentTeb()->Peb;
2377 case GPD_STARTF_SHELLDATA: /* return stdoutput handle from startupinfo ??? */
2378 GetStartupInfoW(&siw);
2379 return (DWORD)siw.hStdOutput;
2380 case GPD_STARTF_HOTKEY: /* return stdinput handle from startupinfo ??? */
2381 GetStartupInfoW(&siw);
2382 return (DWORD)siw.hStdInput;
2383 case GPD_STARTF_SHOWWINDOW:
2384 GetStartupInfoW(&siw);
2385 return siw.wShowWindow;
2386 case GPD_STARTF_SIZE:
2387 GetStartupInfoW(&siw);
2388 x = siw.dwXSize;
2389 if ( (INT)x == CW_USEDEFAULT ) x = CW_USEDEFAULT16;
2390 y = siw.dwYSize;
2391 if ( (INT)y == CW_USEDEFAULT ) y = CW_USEDEFAULT16;
2392 return MAKELONG( x, y );
2393 case GPD_STARTF_POSITION:
2394 GetStartupInfoW(&siw);
2395 x = siw.dwX;
2396 if ( (INT)x == CW_USEDEFAULT ) x = CW_USEDEFAULT16;
2397 y = siw.dwY;
2398 if ( (INT)y == CW_USEDEFAULT ) y = CW_USEDEFAULT16;
2399 return MAKELONG( x, y );
2400 case GPD_STARTF_FLAGS:
2401 GetStartupInfoW(&siw);
2402 return siw.dwFlags;
2403 case GPD_PARENT:
2404 return 0;
2405 case GPD_FLAGS:
2406 return GetProcessFlags(0);
2407 case GPD_USERDATA:
2408 return process_dword;
2409 default:
2410 ERR("Unknown offset %d\n", offset );
2411 return 0;
2415 /***********************************************************************
2416 * SetProcessDword (KERNEL.484)
2417 * 'Of course you cannot directly access Windows internal structures'
2419 void WINAPI SetProcessDword( DWORD dwProcessID, INT offset, DWORD value )
2421 TRACE("(%ld, %d)\n", dwProcessID, offset );
2423 if (dwProcessID && dwProcessID != GetCurrentProcessId())
2425 ERR("%d: process %lx not accessible\n", offset, dwProcessID);
2426 return;
2429 switch ( offset )
2431 case GPD_APP_COMPAT_FLAGS:
2432 case GPD_LOAD_DONE_EVENT:
2433 case GPD_HINSTANCE16:
2434 case GPD_WINDOWS_VERSION:
2435 case GPD_THDB:
2436 case GPD_PDB:
2437 case GPD_STARTF_SHELLDATA:
2438 case GPD_STARTF_HOTKEY:
2439 case GPD_STARTF_SHOWWINDOW:
2440 case GPD_STARTF_SIZE:
2441 case GPD_STARTF_POSITION:
2442 case GPD_STARTF_FLAGS:
2443 case GPD_PARENT:
2444 case GPD_FLAGS:
2445 ERR("Not allowed to modify offset %d\n", offset );
2446 break;
2447 case GPD_USERDATA:
2448 process_dword = value;
2449 break;
2450 default:
2451 ERR("Unknown offset %d\n", offset );
2452 break;
2457 /***********************************************************************
2458 * ExitProcess (KERNEL.466)
2460 void WINAPI ExitProcess16( WORD status )
2462 DWORD count;
2463 ReleaseThunkLock( &count );
2464 ExitProcess( status );
2468 /*********************************************************************
2469 * OpenProcess (KERNEL32.@)
2471 HANDLE WINAPI OpenProcess( DWORD access, BOOL inherit, DWORD id )
2473 HANDLE ret = 0;
2474 SERVER_START_REQ( open_process )
2476 req->pid = id;
2477 req->access = access;
2478 req->inherit = inherit;
2479 if (!wine_server_call_err( req )) ret = reply->handle;
2481 SERVER_END_REQ;
2482 return ret;
2486 /*********************************************************************
2487 * MapProcessHandle (KERNEL.483)
2488 * GetProcessId (KERNEL32.@)
2490 DWORD WINAPI GetProcessId( HANDLE hProcess )
2492 NTSTATUS status;
2493 PROCESS_BASIC_INFORMATION pbi;
2495 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
2496 sizeof(pbi), NULL);
2497 if (status == STATUS_SUCCESS) return pbi.UniqueProcessId;
2498 SetLastError( RtlNtStatusToDosError(status) );
2499 return 0;
2503 /*********************************************************************
2504 * CloseW32Handle (KERNEL.474)
2505 * CloseHandle (KERNEL32.@)
2507 BOOL WINAPI CloseHandle( HANDLE handle )
2509 NTSTATUS status;
2511 /* stdio handles need special treatment */
2512 if ((handle == (HANDLE)STD_INPUT_HANDLE) ||
2513 (handle == (HANDLE)STD_OUTPUT_HANDLE) ||
2514 (handle == (HANDLE)STD_ERROR_HANDLE))
2515 handle = GetStdHandle( (DWORD)handle );
2517 if (is_console_handle(handle))
2518 return CloseConsoleHandle(handle);
2520 status = NtClose( handle );
2521 if (status) SetLastError( RtlNtStatusToDosError(status) );
2522 return !status;
2526 /*********************************************************************
2527 * GetHandleInformation (KERNEL32.@)
2529 BOOL WINAPI GetHandleInformation( HANDLE handle, LPDWORD flags )
2531 BOOL ret;
2532 SERVER_START_REQ( set_handle_info )
2534 req->handle = handle;
2535 req->flags = 0;
2536 req->mask = 0;
2537 req->fd = -1;
2538 ret = !wine_server_call_err( req );
2539 if (ret && flags) *flags = reply->old_flags;
2541 SERVER_END_REQ;
2542 return ret;
2546 /*********************************************************************
2547 * SetHandleInformation (KERNEL32.@)
2549 BOOL WINAPI SetHandleInformation( HANDLE handle, DWORD mask, DWORD flags )
2551 BOOL ret;
2552 SERVER_START_REQ( set_handle_info )
2554 req->handle = handle;
2555 req->flags = flags;
2556 req->mask = mask;
2557 req->fd = -1;
2558 ret = !wine_server_call_err( req );
2560 SERVER_END_REQ;
2561 return ret;
2565 /*********************************************************************
2566 * DuplicateHandle (KERNEL32.@)
2568 BOOL WINAPI DuplicateHandle( HANDLE source_process, HANDLE source,
2569 HANDLE dest_process, HANDLE *dest,
2570 DWORD access, BOOL inherit, DWORD options )
2572 NTSTATUS status;
2574 if (is_console_handle(source))
2576 /* FIXME: this test is not sufficient, we need to test process ids, not handles */
2577 if (source_process != dest_process ||
2578 source_process != GetCurrentProcess())
2580 SetLastError(ERROR_INVALID_PARAMETER);
2581 return FALSE;
2583 *dest = DuplicateConsoleHandle( source, access, inherit, options );
2584 return (*dest != INVALID_HANDLE_VALUE);
2586 status = NtDuplicateObject( source_process, source, dest_process, dest,
2587 access, inherit ? OBJ_INHERIT : 0, options );
2588 if (status) SetLastError( RtlNtStatusToDosError(status) );
2589 return !status;
2593 /***********************************************************************
2594 * ConvertToGlobalHandle (KERNEL.476)
2595 * ConvertToGlobalHandle (KERNEL32.@)
2597 HANDLE WINAPI ConvertToGlobalHandle(HANDLE hSrc)
2599 HANDLE ret = INVALID_HANDLE_VALUE;
2600 DuplicateHandle( GetCurrentProcess(), hSrc, GetCurrentProcess(), &ret, 0, FALSE,
2601 DUP_HANDLE_MAKE_GLOBAL | DUP_HANDLE_SAME_ACCESS | DUP_HANDLE_CLOSE_SOURCE );
2602 return ret;
2606 /***********************************************************************
2607 * SetHandleContext (KERNEL32.@)
2609 BOOL WINAPI SetHandleContext(HANDLE hnd,DWORD context)
2611 FIXME("(%p,%ld), stub. In case this got called by WSOCK32/WS2_32: "
2612 "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd,context);
2613 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2614 return FALSE;
2618 /***********************************************************************
2619 * GetHandleContext (KERNEL32.@)
2621 DWORD WINAPI GetHandleContext(HANDLE hnd)
2623 FIXME("(%p), stub. In case this got called by WSOCK32/WS2_32: "
2624 "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd);
2625 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2626 return 0;
2630 /***********************************************************************
2631 * CreateSocketHandle (KERNEL32.@)
2633 HANDLE WINAPI CreateSocketHandle(void)
2635 FIXME("(), stub. In case this got called by WSOCK32/WS2_32: "
2636 "the external WINSOCK DLLs won't work with WINE, don't use them.\n");
2637 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2638 return INVALID_HANDLE_VALUE;
2642 /***********************************************************************
2643 * SetPriorityClass (KERNEL32.@)
2645 BOOL WINAPI SetPriorityClass( HANDLE hprocess, DWORD priorityclass )
2647 BOOL ret;
2648 SERVER_START_REQ( set_process_info )
2650 req->handle = hprocess;
2651 req->priority = priorityclass;
2652 req->mask = SET_PROCESS_INFO_PRIORITY;
2653 ret = !wine_server_call_err( req );
2655 SERVER_END_REQ;
2656 return ret;
2660 /***********************************************************************
2661 * GetPriorityClass (KERNEL32.@)
2663 DWORD WINAPI GetPriorityClass(HANDLE hProcess)
2665 NTSTATUS status;
2666 PROCESS_BASIC_INFORMATION pbi;
2668 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
2669 sizeof(pbi), NULL);
2670 if (status == STATUS_SUCCESS) return pbi.BasePriority;
2671 SetLastError( RtlNtStatusToDosError(status) );
2672 return 0;
2676 /***********************************************************************
2677 * SetProcessAffinityMask (KERNEL32.@)
2679 BOOL WINAPI SetProcessAffinityMask( HANDLE hProcess, DWORD_PTR affmask )
2681 BOOL ret;
2682 SERVER_START_REQ( set_process_info )
2684 req->handle = hProcess;
2685 req->affinity = affmask;
2686 req->mask = SET_PROCESS_INFO_AFFINITY;
2687 ret = !wine_server_call_err( req );
2689 SERVER_END_REQ;
2690 return ret;
2694 /**********************************************************************
2695 * GetProcessAffinityMask (KERNEL32.@)
2697 BOOL WINAPI GetProcessAffinityMask( HANDLE hProcess,
2698 LPDWORD lpProcessAffinityMask,
2699 LPDWORD lpSystemAffinityMask )
2701 BOOL ret = FALSE;
2702 SERVER_START_REQ( get_process_info )
2704 req->handle = hProcess;
2705 if (!wine_server_call_err( req ))
2707 if (lpProcessAffinityMask) *lpProcessAffinityMask = reply->process_affinity;
2708 if (lpSystemAffinityMask) *lpSystemAffinityMask = reply->system_affinity;
2709 ret = TRUE;
2712 SERVER_END_REQ;
2713 return ret;
2717 /***********************************************************************
2718 * GetProcessVersion (KERNEL32.@)
2720 DWORD WINAPI GetProcessVersion( DWORD processid )
2722 IMAGE_NT_HEADERS *nt;
2724 if (processid && processid != GetCurrentProcessId())
2726 FIXME("should use ReadProcessMemory\n");
2727 return 0;
2729 if ((nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress )))
2730 return ((nt->OptionalHeader.MajorSubsystemVersion << 16) |
2731 nt->OptionalHeader.MinorSubsystemVersion);
2732 return 0;
2736 /***********************************************************************
2737 * SetProcessWorkingSetSize [KERNEL32.@]
2738 * Sets the min/max working set sizes for a specified process.
2740 * PARAMS
2741 * hProcess [I] Handle to the process of interest
2742 * minset [I] Specifies minimum working set size
2743 * maxset [I] Specifies maximum working set size
2745 * RETURNS
2746 * Success: TRUE
2747 * Failure: FALSE
2749 BOOL WINAPI SetProcessWorkingSetSize(HANDLE hProcess, SIZE_T minset,
2750 SIZE_T maxset)
2752 FIXME("(%p,%ld,%ld): stub - harmless\n",hProcess,minset,maxset);
2753 if(( minset == (SIZE_T)-1) && (maxset == (SIZE_T)-1)) {
2754 /* Trim the working set to zero */
2755 /* Swap the process out of physical RAM */
2757 return TRUE;
2760 /***********************************************************************
2761 * GetProcessWorkingSetSize (KERNEL32.@)
2763 BOOL WINAPI GetProcessWorkingSetSize(HANDLE hProcess, PSIZE_T minset,
2764 PSIZE_T maxset)
2766 FIXME("(%p,%p,%p): stub\n",hProcess,minset,maxset);
2767 /* 32 MB working set size */
2768 if (minset) *minset = 32*1024*1024;
2769 if (maxset) *maxset = 32*1024*1024;
2770 return TRUE;
2774 /***********************************************************************
2775 * SetProcessShutdownParameters (KERNEL32.@)
2777 BOOL WINAPI SetProcessShutdownParameters(DWORD level, DWORD flags)
2779 FIXME("(%08lx, %08lx): partial stub.\n", level, flags);
2780 shutdown_flags = flags;
2781 shutdown_priority = level;
2782 return TRUE;
2786 /***********************************************************************
2787 * GetProcessShutdownParameters (KERNEL32.@)
2790 BOOL WINAPI GetProcessShutdownParameters( LPDWORD lpdwLevel, LPDWORD lpdwFlags )
2792 *lpdwLevel = shutdown_priority;
2793 *lpdwFlags = shutdown_flags;
2794 return TRUE;
2798 /***********************************************************************
2799 * GetProcessPriorityBoost (KERNEL32.@)
2801 BOOL WINAPI GetProcessPriorityBoost(HANDLE hprocess,PBOOL pDisablePriorityBoost)
2803 FIXME("(%p,%p): semi-stub\n", hprocess, pDisablePriorityBoost);
2805 /* Report that no boost is present.. */
2806 *pDisablePriorityBoost = FALSE;
2808 return TRUE;
2811 /***********************************************************************
2812 * SetProcessPriorityBoost (KERNEL32.@)
2814 BOOL WINAPI SetProcessPriorityBoost(HANDLE hprocess,BOOL disableboost)
2816 FIXME("(%p,%d): stub\n",hprocess,disableboost);
2817 /* Say we can do it. I doubt the program will notice that we don't. */
2818 return TRUE;
2822 /***********************************************************************
2823 * ReadProcessMemory (KERNEL32.@)
2825 BOOL WINAPI ReadProcessMemory( HANDLE process, LPCVOID addr, LPVOID buffer, SIZE_T size,
2826 SIZE_T *bytes_read )
2828 NTSTATUS status = NtReadVirtualMemory( process, addr, buffer, size, bytes_read );
2829 if (status) SetLastError( RtlNtStatusToDosError(status) );
2830 return !status;
2834 /***********************************************************************
2835 * WriteProcessMemory (KERNEL32.@)
2837 BOOL WINAPI WriteProcessMemory( HANDLE process, LPVOID addr, LPCVOID buffer, SIZE_T size,
2838 SIZE_T *bytes_written )
2840 NTSTATUS status = NtWriteVirtualMemory( process, addr, buffer, size, bytes_written );
2841 if (status) SetLastError( RtlNtStatusToDosError(status) );
2842 return !status;
2846 /****************************************************************************
2847 * FlushInstructionCache (KERNEL32.@)
2849 BOOL WINAPI FlushInstructionCache(HANDLE hProcess, LPCVOID lpBaseAddress, SIZE_T dwSize)
2851 NTSTATUS status;
2852 if (GetVersion() & 0x80000000) return TRUE; /* not NT, always TRUE */
2853 status = NtFlushInstructionCache( hProcess, lpBaseAddress, dwSize );
2854 if (status) SetLastError( RtlNtStatusToDosError(status) );
2855 return !status;
2859 /******************************************************************
2860 * GetProcessIoCounters (KERNEL32.@)
2862 BOOL WINAPI GetProcessIoCounters(HANDLE hProcess, PIO_COUNTERS ioc)
2864 NTSTATUS status;
2866 status = NtQueryInformationProcess(hProcess, ProcessIoCounters,
2867 ioc, sizeof(*ioc), NULL);
2868 if (status) SetLastError( RtlNtStatusToDosError(status) );
2869 return !status;
2872 /***********************************************************************
2873 * ProcessIdToSessionId (KERNEL32.@)
2874 * This function is available on Terminal Server 4SP4 and Windows 2000
2876 BOOL WINAPI ProcessIdToSessionId( DWORD procid, DWORD *sessionid_ptr )
2878 /* According to MSDN, if the calling process is not in a terminal
2879 * services environment, then the sessionid returned is zero.
2881 *sessionid_ptr = 0;
2882 return TRUE;
2886 /***********************************************************************
2887 * RegisterServiceProcess (KERNEL.491)
2888 * RegisterServiceProcess (KERNEL32.@)
2890 * A service process calls this function to ensure that it continues to run
2891 * even after a user logged off.
2893 DWORD WINAPI RegisterServiceProcess(DWORD dwProcessId, DWORD dwType)
2895 /* I don't think that Wine needs to do anything in this function */
2896 return 1; /* success */
2900 /***********************************************************************
2901 * GetSystemMSecCount (SYSTEM.6)
2902 * GetTickCount (KERNEL32.@)
2904 * Get the number of milliseconds the system has been running.
2906 * PARANS
2907 * None.
2909 * RETURNS
2910 * The current tick count.
2912 * NOTES
2913 * -The value returned will wrap arounf every 2^32 milliseconds.
2914 * -Under Windows, tick 0 is the moment at which the system is rebooted.
2915 * Under Wine, tick 0 begins at the moment the wineserver process is started,
2917 DWORD WINAPI GetTickCount(void)
2919 struct timeval t;
2920 gettimeofday( &t, NULL );
2921 return ((t.tv_sec * 1000) + (t.tv_usec / 1000)) - server_startticks;
2925 /***********************************************************************
2926 * GetCurrentProcess (KERNEL32.@)
2928 * Get a handle to the current process.
2930 * PARAMS
2931 * None.
2933 * RETURNS
2934 * A handle representing the current process.
2936 #undef GetCurrentProcess
2937 HANDLE WINAPI GetCurrentProcess(void)
2939 return (HANDLE)0xffffffff;