Added some unit tests for the CryptAcquireContext API function.
[wine.git] / dlls / kernel / process.c
blobe00cae29ab37278eae7c4c1e331609368b9e58d3
1 /*
2 * Win32 processes
4 * Copyright 1996, 1998 Alexandre Julliard
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
21 #include "config.h"
22 #include "wine/port.h"
24 #include <assert.h>
25 #include <ctype.h>
26 #include <errno.h>
27 #include <locale.h>
28 #include <signal.h>
29 #include <stdio.h>
30 #include <time.h>
31 #ifdef HAVE_SYS_TIME_H
32 # include <sys/time.h>
33 #endif
34 #include <sys/types.h>
36 #include "wine/winbase16.h"
37 #include "wine/winuser16.h"
38 #include "ntstatus.h"
39 #include "thread.h"
40 #include "module.h"
41 #include "kernel_private.h"
42 #include "wine/exception.h"
43 #include "wine/server.h"
44 #include "wine/unicode.h"
45 #include "wine/debug.h"
47 WINE_DEFAULT_DEBUG_CHANNEL(process);
48 WINE_DECLARE_DEBUG_CHANNEL(file);
49 WINE_DECLARE_DEBUG_CHANNEL(server);
50 WINE_DECLARE_DEBUG_CHANNEL(relay);
52 typedef struct
54 LPSTR lpEnvAddress;
55 LPSTR lpCmdLine;
56 LPSTR lpCmdShow;
57 DWORD dwReserved;
58 } LOADPARMS32;
60 static UINT process_error_mode;
62 static HANDLE main_exe_file;
63 static DWORD shutdown_flags = 0;
64 static DWORD shutdown_priority = 0x280;
65 static DWORD process_dword;
67 static unsigned int server_startticks;
68 int main_create_flags = 0;
69 HMODULE kernel32_handle = 0;
71 const WCHAR *DIR_Windows = NULL;
72 const WCHAR *DIR_System = NULL;
74 /* Process flags */
75 #define PDB32_DEBUGGED 0x0001 /* Process is being debugged */
76 #define PDB32_WIN16_PROC 0x0008 /* Win16 process */
77 #define PDB32_DOS_PROC 0x0010 /* Dos process */
78 #define PDB32_CONSOLE_PROC 0x0020 /* Console process */
79 #define PDB32_FILE_APIS_OEM 0x0040 /* File APIs are OEM */
80 #define PDB32_WIN32S_PROC 0x8000 /* Win32s process */
82 static const WCHAR comW[] = {'.','c','o','m',0};
83 static const WCHAR batW[] = {'.','b','a','t',0};
84 static const WCHAR winevdmW[] = {'w','i','n','e','v','d','m','.','e','x','e',0};
86 extern void SHELL_LoadRegistry(void);
87 extern void VOLUME_CreateDevices(void);
88 extern void VERSION_Init( const WCHAR *appname );
89 extern void LOCALE_Init(void);
91 /***********************************************************************
92 * contains_path
94 inline static int contains_path( LPCWSTR name )
96 return ((*name && (name[1] == ':')) || strchrW(name, '/') || strchrW(name, '\\'));
100 /***********************************************************************
101 * is_special_env_var
103 * Check if an environment variable needs to be handled specially when
104 * passed through the Unix environment (i.e. prefixed with "WINE").
106 inline static int is_special_env_var( const char *var )
108 return (!strncmp( var, "PATH=", sizeof("PATH=")-1 ) ||
109 !strncmp( var, "HOME=", sizeof("HOME=")-1 ) ||
110 !strncmp( var, "TEMP=", sizeof("TEMP=")-1 ) ||
111 !strncmp( var, "TMP=", sizeof("TMP=")-1 ));
115 /***************************************************************************
116 * get_builtin_path
118 * Get the path of a builtin module when the native file does not exist.
120 static BOOL get_builtin_path( const WCHAR *libname, const WCHAR *ext, WCHAR *filename, UINT size )
122 WCHAR *file_part;
123 UINT len = strlenW( DIR_System );
125 if (contains_path( libname ))
127 if (RtlGetFullPathName_U( libname, size * sizeof(WCHAR),
128 filename, &file_part ) > size * sizeof(WCHAR))
129 return FALSE; /* too long */
131 if (strncmpiW( filename, DIR_System, len ) || filename[len] != '\\')
132 return FALSE;
133 while (filename[len] == '\\') len++;
134 if (filename + len != file_part) return FALSE;
136 else
138 if (strlenW(libname) + len + 2 >= size) return FALSE; /* too long */
139 memcpy( filename, DIR_System, len * sizeof(WCHAR) );
140 file_part = filename + len;
141 if (file_part > filename && file_part[-1] != '\\') *file_part++ = '\\';
142 strcpyW( file_part, libname );
144 if (ext && !strchrW( file_part, '.' ))
146 if (file_part + strlenW(file_part) + strlenW(ext) + 1 > filename + size)
147 return FALSE; /* too long */
148 strcatW( file_part, ext );
150 return TRUE;
154 /***********************************************************************
155 * open_builtin_exe_file
157 * Open an exe file for a builtin exe.
159 static void *open_builtin_exe_file( const WCHAR *name, char *error, int error_size,
160 int test_only, int *file_exists )
162 char exename[MAX_PATH];
163 WCHAR *p;
164 UINT i, len;
166 if ((p = strrchrW( name, '/' ))) name = p + 1;
167 if ((p = strrchrW( name, '\\' ))) name = p + 1;
169 /* we don't want to depend on the current codepage here */
170 len = strlenW( name ) + 1;
171 if (len >= sizeof(exename)) return NULL;
172 for (i = 0; i < len; i++)
174 if (name[i] > 127) return NULL;
175 exename[i] = (char)name[i];
176 if (exename[i] >= 'A' && exename[i] <= 'Z') exename[i] += 'a' - 'A';
178 return wine_dll_load_main_exe( exename, error, error_size, test_only, file_exists );
182 /***********************************************************************
183 * open_exe_file
185 * Open a specific exe file, taking load order into account.
186 * Returns the file handle or 0 for a builtin exe.
188 static HANDLE open_exe_file( const WCHAR *name )
190 enum loadorder_type loadorder[LOADORDER_NTYPES];
191 WCHAR buffer[MAX_PATH];
192 HANDLE handle;
193 int i, file_exists;
195 TRACE("looking for %s\n", debugstr_w(name) );
197 if ((handle = CreateFileW( name, GENERIC_READ, FILE_SHARE_READ,
198 NULL, OPEN_EXISTING, 0, 0 )) == INVALID_HANDLE_VALUE)
200 /* file doesn't exist, check for builtin */
201 if (!contains_path( name )) goto error;
202 if (!get_builtin_path( name, NULL, buffer, sizeof(buffer) )) goto error;
203 name = buffer;
206 MODULE_GetLoadOrderW( loadorder, NULL, name );
208 for(i = 0; i < LOADORDER_NTYPES; i++)
210 if (loadorder[i] == LOADORDER_INVALID) break;
211 switch(loadorder[i])
213 case LOADORDER_DLL:
214 TRACE( "Trying native exe %s\n", debugstr_w(name) );
215 if (handle != INVALID_HANDLE_VALUE) return handle;
216 break;
217 case LOADORDER_BI:
218 TRACE( "Trying built-in exe %s\n", debugstr_w(name) );
219 open_builtin_exe_file( name, NULL, 0, 1, &file_exists );
220 if (file_exists)
222 if (handle != INVALID_HANDLE_VALUE) CloseHandle(handle);
223 return 0;
225 default:
226 break;
229 if (handle != INVALID_HANDLE_VALUE) CloseHandle(handle);
231 error:
232 SetLastError( ERROR_FILE_NOT_FOUND );
233 return INVALID_HANDLE_VALUE;
237 /***********************************************************************
238 * find_exe_file
240 * Open an exe file, and return the full name and file handle.
241 * Returns FALSE if file could not be found.
242 * If file exists but cannot be opened, returns TRUE and set handle to INVALID_HANDLE_VALUE.
243 * If file is a builtin exe, returns TRUE and sets handle to 0.
245 static BOOL find_exe_file( const WCHAR *name, WCHAR *buffer, int buflen, HANDLE *handle )
247 static const WCHAR exeW[] = {'.','e','x','e',0};
249 enum loadorder_type loadorder[LOADORDER_NTYPES];
250 int i, file_exists;
252 TRACE("looking for %s\n", debugstr_w(name) );
254 if (!SearchPathW( NULL, name, exeW, buflen, buffer, NULL ) &&
255 !get_builtin_path( name, exeW, buffer, buflen ))
257 /* no builtin found, try native without extension in case it is a Unix app */
259 if (SearchPathW( NULL, name, NULL, buflen, buffer, NULL ))
261 TRACE( "Trying native/Unix binary %s\n", debugstr_w(buffer) );
262 if ((*handle = CreateFileW( buffer, GENERIC_READ, FILE_SHARE_READ,
263 NULL, OPEN_EXISTING, 0, 0 )) != INVALID_HANDLE_VALUE)
264 return TRUE;
266 return FALSE;
269 MODULE_GetLoadOrderW( loadorder, NULL, buffer );
271 for(i = 0; i < LOADORDER_NTYPES; i++)
273 if (loadorder[i] == LOADORDER_INVALID) break;
274 switch(loadorder[i])
276 case LOADORDER_DLL:
277 TRACE( "Trying native exe %s\n", debugstr_w(buffer) );
278 if ((*handle = CreateFileW( buffer, GENERIC_READ, FILE_SHARE_READ,
279 NULL, OPEN_EXISTING, 0, 0 )) != INVALID_HANDLE_VALUE)
280 return TRUE;
281 if (GetLastError() != ERROR_FILE_NOT_FOUND) return TRUE;
282 break;
283 case LOADORDER_BI:
284 TRACE( "Trying built-in exe %s\n", debugstr_w(buffer) );
285 open_builtin_exe_file( buffer, NULL, 0, 1, &file_exists );
286 if (file_exists)
288 *handle = 0;
289 return TRUE;
291 break;
292 default:
293 break;
296 SetLastError( ERROR_FILE_NOT_FOUND );
297 return FALSE;
301 /**********************************************************************
302 * load_pe_exe
304 * Load a PE format EXE file.
306 static HMODULE load_pe_exe( const WCHAR *name, HANDLE file )
308 IMAGE_NT_HEADERS *nt;
309 HANDLE mapping;
310 void *module;
311 OBJECT_ATTRIBUTES attr;
312 LARGE_INTEGER size;
313 DWORD len = 0;
314 UINT drive_type;
316 attr.Length = sizeof(attr);
317 attr.RootDirectory = 0;
318 attr.ObjectName = NULL;
319 attr.Attributes = 0;
320 attr.SecurityDescriptor = NULL;
321 attr.SecurityQualityOfService = NULL;
322 size.QuadPart = 0;
324 if (NtCreateSection( &mapping, STANDARD_RIGHTS_REQUIRED | SECTION_QUERY | SECTION_MAP_READ,
325 &attr, &size, 0, SEC_IMAGE, file ) != STATUS_SUCCESS)
326 return NULL;
328 module = NULL;
329 if (NtMapViewOfSection( mapping, GetCurrentProcess(), &module, 0, 0, &size, &len,
330 ViewShare, 0, PAGE_READONLY ) != STATUS_SUCCESS)
331 return NULL;
333 NtClose( mapping );
335 /* virus check */
336 nt = RtlImageNtHeader( module );
337 if (nt->OptionalHeader.AddressOfEntryPoint)
339 if (!RtlImageRvaToSection( nt, module, nt->OptionalHeader.AddressOfEntryPoint ))
340 MESSAGE("VIRUS WARNING: PE module %s has an invalid entrypoint (0x%08lx) "
341 "outside all sections (possibly infected by Tchernobyl/SpaceFiller virus)!\n",
342 debugstr_w(name), nt->OptionalHeader.AddressOfEntryPoint );
345 drive_type = GetDriveTypeW( name );
346 /* don't keep the file handle open on removable media */
347 if (drive_type == DRIVE_REMOVABLE || drive_type == DRIVE_CDROM)
349 CloseHandle( main_exe_file );
350 main_exe_file = 0;
353 return module;
356 /***********************************************************************
357 * build_initial_environment
359 * Build the Win32 environment from the Unix environment
361 static BOOL build_initial_environment( char **environ )
363 ULONG size = 1;
364 char **e;
365 WCHAR *p, *endptr;
366 void *ptr;
368 /* Compute the total size of the Unix environment */
369 for (e = environ; *e; e++)
371 if (is_special_env_var( *e )) continue;
372 size += MultiByteToWideChar( CP_UNIXCP, 0, *e, -1, NULL, 0 );
374 size *= sizeof(WCHAR);
376 /* Now allocate the environment */
377 if (NtAllocateVirtualMemory(NtCurrentProcess(), &ptr, 0, &size,
378 MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) != STATUS_SUCCESS)
379 return FALSE;
381 NtCurrentTeb()->Peb->ProcessParameters->Environment = p = ptr;
382 endptr = p + size / sizeof(WCHAR);
384 /* And fill it with the Unix environment */
385 for (e = environ; *e; e++)
387 char *str = *e;
389 /* skip Unix special variables and use the Wine variants instead */
390 if (!strncmp( str, "WINE", 4 ))
392 if (is_special_env_var( str + 4 )) str += 4;
393 else if (!strncmp( str, "WINEPRELOADRESERVE=", 19 )) continue; /* skip it */
395 else if (is_special_env_var( str )) continue; /* skip it */
397 MultiByteToWideChar( CP_UNIXCP, 0, str, -1, p, endptr - p );
398 p += strlenW(p) + 1;
400 *p = 0;
401 return TRUE;
405 /***********************************************************************
406 * set_registry_variables
408 * Set environment variables by enumerating the values of a key;
409 * helper for set_registry_environment().
411 static void set_registry_variables( HKEY hkey )
413 UNICODE_STRING env_name, env_value;
414 NTSTATUS status;
415 DWORD size;
416 int index;
417 char buffer[1024 + sizeof(KEY_VALUE_FULL_INFORMATION)];
418 KEY_VALUE_FULL_INFORMATION *info = (KEY_VALUE_FULL_INFORMATION *)buffer;
420 for (index = 0; ; index++)
422 status = NtEnumerateValueKey( hkey, index, KeyValueFullInformation,
423 buffer, sizeof(buffer), &size );
424 if (status == STATUS_BUFFER_OVERFLOW) continue;
425 if (status != STATUS_SUCCESS) break;
426 if (info->Type != REG_SZ) continue; /* FIXME: handle REG_EXPAND_SZ */
427 env_name.Buffer = info->Name;
428 env_name.Length = env_name.MaximumLength = info->NameLength;
429 env_value.Buffer = (WCHAR *)(buffer + info->DataOffset);
430 env_value.Length = env_value.MaximumLength = info->DataLength;
431 if (env_value.Length && !env_value.Buffer[env_value.Length/sizeof(WCHAR)-1])
432 env_value.Length--; /* don't count terminating null if any */
433 RtlSetEnvironmentVariable( NULL, &env_name, &env_value );
438 /***********************************************************************
439 * set_registry_environment
441 * Set the environment variables specified in the registry.
443 static void set_registry_environment(void)
445 static const WCHAR env_keyW[] = {'M','a','c','h','i','n','e','\\',
446 'S','y','s','t','e','m','\\',
447 'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
448 'C','o','n','t','r','o','l','\\',
449 'S','e','s','s','i','o','n',' ','M','a','n','a','g','e','r','\\',
450 'E','n','v','i','r','o','n','m','e','n','t',0};
451 static const WCHAR envW[] = {'E','n','v','i','r','o','n','m','e','n','t',0};
453 OBJECT_ATTRIBUTES attr;
454 UNICODE_STRING nameW;
455 HKEY hkey;
457 attr.Length = sizeof(attr);
458 attr.RootDirectory = 0;
459 attr.ObjectName = &nameW;
460 attr.Attributes = 0;
461 attr.SecurityDescriptor = NULL;
462 attr.SecurityQualityOfService = NULL;
464 /* first the system environment variables */
465 RtlInitUnicodeString( &nameW, env_keyW );
466 if (NtOpenKey( &hkey, KEY_ALL_ACCESS, &attr ) == STATUS_SUCCESS)
468 set_registry_variables( hkey );
469 NtClose( hkey );
472 /* then the ones for the current user */
473 if (RtlOpenCurrentUser( KEY_ALL_ACCESS, (HKEY *)&attr.RootDirectory ) != STATUS_SUCCESS) return;
474 RtlInitUnicodeString( &nameW, envW );
475 if (NtOpenKey( &hkey, KEY_ALL_ACCESS, &attr ) == STATUS_SUCCESS)
477 set_registry_variables( hkey );
478 NtClose( hkey );
480 NtClose( attr.RootDirectory );
484 /***********************************************************************
485 * set_library_wargv
487 * Set the Wine library Unicode argv global variables.
489 static void set_library_wargv( char **argv )
491 int argc;
492 WCHAR *p;
493 WCHAR **wargv;
494 DWORD total = 0;
496 for (argc = 0; argv[argc]; argc++)
497 total += MultiByteToWideChar( CP_UNIXCP, 0, argv[argc], -1, NULL, 0 );
499 wargv = RtlAllocateHeap( GetProcessHeap(), 0,
500 total * sizeof(WCHAR) + (argc + 1) * sizeof(*wargv) );
501 p = (WCHAR *)(wargv + argc + 1);
502 for (argc = 0; argv[argc]; argc++)
504 DWORD reslen = MultiByteToWideChar( CP_UNIXCP, 0, argv[argc], -1, p, total );
505 wargv[argc] = p;
506 p += reslen;
507 total -= reslen;
509 wargv[argc] = NULL;
510 __wine_main_wargv = wargv;
514 /***********************************************************************
515 * build_command_line
517 * Build the command line of a process from the argv array.
519 * Note that it does NOT necessarily include the file name.
520 * Sometimes we don't even have any command line options at all.
522 * We must quote and escape characters so that the argv array can be rebuilt
523 * from the command line:
524 * - spaces and tabs must be quoted
525 * 'a b' -> '"a b"'
526 * - quotes must be escaped
527 * '"' -> '\"'
528 * - if '\'s are followed by a '"', they must be doubled and followed by '\"',
529 * resulting in an odd number of '\' followed by a '"'
530 * '\"' -> '\\\"'
531 * '\\"' -> '\\\\\"'
532 * - '\'s that are not followed by a '"' can be left as is
533 * 'a\b' == 'a\b'
534 * 'a\\b' == 'a\\b'
536 static BOOL build_command_line( WCHAR **argv )
538 int len;
539 WCHAR **arg;
540 LPWSTR p;
541 RTL_USER_PROCESS_PARAMETERS* rupp = NtCurrentTeb()->Peb->ProcessParameters;
543 if (rupp->CommandLine.Buffer) return TRUE; /* already got it from the server */
545 len = 0;
546 for (arg = argv; *arg; arg++)
548 int has_space,bcount;
549 WCHAR* a;
551 has_space=0;
552 bcount=0;
553 a=*arg;
554 if( !*a ) has_space=1;
555 while (*a!='\0') {
556 if (*a=='\\') {
557 bcount++;
558 } else {
559 if (*a==' ' || *a=='\t') {
560 has_space=1;
561 } else if (*a=='"') {
562 /* doubling of '\' preceeding a '"',
563 * plus escaping of said '"'
565 len+=2*bcount+1;
567 bcount=0;
569 a++;
571 len+=(a-*arg)+1 /* for the separating space */;
572 if (has_space)
573 len+=2; /* for the quotes */
576 if (!(rupp->CommandLine.Buffer = RtlAllocateHeap( GetProcessHeap(), 0, len * sizeof(WCHAR))))
577 return FALSE;
579 p = rupp->CommandLine.Buffer;
580 rupp->CommandLine.Length = (len - 1) * sizeof(WCHAR);
581 rupp->CommandLine.MaximumLength = len * sizeof(WCHAR);
582 for (arg = argv; *arg; arg++)
584 int has_space,has_quote;
585 WCHAR* a;
587 /* Check for quotes and spaces in this argument */
588 has_space=has_quote=0;
589 a=*arg;
590 if( !*a ) has_space=1;
591 while (*a!='\0') {
592 if (*a==' ' || *a=='\t') {
593 has_space=1;
594 if (has_quote)
595 break;
596 } else if (*a=='"') {
597 has_quote=1;
598 if (has_space)
599 break;
601 a++;
604 /* Now transfer it to the command line */
605 if (has_space)
606 *p++='"';
607 if (has_quote) {
608 int bcount;
609 WCHAR* a;
611 bcount=0;
612 a=*arg;
613 while (*a!='\0') {
614 if (*a=='\\') {
615 *p++=*a;
616 bcount++;
617 } else {
618 if (*a=='"') {
619 int i;
621 /* Double all the '\\' preceeding this '"', plus one */
622 for (i=0;i<=bcount;i++)
623 *p++='\\';
624 *p++='"';
625 } else {
626 *p++=*a;
628 bcount=0;
630 a++;
632 } else {
633 WCHAR* x = *arg;
634 while ((*p=*x++)) p++;
636 if (has_space)
637 *p++='"';
638 *p++=' ';
640 if (p > rupp->CommandLine.Buffer)
641 p--; /* remove last space */
642 *p = '\0';
644 return TRUE;
648 /* make sure the unicode string doesn't point beyond the end pointer */
649 static inline void fix_unicode_string( UNICODE_STRING *str, char *end_ptr )
651 if ((char *)str->Buffer >= end_ptr)
653 str->Length = str->MaximumLength = 0;
654 str->Buffer = NULL;
655 return;
657 if ((char *)str->Buffer + str->MaximumLength > end_ptr)
659 str->MaximumLength = (end_ptr - (char *)str->Buffer) & ~(sizeof(WCHAR) - 1);
661 if (str->Length >= str->MaximumLength)
663 if (str->MaximumLength >= sizeof(WCHAR))
664 str->Length = str->MaximumLength - sizeof(WCHAR);
665 else
666 str->Length = str->MaximumLength = 0;
670 static void version(void)
672 MESSAGE( "%s\n", PACKAGE_STRING );
673 ExitProcess(0);
676 static void usage(void)
678 MESSAGE( "%s\n", PACKAGE_STRING );
679 MESSAGE( "Usage: wine PROGRAM [ARGUMENTS...] Run the specified program\n" );
680 MESSAGE( " wine --help Display this help and exit\n");
681 MESSAGE( " wine --version Output version information and exit\n");
682 ExitProcess(0);
686 /***********************************************************************
687 * init_user_process_params
689 * Fill the RTL_USER_PROCESS_PARAMETERS structure from the server.
691 static RTL_USER_PROCESS_PARAMETERS *init_user_process_params( size_t info_size )
693 void *ptr;
694 DWORD size, env_size;
695 RTL_USER_PROCESS_PARAMETERS *params;
697 size = info_size;
698 if (NtAllocateVirtualMemory( NtCurrentProcess(), &ptr, NULL, &size,
699 MEM_COMMIT, PAGE_READWRITE ) != STATUS_SUCCESS)
700 return NULL;
702 SERVER_START_REQ( get_startup_info )
704 wine_server_set_reply( req, ptr, info_size );
705 wine_server_call( req );
706 info_size = wine_server_reply_size( reply );
708 SERVER_END_REQ;
710 params = ptr;
711 params->AllocationSize = size;
712 if (params->Size > info_size) params->Size = info_size;
714 /* make sure the strings are valid */
715 fix_unicode_string( &params->CurrentDirectory.DosPath, (char *)info_size );
716 fix_unicode_string( &params->DllPath, (char *)info_size );
717 fix_unicode_string( &params->ImagePathName, (char *)info_size );
718 fix_unicode_string( &params->CommandLine, (char *)info_size );
719 fix_unicode_string( &params->WindowTitle, (char *)info_size );
720 fix_unicode_string( &params->Desktop, (char *)info_size );
721 fix_unicode_string( &params->ShellInfo, (char *)info_size );
722 fix_unicode_string( &params->RuntimeInfo, (char *)info_size );
724 /* environment needs to be a separate memory block */
725 env_size = info_size - params->Size;
726 if (!env_size) env_size = 1;
727 if (NtAllocateVirtualMemory( NtCurrentProcess(), &ptr, NULL, &env_size,
728 MEM_COMMIT, PAGE_READWRITE ) != STATUS_SUCCESS)
729 return NULL;
730 memcpy( ptr, (char *)params + params->Size, info_size - params->Size );
731 params->Environment = ptr;
733 return RtlNormalizeProcessParams( params );
737 /***********************************************************************
738 * init_current_directory
740 * Initialize the current directory from the Unix cwd or the parent info.
742 static void init_current_directory( CURDIR *cur_dir )
744 UNICODE_STRING dir_str;
745 char *cwd;
746 int size;
748 /* if we received a cur dir from the parent, try this first */
750 if (cur_dir->DosPath.Length)
752 if (RtlSetCurrentDirectory_U( &cur_dir->DosPath ) == STATUS_SUCCESS) goto done;
755 /* now try to get it from the Unix cwd */
757 for (size = 256; ; size *= 2)
759 if (!(cwd = HeapAlloc( GetProcessHeap(), 0, size ))) break;
760 if (getcwd( cwd, size )) break;
761 HeapFree( GetProcessHeap(), 0, cwd );
762 if (errno == ERANGE) continue;
763 cwd = NULL;
764 break;
767 if (cwd)
769 WCHAR *dirW;
770 int lenW = MultiByteToWideChar( CP_UNIXCP, 0, cwd, -1, NULL, 0 );
771 if ((dirW = HeapAlloc( GetProcessHeap(), 0, lenW * sizeof(WCHAR) )))
773 MultiByteToWideChar( CP_UNIXCP, 0, cwd, -1, dirW, lenW );
774 RtlInitUnicodeString( &dir_str, dirW );
775 RtlSetCurrentDirectory_U( &dir_str );
776 RtlFreeUnicodeString( &dir_str );
780 if (!cur_dir->DosPath.Length) /* still not initialized */
782 MESSAGE("Warning: could not find DOS drive for current working directory '%s', "
783 "starting in the Windows directory.\n", cwd ? cwd : "" );
784 RtlInitUnicodeString( &dir_str, DIR_Windows );
785 RtlSetCurrentDirectory_U( &dir_str );
787 if (cwd) HeapFree( GetProcessHeap(), 0, cwd );
789 done:
790 if (!cur_dir->Handle) chdir("/"); /* change to root directory so as not to lock cdroms */
791 TRACE( "starting in %s %p\n", debugstr_w( cur_dir->DosPath.Buffer ), cur_dir->Handle );
795 /***********************************************************************
796 * init_windows_dirs
798 * Initialize the windows and system directories from the environment.
800 static void init_windows_dirs(void)
802 extern void __wine_init_windows_dir( const WCHAR *windir, const WCHAR *sysdir );
804 static const WCHAR windirW[] = {'w','i','n','d','i','r',0};
805 static const WCHAR winsysdirW[] = {'w','i','n','s','y','s','d','i','r',0};
806 static const WCHAR default_windirW[] = {'c',':','\\','w','i','n','d','o','w','s',0};
807 static const WCHAR default_sysdirW[] = {'\\','s','y','s','t','e','m',0};
809 DWORD len;
810 WCHAR *buffer;
812 if ((len = GetEnvironmentVariableW( windirW, NULL, 0 )))
814 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
815 GetEnvironmentVariableW( windirW, buffer, len );
816 DIR_Windows = buffer;
818 else DIR_Windows = default_windirW;
820 if ((len = GetEnvironmentVariableW( winsysdirW, NULL, 0 )))
822 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
823 GetEnvironmentVariableW( winsysdirW, buffer, len );
824 DIR_System = buffer;
826 else
828 len = strlenW( DIR_Windows );
829 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) + sizeof(default_sysdirW) );
830 memcpy( buffer, DIR_Windows, len * sizeof(WCHAR) );
831 memcpy( buffer + len, default_sysdirW, sizeof(default_sysdirW) );
832 DIR_System = buffer;
835 if (GetFileAttributesW( DIR_Windows ) == INVALID_FILE_ATTRIBUTES)
836 MESSAGE( "Warning: the specified Windows directory %s is not accessible.\n",
837 debugstr_w(DIR_Windows) );
838 if (GetFileAttributesW( DIR_System ) == INVALID_FILE_ATTRIBUTES)
839 MESSAGE( "Warning: the specified System directory %s is not accessible.\n",
840 debugstr_w(DIR_System) );
842 TRACE_(file)( "WindowsDir = %s\n", debugstr_w(DIR_Windows) );
843 TRACE_(file)( "SystemDir = %s\n", debugstr_w(DIR_System) );
845 /* set the directories in ntdll too */
846 __wine_init_windows_dir( DIR_Windows, DIR_System );
850 /***********************************************************************
851 * process_init
853 * Main process initialisation code
855 static BOOL process_init(void)
857 static const WCHAR kernel32W[] = {'k','e','r','n','e','l','3','2',0};
858 BOOL ret;
859 size_t info_size = 0;
860 RTL_USER_PROCESS_PARAMETERS *params;
861 PEB *peb = NtCurrentTeb()->Peb;
862 HANDLE hstdin, hstdout, hstderr;
863 extern void __wine_dbg_kernel32_init(void);
865 PTHREAD_Init();
867 __wine_dbg_kernel32_init(); /* hack: register debug channels early */
869 setbuf(stdout,NULL);
870 setbuf(stderr,NULL);
871 setlocale(LC_CTYPE,"");
873 /* Retrieve startup info from the server */
874 SERVER_START_REQ( init_process )
876 req->peb = peb;
877 req->ldt_copy = &wine_ldt_copy;
878 if ((ret = !wine_server_call_err( req )))
880 main_exe_file = reply->exe_file;
881 main_create_flags = reply->create_flags;
882 info_size = reply->info_size;
883 server_startticks = reply->server_start;
884 hstdin = reply->hstdin;
885 hstdout = reply->hstdout;
886 hstderr = reply->hstderr;
889 SERVER_END_REQ;
890 if (!ret) return FALSE;
892 if (info_size == 0)
894 params = peb->ProcessParameters;
896 /* This is wine specific: we have no parent (we're started from unix)
897 * so, create a simple console with bare handles to unix stdio
898 * input & output streams (aka simple console)
900 wine_server_fd_to_handle( 0, GENERIC_READ|SYNCHRONIZE, TRUE, &params->hStdInput );
901 wine_server_fd_to_handle( 1, GENERIC_WRITE|SYNCHRONIZE, TRUE, &params->hStdOutput );
902 wine_server_fd_to_handle( 2, GENERIC_WRITE|SYNCHRONIZE, TRUE, &params->hStdError );
904 params->CurrentDirectory.DosPath.Length = 0;
905 params->CurrentDirectory.DosPath.MaximumLength = RtlGetLongestNtPathLength() * sizeof(WCHAR);
906 params->CurrentDirectory.DosPath.Buffer = RtlAllocateHeap( GetProcessHeap(), 0, params->CurrentDirectory.DosPath.MaximumLength);
908 else
910 if (!(params = init_user_process_params( info_size ))) return FALSE;
911 peb->ProcessParameters = params;
913 /* convert value from server:
914 * + 0 => INVALID_HANDLE_VALUE
915 * + console handle need to be mapped
917 if (!hstdin)
918 hstdin = INVALID_HANDLE_VALUE;
919 else if (VerifyConsoleIoHandle(console_handle_map(hstdin)))
920 hstdin = console_handle_map(hstdin);
922 if (!hstdout)
923 hstdout = INVALID_HANDLE_VALUE;
924 else if (VerifyConsoleIoHandle(console_handle_map(hstdout)))
925 hstdout = console_handle_map(hstdout);
927 if (!hstderr)
928 hstderr = INVALID_HANDLE_VALUE;
929 else if (VerifyConsoleIoHandle(console_handle_map(hstderr)))
930 hstderr = console_handle_map(hstderr);
932 params->hStdInput = hstdin;
933 params->hStdOutput = hstdout;
934 params->hStdError = hstderr;
937 kernel32_handle = GetModuleHandleW(kernel32W);
939 LOCALE_Init();
941 if (!info_size)
943 /* Copy the parent environment */
944 if (!build_initial_environment( __wine_main_environ )) return FALSE;
946 /* Create device symlinks */
947 VOLUME_CreateDevices();
949 /* registry initialisation */
950 SHELL_LoadRegistry();
952 /* global boot finished, the rest is process-local */
953 SERVER_START_REQ( boot_done )
955 req->debug_level = TRACE_ON(server);
956 wine_server_call( req );
958 SERVER_END_REQ;
960 set_registry_environment();
963 init_windows_dirs();
964 init_current_directory( &params->CurrentDirectory );
966 return TRUE;
970 /***********************************************************************
971 * start_process
973 * Startup routine of a new process. Runs on the new process stack.
975 static void start_process( void *arg )
977 __TRY
979 PEB *peb = NtCurrentTeb()->Peb;
980 IMAGE_NT_HEADERS *nt;
981 LPTHREAD_START_ROUTINE entry;
983 LdrInitializeThunk( main_exe_file, 0, 0, 0 );
985 nt = RtlImageNtHeader( peb->ImageBaseAddress );
986 entry = (LPTHREAD_START_ROUTINE)((char *)peb->ImageBaseAddress +
987 nt->OptionalHeader.AddressOfEntryPoint);
989 if (TRACE_ON(relay))
990 DPRINTF( "%04lx:Starting process %s (entryproc=%p)\n", GetCurrentThreadId(),
991 debugstr_w(peb->ProcessParameters->ImagePathName.Buffer), entry );
993 SetLastError( 0 ); /* clear error code */
994 if (peb->BeingDebugged) DbgBreakPoint();
995 ExitProcess( entry( peb ) );
997 __EXCEPT(UnhandledExceptionFilter)
999 TerminateThread( GetCurrentThread(), GetExceptionCode() );
1001 __ENDTRY
1005 /***********************************************************************
1006 * __wine_kernel_init
1008 * Wine initialisation: load and start the main exe file.
1010 void __wine_kernel_init(void)
1012 WCHAR *main_exe_name, *p;
1013 char error[1024];
1014 DWORD stack_size = 0;
1015 int file_exists;
1016 PEB *peb = NtCurrentTeb()->Peb;
1018 /* Initialize everything */
1019 if (!process_init()) exit(1);
1021 __wine_main_argv++; /* remove argv[0] (wine itself) */
1022 __wine_main_argc--;
1024 if (!(main_exe_name = peb->ProcessParameters->ImagePathName.Buffer))
1026 WCHAR buffer[MAX_PATH];
1027 WCHAR exe_nameW[MAX_PATH];
1029 if (!__wine_main_argv[0]) usage();
1030 if (__wine_main_argc == 1)
1032 if (strcmp(__wine_main_argv[0], "--help") == 0) usage();
1033 if (strcmp(__wine_main_argv[0], "--version") == 0) version();
1036 MultiByteToWideChar( CP_UNIXCP, 0, __wine_main_argv[0], -1, exe_nameW, MAX_PATH );
1037 if (!find_exe_file( exe_nameW, buffer, MAX_PATH, &main_exe_file ))
1039 MESSAGE( "wine: cannot find '%s'\n", __wine_main_argv[0] );
1040 ExitProcess(1);
1042 if (main_exe_file == INVALID_HANDLE_VALUE)
1044 MESSAGE( "wine: cannot open %s\n", debugstr_w(main_exe_name) );
1045 ExitProcess(1);
1047 RtlCreateUnicodeString( &peb->ProcessParameters->ImagePathName, buffer );
1048 main_exe_name = peb->ProcessParameters->ImagePathName.Buffer;
1051 TRACE( "starting process name=%s file=%p argv[0]=%s\n",
1052 debugstr_w(main_exe_name), main_exe_file, debugstr_a(__wine_main_argv[0]) );
1054 RtlInitUnicodeString( &NtCurrentTeb()->Peb->ProcessParameters->DllPath,
1055 MODULE_get_dll_load_path(NULL) );
1056 VERSION_Init( main_exe_name );
1058 if (!main_exe_file) /* no file handle -> Winelib app */
1060 TRACE( "starting Winelib app %s\n", debugstr_w(main_exe_name) );
1061 if (open_builtin_exe_file( main_exe_name, error, sizeof(error), 0, &file_exists ))
1062 goto found;
1063 MESSAGE( "wine: cannot open builtin library for %s: %s\n",
1064 debugstr_w(main_exe_name), error );
1065 ExitProcess(1);
1068 switch( MODULE_GetBinaryType( main_exe_file, NULL, NULL ))
1070 case BINARY_PE_EXE:
1071 TRACE( "starting Win32 binary %s\n", debugstr_w(main_exe_name) );
1072 if ((peb->ImageBaseAddress = load_pe_exe( main_exe_name, main_exe_file )))
1073 goto found;
1074 MESSAGE( "wine: could not load %s as Win32 binary\n", debugstr_w(main_exe_name) );
1075 ExitProcess(1);
1076 case BINARY_PE_DLL:
1077 MESSAGE( "wine: %s is a DLL, not an executable\n", debugstr_w(main_exe_name) );
1078 ExitProcess(1);
1079 case BINARY_UNKNOWN:
1080 /* check for .com extension */
1081 if (!(p = strrchrW( main_exe_name, '.' )) || strcmpiW( p, comW ))
1083 MESSAGE( "wine: cannot determine executable type for %s\n",
1084 debugstr_w(main_exe_name) );
1085 ExitProcess(1);
1087 /* fall through */
1088 case BINARY_WIN16:
1089 case BINARY_DOS:
1090 TRACE( "starting Win16/DOS binary %s\n", debugstr_w(main_exe_name) );
1091 CloseHandle( main_exe_file );
1092 main_exe_file = 0;
1093 __wine_main_argv--;
1094 __wine_main_argc++;
1095 __wine_main_argv[0] = "winevdm.exe";
1096 if (open_builtin_exe_file( winevdmW, error, sizeof(error), 0, &file_exists ))
1097 goto found;
1098 MESSAGE( "wine: trying to run %s, cannot open builtin library for 'winevdm.exe': %s\n",
1099 debugstr_w(main_exe_name), error );
1100 ExitProcess(1);
1101 case BINARY_OS216:
1102 MESSAGE( "wine: %s is an OS/2 binary, not supported\n", debugstr_w(main_exe_name) );
1103 ExitProcess(1);
1104 case BINARY_UNIX_EXE:
1105 MESSAGE( "wine: %s is a Unix binary, not supported\n", debugstr_w(main_exe_name) );
1106 ExitProcess(1);
1107 case BINARY_UNIX_LIB:
1109 char *unix_name;
1111 TRACE( "starting Winelib app %s\n", debugstr_w(main_exe_name) );
1112 CloseHandle( main_exe_file );
1113 main_exe_file = 0;
1114 if ((unix_name = wine_get_unix_file_name( main_exe_name )) &&
1115 wine_dlopen( unix_name, RTLD_NOW, error, sizeof(error) ))
1117 static const WCHAR soW[] = {'.','s','o',0};
1118 if ((p = strrchrW( main_exe_name, '.' )) && !strcmpW( p, soW ))
1120 *p = 0;
1121 /* update the unicode string */
1122 RtlInitUnicodeString( &peb->ProcessParameters->ImagePathName, main_exe_name );
1124 HeapFree( GetProcessHeap(), 0, unix_name );
1125 goto found;
1127 MESSAGE( "wine: could not load %s: %s\n", debugstr_w(main_exe_name), error );
1128 ExitProcess(1);
1132 found:
1133 /* build command line */
1134 set_library_wargv( __wine_main_argv );
1135 if (!build_command_line( __wine_main_wargv )) goto error;
1137 stack_size = RtlImageNtHeader(peb->ImageBaseAddress)->OptionalHeader.SizeOfStackReserve;
1139 /* allocate main thread stack */
1140 if (!THREAD_InitStack( NtCurrentTeb(), stack_size )) goto error;
1142 /* switch to the new stack */
1143 wine_switch_to_stack( start_process, NULL, NtCurrentTeb()->Tib.StackBase );
1145 error:
1146 ExitProcess( GetLastError() );
1150 /***********************************************************************
1151 * build_argv
1153 * Build an argv array from a command-line.
1154 * 'reserved' is the number of args to reserve before the first one.
1156 static char **build_argv( const WCHAR *cmdlineW, int reserved )
1158 int argc;
1159 char** argv;
1160 char *arg,*s,*d,*cmdline;
1161 int in_quotes,bcount,len;
1163 len = WideCharToMultiByte( CP_UNIXCP, 0, cmdlineW, -1, NULL, 0, NULL, NULL );
1164 if (!(cmdline = malloc(len))) return NULL;
1165 WideCharToMultiByte( CP_UNIXCP, 0, cmdlineW, -1, cmdline, len, NULL, NULL );
1167 argc=reserved+1;
1168 bcount=0;
1169 in_quotes=0;
1170 s=cmdline;
1171 while (1) {
1172 if (*s=='\0' || ((*s==' ' || *s=='\t') && !in_quotes)) {
1173 /* space */
1174 argc++;
1175 /* skip the remaining spaces */
1176 while (*s==' ' || *s=='\t') {
1177 s++;
1179 if (*s=='\0')
1180 break;
1181 bcount=0;
1182 continue;
1183 } else if (*s=='\\') {
1184 /* '\', count them */
1185 bcount++;
1186 } else if ((*s=='"') && ((bcount & 1)==0)) {
1187 /* unescaped '"' */
1188 in_quotes=!in_quotes;
1189 bcount=0;
1190 } else {
1191 /* a regular character */
1192 bcount=0;
1194 s++;
1196 argv=malloc(argc*sizeof(*argv));
1197 if (!argv)
1198 return NULL;
1200 arg=d=s=cmdline;
1201 bcount=0;
1202 in_quotes=0;
1203 argc=reserved;
1204 while (*s) {
1205 if ((*s==' ' || *s=='\t') && !in_quotes) {
1206 /* Close the argument and copy it */
1207 *d=0;
1208 argv[argc++]=arg;
1210 /* skip the remaining spaces */
1211 do {
1212 s++;
1213 } while (*s==' ' || *s=='\t');
1215 /* Start with a new argument */
1216 arg=d=s;
1217 bcount=0;
1218 } else if (*s=='\\') {
1219 /* '\\' */
1220 *d++=*s++;
1221 bcount++;
1222 } else if (*s=='"') {
1223 /* '"' */
1224 if ((bcount & 1)==0) {
1225 /* Preceeded by an even number of '\', this is half that
1226 * number of '\', plus a '"' which we discard.
1228 d-=bcount/2;
1229 s++;
1230 in_quotes=!in_quotes;
1231 } else {
1232 /* Preceeded by an odd number of '\', this is half that
1233 * number of '\' followed by a '"'
1235 d=d-bcount/2-1;
1236 *d++='"';
1237 s++;
1239 bcount=0;
1240 } else {
1241 /* a regular character */
1242 *d++=*s++;
1243 bcount=0;
1246 if (*arg) {
1247 *d='\0';
1248 argv[argc++]=arg;
1250 argv[argc]=NULL;
1252 return argv;
1256 /***********************************************************************
1257 * alloc_env_string
1259 * Allocate an environment string; helper for build_envp
1261 static char *alloc_env_string( const char *name, const char *value )
1263 char *ret = malloc( strlen(name) + strlen(value) + 1 );
1264 strcpy( ret, name );
1265 strcat( ret, value );
1266 return ret;
1269 /***********************************************************************
1270 * build_envp
1272 * Build the environment of a new child process.
1274 static char **build_envp( const WCHAR *envW )
1276 const WCHAR *end;
1277 char **envp;
1278 char *env, *p;
1279 int count = 0, length;
1281 for (end = envW; *end; count++) end += strlenW(end) + 1;
1282 end++;
1283 length = WideCharToMultiByte( CP_UNIXCP, 0, envW, end - envW, NULL, 0, NULL, NULL );
1284 if (!(env = malloc( length ))) return NULL;
1285 WideCharToMultiByte( CP_UNIXCP, 0, envW, end - envW, env, length, NULL, NULL );
1287 count += 4;
1289 if ((envp = malloc( count * sizeof(*envp) )))
1291 char **envptr = envp;
1293 /* some variables must not be modified, so we get them directly from the unix env */
1294 if ((p = getenv("PATH"))) *envptr++ = alloc_env_string( "PATH=", p );
1295 if ((p = getenv("TEMP"))) *envptr++ = alloc_env_string( "TEMP=", p );
1296 if ((p = getenv("TMP"))) *envptr++ = alloc_env_string( "TMP=", p );
1297 if ((p = getenv("HOME"))) *envptr++ = alloc_env_string( "HOME=", p );
1298 /* now put the Windows environment strings */
1299 for (p = env; *p; p += strlen(p) + 1)
1301 if (*p == '=') continue; /* skip drive curdirs, this crashes some unix apps */
1302 if (!strncmp( p, "WINEPRELOADRESERVE=", sizeof("WINEPRELOADRESERVE=")-1 )) continue;
1303 if (is_special_env_var( p )) /* prefix it with "WINE" */
1304 *envptr++ = alloc_env_string( "WINE", p );
1305 else
1306 *envptr++ = p;
1308 *envptr = 0;
1310 return envp;
1314 /***********************************************************************
1315 * fork_and_exec
1317 * Fork and exec a new Unix binary, checking for errors.
1319 static int fork_and_exec( const char *filename, const WCHAR *cmdline,
1320 const WCHAR *env, const char *newdir )
1322 int fd[2];
1323 int pid, err;
1325 if (!env) env = GetEnvironmentStringsW();
1327 if (pipe(fd) == -1)
1329 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
1330 return -1;
1332 fcntl( fd[1], F_SETFD, 1 ); /* set close on exec */
1333 if (!(pid = fork())) /* child */
1335 char **argv = build_argv( cmdline, 0 );
1336 char **envp = build_envp( env );
1337 close( fd[0] );
1339 /* Reset signals that we previously set to SIG_IGN */
1340 signal( SIGPIPE, SIG_DFL );
1341 signal( SIGCHLD, SIG_DFL );
1343 if (newdir) chdir(newdir);
1345 if (argv && envp) execve( filename, argv, envp );
1346 err = errno;
1347 write( fd[1], &err, sizeof(err) );
1348 _exit(1);
1350 close( fd[1] );
1351 if ((pid != -1) && (read( fd[0], &err, sizeof(err) ) > 0)) /* exec failed */
1353 errno = err;
1354 pid = -1;
1356 if (pid == -1) FILE_SetDosError();
1357 close( fd[0] );
1358 return pid;
1362 /***********************************************************************
1363 * create_user_params
1365 static RTL_USER_PROCESS_PARAMETERS *create_user_params( LPCWSTR filename, LPCWSTR cmdline,
1366 LPCWSTR cur_dir, LPWSTR env,
1367 const STARTUPINFOW *startup )
1369 RTL_USER_PROCESS_PARAMETERS *params;
1370 UNICODE_STRING image_str, cmdline_str, curdir_str, desktop, title;
1371 NTSTATUS status;
1372 WCHAR buffer[MAX_PATH];
1374 if(!GetLongPathNameW( filename, buffer, MAX_PATH ))
1375 lstrcpynW( buffer, filename, MAX_PATH );
1376 if(!GetFullPathNameW( buffer, MAX_PATH, buffer, NULL ))
1377 lstrcpynW( buffer, filename, MAX_PATH );
1378 RtlInitUnicodeString( &image_str, buffer );
1380 RtlInitUnicodeString( &cmdline_str, cmdline );
1381 if (cur_dir) RtlInitUnicodeString( &curdir_str, cur_dir );
1382 if (startup->lpDesktop) RtlInitUnicodeString( &desktop, startup->lpDesktop );
1383 if (startup->lpTitle) RtlInitUnicodeString( &title, startup->lpTitle );
1385 status = RtlCreateProcessParameters( &params, &image_str, NULL,
1386 cur_dir ? &curdir_str : NULL,
1387 &cmdline_str, env,
1388 startup->lpTitle ? &title : NULL,
1389 startup->lpDesktop ? &desktop : NULL,
1390 NULL, NULL );
1391 if (status != STATUS_SUCCESS)
1393 SetLastError( RtlNtStatusToDosError(status) );
1394 return NULL;
1397 params->hStdInput = startup->hStdInput;
1398 params->hStdOutput = startup->hStdOutput;
1399 params->hStdError = startup->hStdError;
1400 params->dwX = startup->dwX;
1401 params->dwY = startup->dwY;
1402 params->dwXSize = startup->dwXSize;
1403 params->dwYSize = startup->dwYSize;
1404 params->dwXCountChars = startup->dwXCountChars;
1405 params->dwYCountChars = startup->dwYCountChars;
1406 params->dwFillAttribute = startup->dwFillAttribute;
1407 params->dwFlags = startup->dwFlags;
1408 params->wShowWindow = startup->wShowWindow;
1409 return params;
1413 /***********************************************************************
1414 * create_process
1416 * Create a new process. If hFile is a valid handle we have an exe
1417 * file, otherwise it is a Winelib app.
1419 static BOOL create_process( HANDLE hFile, LPCWSTR filename, LPWSTR cmd_line, LPWSTR env,
1420 LPCWSTR cur_dir, LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1421 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
1422 LPPROCESS_INFORMATION info, LPCSTR unixdir,
1423 void *res_start, void *res_end )
1425 BOOL ret, success = FALSE;
1426 HANDLE process_info;
1427 WCHAR *env_end;
1428 RTL_USER_PROCESS_PARAMETERS *params;
1429 int startfd[2];
1430 int execfd[2];
1431 pid_t pid;
1432 int err;
1433 char dummy = 0;
1434 char preloader_reserve[64];
1436 if (!env) RtlAcquirePebLock();
1438 if (!(params = create_user_params( filename, cmd_line, cur_dir, env, startup )))
1440 if (!env) RtlReleasePebLock();
1441 return FALSE;
1443 env_end = params->Environment;
1444 while (*env_end) env_end += strlenW(env_end) + 1;
1445 env_end++;
1447 sprintf( preloader_reserve, "WINEPRELOADRESERVE=%lx-%lx%c",
1448 (unsigned long)res_start, (unsigned long)res_end, 0 );
1450 /* create the synchronization pipes */
1452 if (pipe( startfd ) == -1)
1454 if (!env) RtlReleasePebLock();
1455 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
1456 RtlDestroyProcessParameters( params );
1457 return FALSE;
1459 if (pipe( execfd ) == -1)
1461 if (!env) RtlReleasePebLock();
1462 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
1463 close( startfd[0] );
1464 close( startfd[1] );
1465 RtlDestroyProcessParameters( params );
1466 return FALSE;
1468 fcntl( execfd[1], F_SETFD, 1 ); /* set close on exec */
1470 /* create the child process */
1472 if (!(pid = fork())) /* child */
1474 char **argv = build_argv( cmd_line, 1 );
1476 close( startfd[1] );
1477 close( execfd[0] );
1479 /* wait for parent to tell us to start */
1480 if (read( startfd[0], &dummy, 1 ) != 1) _exit(1);
1482 close( startfd[0] );
1483 /* Reset signals that we previously set to SIG_IGN */
1484 signal( SIGPIPE, SIG_DFL );
1485 signal( SIGCHLD, SIG_DFL );
1487 putenv( preloader_reserve );
1488 if (unixdir) chdir(unixdir);
1490 if (argv)
1492 /* first, try for a WINELOADER environment variable */
1493 const char *loader = getenv("WINELOADER");
1494 if (loader) wine_exec_wine_binary( loader, argv, NULL, TRUE );
1495 /* now use the standard search strategy */
1496 wine_exec_wine_binary( NULL, argv, NULL, TRUE );
1498 err = errno;
1499 write( execfd[1], &err, sizeof(err) );
1500 _exit(1);
1503 /* this is the parent */
1505 close( startfd[0] );
1506 close( execfd[1] );
1507 if (pid == -1)
1509 if (!env) RtlReleasePebLock();
1510 close( startfd[1] );
1511 close( execfd[0] );
1512 FILE_SetDosError();
1513 RtlDestroyProcessParameters( params );
1514 return FALSE;
1517 /* create the process on the server side */
1519 SERVER_START_REQ( new_process )
1521 req->inherit_all = inherit;
1522 req->create_flags = flags;
1523 req->unix_pid = pid;
1524 req->exe_file = hFile;
1525 if (startup->dwFlags & STARTF_USESTDHANDLES)
1527 req->hstdin = startup->hStdInput;
1528 req->hstdout = startup->hStdOutput;
1529 req->hstderr = startup->hStdError;
1531 else
1533 req->hstdin = GetStdHandle( STD_INPUT_HANDLE );
1534 req->hstdout = GetStdHandle( STD_OUTPUT_HANDLE );
1535 req->hstderr = GetStdHandle( STD_ERROR_HANDLE );
1538 if ((flags & (CREATE_NEW_CONSOLE | DETACHED_PROCESS)) != 0)
1540 /* this is temporary (for console handles). We have no way to control that the handle is invalid in child process otherwise */
1541 if (is_console_handle(req->hstdin)) req->hstdin = INVALID_HANDLE_VALUE;
1542 if (is_console_handle(req->hstdout)) req->hstdout = INVALID_HANDLE_VALUE;
1543 if (is_console_handle(req->hstderr)) req->hstderr = INVALID_HANDLE_VALUE;
1545 else
1547 if (is_console_handle(req->hstdin)) req->hstdin = console_handle_unmap(req->hstdin);
1548 if (is_console_handle(req->hstdout)) req->hstdout = console_handle_unmap(req->hstdout);
1549 if (is_console_handle(req->hstderr)) req->hstderr = console_handle_unmap(req->hstderr);
1552 wine_server_add_data( req, params, params->Size );
1553 wine_server_add_data( req, params->Environment, (env_end-params->Environment)*sizeof(WCHAR) );
1554 ret = !wine_server_call_err( req );
1555 process_info = reply->info;
1557 SERVER_END_REQ;
1559 if (!env) RtlReleasePebLock();
1560 RtlDestroyProcessParameters( params );
1561 if (!ret)
1563 close( startfd[1] );
1564 close( execfd[0] );
1565 return FALSE;
1568 /* tell child to start and wait for it to exec */
1570 write( startfd[1], &dummy, 1 );
1571 close( startfd[1] );
1573 if (read( execfd[0], &err, sizeof(err) ) > 0) /* exec failed */
1575 errno = err;
1576 FILE_SetDosError();
1577 close( execfd[0] );
1578 CloseHandle( process_info );
1579 return FALSE;
1581 close( execfd[0] );
1583 /* wait for the new process info to be ready */
1585 WaitForSingleObject( process_info, INFINITE );
1586 SERVER_START_REQ( get_new_process_info )
1588 req->info = process_info;
1589 req->pinherit = (psa && (psa->nLength >= sizeof(*psa)) && psa->bInheritHandle);
1590 req->tinherit = (tsa && (tsa->nLength >= sizeof(*tsa)) && tsa->bInheritHandle);
1591 if ((ret = !wine_server_call_err( req )))
1593 info->dwProcessId = (DWORD)reply->pid;
1594 info->dwThreadId = (DWORD)reply->tid;
1595 info->hProcess = reply->phandle;
1596 info->hThread = reply->thandle;
1597 success = reply->success;
1600 SERVER_END_REQ;
1602 if (ret && !success) /* new process failed to start */
1604 DWORD exitcode;
1605 if (GetExitCodeProcess( info->hProcess, &exitcode )) SetLastError( exitcode );
1606 CloseHandle( info->hThread );
1607 CloseHandle( info->hProcess );
1608 ret = FALSE;
1610 CloseHandle( process_info );
1611 return ret;
1615 /***********************************************************************
1616 * create_vdm_process
1618 * Create a new VDM process for a 16-bit or DOS application.
1620 static BOOL create_vdm_process( LPCWSTR filename, LPWSTR cmd_line, LPWSTR env, LPCWSTR cur_dir,
1621 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1622 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
1623 LPPROCESS_INFORMATION info, LPCSTR unixdir )
1625 static const WCHAR argsW[] = {'%','s',' ','-','-','a','p','p','-','n','a','m','e',' ','"','%','s','"',' ','%','s',0};
1627 BOOL ret;
1628 LPWSTR new_cmd_line = HeapAlloc( GetProcessHeap(), 0,
1629 (strlenW(filename) + strlenW(cmd_line) + 30) * sizeof(WCHAR) );
1631 if (!new_cmd_line)
1633 SetLastError( ERROR_OUTOFMEMORY );
1634 return FALSE;
1636 sprintfW( new_cmd_line, argsW, winevdmW, filename, cmd_line );
1637 ret = create_process( 0, winevdmW, new_cmd_line, env, cur_dir, psa, tsa, inherit,
1638 flags, startup, info, unixdir, NULL, NULL );
1639 HeapFree( GetProcessHeap(), 0, new_cmd_line );
1640 return ret;
1644 /***********************************************************************
1645 * create_cmd_process
1647 * Create a new cmd shell process for a .BAT file.
1649 static BOOL create_cmd_process( LPCWSTR filename, LPWSTR cmd_line, LPVOID env, LPCWSTR cur_dir,
1650 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1651 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
1652 LPPROCESS_INFORMATION info )
1655 static const WCHAR comspecW[] = {'C','O','M','S','P','E','C',0};
1656 static const WCHAR slashcW[] = {' ','/','c',' ',0};
1657 WCHAR comspec[MAX_PATH];
1658 WCHAR *newcmdline;
1659 BOOL ret;
1661 if (!GetEnvironmentVariableW( comspecW, comspec, sizeof(comspec)/sizeof(WCHAR) ))
1662 return FALSE;
1663 if (!(newcmdline = HeapAlloc( GetProcessHeap(), 0,
1664 (strlenW(comspec) + 4 + strlenW(cmd_line) + 1) * sizeof(WCHAR))))
1665 return FALSE;
1667 strcpyW( newcmdline, comspec );
1668 strcatW( newcmdline, slashcW );
1669 strcatW( newcmdline, cmd_line );
1670 ret = CreateProcessW( comspec, newcmdline, psa, tsa, inherit,
1671 flags, env, cur_dir, startup, info );
1672 HeapFree( GetProcessHeap(), 0, newcmdline );
1673 return ret;
1677 /*************************************************************************
1678 * get_file_name
1680 * Helper for CreateProcess: retrieve the file name to load from the
1681 * app name and command line. Store the file name in buffer, and
1682 * return a possibly modified command line.
1683 * Also returns a handle to the opened file if it's a Windows binary.
1685 static LPWSTR get_file_name( LPCWSTR appname, LPWSTR cmdline, LPWSTR buffer,
1686 int buflen, HANDLE *handle )
1688 static const WCHAR quotesW[] = {'"','%','s','"',0};
1690 WCHAR *name, *pos, *ret = NULL;
1691 const WCHAR *p;
1693 /* if we have an app name, everything is easy */
1695 if (appname)
1697 /* use the unmodified app name as file name */
1698 lstrcpynW( buffer, appname, buflen );
1699 *handle = open_exe_file( buffer );
1700 if (!(ret = cmdline) || !cmdline[0])
1702 /* no command-line, create one */
1703 if ((ret = HeapAlloc( GetProcessHeap(), 0, (strlenW(appname) + 3) * sizeof(WCHAR) )))
1704 sprintfW( ret, quotesW, appname );
1706 return ret;
1709 if (!cmdline)
1711 SetLastError( ERROR_INVALID_PARAMETER );
1712 return NULL;
1715 /* first check for a quoted file name */
1717 if ((cmdline[0] == '"') && ((p = strchrW( cmdline + 1, '"' ))))
1719 int len = p - cmdline - 1;
1720 /* extract the quoted portion as file name */
1721 if (!(name = HeapAlloc( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) ))) return NULL;
1722 memcpy( name, cmdline + 1, len * sizeof(WCHAR) );
1723 name[len] = 0;
1725 if (find_exe_file( name, buffer, buflen, handle ))
1726 ret = cmdline; /* no change necessary */
1727 goto done;
1730 /* now try the command-line word by word */
1732 if (!(name = HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline) + 1) * sizeof(WCHAR) )))
1733 return NULL;
1734 pos = name;
1735 p = cmdline;
1737 while (*p)
1739 do *pos++ = *p++; while (*p && *p != ' ');
1740 *pos = 0;
1741 if (find_exe_file( name, buffer, buflen, handle ))
1743 ret = cmdline;
1744 break;
1748 if (!ret || !strchrW( name, ' ' )) goto done; /* no change necessary */
1750 /* now build a new command-line with quotes */
1752 if (!(ret = HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline) + 3) * sizeof(WCHAR) )))
1753 goto done;
1754 sprintfW( ret, quotesW, name );
1755 strcatW( ret, p );
1757 done:
1758 HeapFree( GetProcessHeap(), 0, name );
1759 return ret;
1763 /**********************************************************************
1764 * CreateProcessA (KERNEL32.@)
1766 BOOL WINAPI CreateProcessA( LPCSTR app_name, LPSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
1767 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit,
1768 DWORD flags, LPVOID env, LPCSTR cur_dir,
1769 LPSTARTUPINFOA startup_info, LPPROCESS_INFORMATION info )
1771 BOOL ret = FALSE;
1772 WCHAR *app_nameW = NULL, *cmd_lineW = NULL, *cur_dirW = NULL;
1773 UNICODE_STRING desktopW, titleW;
1774 STARTUPINFOW infoW;
1776 desktopW.Buffer = NULL;
1777 titleW.Buffer = NULL;
1778 if (app_name && !(app_nameW = FILE_name_AtoW( app_name, TRUE ))) goto done;
1779 if (cmd_line && !(cmd_lineW = FILE_name_AtoW( cmd_line, TRUE ))) goto done;
1780 if (cur_dir && !(cur_dirW = FILE_name_AtoW( cur_dir, TRUE ))) goto done;
1782 if (startup_info->lpDesktop) RtlCreateUnicodeStringFromAsciiz( &desktopW, startup_info->lpDesktop );
1783 if (startup_info->lpTitle) RtlCreateUnicodeStringFromAsciiz( &titleW, startup_info->lpTitle );
1785 memcpy( &infoW, startup_info, sizeof(infoW) );
1786 infoW.lpDesktop = desktopW.Buffer;
1787 infoW.lpTitle = titleW.Buffer;
1789 if (startup_info->lpReserved)
1790 FIXME("StartupInfo.lpReserved is used, please report (%s)\n",
1791 debugstr_a(startup_info->lpReserved));
1793 ret = CreateProcessW( app_nameW, cmd_lineW, process_attr, thread_attr,
1794 inherit, flags, env, cur_dirW, &infoW, info );
1795 done:
1796 if (app_nameW) HeapFree( GetProcessHeap(), 0, app_nameW );
1797 if (cmd_lineW) HeapFree( GetProcessHeap(), 0, cmd_lineW );
1798 if (cur_dirW) HeapFree( GetProcessHeap(), 0, cur_dirW );
1799 RtlFreeUnicodeString( &desktopW );
1800 RtlFreeUnicodeString( &titleW );
1801 return ret;
1805 /**********************************************************************
1806 * CreateProcessW (KERNEL32.@)
1808 BOOL WINAPI CreateProcessW( LPCWSTR app_name, LPWSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
1809 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit, DWORD flags,
1810 LPVOID env, LPCWSTR cur_dir, LPSTARTUPINFOW startup_info,
1811 LPPROCESS_INFORMATION info )
1813 BOOL retv = FALSE;
1814 HANDLE hFile = 0;
1815 char *unixdir = NULL;
1816 WCHAR name[MAX_PATH];
1817 WCHAR *tidy_cmdline, *p, *envW = env;
1818 void *res_start, *res_end;
1820 /* Process the AppName and/or CmdLine to get module name and path */
1822 TRACE("app %s cmdline %s\n", debugstr_w(app_name), debugstr_w(cmd_line) );
1824 if (!(tidy_cmdline = get_file_name( app_name, cmd_line, name, sizeof(name), &hFile )))
1825 return FALSE;
1826 if (hFile == INVALID_HANDLE_VALUE) goto done;
1828 /* Warn if unsupported features are used */
1830 if (flags & (IDLE_PRIORITY_CLASS | HIGH_PRIORITY_CLASS | REALTIME_PRIORITY_CLASS |
1831 CREATE_NEW_PROCESS_GROUP | CREATE_SEPARATE_WOW_VDM | CREATE_SHARED_WOW_VDM |
1832 CREATE_DEFAULT_ERROR_MODE | CREATE_NO_WINDOW |
1833 PROFILE_USER | PROFILE_KERNEL | PROFILE_SERVER))
1834 WARN("(%s,...): ignoring some flags in %lx\n", debugstr_w(name), flags);
1836 if (cur_dir)
1838 unixdir = wine_get_unix_file_name( cur_dir );
1840 else
1842 WCHAR buf[MAX_PATH];
1843 if (GetCurrentDirectoryW(MAX_PATH, buf)) unixdir = wine_get_unix_file_name( buf );
1846 if (env && !(flags & CREATE_UNICODE_ENVIRONMENT)) /* convert environment to unicode */
1848 char *p = env;
1849 DWORD lenW;
1851 while (*p) p += strlen(p) + 1;
1852 p++; /* final null */
1853 lenW = MultiByteToWideChar( CP_ACP, 0, env, p - (char*)env, NULL, 0 );
1854 envW = HeapAlloc( GetProcessHeap(), 0, lenW * sizeof(WCHAR) );
1855 MultiByteToWideChar( CP_ACP, 0, env, p - (char*)env, envW, lenW );
1856 flags |= CREATE_UNICODE_ENVIRONMENT;
1859 info->hThread = info->hProcess = 0;
1860 info->dwProcessId = info->dwThreadId = 0;
1862 /* Determine executable type */
1864 if (!hFile) /* builtin exe */
1866 TRACE( "starting %s as Winelib app\n", debugstr_w(name) );
1867 retv = create_process( 0, name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1868 inherit, flags, startup_info, info, unixdir, NULL, NULL );
1869 goto done;
1872 switch( MODULE_GetBinaryType( hFile, &res_start, &res_end ))
1874 case BINARY_PE_EXE:
1875 TRACE( "starting %s as Win32 binary (%p-%p)\n", debugstr_w(name), res_start, res_end );
1876 retv = create_process( hFile, name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1877 inherit, flags, startup_info, info, unixdir, res_start, res_end );
1878 break;
1879 case BINARY_WIN16:
1880 case BINARY_DOS:
1881 TRACE( "starting %s as Win16/DOS binary\n", debugstr_w(name) );
1882 retv = create_vdm_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1883 inherit, flags, startup_info, info, unixdir );
1884 break;
1885 case BINARY_OS216:
1886 FIXME( "%s is OS/2 binary, not supported\n", debugstr_w(name) );
1887 SetLastError( ERROR_BAD_EXE_FORMAT );
1888 break;
1889 case BINARY_PE_DLL:
1890 TRACE( "not starting %s since it is a dll\n", debugstr_w(name) );
1891 SetLastError( ERROR_BAD_EXE_FORMAT );
1892 break;
1893 case BINARY_UNIX_LIB:
1894 TRACE( "%s is a Unix library, starting as Winelib app\n", debugstr_w(name) );
1895 retv = create_process( hFile, name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1896 inherit, flags, startup_info, info, unixdir, NULL, NULL );
1897 break;
1898 case BINARY_UNKNOWN:
1899 /* check for .com or .bat extension */
1900 if ((p = strrchrW( name, '.' )))
1902 if (!strcmpiW( p, comW ))
1904 TRACE( "starting %s as DOS binary\n", debugstr_w(name) );
1905 retv = create_vdm_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1906 inherit, flags, startup_info, info, unixdir );
1907 break;
1909 if (!strcmpiW( p, batW ))
1911 TRACE( "starting %s as batch binary\n", debugstr_w(name) );
1912 retv = create_cmd_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1913 inherit, flags, startup_info, info );
1914 break;
1917 /* fall through */
1918 case BINARY_UNIX_EXE:
1920 /* unknown file, try as unix executable */
1921 char *unix_name;
1923 TRACE( "starting %s as Unix binary\n", debugstr_w(name) );
1925 if ((unix_name = wine_get_unix_file_name( name )))
1927 retv = (fork_and_exec( unix_name, tidy_cmdline, envW, unixdir ) != -1);
1928 HeapFree( GetProcessHeap(), 0, unix_name );
1931 break;
1933 CloseHandle( hFile );
1935 done:
1936 if (tidy_cmdline != cmd_line) HeapFree( GetProcessHeap(), 0, tidy_cmdline );
1937 if (envW != env) HeapFree( GetProcessHeap(), 0, envW );
1938 if (unixdir) HeapFree( GetProcessHeap(), 0, unixdir );
1939 return retv;
1943 /***********************************************************************
1944 * wait_input_idle
1946 * Wrapper to call WaitForInputIdle USER function
1948 typedef DWORD (WINAPI *WaitForInputIdle_ptr)( HANDLE hProcess, DWORD dwTimeOut );
1950 static DWORD wait_input_idle( HANDLE process, DWORD timeout )
1952 HMODULE mod = GetModuleHandleA( "user32.dll" );
1953 if (mod)
1955 WaitForInputIdle_ptr ptr = (WaitForInputIdle_ptr)GetProcAddress( mod, "WaitForInputIdle" );
1956 if (ptr) return ptr( process, timeout );
1958 return 0;
1962 /***********************************************************************
1963 * WinExec (KERNEL32.@)
1965 UINT WINAPI WinExec( LPCSTR lpCmdLine, UINT nCmdShow )
1967 PROCESS_INFORMATION info;
1968 STARTUPINFOA startup;
1969 char *cmdline;
1970 UINT ret;
1972 memset( &startup, 0, sizeof(startup) );
1973 startup.cb = sizeof(startup);
1974 startup.dwFlags = STARTF_USESHOWWINDOW;
1975 startup.wShowWindow = nCmdShow;
1977 /* cmdline needs to be writeable for CreateProcess */
1978 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(lpCmdLine)+1 ))) return 0;
1979 strcpy( cmdline, lpCmdLine );
1981 if (CreateProcessA( NULL, cmdline, NULL, NULL, FALSE,
1982 0, NULL, NULL, &startup, &info ))
1984 /* Give 30 seconds to the app to come up */
1985 if (wait_input_idle( info.hProcess, 30000 ) == WAIT_FAILED)
1986 WARN("WaitForInputIdle failed: Error %ld\n", GetLastError() );
1987 ret = 33;
1988 /* Close off the handles */
1989 CloseHandle( info.hThread );
1990 CloseHandle( info.hProcess );
1992 else if ((ret = GetLastError()) >= 32)
1994 FIXME("Strange error set by CreateProcess: %d\n", ret );
1995 ret = 11;
1997 HeapFree( GetProcessHeap(), 0, cmdline );
1998 return ret;
2002 /**********************************************************************
2003 * LoadModule (KERNEL32.@)
2005 HINSTANCE WINAPI LoadModule( LPCSTR name, LPVOID paramBlock )
2007 LOADPARMS32 *params = paramBlock;
2008 PROCESS_INFORMATION info;
2009 STARTUPINFOA startup;
2010 HINSTANCE hInstance;
2011 LPSTR cmdline, p;
2012 char filename[MAX_PATH];
2013 BYTE len;
2015 if (!name) return (HINSTANCE)ERROR_FILE_NOT_FOUND;
2017 if (!SearchPathA( NULL, name, ".exe", sizeof(filename), filename, NULL ) &&
2018 !SearchPathA( NULL, name, NULL, sizeof(filename), filename, NULL ))
2019 return (HINSTANCE)GetLastError();
2021 len = (BYTE)params->lpCmdLine[0];
2022 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(filename) + len + 2 )))
2023 return (HINSTANCE)ERROR_NOT_ENOUGH_MEMORY;
2025 strcpy( cmdline, filename );
2026 p = cmdline + strlen(cmdline);
2027 *p++ = ' ';
2028 memcpy( p, params->lpCmdLine + 1, len );
2029 p[len] = 0;
2031 memset( &startup, 0, sizeof(startup) );
2032 startup.cb = sizeof(startup);
2033 if (params->lpCmdShow)
2035 startup.dwFlags = STARTF_USESHOWWINDOW;
2036 startup.wShowWindow = ((WORD *)params->lpCmdShow)[1];
2039 if (CreateProcessA( filename, cmdline, NULL, NULL, FALSE, 0,
2040 params->lpEnvAddress, NULL, &startup, &info ))
2042 /* Give 30 seconds to the app to come up */
2043 if (wait_input_idle( info.hProcess, 30000 ) == WAIT_FAILED)
2044 WARN("WaitForInputIdle failed: Error %ld\n", GetLastError() );
2045 hInstance = (HINSTANCE)33;
2046 /* Close off the handles */
2047 CloseHandle( info.hThread );
2048 CloseHandle( info.hProcess );
2050 else if ((hInstance = (HINSTANCE)GetLastError()) >= (HINSTANCE)32)
2052 FIXME("Strange error set by CreateProcess: %p\n", hInstance );
2053 hInstance = (HINSTANCE)11;
2056 HeapFree( GetProcessHeap(), 0, cmdline );
2057 return hInstance;
2061 /******************************************************************************
2062 * TerminateProcess (KERNEL32.@)
2064 BOOL WINAPI TerminateProcess( HANDLE handle, DWORD exit_code )
2066 NTSTATUS status = NtTerminateProcess( handle, exit_code );
2067 if (status) SetLastError( RtlNtStatusToDosError(status) );
2068 return !status;
2072 /***********************************************************************
2073 * ExitProcess (KERNEL32.@)
2075 void WINAPI ExitProcess( DWORD status )
2077 LdrShutdownProcess();
2078 SERVER_START_REQ( terminate_process )
2080 /* send the exit code to the server */
2081 req->handle = GetCurrentProcess();
2082 req->exit_code = status;
2083 wine_server_call( req );
2085 SERVER_END_REQ;
2086 exit( status );
2090 /***********************************************************************
2091 * GetExitCodeProcess [KERNEL32.@]
2093 * Gets termination status of specified process
2095 * RETURNS
2096 * Success: TRUE
2097 * Failure: FALSE
2099 BOOL WINAPI GetExitCodeProcess(
2100 HANDLE hProcess, /* [in] handle to the process */
2101 LPDWORD lpExitCode) /* [out] address to receive termination status */
2103 NTSTATUS status;
2104 PROCESS_BASIC_INFORMATION pbi;
2106 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
2107 sizeof(pbi), NULL);
2108 if (status == STATUS_SUCCESS)
2110 if (lpExitCode) *lpExitCode = pbi.ExitStatus;
2111 return TRUE;
2113 SetLastError( RtlNtStatusToDosError(status) );
2114 return FALSE;
2118 /***********************************************************************
2119 * SetErrorMode (KERNEL32.@)
2121 UINT WINAPI SetErrorMode( UINT mode )
2123 UINT old = process_error_mode;
2124 process_error_mode = mode;
2125 return old;
2129 /**********************************************************************
2130 * TlsAlloc [KERNEL32.@] Allocates a TLS index.
2132 * Allocates a thread local storage index
2134 * RETURNS
2135 * Success: TLS Index
2136 * Failure: 0xFFFFFFFF
2138 DWORD WINAPI TlsAlloc( void )
2140 DWORD index;
2142 RtlAcquirePebLock();
2143 index = RtlFindClearBitsAndSet( NtCurrentTeb()->Peb->TlsBitmap, 1, 0 );
2144 if (index != ~0UL) NtCurrentTeb()->TlsSlots[index] = 0; /* clear the value */
2145 else SetLastError( ERROR_NO_MORE_ITEMS );
2146 RtlReleasePebLock();
2147 return index;
2151 /**********************************************************************
2152 * TlsFree [KERNEL32.@] Releases a TLS index.
2154 * Releases a thread local storage index, making it available for reuse
2156 * RETURNS
2157 * Success: TRUE
2158 * Failure: FALSE
2160 BOOL WINAPI TlsFree(
2161 DWORD index) /* [in] TLS Index to free */
2163 BOOL ret;
2165 RtlAcquirePebLock();
2166 ret = RtlAreBitsSet( NtCurrentTeb()->Peb->TlsBitmap, index, 1 );
2167 if (ret)
2169 RtlClearBits( NtCurrentTeb()->Peb->TlsBitmap, index, 1 );
2170 NtSetInformationThread( GetCurrentThread(), ThreadZeroTlsCell, &index, sizeof(index) );
2172 else SetLastError( ERROR_INVALID_PARAMETER );
2173 RtlReleasePebLock();
2174 return TRUE;
2178 /**********************************************************************
2179 * TlsGetValue [KERNEL32.@] Gets value in a thread's TLS slot
2181 * RETURNS
2182 * Success: Value stored in calling thread's TLS slot for index
2183 * Failure: 0 and GetLastError returns NO_ERROR
2185 LPVOID WINAPI TlsGetValue(
2186 DWORD index) /* [in] TLS index to retrieve value for */
2188 if (index >= NtCurrentTeb()->Peb->TlsBitmap->SizeOfBitMap)
2190 SetLastError( ERROR_INVALID_PARAMETER );
2191 return NULL;
2193 SetLastError( ERROR_SUCCESS );
2194 return NtCurrentTeb()->TlsSlots[index];
2198 /**********************************************************************
2199 * TlsSetValue [KERNEL32.@] Stores a value in the thread's TLS slot.
2201 * RETURNS
2202 * Success: TRUE
2203 * Failure: FALSE
2205 BOOL WINAPI TlsSetValue(
2206 DWORD index, /* [in] TLS index to set value for */
2207 LPVOID value) /* [in] Value to be stored */
2209 if (index >= NtCurrentTeb()->Peb->TlsBitmap->SizeOfBitMap)
2211 SetLastError( ERROR_INVALID_PARAMETER );
2212 return FALSE;
2214 NtCurrentTeb()->TlsSlots[index] = value;
2215 return TRUE;
2219 /***********************************************************************
2220 * GetProcessFlags (KERNEL32.@)
2222 DWORD WINAPI GetProcessFlags( DWORD processid )
2224 IMAGE_NT_HEADERS *nt;
2225 DWORD flags = 0;
2227 if (processid && processid != GetCurrentProcessId()) return 0;
2229 if ((nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress )))
2231 if (nt->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_CUI)
2232 flags |= PDB32_CONSOLE_PROC;
2234 if (!AreFileApisANSI()) flags |= PDB32_FILE_APIS_OEM;
2235 if (IsDebuggerPresent()) flags |= PDB32_DEBUGGED;
2236 return flags;
2240 /***********************************************************************
2241 * GetProcessDword (KERNEL.485)
2242 * GetProcessDword (KERNEL32.18)
2243 * 'Of course you cannot directly access Windows internal structures'
2245 DWORD WINAPI GetProcessDword( DWORD dwProcessID, INT offset )
2247 DWORD x, y;
2248 STARTUPINFOW siw;
2250 TRACE("(%ld, %d)\n", dwProcessID, offset );
2252 if (dwProcessID && dwProcessID != GetCurrentProcessId())
2254 ERR("%d: process %lx not accessible\n", offset, dwProcessID);
2255 return 0;
2258 switch ( offset )
2260 case GPD_APP_COMPAT_FLAGS:
2261 return GetAppCompatFlags16(0);
2262 case GPD_LOAD_DONE_EVENT:
2263 return 0;
2264 case GPD_HINSTANCE16:
2265 return GetTaskDS16();
2266 case GPD_WINDOWS_VERSION:
2267 return GetExeVersion16();
2268 case GPD_THDB:
2269 return (DWORD)NtCurrentTeb() - 0x10 /* FIXME */;
2270 case GPD_PDB:
2271 return (DWORD)NtCurrentTeb()->Peb;
2272 case GPD_STARTF_SHELLDATA: /* return stdoutput handle from startupinfo ??? */
2273 GetStartupInfoW(&siw);
2274 return (DWORD)siw.hStdOutput;
2275 case GPD_STARTF_HOTKEY: /* return stdinput handle from startupinfo ??? */
2276 GetStartupInfoW(&siw);
2277 return (DWORD)siw.hStdInput;
2278 case GPD_STARTF_SHOWWINDOW:
2279 GetStartupInfoW(&siw);
2280 return siw.wShowWindow;
2281 case GPD_STARTF_SIZE:
2282 GetStartupInfoW(&siw);
2283 x = siw.dwXSize;
2284 if ( (INT)x == CW_USEDEFAULT ) x = CW_USEDEFAULT16;
2285 y = siw.dwYSize;
2286 if ( (INT)y == CW_USEDEFAULT ) y = CW_USEDEFAULT16;
2287 return MAKELONG( x, y );
2288 case GPD_STARTF_POSITION:
2289 GetStartupInfoW(&siw);
2290 x = siw.dwX;
2291 if ( (INT)x == CW_USEDEFAULT ) x = CW_USEDEFAULT16;
2292 y = siw.dwY;
2293 if ( (INT)y == CW_USEDEFAULT ) y = CW_USEDEFAULT16;
2294 return MAKELONG( x, y );
2295 case GPD_STARTF_FLAGS:
2296 GetStartupInfoW(&siw);
2297 return siw.dwFlags;
2298 case GPD_PARENT:
2299 return 0;
2300 case GPD_FLAGS:
2301 return GetProcessFlags(0);
2302 case GPD_USERDATA:
2303 return process_dword;
2304 default:
2305 ERR("Unknown offset %d\n", offset );
2306 return 0;
2310 /***********************************************************************
2311 * SetProcessDword (KERNEL.484)
2312 * 'Of course you cannot directly access Windows internal structures'
2314 void WINAPI SetProcessDword( DWORD dwProcessID, INT offset, DWORD value )
2316 TRACE("(%ld, %d)\n", dwProcessID, offset );
2318 if (dwProcessID && dwProcessID != GetCurrentProcessId())
2320 ERR("%d: process %lx not accessible\n", offset, dwProcessID);
2321 return;
2324 switch ( offset )
2326 case GPD_APP_COMPAT_FLAGS:
2327 case GPD_LOAD_DONE_EVENT:
2328 case GPD_HINSTANCE16:
2329 case GPD_WINDOWS_VERSION:
2330 case GPD_THDB:
2331 case GPD_PDB:
2332 case GPD_STARTF_SHELLDATA:
2333 case GPD_STARTF_HOTKEY:
2334 case GPD_STARTF_SHOWWINDOW:
2335 case GPD_STARTF_SIZE:
2336 case GPD_STARTF_POSITION:
2337 case GPD_STARTF_FLAGS:
2338 case GPD_PARENT:
2339 case GPD_FLAGS:
2340 ERR("Not allowed to modify offset %d\n", offset );
2341 break;
2342 case GPD_USERDATA:
2343 process_dword = value;
2344 break;
2345 default:
2346 ERR("Unknown offset %d\n", offset );
2347 break;
2352 /***********************************************************************
2353 * ExitProcess (KERNEL.466)
2355 void WINAPI ExitProcess16( WORD status )
2357 DWORD count;
2358 ReleaseThunkLock( &count );
2359 ExitProcess( status );
2363 /*********************************************************************
2364 * OpenProcess (KERNEL32.@)
2366 HANDLE WINAPI OpenProcess( DWORD access, BOOL inherit, DWORD id )
2368 HANDLE ret = 0;
2369 SERVER_START_REQ( open_process )
2371 req->pid = id;
2372 req->access = access;
2373 req->inherit = inherit;
2374 if (!wine_server_call_err( req )) ret = reply->handle;
2376 SERVER_END_REQ;
2377 return ret;
2381 /*********************************************************************
2382 * MapProcessHandle (KERNEL.483)
2384 DWORD WINAPI MapProcessHandle( HANDLE hProcess )
2386 NTSTATUS status;
2387 PROCESS_BASIC_INFORMATION pbi;
2389 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
2390 sizeof(pbi), NULL);
2391 if (status == STATUS_SUCCESS) return pbi.UniqueProcessId;
2392 SetLastError( RtlNtStatusToDosError(status) );
2393 return 0;
2397 /*********************************************************************
2398 * CloseW32Handle (KERNEL.474)
2399 * CloseHandle (KERNEL32.@)
2401 BOOL WINAPI CloseHandle( HANDLE handle )
2403 NTSTATUS status;
2405 /* stdio handles need special treatment */
2406 if ((handle == (HANDLE)STD_INPUT_HANDLE) ||
2407 (handle == (HANDLE)STD_OUTPUT_HANDLE) ||
2408 (handle == (HANDLE)STD_ERROR_HANDLE))
2409 handle = GetStdHandle( (DWORD)handle );
2411 if (is_console_handle(handle))
2412 return CloseConsoleHandle(handle);
2414 status = NtClose( handle );
2415 if (status) SetLastError( RtlNtStatusToDosError(status) );
2416 return !status;
2420 /*********************************************************************
2421 * GetHandleInformation (KERNEL32.@)
2423 BOOL WINAPI GetHandleInformation( HANDLE handle, LPDWORD flags )
2425 BOOL ret;
2426 SERVER_START_REQ( set_handle_info )
2428 req->handle = handle;
2429 req->flags = 0;
2430 req->mask = 0;
2431 req->fd = -1;
2432 ret = !wine_server_call_err( req );
2433 if (ret && flags) *flags = reply->old_flags;
2435 SERVER_END_REQ;
2436 return ret;
2440 /*********************************************************************
2441 * SetHandleInformation (KERNEL32.@)
2443 BOOL WINAPI SetHandleInformation( HANDLE handle, DWORD mask, DWORD flags )
2445 BOOL ret;
2446 SERVER_START_REQ( set_handle_info )
2448 req->handle = handle;
2449 req->flags = flags;
2450 req->mask = mask;
2451 req->fd = -1;
2452 ret = !wine_server_call_err( req );
2454 SERVER_END_REQ;
2455 return ret;
2459 /*********************************************************************
2460 * DuplicateHandle (KERNEL32.@)
2462 BOOL WINAPI DuplicateHandle( HANDLE source_process, HANDLE source,
2463 HANDLE dest_process, HANDLE *dest,
2464 DWORD access, BOOL inherit, DWORD options )
2466 NTSTATUS status;
2468 if (is_console_handle(source))
2470 /* FIXME: this test is not sufficient, we need to test process ids, not handles */
2471 if (source_process != dest_process ||
2472 source_process != GetCurrentProcess())
2474 SetLastError(ERROR_INVALID_PARAMETER);
2475 return FALSE;
2477 *dest = DuplicateConsoleHandle( source, access, inherit, options );
2478 return (*dest != INVALID_HANDLE_VALUE);
2480 status = NtDuplicateObject( source_process, source, dest_process, dest,
2481 access, inherit ? OBJ_INHERIT : 0, options );
2482 if (status) SetLastError( RtlNtStatusToDosError(status) );
2483 return !status;
2487 /***********************************************************************
2488 * ConvertToGlobalHandle (KERNEL.476)
2489 * ConvertToGlobalHandle (KERNEL32.@)
2491 HANDLE WINAPI ConvertToGlobalHandle(HANDLE hSrc)
2493 HANDLE ret = INVALID_HANDLE_VALUE;
2494 DuplicateHandle( GetCurrentProcess(), hSrc, GetCurrentProcess(), &ret, 0, FALSE,
2495 DUP_HANDLE_MAKE_GLOBAL | DUP_HANDLE_SAME_ACCESS | DUP_HANDLE_CLOSE_SOURCE );
2496 return ret;
2500 /***********************************************************************
2501 * SetHandleContext (KERNEL32.@)
2503 BOOL WINAPI SetHandleContext(HANDLE hnd,DWORD context)
2505 FIXME("(%p,%ld), stub. In case this got called by WSOCK32/WS2_32: "
2506 "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd,context);
2507 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2508 return FALSE;
2512 /***********************************************************************
2513 * GetHandleContext (KERNEL32.@)
2515 DWORD WINAPI GetHandleContext(HANDLE hnd)
2517 FIXME("(%p), stub. In case this got called by WSOCK32/WS2_32: "
2518 "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd);
2519 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2520 return 0;
2524 /***********************************************************************
2525 * CreateSocketHandle (KERNEL32.@)
2527 HANDLE WINAPI CreateSocketHandle(void)
2529 FIXME("(), stub. In case this got called by WSOCK32/WS2_32: "
2530 "the external WINSOCK DLLs won't work with WINE, don't use them.\n");
2531 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2532 return INVALID_HANDLE_VALUE;
2536 /***********************************************************************
2537 * SetPriorityClass (KERNEL32.@)
2539 BOOL WINAPI SetPriorityClass( HANDLE hprocess, DWORD priorityclass )
2541 BOOL ret;
2542 SERVER_START_REQ( set_process_info )
2544 req->handle = hprocess;
2545 req->priority = priorityclass;
2546 req->mask = SET_PROCESS_INFO_PRIORITY;
2547 ret = !wine_server_call_err( req );
2549 SERVER_END_REQ;
2550 return ret;
2554 /***********************************************************************
2555 * GetPriorityClass (KERNEL32.@)
2557 DWORD WINAPI GetPriorityClass(HANDLE hProcess)
2559 NTSTATUS status;
2560 PROCESS_BASIC_INFORMATION pbi;
2562 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
2563 sizeof(pbi), NULL);
2564 if (status == STATUS_SUCCESS) return pbi.BasePriority;
2565 SetLastError( RtlNtStatusToDosError(status) );
2566 return 0;
2570 /***********************************************************************
2571 * SetProcessAffinityMask (KERNEL32.@)
2573 BOOL WINAPI SetProcessAffinityMask( HANDLE hProcess, DWORD affmask )
2575 BOOL ret;
2576 SERVER_START_REQ( set_process_info )
2578 req->handle = hProcess;
2579 req->affinity = affmask;
2580 req->mask = SET_PROCESS_INFO_AFFINITY;
2581 ret = !wine_server_call_err( req );
2583 SERVER_END_REQ;
2584 return ret;
2588 /**********************************************************************
2589 * GetProcessAffinityMask (KERNEL32.@)
2591 BOOL WINAPI GetProcessAffinityMask( HANDLE hProcess,
2592 LPDWORD lpProcessAffinityMask,
2593 LPDWORD lpSystemAffinityMask )
2595 BOOL ret = FALSE;
2596 SERVER_START_REQ( get_process_info )
2598 req->handle = hProcess;
2599 if (!wine_server_call_err( req ))
2601 if (lpProcessAffinityMask) *lpProcessAffinityMask = reply->process_affinity;
2602 if (lpSystemAffinityMask) *lpSystemAffinityMask = reply->system_affinity;
2603 ret = TRUE;
2606 SERVER_END_REQ;
2607 return ret;
2611 /***********************************************************************
2612 * GetProcessVersion (KERNEL32.@)
2614 DWORD WINAPI GetProcessVersion( DWORD processid )
2616 IMAGE_NT_HEADERS *nt;
2618 if (processid && processid != GetCurrentProcessId())
2620 FIXME("should use ReadProcessMemory\n");
2621 return 0;
2623 if ((nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress )))
2624 return ((nt->OptionalHeader.MajorSubsystemVersion << 16) |
2625 nt->OptionalHeader.MinorSubsystemVersion);
2626 return 0;
2630 /***********************************************************************
2631 * SetProcessWorkingSetSize [KERNEL32.@]
2632 * Sets the min/max working set sizes for a specified process.
2634 * PARAMS
2635 * hProcess [I] Handle to the process of interest
2636 * minset [I] Specifies minimum working set size
2637 * maxset [I] Specifies maximum working set size
2639 * RETURNS STD
2641 BOOL WINAPI SetProcessWorkingSetSize(HANDLE hProcess, SIZE_T minset,
2642 SIZE_T maxset)
2644 FIXME("(%p,%ld,%ld): stub - harmless\n",hProcess,minset,maxset);
2645 if(( minset == (SIZE_T)-1) && (maxset == (SIZE_T)-1)) {
2646 /* Trim the working set to zero */
2647 /* Swap the process out of physical RAM */
2649 return TRUE;
2652 /***********************************************************************
2653 * GetProcessWorkingSetSize (KERNEL32.@)
2655 BOOL WINAPI GetProcessWorkingSetSize(HANDLE hProcess, PSIZE_T minset,
2656 PSIZE_T maxset)
2658 FIXME("(%p,%p,%p): stub\n",hProcess,minset,maxset);
2659 /* 32 MB working set size */
2660 if (minset) *minset = 32*1024*1024;
2661 if (maxset) *maxset = 32*1024*1024;
2662 return TRUE;
2666 /***********************************************************************
2667 * SetProcessShutdownParameters (KERNEL32.@)
2669 BOOL WINAPI SetProcessShutdownParameters(DWORD level, DWORD flags)
2671 FIXME("(%08lx, %08lx): partial stub.\n", level, flags);
2672 shutdown_flags = flags;
2673 shutdown_priority = level;
2674 return TRUE;
2678 /***********************************************************************
2679 * GetProcessShutdownParameters (KERNEL32.@)
2682 BOOL WINAPI GetProcessShutdownParameters( LPDWORD lpdwLevel, LPDWORD lpdwFlags )
2684 *lpdwLevel = shutdown_priority;
2685 *lpdwFlags = shutdown_flags;
2686 return TRUE;
2690 /***********************************************************************
2691 * GetProcessPriorityBoost (KERNEL32.@)
2693 BOOL WINAPI GetProcessPriorityBoost(HANDLE hprocess,PBOOL pDisablePriorityBoost)
2695 FIXME("(%p,%p): semi-stub\n", hprocess, pDisablePriorityBoost);
2697 /* Report that no boost is present.. */
2698 *pDisablePriorityBoost = FALSE;
2700 return TRUE;
2703 /***********************************************************************
2704 * SetProcessPriorityBoost (KERNEL32.@)
2706 BOOL WINAPI SetProcessPriorityBoost(HANDLE hprocess,BOOL disableboost)
2708 FIXME("(%p,%d): stub\n",hprocess,disableboost);
2709 /* Say we can do it. I doubt the program will notice that we don't. */
2710 return TRUE;
2714 /***********************************************************************
2715 * ReadProcessMemory (KERNEL32.@)
2717 BOOL WINAPI ReadProcessMemory( HANDLE process, LPCVOID addr, LPVOID buffer, SIZE_T size,
2718 SIZE_T *bytes_read )
2720 NTSTATUS status = NtReadVirtualMemory( process, addr, buffer, size, bytes_read );
2721 if (status) SetLastError( RtlNtStatusToDosError(status) );
2722 return !status;
2726 /***********************************************************************
2727 * WriteProcessMemory (KERNEL32.@)
2729 BOOL WINAPI WriteProcessMemory( HANDLE process, LPVOID addr, LPCVOID buffer, SIZE_T size,
2730 SIZE_T *bytes_written )
2732 NTSTATUS status = NtWriteVirtualMemory( process, addr, buffer, size, bytes_written );
2733 if (status) SetLastError( RtlNtStatusToDosError(status) );
2734 return !status;
2738 /****************************************************************************
2739 * FlushInstructionCache (KERNEL32.@)
2741 BOOL WINAPI FlushInstructionCache(HANDLE hProcess, LPCVOID lpBaseAddress, SIZE_T dwSize)
2743 if (GetVersion() & 0x80000000) return TRUE; /* not NT, always TRUE */
2744 FIXME("(%p,%p,0x%08lx): stub\n",hProcess, lpBaseAddress, dwSize);
2745 return TRUE;
2749 /******************************************************************
2750 * GetProcessIoCounters (KERNEL32.@)
2752 BOOL WINAPI GetProcessIoCounters(HANDLE hProcess, PIO_COUNTERS ioc)
2754 NTSTATUS status;
2756 status = NtQueryInformationProcess(hProcess, ProcessIoCounters,
2757 ioc, sizeof(*ioc), NULL);
2758 if (status) SetLastError( RtlNtStatusToDosError(status) );
2759 return !status;
2762 /***********************************************************************
2763 * ProcessIdToSessionId (KERNEL32.@)
2764 * This function is available on Terminal Server 4SP4 and Windows 2000
2766 BOOL WINAPI ProcessIdToSessionId( DWORD procid, DWORD *sessionid_ptr )
2768 /* According to MSDN, if the calling process is not in a terminal
2769 * services environment, then the sessionid returned is zero.
2771 *sessionid_ptr = 0;
2772 return TRUE;
2776 /***********************************************************************
2777 * RegisterServiceProcess (KERNEL.491)
2778 * RegisterServiceProcess (KERNEL32.@)
2780 * A service process calls this function to ensure that it continues to run
2781 * even after a user logged off.
2783 DWORD WINAPI RegisterServiceProcess(DWORD dwProcessId, DWORD dwType)
2785 /* I don't think that Wine needs to do anything in that function */
2786 return 1; /* success */
2790 /***********************************************************************
2791 * GetSystemMSecCount (SYSTEM.6)
2792 * GetTickCount (KERNEL32.@)
2794 * Returns the number of milliseconds, modulo 2^32, since the start
2795 * of the wineserver.
2797 DWORD WINAPI GetTickCount(void)
2799 struct timeval t;
2800 gettimeofday( &t, NULL );
2801 return ((t.tv_sec * 1000) + (t.tv_usec / 1000)) - server_startticks;
2805 /***********************************************************************
2806 * GetCurrentProcess (KERNEL32.@)
2808 #undef GetCurrentProcess
2809 HANDLE WINAPI GetCurrentProcess(void)
2811 return (HANDLE)0xffffffff;