Added YUV routines needed for v4l driver, and in the future possibly
[wine/gsoc-2012-control.git] / dlls / kernel / process.c
blob5c63387b8cc077035315a1f489d40ff0dfc86836
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 "thread.h"
41 #include "module.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(file);
50 WINE_DECLARE_DEBUG_CHANNEL(server);
51 WINE_DECLARE_DEBUG_CHANNEL(relay);
53 typedef struct
55 LPSTR lpEnvAddress;
56 LPSTR lpCmdLine;
57 LPSTR lpCmdShow;
58 DWORD dwReserved;
59 } LOADPARMS32;
61 static UINT process_error_mode;
63 static HANDLE main_exe_file;
64 static DWORD shutdown_flags = 0;
65 static DWORD shutdown_priority = 0x280;
66 static DWORD process_dword;
68 static unsigned int server_startticks;
69 int main_create_flags = 0;
70 HMODULE kernel32_handle = 0;
72 const WCHAR *DIR_Windows = NULL;
73 const WCHAR *DIR_System = NULL;
75 /* Process flags */
76 #define PDB32_DEBUGGED 0x0001 /* Process is being debugged */
77 #define PDB32_WIN16_PROC 0x0008 /* Win16 process */
78 #define PDB32_DOS_PROC 0x0010 /* Dos process */
79 #define PDB32_CONSOLE_PROC 0x0020 /* Console process */
80 #define PDB32_FILE_APIS_OEM 0x0040 /* File APIs are OEM */
81 #define PDB32_WIN32S_PROC 0x8000 /* Win32s process */
83 static const WCHAR comW[] = {'.','c','o','m',0};
84 static const WCHAR batW[] = {'.','b','a','t',0};
85 static const WCHAR pifW[] = {'.','p','i','f',0};
86 static const WCHAR winevdmW[] = {'w','i','n','e','v','d','m','.','e','x','e',0};
88 extern void SHELL_LoadRegistry(void);
89 extern void convert_old_config(void);
90 extern void VERSION_Init( const WCHAR *appname );
91 extern void LOCALE_Init(void);
93 /***********************************************************************
94 * contains_path
96 inline static int contains_path( LPCWSTR name )
98 return ((*name && (name[1] == ':')) || strchrW(name, '/') || strchrW(name, '\\'));
102 /***********************************************************************
103 * is_special_env_var
105 * Check if an environment variable needs to be handled specially when
106 * passed through the Unix environment (i.e. prefixed with "WINE").
108 inline static int is_special_env_var( const char *var )
110 return (!strncmp( var, "PATH=", sizeof("PATH=")-1 ) ||
111 !strncmp( var, "HOME=", sizeof("HOME=")-1 ) ||
112 !strncmp( var, "TEMP=", sizeof("TEMP=")-1 ) ||
113 !strncmp( var, "TMP=", sizeof("TMP=")-1 ));
117 /***************************************************************************
118 * get_builtin_path
120 * Get the path of a builtin module when the native file does not exist.
122 static BOOL get_builtin_path( const WCHAR *libname, const WCHAR *ext, WCHAR *filename, UINT size )
124 WCHAR *file_part;
125 UINT len = strlenW( DIR_System );
127 if (contains_path( libname ))
129 if (RtlGetFullPathName_U( libname, size * sizeof(WCHAR),
130 filename, &file_part ) > size * sizeof(WCHAR))
131 return FALSE; /* too long */
133 if (strncmpiW( filename, DIR_System, len ) || filename[len] != '\\')
134 return FALSE;
135 while (filename[len] == '\\') len++;
136 if (filename + len != file_part) return FALSE;
138 else
140 if (strlenW(libname) + len + 2 >= size) return FALSE; /* too long */
141 memcpy( filename, DIR_System, len * sizeof(WCHAR) );
142 file_part = filename + len;
143 if (file_part > filename && file_part[-1] != '\\') *file_part++ = '\\';
144 strcpyW( file_part, libname );
146 if (ext && !strchrW( file_part, '.' ))
148 if (file_part + strlenW(file_part) + strlenW(ext) + 1 > filename + size)
149 return FALSE; /* too long */
150 strcatW( file_part, ext );
152 return TRUE;
156 /***********************************************************************
157 * open_builtin_exe_file
159 * Open an exe file for a builtin exe.
161 static void *open_builtin_exe_file( const WCHAR *name, char *error, int error_size,
162 int test_only, int *file_exists )
164 char exename[MAX_PATH];
165 WCHAR *p;
166 UINT i, len;
168 if ((p = strrchrW( name, '/' ))) name = p + 1;
169 if ((p = strrchrW( name, '\\' ))) name = p + 1;
171 /* we don't want to depend on the current codepage here */
172 len = strlenW( name ) + 1;
173 if (len >= sizeof(exename)) return NULL;
174 for (i = 0; i < len; i++)
176 if (name[i] > 127) return NULL;
177 exename[i] = (char)name[i];
178 if (exename[i] >= 'A' && exename[i] <= 'Z') exename[i] += 'a' - 'A';
180 return wine_dll_load_main_exe( exename, error, error_size, test_only, file_exists );
184 /***********************************************************************
185 * open_exe_file
187 * Open a specific exe file, taking load order into account.
188 * Returns the file handle or 0 for a builtin exe.
190 static HANDLE open_exe_file( const WCHAR *name )
192 enum loadorder_type loadorder[LOADORDER_NTYPES];
193 WCHAR buffer[MAX_PATH];
194 HANDLE handle;
195 int i, file_exists;
197 TRACE("looking for %s\n", debugstr_w(name) );
199 if ((handle = CreateFileW( name, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_DELETE,
200 NULL, OPEN_EXISTING, 0, 0 )) == INVALID_HANDLE_VALUE)
202 /* file doesn't exist, check for builtin */
203 if (!contains_path( name )) goto error;
204 if (!get_builtin_path( name, NULL, buffer, sizeof(buffer) )) goto error;
205 name = buffer;
208 MODULE_GetLoadOrderW( loadorder, NULL, name );
210 for(i = 0; i < LOADORDER_NTYPES; i++)
212 if (loadorder[i] == LOADORDER_INVALID) break;
213 switch(loadorder[i])
215 case LOADORDER_DLL:
216 TRACE( "Trying native exe %s\n", debugstr_w(name) );
217 if (handle != INVALID_HANDLE_VALUE) return handle;
218 break;
219 case LOADORDER_BI:
220 TRACE( "Trying built-in exe %s\n", debugstr_w(name) );
221 open_builtin_exe_file( name, NULL, 0, 1, &file_exists );
222 if (file_exists)
224 if (handle != INVALID_HANDLE_VALUE) CloseHandle(handle);
225 return 0;
227 default:
228 break;
231 if (handle != INVALID_HANDLE_VALUE) CloseHandle(handle);
233 error:
234 SetLastError( ERROR_FILE_NOT_FOUND );
235 return INVALID_HANDLE_VALUE;
239 /***********************************************************************
240 * find_exe_file
242 * Open an exe file, and return the full name and file handle.
243 * Returns FALSE if file could not be found.
244 * If file exists but cannot be opened, returns TRUE and set handle to INVALID_HANDLE_VALUE.
245 * If file is a builtin exe, returns TRUE and sets handle to 0.
247 static BOOL find_exe_file( const WCHAR *name, WCHAR *buffer, int buflen, HANDLE *handle )
249 static const WCHAR exeW[] = {'.','e','x','e',0};
251 enum loadorder_type loadorder[LOADORDER_NTYPES];
252 int i, file_exists;
254 TRACE("looking for %s\n", debugstr_w(name) );
256 if (!SearchPathW( NULL, name, exeW, buflen, buffer, NULL ) &&
257 !get_builtin_path( name, exeW, buffer, buflen ))
259 /* no builtin found, try native without extension in case it is a Unix app */
261 if (SearchPathW( NULL, name, NULL, buflen, buffer, NULL ))
263 TRACE( "Trying native/Unix binary %s\n", debugstr_w(buffer) );
264 if ((*handle = CreateFileW( buffer, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_DELETE,
265 NULL, OPEN_EXISTING, 0, 0 )) != INVALID_HANDLE_VALUE)
266 return TRUE;
268 return FALSE;
271 MODULE_GetLoadOrderW( loadorder, NULL, buffer );
273 for(i = 0; i < LOADORDER_NTYPES; i++)
275 if (loadorder[i] == LOADORDER_INVALID) break;
276 switch(loadorder[i])
278 case LOADORDER_DLL:
279 TRACE( "Trying native exe %s\n", debugstr_w(buffer) );
280 if ((*handle = CreateFileW( buffer, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_DELETE,
281 NULL, OPEN_EXISTING, 0, 0 )) != INVALID_HANDLE_VALUE)
282 return TRUE;
283 if (GetLastError() != ERROR_FILE_NOT_FOUND) return TRUE;
284 break;
285 case LOADORDER_BI:
286 TRACE( "Trying built-in exe %s\n", debugstr_w(buffer) );
287 open_builtin_exe_file( buffer, NULL, 0, 1, &file_exists );
288 if (file_exists)
290 *handle = 0;
291 return TRUE;
293 break;
294 default:
295 break;
298 SetLastError( ERROR_FILE_NOT_FOUND );
299 return FALSE;
303 /**********************************************************************
304 * load_pe_exe
306 * Load a PE format EXE file.
308 static HMODULE load_pe_exe( const WCHAR *name, HANDLE file )
310 IO_STATUS_BLOCK io;
311 FILE_FS_DEVICE_INFORMATION device_info;
312 IMAGE_NT_HEADERS *nt;
313 HANDLE mapping;
314 void *module;
315 OBJECT_ATTRIBUTES attr;
316 LARGE_INTEGER size;
317 DWORD len = 0;
319 attr.Length = sizeof(attr);
320 attr.RootDirectory = 0;
321 attr.ObjectName = NULL;
322 attr.Attributes = 0;
323 attr.SecurityDescriptor = NULL;
324 attr.SecurityQualityOfService = NULL;
325 size.QuadPart = 0;
327 if (NtCreateSection( &mapping, STANDARD_RIGHTS_REQUIRED | SECTION_QUERY | SECTION_MAP_READ,
328 &attr, &size, 0, SEC_IMAGE, file ) != STATUS_SUCCESS)
329 return NULL;
331 module = NULL;
332 if (NtMapViewOfSection( mapping, GetCurrentProcess(), &module, 0, 0, &size, &len,
333 ViewShare, 0, PAGE_READONLY ) != STATUS_SUCCESS)
334 return NULL;
336 NtClose( mapping );
338 /* virus check */
339 nt = RtlImageNtHeader( module );
340 if (nt->OptionalHeader.AddressOfEntryPoint)
342 if (!RtlImageRvaToSection( nt, module, nt->OptionalHeader.AddressOfEntryPoint ))
343 MESSAGE("VIRUS WARNING: PE module %s has an invalid entrypoint (0x%08lx) "
344 "outside all sections (possibly infected by Tchernobyl/SpaceFiller virus)!\n",
345 debugstr_w(name), nt->OptionalHeader.AddressOfEntryPoint );
348 if (NtQueryVolumeInformationFile( file, &io, &device_info, sizeof(device_info),
349 FileFsDeviceInformation ) == STATUS_SUCCESS)
351 /* don't keep the file handle open on removable media */
352 if (device_info.Characteristics & FILE_REMOVABLE_MEDIA)
354 CloseHandle( main_exe_file );
355 main_exe_file = 0;
359 return module;
362 /***********************************************************************
363 * build_initial_environment
365 * Build the Win32 environment from the Unix environment
367 static BOOL build_initial_environment( char **environ )
369 ULONG size = 1;
370 char **e;
371 WCHAR *p, *endptr;
372 void *ptr;
374 /* Compute the total size of the Unix environment */
375 for (e = environ; *e; e++)
377 if (is_special_env_var( *e )) continue;
378 size += MultiByteToWideChar( CP_UNIXCP, 0, *e, -1, NULL, 0 );
380 size *= sizeof(WCHAR);
382 /* Now allocate the environment */
383 ptr = NULL;
384 if (NtAllocateVirtualMemory(NtCurrentProcess(), &ptr, 0, &size,
385 MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) != STATUS_SUCCESS)
386 return FALSE;
388 NtCurrentTeb()->Peb->ProcessParameters->Environment = p = ptr;
389 endptr = p + size / sizeof(WCHAR);
391 /* And fill it with the Unix environment */
392 for (e = environ; *e; e++)
394 char *str = *e;
396 /* skip Unix special variables and use the Wine variants instead */
397 if (!strncmp( str, "WINE", 4 ))
399 if (is_special_env_var( str + 4 )) str += 4;
400 else if (!strncmp( str, "WINEPRELOADRESERVE=", 19 )) continue; /* skip it */
402 else if (is_special_env_var( str )) continue; /* skip it */
404 MultiByteToWideChar( CP_UNIXCP, 0, str, -1, p, endptr - p );
405 p += strlenW(p) + 1;
407 *p = 0;
408 return TRUE;
412 /***********************************************************************
413 * set_registry_variables
415 * Set environment variables by enumerating the values of a key;
416 * helper for set_registry_environment().
417 * Note that Windows happily truncates the value if it's too big.
419 static void set_registry_variables( HKEY hkey, ULONG type )
421 UNICODE_STRING env_name, env_value;
422 NTSTATUS status;
423 DWORD size;
424 int index;
425 char buffer[1024*sizeof(WCHAR) + sizeof(KEY_VALUE_FULL_INFORMATION)];
426 KEY_VALUE_FULL_INFORMATION *info = (KEY_VALUE_FULL_INFORMATION *)buffer;
428 for (index = 0; ; index++)
430 status = NtEnumerateValueKey( hkey, index, KeyValueFullInformation,
431 buffer, sizeof(buffer), &size );
432 if (status != STATUS_SUCCESS && status != STATUS_BUFFER_OVERFLOW)
433 break;
434 if (info->Type != type)
435 continue;
436 env_name.Buffer = info->Name;
437 env_name.Length = env_name.MaximumLength = info->NameLength;
438 env_value.Buffer = (WCHAR *)(buffer + info->DataOffset);
439 env_value.Length = env_value.MaximumLength = info->DataLength;
440 if (env_value.Length && !env_value.Buffer[env_value.Length/sizeof(WCHAR)-1])
441 env_value.Length--; /* don't count terminating null if any */
442 if (info->Type == REG_EXPAND_SZ)
444 WCHAR buf_expanded[1024];
445 UNICODE_STRING env_expanded;
446 env_expanded.Length = env_expanded.MaximumLength = sizeof(buf_expanded);
447 env_expanded.Buffer=buf_expanded;
448 status = RtlExpandEnvironmentStrings_U(NULL, &env_value, &env_expanded, NULL);
449 if (status == STATUS_SUCCESS || status == STATUS_BUFFER_OVERFLOW)
450 RtlSetEnvironmentVariable( NULL, &env_name, &env_expanded );
452 else
454 RtlSetEnvironmentVariable( NULL, &env_name, &env_value );
460 /***********************************************************************
461 * set_registry_environment
463 * Set the environment variables specified in the registry.
465 * Note: Windows handles REG_SZ and REG_EXPAND_SZ in one pass with the
466 * consequence that REG_EXPAND_SZ cannot be used reliably as it depends
467 * on the order in which the variables are processed. But on Windows it
468 * does not really matter since they only use %SystemDrive% and
469 * %SystemRoot% which are predefined. But Wine defines these in the
470 * registry, so we need two passes.
472 static void set_registry_environment(void)
474 static const WCHAR env_keyW[] = {'M','a','c','h','i','n','e','\\',
475 'S','y','s','t','e','m','\\',
476 'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
477 'C','o','n','t','r','o','l','\\',
478 'S','e','s','s','i','o','n',' ','M','a','n','a','g','e','r','\\',
479 'E','n','v','i','r','o','n','m','e','n','t',0};
480 static const WCHAR envW[] = {'E','n','v','i','r','o','n','m','e','n','t',0};
482 OBJECT_ATTRIBUTES attr;
483 UNICODE_STRING nameW;
484 HKEY hkey;
486 attr.Length = sizeof(attr);
487 attr.RootDirectory = 0;
488 attr.ObjectName = &nameW;
489 attr.Attributes = 0;
490 attr.SecurityDescriptor = NULL;
491 attr.SecurityQualityOfService = NULL;
493 /* first the system environment variables */
494 RtlInitUnicodeString( &nameW, env_keyW );
495 if (NtOpenKey( &hkey, KEY_ALL_ACCESS, &attr ) == STATUS_SUCCESS)
497 set_registry_variables( hkey, REG_SZ );
498 set_registry_variables( hkey, REG_EXPAND_SZ );
499 NtClose( hkey );
502 /* then the ones for the current user */
503 if (RtlOpenCurrentUser( KEY_ALL_ACCESS, (HKEY *)&attr.RootDirectory ) != STATUS_SUCCESS) return;
504 RtlInitUnicodeString( &nameW, envW );
505 if (NtOpenKey( &hkey, KEY_ALL_ACCESS, &attr ) == STATUS_SUCCESS)
507 set_registry_variables( hkey, REG_SZ );
508 set_registry_variables( hkey, REG_EXPAND_SZ );
509 NtClose( hkey );
511 NtClose( attr.RootDirectory );
515 /***********************************************************************
516 * set_library_wargv
518 * Set the Wine library Unicode argv global variables.
520 static void set_library_wargv( char **argv )
522 int argc;
523 char *q;
524 WCHAR *p;
525 WCHAR **wargv;
526 DWORD total = 0;
528 for (argc = 0; argv[argc]; argc++)
529 total += MultiByteToWideChar( CP_UNIXCP, 0, argv[argc], -1, NULL, 0 );
531 wargv = RtlAllocateHeap( GetProcessHeap(), 0,
532 total * sizeof(WCHAR) + (argc + 1) * sizeof(*wargv) );
533 p = (WCHAR *)(wargv + argc + 1);
534 for (argc = 0; argv[argc]; argc++)
536 DWORD reslen = MultiByteToWideChar( CP_UNIXCP, 0, argv[argc], -1, p, total );
537 wargv[argc] = p;
538 p += reslen;
539 total -= reslen;
541 wargv[argc] = NULL;
543 /* convert argv back from Unicode since it has to be in the Ansi codepage not the Unix one */
545 for (argc = 0; wargv[argc]; argc++)
546 total += WideCharToMultiByte( CP_ACP, 0, wargv[argc], -1, NULL, 0, NULL, NULL );
548 argv = RtlAllocateHeap( GetProcessHeap(), 0, total + (argc + 1) * sizeof(*argv) );
549 q = (char *)(argv + argc + 1);
550 for (argc = 0; wargv[argc]; argc++)
552 DWORD reslen = WideCharToMultiByte( CP_ACP, 0, wargv[argc], -1, q, total, NULL, NULL );
553 argv[argc] = q;
554 q += reslen;
555 total -= reslen;
557 argv[argc] = NULL;
559 __wine_main_argv = argv;
560 __wine_main_wargv = wargv;
564 /***********************************************************************
565 * build_command_line
567 * Build the command line of a process from the argv array.
569 * Note that it does NOT necessarily include the file name.
570 * Sometimes we don't even have any command line options at all.
572 * We must quote and escape characters so that the argv array can be rebuilt
573 * from the command line:
574 * - spaces and tabs must be quoted
575 * 'a b' -> '"a b"'
576 * - quotes must be escaped
577 * '"' -> '\"'
578 * - if '\'s are followed by a '"', they must be doubled and followed by '\"',
579 * resulting in an odd number of '\' followed by a '"'
580 * '\"' -> '\\\"'
581 * '\\"' -> '\\\\\"'
582 * - '\'s that are not followed by a '"' can be left as is
583 * 'a\b' == 'a\b'
584 * 'a\\b' == 'a\\b'
586 static BOOL build_command_line( WCHAR **argv )
588 int len;
589 WCHAR **arg;
590 LPWSTR p;
591 RTL_USER_PROCESS_PARAMETERS* rupp = NtCurrentTeb()->Peb->ProcessParameters;
593 if (rupp->CommandLine.Buffer) return TRUE; /* already got it from the server */
595 len = 0;
596 for (arg = argv; *arg; arg++)
598 int has_space,bcount;
599 WCHAR* a;
601 has_space=0;
602 bcount=0;
603 a=*arg;
604 if( !*a ) has_space=1;
605 while (*a!='\0') {
606 if (*a=='\\') {
607 bcount++;
608 } else {
609 if (*a==' ' || *a=='\t') {
610 has_space=1;
611 } else if (*a=='"') {
612 /* doubling of '\' preceding a '"',
613 * plus escaping of said '"'
615 len+=2*bcount+1;
617 bcount=0;
619 a++;
621 len+=(a-*arg)+1 /* for the separating space */;
622 if (has_space)
623 len+=2; /* for the quotes */
626 if (!(rupp->CommandLine.Buffer = RtlAllocateHeap( GetProcessHeap(), 0, len * sizeof(WCHAR))))
627 return FALSE;
629 p = rupp->CommandLine.Buffer;
630 rupp->CommandLine.Length = (len - 1) * sizeof(WCHAR);
631 rupp->CommandLine.MaximumLength = len * sizeof(WCHAR);
632 for (arg = argv; *arg; arg++)
634 int has_space,has_quote;
635 WCHAR* a;
637 /* Check for quotes and spaces in this argument */
638 has_space=has_quote=0;
639 a=*arg;
640 if( !*a ) has_space=1;
641 while (*a!='\0') {
642 if (*a==' ' || *a=='\t') {
643 has_space=1;
644 if (has_quote)
645 break;
646 } else if (*a=='"') {
647 has_quote=1;
648 if (has_space)
649 break;
651 a++;
654 /* Now transfer it to the command line */
655 if (has_space)
656 *p++='"';
657 if (has_quote) {
658 int bcount;
659 WCHAR* a;
661 bcount=0;
662 a=*arg;
663 while (*a!='\0') {
664 if (*a=='\\') {
665 *p++=*a;
666 bcount++;
667 } else {
668 if (*a=='"') {
669 int i;
671 /* Double all the '\\' preceding this '"', plus one */
672 for (i=0;i<=bcount;i++)
673 *p++='\\';
674 *p++='"';
675 } else {
676 *p++=*a;
678 bcount=0;
680 a++;
682 } else {
683 WCHAR* x = *arg;
684 while ((*p=*x++)) p++;
686 if (has_space)
687 *p++='"';
688 *p++=' ';
690 if (p > rupp->CommandLine.Buffer)
691 p--; /* remove last space */
692 *p = '\0';
694 return TRUE;
698 /* make sure the unicode string doesn't point beyond the end pointer */
699 static inline void fix_unicode_string( UNICODE_STRING *str, char *end_ptr )
701 if ((char *)str->Buffer >= end_ptr)
703 str->Length = str->MaximumLength = 0;
704 str->Buffer = NULL;
705 return;
707 if ((char *)str->Buffer + str->MaximumLength > end_ptr)
709 str->MaximumLength = (end_ptr - (char *)str->Buffer) & ~(sizeof(WCHAR) - 1);
711 if (str->Length >= str->MaximumLength)
713 if (str->MaximumLength >= sizeof(WCHAR))
714 str->Length = str->MaximumLength - sizeof(WCHAR);
715 else
716 str->Length = str->MaximumLength = 0;
720 static void version(void)
722 MESSAGE( "%s\n", PACKAGE_STRING );
723 ExitProcess(0);
726 static void usage(void)
728 MESSAGE( "%s\n", PACKAGE_STRING );
729 MESSAGE( "Usage: wine PROGRAM [ARGUMENTS...] Run the specified program\n" );
730 MESSAGE( " wine --help Display this help and exit\n");
731 MESSAGE( " wine --version Output version information and exit\n");
732 ExitProcess(0);
736 /***********************************************************************
737 * init_user_process_params
739 * Fill the RTL_USER_PROCESS_PARAMETERS structure from the server.
741 static RTL_USER_PROCESS_PARAMETERS *init_user_process_params( size_t info_size )
743 void *ptr;
744 DWORD size, env_size;
745 RTL_USER_PROCESS_PARAMETERS *params;
747 size = info_size;
748 ptr = NULL;
749 if (NtAllocateVirtualMemory( NtCurrentProcess(), &ptr, 0, &size,
750 MEM_COMMIT, PAGE_READWRITE ) != STATUS_SUCCESS)
751 return NULL;
753 SERVER_START_REQ( get_startup_info )
755 wine_server_set_reply( req, ptr, info_size );
756 wine_server_call( req );
757 info_size = wine_server_reply_size( reply );
759 SERVER_END_REQ;
761 params = ptr;
762 params->AllocationSize = size;
763 if (params->Size > info_size) params->Size = info_size;
765 /* make sure the strings are valid */
766 fix_unicode_string( &params->CurrentDirectory.DosPath, (char *)info_size );
767 fix_unicode_string( &params->DllPath, (char *)info_size );
768 fix_unicode_string( &params->ImagePathName, (char *)info_size );
769 fix_unicode_string( &params->CommandLine, (char *)info_size );
770 fix_unicode_string( &params->WindowTitle, (char *)info_size );
771 fix_unicode_string( &params->Desktop, (char *)info_size );
772 fix_unicode_string( &params->ShellInfo, (char *)info_size );
773 fix_unicode_string( &params->RuntimeInfo, (char *)info_size );
775 /* environment needs to be a separate memory block */
776 env_size = info_size - params->Size;
777 if (!env_size) env_size = 1;
778 ptr = NULL;
779 if (NtAllocateVirtualMemory( NtCurrentProcess(), &ptr, 0, &env_size,
780 MEM_COMMIT, PAGE_READWRITE ) != STATUS_SUCCESS)
781 return NULL;
782 memcpy( ptr, (char *)params + params->Size, info_size - params->Size );
783 params->Environment = ptr;
785 return RtlNormalizeProcessParams( params );
789 /***********************************************************************
790 * init_current_directory
792 * Initialize the current directory from the Unix cwd or the parent info.
794 static void init_current_directory( CURDIR *cur_dir )
796 UNICODE_STRING dir_str;
797 char *cwd;
798 int size;
800 /* if we received a cur dir from the parent, try this first */
802 if (cur_dir->DosPath.Length)
804 if (RtlSetCurrentDirectory_U( &cur_dir->DosPath ) == STATUS_SUCCESS) goto done;
807 /* now try to get it from the Unix cwd */
809 for (size = 256; ; size *= 2)
811 if (!(cwd = HeapAlloc( GetProcessHeap(), 0, size ))) break;
812 if (getcwd( cwd, size )) break;
813 HeapFree( GetProcessHeap(), 0, cwd );
814 if (errno == ERANGE) continue;
815 cwd = NULL;
816 break;
819 if (cwd)
821 WCHAR *dirW;
822 int lenW = MultiByteToWideChar( CP_UNIXCP, 0, cwd, -1, NULL, 0 );
823 if ((dirW = HeapAlloc( GetProcessHeap(), 0, lenW * sizeof(WCHAR) )))
825 MultiByteToWideChar( CP_UNIXCP, 0, cwd, -1, dirW, lenW );
826 RtlInitUnicodeString( &dir_str, dirW );
827 RtlSetCurrentDirectory_U( &dir_str );
828 RtlFreeUnicodeString( &dir_str );
832 if (!cur_dir->DosPath.Length) /* still not initialized */
834 MESSAGE("Warning: could not find DOS drive for current working directory '%s', "
835 "starting in the Windows directory.\n", cwd ? cwd : "" );
836 RtlInitUnicodeString( &dir_str, DIR_Windows );
837 RtlSetCurrentDirectory_U( &dir_str );
839 HeapFree( GetProcessHeap(), 0, cwd );
841 done:
842 if (!cur_dir->Handle) chdir("/"); /* change to root directory so as not to lock cdroms */
843 TRACE( "starting in %s %p\n", debugstr_w( cur_dir->DosPath.Buffer ), cur_dir->Handle );
847 /***********************************************************************
848 * init_windows_dirs
850 * Initialize the windows and system directories from the environment.
852 static void init_windows_dirs(void)
854 extern void __wine_init_windows_dir( const WCHAR *windir, const WCHAR *sysdir );
856 static const WCHAR windirW[] = {'w','i','n','d','i','r',0};
857 static const WCHAR winsysdirW[] = {'w','i','n','s','y','s','d','i','r',0};
858 static const WCHAR default_windirW[] = {'c',':','\\','w','i','n','d','o','w','s',0};
859 static const WCHAR default_sysdirW[] = {'\\','s','y','s','t','e','m',0};
861 DWORD len;
862 WCHAR *buffer;
864 if ((len = GetEnvironmentVariableW( windirW, NULL, 0 )))
866 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
867 GetEnvironmentVariableW( windirW, buffer, len );
868 DIR_Windows = buffer;
870 else DIR_Windows = default_windirW;
872 if ((len = GetEnvironmentVariableW( winsysdirW, NULL, 0 )))
874 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
875 GetEnvironmentVariableW( winsysdirW, buffer, len );
876 DIR_System = buffer;
878 else
880 len = strlenW( DIR_Windows );
881 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) + sizeof(default_sysdirW) );
882 memcpy( buffer, DIR_Windows, len * sizeof(WCHAR) );
883 memcpy( buffer + len, default_sysdirW, sizeof(default_sysdirW) );
884 DIR_System = buffer;
887 if (GetFileAttributesW( DIR_Windows ) == INVALID_FILE_ATTRIBUTES)
888 MESSAGE( "Warning: the specified Windows directory %s is not accessible.\n",
889 debugstr_w(DIR_Windows) );
890 if (GetFileAttributesW( DIR_System ) == INVALID_FILE_ATTRIBUTES)
891 MESSAGE( "Warning: the specified System directory %s is not accessible.\n",
892 debugstr_w(DIR_System) );
894 TRACE_(file)( "WindowsDir = %s\n", debugstr_w(DIR_Windows) );
895 TRACE_(file)( "SystemDir = %s\n", debugstr_w(DIR_System) );
897 /* set the directories in ntdll too */
898 __wine_init_windows_dir( DIR_Windows, DIR_System );
902 /***********************************************************************
903 * process_init
905 * Main process initialisation code
907 static BOOL process_init(void)
909 static const WCHAR kernel32W[] = {'k','e','r','n','e','l','3','2',0};
910 BOOL ret;
911 size_t info_size = 0;
912 RTL_USER_PROCESS_PARAMETERS *params;
913 PEB *peb = NtCurrentTeb()->Peb;
914 HANDLE hstdin, hstdout, hstderr;
915 extern void __wine_dbg_kernel32_init(void);
917 PTHREAD_Init();
919 __wine_dbg_kernel32_init(); /* hack: register debug channels early */
921 setbuf(stdout,NULL);
922 setbuf(stderr,NULL);
923 setlocale(LC_CTYPE,"");
925 /* Retrieve startup info from the server */
926 SERVER_START_REQ( init_process )
928 req->peb = peb;
929 req->ldt_copy = &wine_ldt_copy;
930 if ((ret = !wine_server_call_err( req )))
932 main_exe_file = reply->exe_file;
933 main_create_flags = reply->create_flags;
934 info_size = reply->info_size;
935 server_startticks = reply->server_start;
936 hstdin = reply->hstdin;
937 hstdout = reply->hstdout;
938 hstderr = reply->hstderr;
941 SERVER_END_REQ;
942 if (!ret) return FALSE;
944 if (info_size == 0)
946 params = peb->ProcessParameters;
948 /* This is wine specific: we have no parent (we're started from unix)
949 * so, create a simple console with bare handles to unix stdio
950 * input & output streams (aka simple console)
952 wine_server_fd_to_handle( 0, GENERIC_READ|SYNCHRONIZE, TRUE, &params->hStdInput );
953 wine_server_fd_to_handle( 1, GENERIC_WRITE|SYNCHRONIZE, TRUE, &params->hStdOutput );
954 wine_server_fd_to_handle( 2, GENERIC_WRITE|SYNCHRONIZE, TRUE, &params->hStdError );
956 params->CurrentDirectory.DosPath.Length = 0;
957 params->CurrentDirectory.DosPath.MaximumLength = RtlGetLongestNtPathLength() * sizeof(WCHAR);
958 params->CurrentDirectory.DosPath.Buffer = RtlAllocateHeap( GetProcessHeap(), 0, params->CurrentDirectory.DosPath.MaximumLength);
960 else
962 if (!(params = init_user_process_params( info_size ))) return FALSE;
963 peb->ProcessParameters = params;
965 /* convert value from server:
966 * + 0 => INVALID_HANDLE_VALUE
967 * + console handle need to be mapped
969 if (!hstdin)
970 hstdin = INVALID_HANDLE_VALUE;
971 else if (VerifyConsoleIoHandle(console_handle_map(hstdin)))
972 hstdin = console_handle_map(hstdin);
974 if (!hstdout)
975 hstdout = INVALID_HANDLE_VALUE;
976 else if (VerifyConsoleIoHandle(console_handle_map(hstdout)))
977 hstdout = console_handle_map(hstdout);
979 if (!hstderr)
980 hstderr = INVALID_HANDLE_VALUE;
981 else if (VerifyConsoleIoHandle(console_handle_map(hstderr)))
982 hstderr = console_handle_map(hstderr);
984 params->hStdInput = hstdin;
985 params->hStdOutput = hstdout;
986 params->hStdError = hstderr;
989 kernel32_handle = GetModuleHandleW(kernel32W);
991 LOCALE_Init();
993 if (!info_size)
995 /* Copy the parent environment */
996 if (!build_initial_environment( __wine_main_environ )) return FALSE;
998 /* convert old configuration to new format */
999 convert_old_config();
1001 /* global boot finished, the rest is process-local */
1002 SERVER_START_REQ( boot_done )
1004 req->debug_level = TRACE_ON(server);
1005 wine_server_call( req );
1007 SERVER_END_REQ;
1009 set_registry_environment();
1012 init_windows_dirs();
1013 init_current_directory( &params->CurrentDirectory );
1015 return TRUE;
1019 /***********************************************************************
1020 * start_process
1022 * Startup routine of a new process. Runs on the new process stack.
1024 static void start_process( void *arg )
1026 __TRY
1028 PEB *peb = NtCurrentTeb()->Peb;
1029 IMAGE_NT_HEADERS *nt;
1030 LPTHREAD_START_ROUTINE entry;
1032 LdrInitializeThunk( main_exe_file, 0, 0, 0 );
1034 nt = RtlImageNtHeader( peb->ImageBaseAddress );
1035 entry = (LPTHREAD_START_ROUTINE)((char *)peb->ImageBaseAddress +
1036 nt->OptionalHeader.AddressOfEntryPoint);
1038 if (TRACE_ON(relay))
1039 DPRINTF( "%04lx:Starting process %s (entryproc=%p)\n", GetCurrentThreadId(),
1040 debugstr_w(peb->ProcessParameters->ImagePathName.Buffer), entry );
1042 SetLastError( 0 ); /* clear error code */
1043 if (peb->BeingDebugged) DbgBreakPoint();
1044 ExitProcess( entry( peb ) );
1046 __EXCEPT(UnhandledExceptionFilter)
1048 TerminateThread( GetCurrentThread(), GetExceptionCode() );
1050 __ENDTRY
1054 /***********************************************************************
1055 * __wine_kernel_init
1057 * Wine initialisation: load and start the main exe file.
1059 void __wine_kernel_init(void)
1061 WCHAR *main_exe_name, *p;
1062 char error[1024];
1063 DWORD stack_size = 0;
1064 int file_exists;
1065 PEB *peb = NtCurrentTeb()->Peb;
1067 /* Initialize everything */
1068 if (!process_init()) exit(1);
1070 __wine_main_argv++; /* remove argv[0] (wine itself) */
1071 __wine_main_argc--;
1073 if (!(main_exe_name = peb->ProcessParameters->ImagePathName.Buffer))
1075 WCHAR buffer[MAX_PATH];
1076 WCHAR exe_nameW[MAX_PATH];
1078 if (!__wine_main_argv[0]) usage();
1079 if (__wine_main_argc == 1)
1081 if (strcmp(__wine_main_argv[0], "--help") == 0) usage();
1082 if (strcmp(__wine_main_argv[0], "--version") == 0) version();
1085 MultiByteToWideChar( CP_UNIXCP, 0, __wine_main_argv[0], -1, exe_nameW, MAX_PATH );
1086 if (!find_exe_file( exe_nameW, buffer, MAX_PATH, &main_exe_file ))
1088 MESSAGE( "wine: cannot find '%s'\n", __wine_main_argv[0] );
1089 ExitProcess(1);
1091 if (main_exe_file == INVALID_HANDLE_VALUE)
1093 MESSAGE( "wine: cannot open %s\n", debugstr_w(main_exe_name) );
1094 ExitProcess(1);
1096 RtlCreateUnicodeString( &peb->ProcessParameters->ImagePathName, buffer );
1097 main_exe_name = peb->ProcessParameters->ImagePathName.Buffer;
1100 TRACE( "starting process name=%s file=%p argv[0]=%s\n",
1101 debugstr_w(main_exe_name), main_exe_file, debugstr_a(__wine_main_argv[0]) );
1103 RtlInitUnicodeString( &NtCurrentTeb()->Peb->ProcessParameters->DllPath,
1104 MODULE_get_dll_load_path(NULL) );
1105 VERSION_Init( main_exe_name );
1107 if (!main_exe_file) /* no file handle -> Winelib app */
1109 TRACE( "starting Winelib app %s\n", debugstr_w(main_exe_name) );
1110 if (open_builtin_exe_file( main_exe_name, error, sizeof(error), 0, &file_exists ))
1111 goto found;
1112 MESSAGE( "wine: cannot open builtin library for %s: %s\n",
1113 debugstr_w(main_exe_name), error );
1114 ExitProcess(1);
1117 switch( MODULE_GetBinaryType( main_exe_file, NULL, NULL ))
1119 case BINARY_PE_EXE:
1120 TRACE( "starting Win32 binary %s\n", debugstr_w(main_exe_name) );
1121 if ((peb->ImageBaseAddress = load_pe_exe( main_exe_name, main_exe_file )))
1122 goto found;
1123 MESSAGE( "wine: could not load %s as Win32 binary\n", debugstr_w(main_exe_name) );
1124 ExitProcess(1);
1125 case BINARY_PE_DLL:
1126 MESSAGE( "wine: %s is a DLL, not an executable\n", debugstr_w(main_exe_name) );
1127 ExitProcess(1);
1128 case BINARY_UNKNOWN:
1129 /* check for .com extension */
1130 if (!(p = strrchrW( main_exe_name, '.' )) || strcmpiW( p, comW ))
1132 MESSAGE( "wine: cannot determine executable type for %s\n",
1133 debugstr_w(main_exe_name) );
1134 ExitProcess(1);
1136 /* fall through */
1137 case BINARY_OS216:
1138 case BINARY_WIN16:
1139 case BINARY_DOS:
1140 TRACE( "starting Win16/DOS binary %s\n", debugstr_w(main_exe_name) );
1141 CloseHandle( main_exe_file );
1142 main_exe_file = 0;
1143 __wine_main_argv--;
1144 __wine_main_argc++;
1145 __wine_main_argv[0] = "winevdm.exe";
1146 if (open_builtin_exe_file( winevdmW, error, sizeof(error), 0, &file_exists ))
1147 goto found;
1148 MESSAGE( "wine: trying to run %s, cannot open builtin library for 'winevdm.exe': %s\n",
1149 debugstr_w(main_exe_name), error );
1150 ExitProcess(1);
1151 case BINARY_UNIX_EXE:
1152 MESSAGE( "wine: %s is a Unix binary, not supported\n", debugstr_w(main_exe_name) );
1153 ExitProcess(1);
1154 case BINARY_UNIX_LIB:
1156 char *unix_name;
1158 TRACE( "starting Winelib app %s\n", debugstr_w(main_exe_name) );
1159 CloseHandle( main_exe_file );
1160 main_exe_file = 0;
1161 if ((unix_name = wine_get_unix_file_name( main_exe_name )) &&
1162 wine_dlopen( unix_name, RTLD_NOW, error, sizeof(error) ))
1164 static const WCHAR soW[] = {'.','s','o',0};
1165 if ((p = strrchrW( main_exe_name, '.' )) && !strcmpW( p, soW ))
1167 *p = 0;
1168 /* update the unicode string */
1169 RtlInitUnicodeString( &peb->ProcessParameters->ImagePathName, main_exe_name );
1171 HeapFree( GetProcessHeap(), 0, unix_name );
1172 goto found;
1174 MESSAGE( "wine: could not load %s: %s\n", debugstr_w(main_exe_name), error );
1175 ExitProcess(1);
1179 found:
1180 /* build command line */
1181 set_library_wargv( __wine_main_argv );
1182 if (!build_command_line( __wine_main_wargv )) goto error;
1184 stack_size = RtlImageNtHeader(peb->ImageBaseAddress)->OptionalHeader.SizeOfStackReserve;
1186 /* allocate main thread stack */
1187 if (!THREAD_InitStack( NtCurrentTeb(), stack_size )) goto error;
1189 /* switch to the new stack */
1190 wine_switch_to_stack( start_process, NULL, NtCurrentTeb()->Tib.StackBase );
1192 error:
1193 ExitProcess( GetLastError() );
1197 /***********************************************************************
1198 * build_argv
1200 * Build an argv array from a command-line.
1201 * 'reserved' is the number of args to reserve before the first one.
1203 static char **build_argv( const WCHAR *cmdlineW, int reserved )
1205 int argc;
1206 char** argv;
1207 char *arg,*s,*d,*cmdline;
1208 int in_quotes,bcount,len;
1210 len = WideCharToMultiByte( CP_UNIXCP, 0, cmdlineW, -1, NULL, 0, NULL, NULL );
1211 if (!(cmdline = malloc(len))) return NULL;
1212 WideCharToMultiByte( CP_UNIXCP, 0, cmdlineW, -1, cmdline, len, NULL, NULL );
1214 argc=reserved+1;
1215 bcount=0;
1216 in_quotes=0;
1217 s=cmdline;
1218 while (1) {
1219 if (*s=='\0' || ((*s==' ' || *s=='\t') && !in_quotes)) {
1220 /* space */
1221 argc++;
1222 /* skip the remaining spaces */
1223 while (*s==' ' || *s=='\t') {
1224 s++;
1226 if (*s=='\0')
1227 break;
1228 bcount=0;
1229 continue;
1230 } else if (*s=='\\') {
1231 /* '\', count them */
1232 bcount++;
1233 } else if ((*s=='"') && ((bcount & 1)==0)) {
1234 /* unescaped '"' */
1235 in_quotes=!in_quotes;
1236 bcount=0;
1237 } else {
1238 /* a regular character */
1239 bcount=0;
1241 s++;
1243 argv=malloc(argc*sizeof(*argv));
1244 if (!argv)
1245 return NULL;
1247 arg=d=s=cmdline;
1248 bcount=0;
1249 in_quotes=0;
1250 argc=reserved;
1251 while (*s) {
1252 if ((*s==' ' || *s=='\t') && !in_quotes) {
1253 /* Close the argument and copy it */
1254 *d=0;
1255 argv[argc++]=arg;
1257 /* skip the remaining spaces */
1258 do {
1259 s++;
1260 } while (*s==' ' || *s=='\t');
1262 /* Start with a new argument */
1263 arg=d=s;
1264 bcount=0;
1265 } else if (*s=='\\') {
1266 /* '\\' */
1267 *d++=*s++;
1268 bcount++;
1269 } else if (*s=='"') {
1270 /* '"' */
1271 if ((bcount & 1)==0) {
1272 /* Preceded by an even number of '\', this is half that
1273 * number of '\', plus a '"' which we discard.
1275 d-=bcount/2;
1276 s++;
1277 in_quotes=!in_quotes;
1278 } else {
1279 /* Preceded by an odd number of '\', this is half that
1280 * number of '\' followed by a '"'
1282 d=d-bcount/2-1;
1283 *d++='"';
1284 s++;
1286 bcount=0;
1287 } else {
1288 /* a regular character */
1289 *d++=*s++;
1290 bcount=0;
1293 if (*arg) {
1294 *d='\0';
1295 argv[argc++]=arg;
1297 argv[argc]=NULL;
1299 return argv;
1303 /***********************************************************************
1304 * alloc_env_string
1306 * Allocate an environment string; helper for build_envp
1308 static char *alloc_env_string( const char *name, const char *value )
1310 char *ret = malloc( strlen(name) + strlen(value) + 1 );
1311 strcpy( ret, name );
1312 strcat( ret, value );
1313 return ret;
1316 /***********************************************************************
1317 * build_envp
1319 * Build the environment of a new child process.
1321 static char **build_envp( const WCHAR *envW )
1323 const WCHAR *end;
1324 char **envp;
1325 char *env, *p;
1326 int count = 0, length;
1328 for (end = envW; *end; count++) end += strlenW(end) + 1;
1329 end++;
1330 length = WideCharToMultiByte( CP_UNIXCP, 0, envW, end - envW, NULL, 0, NULL, NULL );
1331 if (!(env = malloc( length ))) return NULL;
1332 WideCharToMultiByte( CP_UNIXCP, 0, envW, end - envW, env, length, NULL, NULL );
1334 count += 4;
1336 if ((envp = malloc( count * sizeof(*envp) )))
1338 char **envptr = envp;
1340 /* some variables must not be modified, so we get them directly from the unix env */
1341 if ((p = getenv("PATH"))) *envptr++ = alloc_env_string( "PATH=", p );
1342 if ((p = getenv("TEMP"))) *envptr++ = alloc_env_string( "TEMP=", p );
1343 if ((p = getenv("TMP"))) *envptr++ = alloc_env_string( "TMP=", p );
1344 if ((p = getenv("HOME"))) *envptr++ = alloc_env_string( "HOME=", p );
1345 /* now put the Windows environment strings */
1346 for (p = env; *p; p += strlen(p) + 1)
1348 if (*p == '=') continue; /* skip drive curdirs, this crashes some unix apps */
1349 if (!strncmp( p, "WINEPRELOADRESERVE=", sizeof("WINEPRELOADRESERVE=")-1 )) continue;
1350 if (is_special_env_var( p )) /* prefix it with "WINE" */
1351 *envptr++ = alloc_env_string( "WINE", p );
1352 else
1353 *envptr++ = p;
1355 *envptr = 0;
1357 return envp;
1361 /***********************************************************************
1362 * fork_and_exec
1364 * Fork and exec a new Unix binary, checking for errors.
1366 static int fork_and_exec( const char *filename, const WCHAR *cmdline,
1367 const WCHAR *env, const char *newdir )
1369 int fd[2];
1370 int pid, err;
1372 if (!env) env = GetEnvironmentStringsW();
1374 if (pipe(fd) == -1)
1376 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
1377 return -1;
1379 fcntl( fd[1], F_SETFD, 1 ); /* set close on exec */
1380 if (!(pid = fork())) /* child */
1382 char **argv = build_argv( cmdline, 0 );
1383 char **envp = build_envp( env );
1384 close( fd[0] );
1386 /* Reset signals that we previously set to SIG_IGN */
1387 signal( SIGPIPE, SIG_DFL );
1388 signal( SIGCHLD, SIG_DFL );
1390 if (newdir) chdir(newdir);
1392 if (argv && envp) execve( filename, argv, envp );
1393 err = errno;
1394 write( fd[1], &err, sizeof(err) );
1395 _exit(1);
1397 close( fd[1] );
1398 if ((pid != -1) && (read( fd[0], &err, sizeof(err) ) > 0)) /* exec failed */
1400 errno = err;
1401 pid = -1;
1403 if (pid == -1) FILE_SetDosError();
1404 close( fd[0] );
1405 return pid;
1409 /***********************************************************************
1410 * create_user_params
1412 static RTL_USER_PROCESS_PARAMETERS *create_user_params( LPCWSTR filename, LPCWSTR cmdline,
1413 LPCWSTR cur_dir, LPWSTR env,
1414 const STARTUPINFOW *startup )
1416 RTL_USER_PROCESS_PARAMETERS *params;
1417 UNICODE_STRING image_str, cmdline_str, curdir_str, desktop, title, runtime;
1418 NTSTATUS status;
1419 WCHAR buffer[MAX_PATH];
1421 if(!GetLongPathNameW( filename, buffer, MAX_PATH ))
1422 lstrcpynW( buffer, filename, MAX_PATH );
1423 if(!GetFullPathNameW( buffer, MAX_PATH, buffer, NULL ))
1424 lstrcpynW( buffer, filename, MAX_PATH );
1425 RtlInitUnicodeString( &image_str, buffer );
1427 RtlInitUnicodeString( &cmdline_str, cmdline );
1428 if (cur_dir) RtlInitUnicodeString( &curdir_str, cur_dir );
1429 if (startup->lpDesktop) RtlInitUnicodeString( &desktop, startup->lpDesktop );
1430 if (startup->lpTitle) RtlInitUnicodeString( &title, startup->lpTitle );
1431 if (startup->lpReserved2 && startup->cbReserved2)
1433 runtime.Length = 0;
1434 runtime.MaximumLength = startup->cbReserved2;
1435 runtime.Buffer = (WCHAR*)startup->lpReserved2;
1438 status = RtlCreateProcessParameters( &params, &image_str, NULL,
1439 cur_dir ? &curdir_str : NULL,
1440 &cmdline_str, env,
1441 startup->lpTitle ? &title : NULL,
1442 startup->lpDesktop ? &desktop : NULL,
1443 NULL,
1444 (startup->lpReserved2 && startup->cbReserved2) ? &runtime : NULL );
1445 if (status != STATUS_SUCCESS)
1447 SetLastError( RtlNtStatusToDosError(status) );
1448 return NULL;
1451 params->hStdInput = startup->hStdInput;
1452 params->hStdOutput = startup->hStdOutput;
1453 params->hStdError = startup->hStdError;
1454 params->dwX = startup->dwX;
1455 params->dwY = startup->dwY;
1456 params->dwXSize = startup->dwXSize;
1457 params->dwYSize = startup->dwYSize;
1458 params->dwXCountChars = startup->dwXCountChars;
1459 params->dwYCountChars = startup->dwYCountChars;
1460 params->dwFillAttribute = startup->dwFillAttribute;
1461 params->dwFlags = startup->dwFlags;
1462 params->wShowWindow = startup->wShowWindow;
1463 return params;
1467 /***********************************************************************
1468 * create_process
1470 * Create a new process. If hFile is a valid handle we have an exe
1471 * file, otherwise it is a Winelib app.
1473 static BOOL create_process( HANDLE hFile, LPCWSTR filename, LPWSTR cmd_line, LPWSTR env,
1474 LPCWSTR cur_dir, LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1475 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
1476 LPPROCESS_INFORMATION info, LPCSTR unixdir,
1477 void *res_start, void *res_end )
1479 BOOL ret, success = FALSE;
1480 HANDLE process_info;
1481 WCHAR *env_end;
1482 RTL_USER_PROCESS_PARAMETERS *params;
1483 int startfd[2];
1484 int execfd[2];
1485 pid_t pid;
1486 int err;
1487 char dummy = 0;
1488 char preloader_reserve[64];
1490 if (!env) RtlAcquirePebLock();
1492 if (!(params = create_user_params( filename, cmd_line, cur_dir, env, startup )))
1494 if (!env) RtlReleasePebLock();
1495 return FALSE;
1497 env_end = params->Environment;
1498 while (*env_end) env_end += strlenW(env_end) + 1;
1499 env_end++;
1501 sprintf( preloader_reserve, "WINEPRELOADRESERVE=%lx-%lx%c",
1502 (unsigned long)res_start, (unsigned long)res_end, 0 );
1504 /* create the synchronization pipes */
1506 if (pipe( startfd ) == -1)
1508 if (!env) RtlReleasePebLock();
1509 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
1510 RtlDestroyProcessParameters( params );
1511 return FALSE;
1513 if (pipe( execfd ) == -1)
1515 if (!env) RtlReleasePebLock();
1516 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
1517 close( startfd[0] );
1518 close( startfd[1] );
1519 RtlDestroyProcessParameters( params );
1520 return FALSE;
1522 fcntl( execfd[1], F_SETFD, 1 ); /* set close on exec */
1524 /* create the child process */
1526 if (!(pid = fork())) /* child */
1528 char **argv = build_argv( cmd_line, 1 );
1530 close( startfd[1] );
1531 close( execfd[0] );
1533 /* wait for parent to tell us to start */
1534 if (read( startfd[0], &dummy, 1 ) != 1) _exit(1);
1536 close( startfd[0] );
1537 /* Reset signals that we previously set to SIG_IGN */
1538 signal( SIGPIPE, SIG_DFL );
1539 signal( SIGCHLD, SIG_DFL );
1541 putenv( preloader_reserve );
1542 if (unixdir) chdir(unixdir);
1544 if (argv)
1546 /* first, try for a WINELOADER environment variable */
1547 const char *loader = getenv("WINELOADER");
1548 if (loader) wine_exec_wine_binary( loader, argv, NULL, TRUE );
1549 /* now use the standard search strategy */
1550 wine_exec_wine_binary( NULL, argv, NULL, TRUE );
1552 err = errno;
1553 write( execfd[1], &err, sizeof(err) );
1554 _exit(1);
1557 /* this is the parent */
1559 close( startfd[0] );
1560 close( execfd[1] );
1561 if (pid == -1)
1563 if (!env) RtlReleasePebLock();
1564 close( startfd[1] );
1565 close( execfd[0] );
1566 FILE_SetDosError();
1567 RtlDestroyProcessParameters( params );
1568 return FALSE;
1571 /* create the process on the server side */
1573 SERVER_START_REQ( new_process )
1575 req->inherit_all = inherit;
1576 req->create_flags = flags;
1577 req->unix_pid = pid;
1578 req->exe_file = hFile;
1579 if (startup->dwFlags & STARTF_USESTDHANDLES)
1581 req->hstdin = startup->hStdInput;
1582 req->hstdout = startup->hStdOutput;
1583 req->hstderr = startup->hStdError;
1585 else
1587 req->hstdin = GetStdHandle( STD_INPUT_HANDLE );
1588 req->hstdout = GetStdHandle( STD_OUTPUT_HANDLE );
1589 req->hstderr = GetStdHandle( STD_ERROR_HANDLE );
1592 if ((flags & (CREATE_NEW_CONSOLE | DETACHED_PROCESS)) != 0)
1594 /* this is temporary (for console handles). We have no way to control that the handle is invalid in child process otherwise */
1595 if (is_console_handle(req->hstdin)) req->hstdin = INVALID_HANDLE_VALUE;
1596 if (is_console_handle(req->hstdout)) req->hstdout = INVALID_HANDLE_VALUE;
1597 if (is_console_handle(req->hstderr)) req->hstderr = INVALID_HANDLE_VALUE;
1599 else
1601 if (is_console_handle(req->hstdin)) req->hstdin = console_handle_unmap(req->hstdin);
1602 if (is_console_handle(req->hstdout)) req->hstdout = console_handle_unmap(req->hstdout);
1603 if (is_console_handle(req->hstderr)) req->hstderr = console_handle_unmap(req->hstderr);
1606 wine_server_add_data( req, params, params->Size );
1607 wine_server_add_data( req, params->Environment, (env_end-params->Environment)*sizeof(WCHAR) );
1608 ret = !wine_server_call_err( req );
1609 process_info = reply->info;
1611 SERVER_END_REQ;
1613 if (!env) RtlReleasePebLock();
1614 RtlDestroyProcessParameters( params );
1615 if (!ret)
1617 close( startfd[1] );
1618 close( execfd[0] );
1619 return FALSE;
1622 /* tell child to start and wait for it to exec */
1624 write( startfd[1], &dummy, 1 );
1625 close( startfd[1] );
1627 if (read( execfd[0], &err, sizeof(err) ) > 0) /* exec failed */
1629 errno = err;
1630 FILE_SetDosError();
1631 close( execfd[0] );
1632 CloseHandle( process_info );
1633 return FALSE;
1635 close( execfd[0] );
1637 /* wait for the new process info to be ready */
1639 WaitForSingleObject( process_info, INFINITE );
1640 SERVER_START_REQ( get_new_process_info )
1642 req->info = process_info;
1643 req->pinherit = (psa && (psa->nLength >= sizeof(*psa)) && psa->bInheritHandle);
1644 req->tinherit = (tsa && (tsa->nLength >= sizeof(*tsa)) && tsa->bInheritHandle);
1645 if ((ret = !wine_server_call_err( req )))
1647 info->dwProcessId = (DWORD)reply->pid;
1648 info->dwThreadId = (DWORD)reply->tid;
1649 info->hProcess = reply->phandle;
1650 info->hThread = reply->thandle;
1651 success = reply->success;
1654 SERVER_END_REQ;
1656 if (ret && !success) /* new process failed to start */
1658 DWORD exitcode;
1659 if (GetExitCodeProcess( info->hProcess, &exitcode )) SetLastError( exitcode );
1660 CloseHandle( info->hThread );
1661 CloseHandle( info->hProcess );
1662 ret = FALSE;
1664 CloseHandle( process_info );
1665 return ret;
1669 /***********************************************************************
1670 * create_vdm_process
1672 * Create a new VDM process for a 16-bit or DOS application.
1674 static BOOL create_vdm_process( LPCWSTR filename, LPWSTR cmd_line, LPWSTR env, LPCWSTR cur_dir,
1675 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1676 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
1677 LPPROCESS_INFORMATION info, LPCSTR unixdir )
1679 static const WCHAR argsW[] = {'%','s',' ','-','-','a','p','p','-','n','a','m','e',' ','"','%','s','"',' ','%','s',0};
1681 BOOL ret;
1682 LPWSTR new_cmd_line = HeapAlloc( GetProcessHeap(), 0,
1683 (strlenW(filename) + strlenW(cmd_line) + 30) * sizeof(WCHAR) );
1685 if (!new_cmd_line)
1687 SetLastError( ERROR_OUTOFMEMORY );
1688 return FALSE;
1690 sprintfW( new_cmd_line, argsW, winevdmW, filename, cmd_line );
1691 ret = create_process( 0, winevdmW, new_cmd_line, env, cur_dir, psa, tsa, inherit,
1692 flags, startup, info, unixdir, NULL, NULL );
1693 HeapFree( GetProcessHeap(), 0, new_cmd_line );
1694 return ret;
1698 /***********************************************************************
1699 * create_cmd_process
1701 * Create a new cmd shell process for a .BAT file.
1703 static BOOL create_cmd_process( LPCWSTR filename, LPWSTR cmd_line, LPVOID env, LPCWSTR cur_dir,
1704 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1705 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
1706 LPPROCESS_INFORMATION info )
1709 static const WCHAR comspecW[] = {'C','O','M','S','P','E','C',0};
1710 static const WCHAR slashcW[] = {' ','/','c',' ',0};
1711 WCHAR comspec[MAX_PATH];
1712 WCHAR *newcmdline;
1713 BOOL ret;
1715 if (!GetEnvironmentVariableW( comspecW, comspec, sizeof(comspec)/sizeof(WCHAR) ))
1716 return FALSE;
1717 if (!(newcmdline = HeapAlloc( GetProcessHeap(), 0,
1718 (strlenW(comspec) + 4 + strlenW(cmd_line) + 1) * sizeof(WCHAR))))
1719 return FALSE;
1721 strcpyW( newcmdline, comspec );
1722 strcatW( newcmdline, slashcW );
1723 strcatW( newcmdline, cmd_line );
1724 ret = CreateProcessW( comspec, newcmdline, psa, tsa, inherit,
1725 flags, env, cur_dir, startup, info );
1726 HeapFree( GetProcessHeap(), 0, newcmdline );
1727 return ret;
1731 /*************************************************************************
1732 * get_file_name
1734 * Helper for CreateProcess: retrieve the file name to load from the
1735 * app name and command line. Store the file name in buffer, and
1736 * return a possibly modified command line.
1737 * Also returns a handle to the opened file if it's a Windows binary.
1739 static LPWSTR get_file_name( LPCWSTR appname, LPWSTR cmdline, LPWSTR buffer,
1740 int buflen, HANDLE *handle )
1742 static const WCHAR quotesW[] = {'"','%','s','"',0};
1744 WCHAR *name, *pos, *ret = NULL;
1745 const WCHAR *p;
1747 /* if we have an app name, everything is easy */
1749 if (appname)
1751 /* use the unmodified app name as file name */
1752 lstrcpynW( buffer, appname, buflen );
1753 *handle = open_exe_file( buffer );
1754 if (!(ret = cmdline) || !cmdline[0])
1756 /* no command-line, create one */
1757 if ((ret = HeapAlloc( GetProcessHeap(), 0, (strlenW(appname) + 3) * sizeof(WCHAR) )))
1758 sprintfW( ret, quotesW, appname );
1760 return ret;
1763 if (!cmdline)
1765 SetLastError( ERROR_INVALID_PARAMETER );
1766 return NULL;
1769 /* first check for a quoted file name */
1771 if ((cmdline[0] == '"') && ((p = strchrW( cmdline + 1, '"' ))))
1773 int len = p - cmdline - 1;
1774 /* extract the quoted portion as file name */
1775 if (!(name = HeapAlloc( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) ))) return NULL;
1776 memcpy( name, cmdline + 1, len * sizeof(WCHAR) );
1777 name[len] = 0;
1779 if (find_exe_file( name, buffer, buflen, handle ))
1780 ret = cmdline; /* no change necessary */
1781 goto done;
1784 /* now try the command-line word by word */
1786 if (!(name = HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline) + 1) * sizeof(WCHAR) )))
1787 return NULL;
1788 pos = name;
1789 p = cmdline;
1791 while (*p)
1793 do *pos++ = *p++; while (*p && *p != ' ');
1794 *pos = 0;
1795 if (find_exe_file( name, buffer, buflen, handle ))
1797 ret = cmdline;
1798 break;
1802 if (!ret || !strchrW( name, ' ' )) goto done; /* no change necessary */
1804 /* now build a new command-line with quotes */
1806 if (!(ret = HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline) + 3) * sizeof(WCHAR) )))
1807 goto done;
1808 sprintfW( ret, quotesW, name );
1809 strcatW( ret, p );
1811 done:
1812 HeapFree( GetProcessHeap(), 0, name );
1813 return ret;
1817 /**********************************************************************
1818 * CreateProcessA (KERNEL32.@)
1820 BOOL WINAPI CreateProcessA( LPCSTR app_name, LPSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
1821 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit,
1822 DWORD flags, LPVOID env, LPCSTR cur_dir,
1823 LPSTARTUPINFOA startup_info, LPPROCESS_INFORMATION info )
1825 BOOL ret = FALSE;
1826 WCHAR *app_nameW = NULL, *cmd_lineW = NULL, *cur_dirW = NULL;
1827 UNICODE_STRING desktopW, titleW;
1828 STARTUPINFOW infoW;
1830 desktopW.Buffer = NULL;
1831 titleW.Buffer = NULL;
1832 if (app_name && !(app_nameW = FILE_name_AtoW( app_name, TRUE ))) goto done;
1833 if (cmd_line && !(cmd_lineW = FILE_name_AtoW( cmd_line, TRUE ))) goto done;
1834 if (cur_dir && !(cur_dirW = FILE_name_AtoW( cur_dir, TRUE ))) goto done;
1836 if (startup_info->lpDesktop) RtlCreateUnicodeStringFromAsciiz( &desktopW, startup_info->lpDesktop );
1837 if (startup_info->lpTitle) RtlCreateUnicodeStringFromAsciiz( &titleW, startup_info->lpTitle );
1839 memcpy( &infoW, startup_info, sizeof(infoW) );
1840 infoW.lpDesktop = desktopW.Buffer;
1841 infoW.lpTitle = titleW.Buffer;
1843 if (startup_info->lpReserved)
1844 FIXME("StartupInfo.lpReserved is used, please report (%s)\n",
1845 debugstr_a(startup_info->lpReserved));
1847 ret = CreateProcessW( app_nameW, cmd_lineW, process_attr, thread_attr,
1848 inherit, flags, env, cur_dirW, &infoW, info );
1849 done:
1850 HeapFree( GetProcessHeap(), 0, app_nameW );
1851 HeapFree( GetProcessHeap(), 0, cmd_lineW );
1852 HeapFree( GetProcessHeap(), 0, cur_dirW );
1853 RtlFreeUnicodeString( &desktopW );
1854 RtlFreeUnicodeString( &titleW );
1855 return ret;
1859 /**********************************************************************
1860 * CreateProcessW (KERNEL32.@)
1862 BOOL WINAPI CreateProcessW( LPCWSTR app_name, LPWSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
1863 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit, DWORD flags,
1864 LPVOID env, LPCWSTR cur_dir, LPSTARTUPINFOW startup_info,
1865 LPPROCESS_INFORMATION info )
1867 BOOL retv = FALSE;
1868 HANDLE hFile = 0;
1869 char *unixdir = NULL;
1870 WCHAR name[MAX_PATH];
1871 WCHAR *tidy_cmdline, *p, *envW = env;
1872 void *res_start, *res_end;
1874 /* Process the AppName and/or CmdLine to get module name and path */
1876 TRACE("app %s cmdline %s\n", debugstr_w(app_name), debugstr_w(cmd_line) );
1878 if (!(tidy_cmdline = get_file_name( app_name, cmd_line, name, sizeof(name), &hFile )))
1879 return FALSE;
1880 if (hFile == INVALID_HANDLE_VALUE) goto done;
1882 /* Warn if unsupported features are used */
1884 if (flags & (IDLE_PRIORITY_CLASS | HIGH_PRIORITY_CLASS | REALTIME_PRIORITY_CLASS |
1885 CREATE_NEW_PROCESS_GROUP | CREATE_SEPARATE_WOW_VDM | CREATE_SHARED_WOW_VDM |
1886 CREATE_DEFAULT_ERROR_MODE | CREATE_NO_WINDOW |
1887 PROFILE_USER | PROFILE_KERNEL | PROFILE_SERVER))
1888 WARN("(%s,...): ignoring some flags in %lx\n", debugstr_w(name), flags);
1890 if (cur_dir)
1892 unixdir = wine_get_unix_file_name( cur_dir );
1894 else
1896 WCHAR buf[MAX_PATH];
1897 if (GetCurrentDirectoryW(MAX_PATH, buf)) unixdir = wine_get_unix_file_name( buf );
1900 if (env && !(flags & CREATE_UNICODE_ENVIRONMENT)) /* convert environment to unicode */
1902 char *p = env;
1903 DWORD lenW;
1905 while (*p) p += strlen(p) + 1;
1906 p++; /* final null */
1907 lenW = MultiByteToWideChar( CP_ACP, 0, env, p - (char*)env, NULL, 0 );
1908 envW = HeapAlloc( GetProcessHeap(), 0, lenW * sizeof(WCHAR) );
1909 MultiByteToWideChar( CP_ACP, 0, env, p - (char*)env, envW, lenW );
1910 flags |= CREATE_UNICODE_ENVIRONMENT;
1913 info->hThread = info->hProcess = 0;
1914 info->dwProcessId = info->dwThreadId = 0;
1916 /* Determine executable type */
1918 if (!hFile) /* builtin exe */
1920 TRACE( "starting %s as Winelib app\n", debugstr_w(name) );
1921 retv = create_process( 0, name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1922 inherit, flags, startup_info, info, unixdir, NULL, NULL );
1923 goto done;
1926 switch( MODULE_GetBinaryType( hFile, &res_start, &res_end ))
1928 case BINARY_PE_EXE:
1929 TRACE( "starting %s as Win32 binary (%p-%p)\n", debugstr_w(name), res_start, res_end );
1930 retv = create_process( hFile, name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1931 inherit, flags, startup_info, info, unixdir, res_start, res_end );
1932 break;
1933 case BINARY_OS216:
1934 case BINARY_WIN16:
1935 case BINARY_DOS:
1936 TRACE( "starting %s as Win16/DOS binary\n", debugstr_w(name) );
1937 retv = create_vdm_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1938 inherit, flags, startup_info, info, unixdir );
1939 break;
1940 case BINARY_PE_DLL:
1941 TRACE( "not starting %s since it is a dll\n", debugstr_w(name) );
1942 SetLastError( ERROR_BAD_EXE_FORMAT );
1943 break;
1944 case BINARY_UNIX_LIB:
1945 TRACE( "%s is a Unix library, starting as Winelib app\n", debugstr_w(name) );
1946 retv = create_process( hFile, name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1947 inherit, flags, startup_info, info, unixdir, NULL, NULL );
1948 break;
1949 case BINARY_UNKNOWN:
1950 /* check for .com or .bat extension */
1951 if ((p = strrchrW( name, '.' )))
1953 if (!strcmpiW( p, comW ) || !strcmpiW( p, pifW ))
1955 TRACE( "starting %s as DOS binary\n", debugstr_w(name) );
1956 retv = create_vdm_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1957 inherit, flags, startup_info, info, unixdir );
1958 break;
1960 if (!strcmpiW( p, batW ))
1962 TRACE( "starting %s as batch binary\n", debugstr_w(name) );
1963 retv = create_cmd_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1964 inherit, flags, startup_info, info );
1965 break;
1968 /* fall through */
1969 case BINARY_UNIX_EXE:
1971 /* unknown file, try as unix executable */
1972 char *unix_name;
1974 TRACE( "starting %s as Unix binary\n", debugstr_w(name) );
1976 if ((unix_name = wine_get_unix_file_name( name )))
1978 retv = (fork_and_exec( unix_name, tidy_cmdline, envW, unixdir ) != -1);
1979 HeapFree( GetProcessHeap(), 0, unix_name );
1982 break;
1984 CloseHandle( hFile );
1986 done:
1987 if (tidy_cmdline != cmd_line) HeapFree( GetProcessHeap(), 0, tidy_cmdline );
1988 if (envW != env) HeapFree( GetProcessHeap(), 0, envW );
1989 HeapFree( GetProcessHeap(), 0, unixdir );
1990 return retv;
1994 /***********************************************************************
1995 * wait_input_idle
1997 * Wrapper to call WaitForInputIdle USER function
1999 typedef DWORD (WINAPI *WaitForInputIdle_ptr)( HANDLE hProcess, DWORD dwTimeOut );
2001 static DWORD wait_input_idle( HANDLE process, DWORD timeout )
2003 HMODULE mod = GetModuleHandleA( "user32.dll" );
2004 if (mod)
2006 WaitForInputIdle_ptr ptr = (WaitForInputIdle_ptr)GetProcAddress( mod, "WaitForInputIdle" );
2007 if (ptr) return ptr( process, timeout );
2009 return 0;
2013 /***********************************************************************
2014 * WinExec (KERNEL32.@)
2016 UINT WINAPI WinExec( LPCSTR lpCmdLine, UINT nCmdShow )
2018 PROCESS_INFORMATION info;
2019 STARTUPINFOA startup;
2020 char *cmdline;
2021 UINT ret;
2023 memset( &startup, 0, sizeof(startup) );
2024 startup.cb = sizeof(startup);
2025 startup.dwFlags = STARTF_USESHOWWINDOW;
2026 startup.wShowWindow = nCmdShow;
2028 /* cmdline needs to be writeable for CreateProcess */
2029 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(lpCmdLine)+1 ))) return 0;
2030 strcpy( cmdline, lpCmdLine );
2032 if (CreateProcessA( NULL, cmdline, NULL, NULL, FALSE,
2033 0, NULL, NULL, &startup, &info ))
2035 /* Give 30 seconds to the app to come up */
2036 if (wait_input_idle( info.hProcess, 30000 ) == WAIT_FAILED)
2037 WARN("WaitForInputIdle failed: Error %ld\n", GetLastError() );
2038 ret = 33;
2039 /* Close off the handles */
2040 CloseHandle( info.hThread );
2041 CloseHandle( info.hProcess );
2043 else if ((ret = GetLastError()) >= 32)
2045 FIXME("Strange error set by CreateProcess: %d\n", ret );
2046 ret = 11;
2048 HeapFree( GetProcessHeap(), 0, cmdline );
2049 return ret;
2053 /**********************************************************************
2054 * LoadModule (KERNEL32.@)
2056 HINSTANCE WINAPI LoadModule( LPCSTR name, LPVOID paramBlock )
2058 LOADPARMS32 *params = paramBlock;
2059 PROCESS_INFORMATION info;
2060 STARTUPINFOA startup;
2061 HINSTANCE hInstance;
2062 LPSTR cmdline, p;
2063 char filename[MAX_PATH];
2064 BYTE len;
2066 if (!name) return (HINSTANCE)ERROR_FILE_NOT_FOUND;
2068 if (!SearchPathA( NULL, name, ".exe", sizeof(filename), filename, NULL ) &&
2069 !SearchPathA( NULL, name, NULL, sizeof(filename), filename, NULL ))
2070 return (HINSTANCE)GetLastError();
2072 len = (BYTE)params->lpCmdLine[0];
2073 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(filename) + len + 2 )))
2074 return (HINSTANCE)ERROR_NOT_ENOUGH_MEMORY;
2076 strcpy( cmdline, filename );
2077 p = cmdline + strlen(cmdline);
2078 *p++ = ' ';
2079 memcpy( p, params->lpCmdLine + 1, len );
2080 p[len] = 0;
2082 memset( &startup, 0, sizeof(startup) );
2083 startup.cb = sizeof(startup);
2084 if (params->lpCmdShow)
2086 startup.dwFlags = STARTF_USESHOWWINDOW;
2087 startup.wShowWindow = ((WORD *)params->lpCmdShow)[1];
2090 if (CreateProcessA( filename, cmdline, NULL, NULL, FALSE, 0,
2091 params->lpEnvAddress, NULL, &startup, &info ))
2093 /* Give 30 seconds to the app to come up */
2094 if (wait_input_idle( info.hProcess, 30000 ) == WAIT_FAILED)
2095 WARN("WaitForInputIdle failed: Error %ld\n", GetLastError() );
2096 hInstance = (HINSTANCE)33;
2097 /* Close off the handles */
2098 CloseHandle( info.hThread );
2099 CloseHandle( info.hProcess );
2101 else if ((hInstance = (HINSTANCE)GetLastError()) >= (HINSTANCE)32)
2103 FIXME("Strange error set by CreateProcess: %p\n", hInstance );
2104 hInstance = (HINSTANCE)11;
2107 HeapFree( GetProcessHeap(), 0, cmdline );
2108 return hInstance;
2112 /******************************************************************************
2113 * TerminateProcess (KERNEL32.@)
2115 BOOL WINAPI TerminateProcess( HANDLE handle, DWORD exit_code )
2117 NTSTATUS status = NtTerminateProcess( handle, exit_code );
2118 if (status) SetLastError( RtlNtStatusToDosError(status) );
2119 return !status;
2123 /***********************************************************************
2124 * ExitProcess (KERNEL32.@)
2126 void WINAPI ExitProcess( DWORD status )
2128 LdrShutdownProcess();
2129 SERVER_START_REQ( terminate_process )
2131 /* send the exit code to the server */
2132 req->handle = GetCurrentProcess();
2133 req->exit_code = status;
2134 wine_server_call( req );
2136 SERVER_END_REQ;
2137 exit( status );
2141 /***********************************************************************
2142 * GetExitCodeProcess [KERNEL32.@]
2144 * Gets termination status of specified process
2146 * RETURNS
2147 * Success: TRUE
2148 * Failure: FALSE
2150 BOOL WINAPI GetExitCodeProcess(
2151 HANDLE hProcess, /* [in] handle to the process */
2152 LPDWORD lpExitCode) /* [out] address to receive termination status */
2154 NTSTATUS status;
2155 PROCESS_BASIC_INFORMATION pbi;
2157 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
2158 sizeof(pbi), NULL);
2159 if (status == STATUS_SUCCESS)
2161 if (lpExitCode) *lpExitCode = pbi.ExitStatus;
2162 return TRUE;
2164 SetLastError( RtlNtStatusToDosError(status) );
2165 return FALSE;
2169 /***********************************************************************
2170 * SetErrorMode (KERNEL32.@)
2172 UINT WINAPI SetErrorMode( UINT mode )
2174 UINT old = process_error_mode;
2175 process_error_mode = mode;
2176 return old;
2180 /**********************************************************************
2181 * TlsAlloc [KERNEL32.@] Allocates a TLS index.
2183 * Allocates a thread local storage index
2185 * RETURNS
2186 * Success: TLS Index
2187 * Failure: 0xFFFFFFFF
2189 DWORD WINAPI TlsAlloc( void )
2191 DWORD index;
2192 PEB * const peb = NtCurrentTeb()->Peb;
2194 RtlAcquirePebLock();
2195 index = RtlFindClearBitsAndSet( peb->TlsBitmap, 1, 0 );
2196 if (index != ~0UL) NtCurrentTeb()->TlsSlots[index] = 0; /* clear the value */
2197 else
2199 index = RtlFindClearBitsAndSet( peb->TlsExpansionBitmap, 1, 0 );
2200 if (index != ~0UL)
2202 if (!NtCurrentTeb()->TlsExpansionSlots &&
2203 !(NtCurrentTeb()->TlsExpansionSlots = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY,
2204 8 * sizeof(peb->TlsExpansionBitmapBits) * sizeof(void*) )))
2206 RtlClearBits( peb->TlsExpansionBitmap, index, 1 );
2207 index = ~0UL;
2208 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
2210 else
2212 NtCurrentTeb()->TlsExpansionSlots[index] = 0; /* clear the value */
2213 index += TLS_MINIMUM_AVAILABLE;
2216 else SetLastError( ERROR_NO_MORE_ITEMS );
2218 RtlReleasePebLock();
2219 return index;
2223 /**********************************************************************
2224 * TlsFree [KERNEL32.@] Releases a TLS index.
2226 * Releases a thread local storage index, making it available for reuse
2228 * RETURNS
2229 * Success: TRUE
2230 * Failure: FALSE
2232 BOOL WINAPI TlsFree(
2233 DWORD index) /* [in] TLS Index to free */
2235 BOOL ret;
2237 RtlAcquirePebLock();
2238 if (index >= TLS_MINIMUM_AVAILABLE)
2240 ret = RtlAreBitsSet( NtCurrentTeb()->Peb->TlsExpansionBitmap, index - TLS_MINIMUM_AVAILABLE, 1 );
2241 if (ret) RtlClearBits( NtCurrentTeb()->Peb->TlsExpansionBitmap, index - TLS_MINIMUM_AVAILABLE, 1 );
2243 else
2245 ret = RtlAreBitsSet( NtCurrentTeb()->Peb->TlsBitmap, index, 1 );
2246 if (ret) RtlClearBits( NtCurrentTeb()->Peb->TlsBitmap, index, 1 );
2248 if (ret) NtSetInformationThread( GetCurrentThread(), ThreadZeroTlsCell, &index, sizeof(index) );
2249 else SetLastError( ERROR_INVALID_PARAMETER );
2250 RtlReleasePebLock();
2251 return TRUE;
2255 /**********************************************************************
2256 * TlsGetValue [KERNEL32.@] Gets value in a thread's TLS slot
2258 * RETURNS
2259 * Success: Value stored in calling thread's TLS slot for index
2260 * Failure: 0 and GetLastError() returns NO_ERROR
2262 LPVOID WINAPI TlsGetValue(
2263 DWORD index) /* [in] TLS index to retrieve value for */
2265 LPVOID ret;
2267 if (index < TLS_MINIMUM_AVAILABLE)
2269 ret = NtCurrentTeb()->TlsSlots[index];
2271 else
2273 index -= TLS_MINIMUM_AVAILABLE;
2274 if (index >= 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits))
2276 SetLastError( ERROR_INVALID_PARAMETER );
2277 return NULL;
2279 if (!NtCurrentTeb()->TlsExpansionSlots) ret = NULL;
2280 else ret = NtCurrentTeb()->TlsExpansionSlots[index];
2282 SetLastError( ERROR_SUCCESS );
2283 return ret;
2287 /**********************************************************************
2288 * TlsSetValue [KERNEL32.@] Stores a value in the thread's TLS slot.
2290 * RETURNS
2291 * Success: TRUE
2292 * Failure: FALSE
2294 BOOL WINAPI TlsSetValue(
2295 DWORD index, /* [in] TLS index to set value for */
2296 LPVOID value) /* [in] Value to be stored */
2298 if (index < TLS_MINIMUM_AVAILABLE)
2300 NtCurrentTeb()->TlsSlots[index] = value;
2302 else
2304 index -= TLS_MINIMUM_AVAILABLE;
2305 if (index >= 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits))
2307 SetLastError( ERROR_INVALID_PARAMETER );
2308 return FALSE;
2310 if (!NtCurrentTeb()->TlsExpansionSlots &&
2311 !(NtCurrentTeb()->TlsExpansionSlots = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY,
2312 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits) * sizeof(void*) )))
2314 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
2315 return FALSE;
2317 NtCurrentTeb()->TlsExpansionSlots[index] = value;
2319 return TRUE;
2323 /***********************************************************************
2324 * GetProcessFlags (KERNEL32.@)
2326 DWORD WINAPI GetProcessFlags( DWORD processid )
2328 IMAGE_NT_HEADERS *nt;
2329 DWORD flags = 0;
2331 if (processid && processid != GetCurrentProcessId()) return 0;
2333 if ((nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress )))
2335 if (nt->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_CUI)
2336 flags |= PDB32_CONSOLE_PROC;
2338 if (!AreFileApisANSI()) flags |= PDB32_FILE_APIS_OEM;
2339 if (IsDebuggerPresent()) flags |= PDB32_DEBUGGED;
2340 return flags;
2344 /***********************************************************************
2345 * GetProcessDword (KERNEL.485)
2346 * GetProcessDword (KERNEL32.18)
2347 * 'Of course you cannot directly access Windows internal structures'
2349 DWORD WINAPI GetProcessDword( DWORD dwProcessID, INT offset )
2351 DWORD x, y;
2352 STARTUPINFOW siw;
2354 TRACE("(%ld, %d)\n", dwProcessID, offset );
2356 if (dwProcessID && dwProcessID != GetCurrentProcessId())
2358 ERR("%d: process %lx not accessible\n", offset, dwProcessID);
2359 return 0;
2362 switch ( offset )
2364 case GPD_APP_COMPAT_FLAGS:
2365 return GetAppCompatFlags16(0);
2366 case GPD_LOAD_DONE_EVENT:
2367 return 0;
2368 case GPD_HINSTANCE16:
2369 return GetTaskDS16();
2370 case GPD_WINDOWS_VERSION:
2371 return GetExeVersion16();
2372 case GPD_THDB:
2373 return (DWORD)NtCurrentTeb() - 0x10 /* FIXME */;
2374 case GPD_PDB:
2375 return (DWORD)NtCurrentTeb()->Peb;
2376 case GPD_STARTF_SHELLDATA: /* return stdoutput handle from startupinfo ??? */
2377 GetStartupInfoW(&siw);
2378 return (DWORD)siw.hStdOutput;
2379 case GPD_STARTF_HOTKEY: /* return stdinput handle from startupinfo ??? */
2380 GetStartupInfoW(&siw);
2381 return (DWORD)siw.hStdInput;
2382 case GPD_STARTF_SHOWWINDOW:
2383 GetStartupInfoW(&siw);
2384 return siw.wShowWindow;
2385 case GPD_STARTF_SIZE:
2386 GetStartupInfoW(&siw);
2387 x = siw.dwXSize;
2388 if ( (INT)x == CW_USEDEFAULT ) x = CW_USEDEFAULT16;
2389 y = siw.dwYSize;
2390 if ( (INT)y == CW_USEDEFAULT ) y = CW_USEDEFAULT16;
2391 return MAKELONG( x, y );
2392 case GPD_STARTF_POSITION:
2393 GetStartupInfoW(&siw);
2394 x = siw.dwX;
2395 if ( (INT)x == CW_USEDEFAULT ) x = CW_USEDEFAULT16;
2396 y = siw.dwY;
2397 if ( (INT)y == CW_USEDEFAULT ) y = CW_USEDEFAULT16;
2398 return MAKELONG( x, y );
2399 case GPD_STARTF_FLAGS:
2400 GetStartupInfoW(&siw);
2401 return siw.dwFlags;
2402 case GPD_PARENT:
2403 return 0;
2404 case GPD_FLAGS:
2405 return GetProcessFlags(0);
2406 case GPD_USERDATA:
2407 return process_dword;
2408 default:
2409 ERR("Unknown offset %d\n", offset );
2410 return 0;
2414 /***********************************************************************
2415 * SetProcessDword (KERNEL.484)
2416 * 'Of course you cannot directly access Windows internal structures'
2418 void WINAPI SetProcessDword( DWORD dwProcessID, INT offset, DWORD value )
2420 TRACE("(%ld, %d)\n", dwProcessID, offset );
2422 if (dwProcessID && dwProcessID != GetCurrentProcessId())
2424 ERR("%d: process %lx not accessible\n", offset, dwProcessID);
2425 return;
2428 switch ( offset )
2430 case GPD_APP_COMPAT_FLAGS:
2431 case GPD_LOAD_DONE_EVENT:
2432 case GPD_HINSTANCE16:
2433 case GPD_WINDOWS_VERSION:
2434 case GPD_THDB:
2435 case GPD_PDB:
2436 case GPD_STARTF_SHELLDATA:
2437 case GPD_STARTF_HOTKEY:
2438 case GPD_STARTF_SHOWWINDOW:
2439 case GPD_STARTF_SIZE:
2440 case GPD_STARTF_POSITION:
2441 case GPD_STARTF_FLAGS:
2442 case GPD_PARENT:
2443 case GPD_FLAGS:
2444 ERR("Not allowed to modify offset %d\n", offset );
2445 break;
2446 case GPD_USERDATA:
2447 process_dword = value;
2448 break;
2449 default:
2450 ERR("Unknown offset %d\n", offset );
2451 break;
2456 /***********************************************************************
2457 * ExitProcess (KERNEL.466)
2459 void WINAPI ExitProcess16( WORD status )
2461 DWORD count;
2462 ReleaseThunkLock( &count );
2463 ExitProcess( status );
2467 /*********************************************************************
2468 * OpenProcess (KERNEL32.@)
2470 HANDLE WINAPI OpenProcess( DWORD access, BOOL inherit, DWORD id )
2472 HANDLE ret = 0;
2473 SERVER_START_REQ( open_process )
2475 req->pid = id;
2476 req->access = access;
2477 req->inherit = inherit;
2478 if (!wine_server_call_err( req )) ret = reply->handle;
2480 SERVER_END_REQ;
2481 return ret;
2485 /*********************************************************************
2486 * MapProcessHandle (KERNEL.483)
2487 * GetProcessId (KERNEL32.@)
2489 DWORD WINAPI GetProcessId( HANDLE hProcess )
2491 NTSTATUS status;
2492 PROCESS_BASIC_INFORMATION pbi;
2494 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
2495 sizeof(pbi), NULL);
2496 if (status == STATUS_SUCCESS) return pbi.UniqueProcessId;
2497 SetLastError( RtlNtStatusToDosError(status) );
2498 return 0;
2502 /*********************************************************************
2503 * CloseW32Handle (KERNEL.474)
2504 * CloseHandle (KERNEL32.@)
2506 BOOL WINAPI CloseHandle( HANDLE handle )
2508 NTSTATUS status;
2510 /* stdio handles need special treatment */
2511 if ((handle == (HANDLE)STD_INPUT_HANDLE) ||
2512 (handle == (HANDLE)STD_OUTPUT_HANDLE) ||
2513 (handle == (HANDLE)STD_ERROR_HANDLE))
2514 handle = GetStdHandle( (DWORD)handle );
2516 if (is_console_handle(handle))
2517 return CloseConsoleHandle(handle);
2519 status = NtClose( handle );
2520 if (status) SetLastError( RtlNtStatusToDosError(status) );
2521 return !status;
2525 /*********************************************************************
2526 * GetHandleInformation (KERNEL32.@)
2528 BOOL WINAPI GetHandleInformation( HANDLE handle, LPDWORD flags )
2530 BOOL ret;
2531 SERVER_START_REQ( set_handle_info )
2533 req->handle = handle;
2534 req->flags = 0;
2535 req->mask = 0;
2536 req->fd = -1;
2537 ret = !wine_server_call_err( req );
2538 if (ret && flags) *flags = reply->old_flags;
2540 SERVER_END_REQ;
2541 return ret;
2545 /*********************************************************************
2546 * SetHandleInformation (KERNEL32.@)
2548 BOOL WINAPI SetHandleInformation( HANDLE handle, DWORD mask, DWORD flags )
2550 BOOL ret;
2551 SERVER_START_REQ( set_handle_info )
2553 req->handle = handle;
2554 req->flags = flags;
2555 req->mask = mask;
2556 req->fd = -1;
2557 ret = !wine_server_call_err( req );
2559 SERVER_END_REQ;
2560 return ret;
2564 /*********************************************************************
2565 * DuplicateHandle (KERNEL32.@)
2567 BOOL WINAPI DuplicateHandle( HANDLE source_process, HANDLE source,
2568 HANDLE dest_process, HANDLE *dest,
2569 DWORD access, BOOL inherit, DWORD options )
2571 NTSTATUS status;
2573 if (is_console_handle(source))
2575 /* FIXME: this test is not sufficient, we need to test process ids, not handles */
2576 if (source_process != dest_process ||
2577 source_process != GetCurrentProcess())
2579 SetLastError(ERROR_INVALID_PARAMETER);
2580 return FALSE;
2582 *dest = DuplicateConsoleHandle( source, access, inherit, options );
2583 return (*dest != INVALID_HANDLE_VALUE);
2585 status = NtDuplicateObject( source_process, source, dest_process, dest,
2586 access, inherit ? OBJ_INHERIT : 0, options );
2587 if (status) SetLastError( RtlNtStatusToDosError(status) );
2588 return !status;
2592 /***********************************************************************
2593 * ConvertToGlobalHandle (KERNEL.476)
2594 * ConvertToGlobalHandle (KERNEL32.@)
2596 HANDLE WINAPI ConvertToGlobalHandle(HANDLE hSrc)
2598 HANDLE ret = INVALID_HANDLE_VALUE;
2599 DuplicateHandle( GetCurrentProcess(), hSrc, GetCurrentProcess(), &ret, 0, FALSE,
2600 DUP_HANDLE_MAKE_GLOBAL | DUP_HANDLE_SAME_ACCESS | DUP_HANDLE_CLOSE_SOURCE );
2601 return ret;
2605 /***********************************************************************
2606 * SetHandleContext (KERNEL32.@)
2608 BOOL WINAPI SetHandleContext(HANDLE hnd,DWORD context)
2610 FIXME("(%p,%ld), stub. In case this got called by WSOCK32/WS2_32: "
2611 "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd,context);
2612 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2613 return FALSE;
2617 /***********************************************************************
2618 * GetHandleContext (KERNEL32.@)
2620 DWORD WINAPI GetHandleContext(HANDLE hnd)
2622 FIXME("(%p), stub. In case this got called by WSOCK32/WS2_32: "
2623 "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd);
2624 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2625 return 0;
2629 /***********************************************************************
2630 * CreateSocketHandle (KERNEL32.@)
2632 HANDLE WINAPI CreateSocketHandle(void)
2634 FIXME("(), stub. In case this got called by WSOCK32/WS2_32: "
2635 "the external WINSOCK DLLs won't work with WINE, don't use them.\n");
2636 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2637 return INVALID_HANDLE_VALUE;
2641 /***********************************************************************
2642 * SetPriorityClass (KERNEL32.@)
2644 BOOL WINAPI SetPriorityClass( HANDLE hprocess, DWORD priorityclass )
2646 BOOL ret;
2647 SERVER_START_REQ( set_process_info )
2649 req->handle = hprocess;
2650 req->priority = priorityclass;
2651 req->mask = SET_PROCESS_INFO_PRIORITY;
2652 ret = !wine_server_call_err( req );
2654 SERVER_END_REQ;
2655 return ret;
2659 /***********************************************************************
2660 * GetPriorityClass (KERNEL32.@)
2662 DWORD WINAPI GetPriorityClass(HANDLE hProcess)
2664 NTSTATUS status;
2665 PROCESS_BASIC_INFORMATION pbi;
2667 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
2668 sizeof(pbi), NULL);
2669 if (status == STATUS_SUCCESS) return pbi.BasePriority;
2670 SetLastError( RtlNtStatusToDosError(status) );
2671 return 0;
2675 /***********************************************************************
2676 * SetProcessAffinityMask (KERNEL32.@)
2678 BOOL WINAPI SetProcessAffinityMask( HANDLE hProcess, DWORD_PTR affmask )
2680 BOOL ret;
2681 SERVER_START_REQ( set_process_info )
2683 req->handle = hProcess;
2684 req->affinity = affmask;
2685 req->mask = SET_PROCESS_INFO_AFFINITY;
2686 ret = !wine_server_call_err( req );
2688 SERVER_END_REQ;
2689 return ret;
2693 /**********************************************************************
2694 * GetProcessAffinityMask (KERNEL32.@)
2696 BOOL WINAPI GetProcessAffinityMask( HANDLE hProcess,
2697 LPDWORD lpProcessAffinityMask,
2698 LPDWORD lpSystemAffinityMask )
2700 BOOL ret = FALSE;
2701 SERVER_START_REQ( get_process_info )
2703 req->handle = hProcess;
2704 if (!wine_server_call_err( req ))
2706 if (lpProcessAffinityMask) *lpProcessAffinityMask = reply->process_affinity;
2707 if (lpSystemAffinityMask) *lpSystemAffinityMask = reply->system_affinity;
2708 ret = TRUE;
2711 SERVER_END_REQ;
2712 return ret;
2716 /***********************************************************************
2717 * GetProcessVersion (KERNEL32.@)
2719 DWORD WINAPI GetProcessVersion( DWORD processid )
2721 IMAGE_NT_HEADERS *nt;
2723 if (processid && processid != GetCurrentProcessId())
2725 FIXME("should use ReadProcessMemory\n");
2726 return 0;
2728 if ((nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress )))
2729 return ((nt->OptionalHeader.MajorSubsystemVersion << 16) |
2730 nt->OptionalHeader.MinorSubsystemVersion);
2731 return 0;
2735 /***********************************************************************
2736 * SetProcessWorkingSetSize [KERNEL32.@]
2737 * Sets the min/max working set sizes for a specified process.
2739 * PARAMS
2740 * hProcess [I] Handle to the process of interest
2741 * minset [I] Specifies minimum working set size
2742 * maxset [I] Specifies maximum working set size
2744 * RETURNS
2745 * Success: TRUE
2746 * Failure: FALSE
2748 BOOL WINAPI SetProcessWorkingSetSize(HANDLE hProcess, SIZE_T minset,
2749 SIZE_T maxset)
2751 FIXME("(%p,%ld,%ld): stub - harmless\n",hProcess,minset,maxset);
2752 if(( minset == (SIZE_T)-1) && (maxset == (SIZE_T)-1)) {
2753 /* Trim the working set to zero */
2754 /* Swap the process out of physical RAM */
2756 return TRUE;
2759 /***********************************************************************
2760 * GetProcessWorkingSetSize (KERNEL32.@)
2762 BOOL WINAPI GetProcessWorkingSetSize(HANDLE hProcess, PSIZE_T minset,
2763 PSIZE_T maxset)
2765 FIXME("(%p,%p,%p): stub\n",hProcess,minset,maxset);
2766 /* 32 MB working set size */
2767 if (minset) *minset = 32*1024*1024;
2768 if (maxset) *maxset = 32*1024*1024;
2769 return TRUE;
2773 /***********************************************************************
2774 * SetProcessShutdownParameters (KERNEL32.@)
2776 BOOL WINAPI SetProcessShutdownParameters(DWORD level, DWORD flags)
2778 FIXME("(%08lx, %08lx): partial stub.\n", level, flags);
2779 shutdown_flags = flags;
2780 shutdown_priority = level;
2781 return TRUE;
2785 /***********************************************************************
2786 * GetProcessShutdownParameters (KERNEL32.@)
2789 BOOL WINAPI GetProcessShutdownParameters( LPDWORD lpdwLevel, LPDWORD lpdwFlags )
2791 *lpdwLevel = shutdown_priority;
2792 *lpdwFlags = shutdown_flags;
2793 return TRUE;
2797 /***********************************************************************
2798 * GetProcessPriorityBoost (KERNEL32.@)
2800 BOOL WINAPI GetProcessPriorityBoost(HANDLE hprocess,PBOOL pDisablePriorityBoost)
2802 FIXME("(%p,%p): semi-stub\n", hprocess, pDisablePriorityBoost);
2804 /* Report that no boost is present.. */
2805 *pDisablePriorityBoost = FALSE;
2807 return TRUE;
2810 /***********************************************************************
2811 * SetProcessPriorityBoost (KERNEL32.@)
2813 BOOL WINAPI SetProcessPriorityBoost(HANDLE hprocess,BOOL disableboost)
2815 FIXME("(%p,%d): stub\n",hprocess,disableboost);
2816 /* Say we can do it. I doubt the program will notice that we don't. */
2817 return TRUE;
2821 /***********************************************************************
2822 * ReadProcessMemory (KERNEL32.@)
2824 BOOL WINAPI ReadProcessMemory( HANDLE process, LPCVOID addr, LPVOID buffer, SIZE_T size,
2825 SIZE_T *bytes_read )
2827 NTSTATUS status = NtReadVirtualMemory( process, addr, buffer, size, bytes_read );
2828 if (status) SetLastError( RtlNtStatusToDosError(status) );
2829 return !status;
2833 /***********************************************************************
2834 * WriteProcessMemory (KERNEL32.@)
2836 BOOL WINAPI WriteProcessMemory( HANDLE process, LPVOID addr, LPCVOID buffer, SIZE_T size,
2837 SIZE_T *bytes_written )
2839 NTSTATUS status = NtWriteVirtualMemory( process, addr, buffer, size, bytes_written );
2840 if (status) SetLastError( RtlNtStatusToDosError(status) );
2841 return !status;
2845 /****************************************************************************
2846 * FlushInstructionCache (KERNEL32.@)
2848 BOOL WINAPI FlushInstructionCache(HANDLE hProcess, LPCVOID lpBaseAddress, SIZE_T dwSize)
2850 NTSTATUS status;
2851 if (GetVersion() & 0x80000000) return TRUE; /* not NT, always TRUE */
2852 status = NtFlushInstructionCache( hProcess, lpBaseAddress, dwSize );
2853 if (status) SetLastError( RtlNtStatusToDosError(status) );
2854 return !status;
2858 /******************************************************************
2859 * GetProcessIoCounters (KERNEL32.@)
2861 BOOL WINAPI GetProcessIoCounters(HANDLE hProcess, PIO_COUNTERS ioc)
2863 NTSTATUS status;
2865 status = NtQueryInformationProcess(hProcess, ProcessIoCounters,
2866 ioc, sizeof(*ioc), NULL);
2867 if (status) SetLastError( RtlNtStatusToDosError(status) );
2868 return !status;
2871 /***********************************************************************
2872 * ProcessIdToSessionId (KERNEL32.@)
2873 * This function is available on Terminal Server 4SP4 and Windows 2000
2875 BOOL WINAPI ProcessIdToSessionId( DWORD procid, DWORD *sessionid_ptr )
2877 /* According to MSDN, if the calling process is not in a terminal
2878 * services environment, then the sessionid returned is zero.
2880 *sessionid_ptr = 0;
2881 return TRUE;
2885 /***********************************************************************
2886 * RegisterServiceProcess (KERNEL.491)
2887 * RegisterServiceProcess (KERNEL32.@)
2889 * A service process calls this function to ensure that it continues to run
2890 * even after a user logged off.
2892 DWORD WINAPI RegisterServiceProcess(DWORD dwProcessId, DWORD dwType)
2894 /* I don't think that Wine needs to do anything in this function */
2895 return 1; /* success */
2899 /***********************************************************************
2900 * GetSystemMSecCount (SYSTEM.6)
2901 * GetTickCount (KERNEL32.@)
2903 * Get the number of milliseconds the system has been running.
2905 * PARANS
2906 * None.
2908 * RETURNS
2909 * The current tick count.
2911 * NOTES
2912 * -The value returned will wrap arounf every 2^32 milliseconds.
2913 * -Under Windows, tick 0 is the moment at which the system is rebooted.
2914 * Under Wine, tick 0 begins at the moment the wineserver process is started,
2916 DWORD WINAPI GetTickCount(void)
2918 struct timeval t;
2919 gettimeofday( &t, NULL );
2920 return ((t.tv_sec * 1000) + (t.tv_usec / 1000)) - server_startticks;
2924 /***********************************************************************
2925 * GetCurrentProcess (KERNEL32.@)
2927 * Get a handle to the current process.
2929 * PARAMS
2930 * None.
2932 * RETURNS
2933 * A handle representing the current process.
2935 #undef GetCurrentProcess
2936 HANDLE WINAPI GetCurrentProcess(void)
2938 return (HANDLE)0xffffffff;