Make rsabase.dll self-register.
[wine.git] / dlls / kernel / process.c
blob475a3adf1d4cf307e4a2b1f9909cc31b77041e34
1 /*
2 * Win32 processes
4 * Copyright 1996, 1998 Alexandre Julliard
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
21 #include "config.h"
22 #include "wine/port.h"
24 #include <assert.h>
25 #include <ctype.h>
26 #include <errno.h>
27 #include <locale.h>
28 #include <signal.h>
29 #include <stdio.h>
31 #include "wine/winbase16.h"
32 #include "wine/winuser16.h"
33 #include "ntstatus.h"
34 #include "thread.h"
35 #include "drive.h"
36 #include "file.h"
37 #include "module.h"
38 #include "options.h"
39 #include "kernel_private.h"
40 #include "wine/exception.h"
41 #include "wine/server.h"
42 #include "wine/unicode.h"
43 #include "wine/debug.h"
45 WINE_DEFAULT_DEBUG_CHANNEL(process);
46 WINE_DECLARE_DEBUG_CHANNEL(server);
47 WINE_DECLARE_DEBUG_CHANNEL(relay);
49 typedef struct
51 LPSTR lpEnvAddress;
52 LPSTR lpCmdLine;
53 LPSTR lpCmdShow;
54 DWORD dwReserved;
55 } LOADPARMS32;
57 static UINT process_error_mode;
59 static HANDLE main_exe_file;
60 static DWORD shutdown_flags = 0;
61 static DWORD shutdown_priority = 0x280;
62 static DWORD process_dword;
63 static BOOL oem_file_apis;
65 static unsigned int server_startticks;
66 int main_create_flags = 0;
67 HMODULE kernel32_handle = 0;
69 /* Process flags */
70 #define PDB32_DEBUGGED 0x0001 /* Process is being debugged */
71 #define PDB32_WIN16_PROC 0x0008 /* Win16 process */
72 #define PDB32_DOS_PROC 0x0010 /* Dos process */
73 #define PDB32_CONSOLE_PROC 0x0020 /* Console process */
74 #define PDB32_FILE_APIS_OEM 0x0040 /* File APIs are OEM */
75 #define PDB32_WIN32S_PROC 0x8000 /* Win32s process */
77 static const WCHAR comW[] = {'.','c','o','m',0};
78 static const WCHAR batW[] = {'.','b','a','t',0};
79 static const WCHAR winevdmW[] = {'w','i','n','e','v','d','m','.','e','x','e',0};
81 extern void SHELL_LoadRegistry(void);
82 extern void VERSION_Init( const WCHAR *appname );
83 extern void MODULE_InitLoadPath(void);
84 extern void LOCALE_Init(void);
86 /***********************************************************************
87 * contains_path
89 inline static int contains_path( LPCWSTR name )
91 return ((*name && (name[1] == ':')) || strchrW(name, '/') || strchrW(name, '\\'));
95 /***************************************************************************
96 * get_builtin_path
98 * Get the path of a builtin module when the native file does not exist.
100 static BOOL get_builtin_path( const WCHAR *libname, const WCHAR *ext, WCHAR *filename, UINT size )
102 WCHAR *file_part;
103 WCHAR sysdir[MAX_PATH];
104 UINT len = GetSystemDirectoryW( sysdir, MAX_PATH );
106 if (contains_path( libname ))
108 if (RtlGetFullPathName_U( libname, size * sizeof(WCHAR),
109 filename, &file_part ) > size * sizeof(WCHAR))
110 return FALSE; /* too long */
112 if (strncmpiW( filename, sysdir, len ) || filename[len] != '\\')
113 return FALSE;
114 while (filename[len] == '\\') len++;
115 if (filename + len != file_part) return FALSE;
117 else
119 if (strlenW(libname) + len + 2 >= size) return FALSE; /* too long */
120 memcpy( filename, sysdir, len * sizeof(WCHAR) );
121 file_part = filename + len;
122 if (file_part > filename && file_part[-1] != '\\') *file_part++ = '\\';
123 strcpyW( file_part, libname );
125 if (ext && !strchrW( file_part, '.' ))
127 if (file_part + strlenW(file_part) + strlenW(ext) + 1 > filename + size)
128 return FALSE; /* too long */
129 strcatW( file_part, ext );
131 return TRUE;
135 /***********************************************************************
136 * open_builtin_exe_file
138 * Open an exe file for a builtin exe.
140 static void *open_builtin_exe_file( const WCHAR *name, char *error, int error_size,
141 int test_only, int *file_exists )
143 char exename[MAX_PATH];
144 WCHAR *p;
145 UINT i, len;
147 if ((p = strrchrW( name, '/' ))) name = p + 1;
148 if ((p = strrchrW( name, '\\' ))) name = p + 1;
150 /* we don't want to depend on the current codepage here */
151 len = strlenW( name ) + 1;
152 if (len >= sizeof(exename)) return NULL;
153 for (i = 0; i < len; i++)
155 if (name[i] > 127) return NULL;
156 exename[i] = (char)name[i];
157 if (exename[i] >= 'A' && exename[i] <= 'Z') exename[i] += 'a' - 'A';
159 return wine_dll_load_main_exe( exename, error, error_size, test_only, file_exists );
163 /***********************************************************************
164 * open_exe_file
166 * Open a specific exe file, taking load order into account.
167 * Returns the file handle or 0 for a builtin exe.
169 static HANDLE open_exe_file( const WCHAR *name )
171 enum loadorder_type loadorder[LOADORDER_NTYPES];
172 WCHAR buffer[MAX_PATH];
173 HANDLE handle;
174 int i, file_exists;
176 TRACE("looking for %s\n", debugstr_w(name) );
178 if ((handle = CreateFileW( name, GENERIC_READ, FILE_SHARE_READ,
179 NULL, OPEN_EXISTING, 0, 0 )) == INVALID_HANDLE_VALUE)
181 /* file doesn't exist, check for builtin */
182 if (!contains_path( name )) goto error;
183 if (!get_builtin_path( name, NULL, buffer, sizeof(buffer) )) goto error;
184 name = buffer;
187 MODULE_GetLoadOrderW( loadorder, NULL, name );
189 for(i = 0; i < LOADORDER_NTYPES; i++)
191 if (loadorder[i] == LOADORDER_INVALID) break;
192 switch(loadorder[i])
194 case LOADORDER_DLL:
195 TRACE( "Trying native exe %s\n", debugstr_w(name) );
196 if (handle != INVALID_HANDLE_VALUE) return handle;
197 break;
198 case LOADORDER_BI:
199 TRACE( "Trying built-in exe %s\n", debugstr_w(name) );
200 open_builtin_exe_file( name, NULL, 0, 1, &file_exists );
201 if (file_exists)
203 if (handle != INVALID_HANDLE_VALUE) CloseHandle(handle);
204 return 0;
206 default:
207 break;
210 if (handle != INVALID_HANDLE_VALUE) CloseHandle(handle);
212 error:
213 SetLastError( ERROR_FILE_NOT_FOUND );
214 return INVALID_HANDLE_VALUE;
218 /***********************************************************************
219 * find_exe_file
221 * Open an exe file, and return the full name and file handle.
222 * Returns FALSE if file could not be found.
223 * If file exists but cannot be opened, returns TRUE and set handle to INVALID_HANDLE_VALUE.
224 * If file is a builtin exe, returns TRUE and sets handle to 0.
226 static BOOL find_exe_file( const WCHAR *name, WCHAR *buffer, int buflen, HANDLE *handle )
228 static const WCHAR exeW[] = {'.','e','x','e',0};
230 enum loadorder_type loadorder[LOADORDER_NTYPES];
231 int i, file_exists;
233 TRACE("looking for %s\n", debugstr_w(name) );
235 if (!SearchPathW( NULL, name, exeW, buflen, buffer, NULL ) &&
236 !get_builtin_path( name, exeW, buffer, buflen ))
238 /* no builtin found, try native without extension in case it is a Unix app */
240 if (SearchPathW( NULL, name, NULL, buflen, buffer, NULL ))
242 TRACE( "Trying native/Unix binary %s\n", debugstr_w(buffer) );
243 if ((*handle = CreateFileW( buffer, GENERIC_READ, FILE_SHARE_READ,
244 NULL, OPEN_EXISTING, 0, 0 )) != INVALID_HANDLE_VALUE)
245 return TRUE;
247 return FALSE;
250 MODULE_GetLoadOrderW( loadorder, NULL, buffer );
252 for(i = 0; i < LOADORDER_NTYPES; i++)
254 if (loadorder[i] == LOADORDER_INVALID) break;
255 switch(loadorder[i])
257 case LOADORDER_DLL:
258 TRACE( "Trying native exe %s\n", debugstr_w(buffer) );
259 if ((*handle = CreateFileW( buffer, GENERIC_READ, FILE_SHARE_READ,
260 NULL, OPEN_EXISTING, 0, 0 )) != INVALID_HANDLE_VALUE)
261 return TRUE;
262 if (GetLastError() != ERROR_FILE_NOT_FOUND) return TRUE;
263 break;
264 case LOADORDER_BI:
265 TRACE( "Trying built-in exe %s\n", debugstr_w(buffer) );
266 open_builtin_exe_file( buffer, NULL, 0, 1, &file_exists );
267 if (file_exists)
269 *handle = 0;
270 return TRUE;
272 break;
273 default:
274 break;
277 SetLastError( ERROR_FILE_NOT_FOUND );
278 return FALSE;
282 /**********************************************************************
283 * load_pe_exe
285 * Load a PE format EXE file.
287 static HMODULE load_pe_exe( const WCHAR *name, HANDLE file )
289 IMAGE_NT_HEADERS *nt;
290 HANDLE mapping;
291 void *module;
292 OBJECT_ATTRIBUTES attr;
293 LARGE_INTEGER size;
294 DWORD len = 0;
295 UINT drive_type;
297 attr.Length = sizeof(attr);
298 attr.RootDirectory = 0;
299 attr.ObjectName = NULL;
300 attr.Attributes = 0;
301 attr.SecurityDescriptor = NULL;
302 attr.SecurityQualityOfService = NULL;
303 size.QuadPart = 0;
305 if (NtCreateSection( &mapping, STANDARD_RIGHTS_REQUIRED | SECTION_QUERY | SECTION_MAP_READ,
306 &attr, &size, 0, SEC_IMAGE, file ) != STATUS_SUCCESS)
307 return NULL;
309 module = NULL;
310 if (NtMapViewOfSection( mapping, GetCurrentProcess(), &module, 0, 0, &size, &len,
311 ViewShare, 0, PAGE_READONLY ) != STATUS_SUCCESS)
312 return NULL;
314 NtClose( mapping );
316 /* virus check */
317 nt = RtlImageNtHeader( module );
318 if (nt->OptionalHeader.AddressOfEntryPoint)
320 if (!RtlImageRvaToSection( nt, module, nt->OptionalHeader.AddressOfEntryPoint ))
321 MESSAGE("VIRUS WARNING: PE module %s has an invalid entrypoint (0x%08lx) "
322 "outside all sections (possibly infected by Tchernobyl/SpaceFiller virus)!\n",
323 debugstr_w(name), nt->OptionalHeader.AddressOfEntryPoint );
326 drive_type = GetDriveTypeW( name );
327 /* don't keep the file handle open on removable media */
328 if (drive_type == DRIVE_REMOVABLE || drive_type == DRIVE_CDROM)
330 CloseHandle( main_exe_file );
331 main_exe_file = 0;
334 return module;
337 /***********************************************************************
338 * build_initial_environment
340 * Build the Win32 environment from the Unix environment
342 static BOOL build_initial_environment( char **environ )
344 ULONG size = 1;
345 char **e;
346 WCHAR *p, *endptr;
347 void *ptr;
349 /* Compute the total size of the Unix environment */
350 for (e = environ; *e; e++)
352 if (!memcmp(*e, "PATH=", 5)) continue;
353 size += MultiByteToWideChar( CP_UNIXCP, 0, *e, -1, NULL, 0 );
355 size *= sizeof(WCHAR);
357 /* Now allocate the environment */
358 if (NtAllocateVirtualMemory(NtCurrentProcess(), &ptr, 0, &size,
359 MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) != STATUS_SUCCESS)
360 return FALSE;
362 NtCurrentTeb()->Peb->ProcessParameters->Environment = p = ptr;
363 endptr = p + size / sizeof(WCHAR);
365 /* And fill it with the Unix environment */
366 for (e = environ; *e; e++)
368 char *str = *e;
369 /* skip Unix PATH and store WINEPATH as PATH */
370 if (!memcmp(str, "PATH=", 5)) continue;
371 if (!memcmp(str, "WINEPATH=", 9 )) str += 4;
372 MultiByteToWideChar( CP_UNIXCP, 0, str, -1, p, endptr - p );
373 p += strlenW(p) + 1;
375 *p = 0;
376 return TRUE;
380 /***********************************************************************
381 * set_library_wargv
383 * Set the Wine library Unicode argv global variables.
385 static void set_library_wargv( char **argv )
387 int argc;
388 WCHAR *p;
389 WCHAR **wargv;
390 DWORD total = 0;
392 for (argc = 0; argv[argc]; argc++)
393 total += MultiByteToWideChar( CP_UNIXCP, 0, argv[argc], -1, NULL, 0 );
395 wargv = RtlAllocateHeap( GetProcessHeap(), 0,
396 total * sizeof(WCHAR) + (argc + 1) * sizeof(*wargv) );
397 p = (WCHAR *)(wargv + argc + 1);
398 for (argc = 0; argv[argc]; argc++)
400 DWORD reslen = MultiByteToWideChar( CP_UNIXCP, 0, argv[argc], -1, p, total );
401 wargv[argc] = p;
402 p += reslen;
403 total -= reslen;
405 wargv[argc] = NULL;
406 __wine_main_wargv = wargv;
410 /***********************************************************************
411 * build_command_line
413 * Build the command line of a process from the argv array.
415 * Note that it does NOT necessarily include the file name.
416 * Sometimes we don't even have any command line options at all.
418 * We must quote and escape characters so that the argv array can be rebuilt
419 * from the command line:
420 * - spaces and tabs must be quoted
421 * 'a b' -> '"a b"'
422 * - quotes must be escaped
423 * '"' -> '\"'
424 * - if '\'s are followed by a '"', they must be doubled and followed by '\"',
425 * resulting in an odd number of '\' followed by a '"'
426 * '\"' -> '\\\"'
427 * '\\"' -> '\\\\\"'
428 * - '\'s that are not followed by a '"' can be left as is
429 * 'a\b' == 'a\b'
430 * 'a\\b' == 'a\\b'
432 static BOOL build_command_line( WCHAR **argv )
434 int len;
435 WCHAR **arg;
436 LPWSTR p;
437 RTL_USER_PROCESS_PARAMETERS* rupp = NtCurrentTeb()->Peb->ProcessParameters;
439 if (rupp->CommandLine.Buffer) return TRUE; /* already got it from the server */
441 len = 0;
442 for (arg = argv; *arg; arg++)
444 int has_space,bcount;
445 WCHAR* a;
447 has_space=0;
448 bcount=0;
449 a=*arg;
450 if( !*a ) has_space=1;
451 while (*a!='\0') {
452 if (*a=='\\') {
453 bcount++;
454 } else {
455 if (*a==' ' || *a=='\t') {
456 has_space=1;
457 } else if (*a=='"') {
458 /* doubling of '\' preceeding a '"',
459 * plus escaping of said '"'
461 len+=2*bcount+1;
463 bcount=0;
465 a++;
467 len+=(a-*arg)+1 /* for the separating space */;
468 if (has_space)
469 len+=2; /* for the quotes */
472 if (!(rupp->CommandLine.Buffer = RtlAllocateHeap( GetProcessHeap(), 0, len * sizeof(WCHAR))))
473 return FALSE;
475 p = rupp->CommandLine.Buffer;
476 rupp->CommandLine.Length = (len - 1) * sizeof(WCHAR);
477 rupp->CommandLine.MaximumLength = len * sizeof(WCHAR);
478 for (arg = argv; *arg; arg++)
480 int has_space,has_quote;
481 WCHAR* a;
483 /* Check for quotes and spaces in this argument */
484 has_space=has_quote=0;
485 a=*arg;
486 if( !*a ) has_space=1;
487 while (*a!='\0') {
488 if (*a==' ' || *a=='\t') {
489 has_space=1;
490 if (has_quote)
491 break;
492 } else if (*a=='"') {
493 has_quote=1;
494 if (has_space)
495 break;
497 a++;
500 /* Now transfer it to the command line */
501 if (has_space)
502 *p++='"';
503 if (has_quote) {
504 int bcount;
505 WCHAR* a;
507 bcount=0;
508 a=*arg;
509 while (*a!='\0') {
510 if (*a=='\\') {
511 *p++=*a;
512 bcount++;
513 } else {
514 if (*a=='"') {
515 int i;
517 /* Double all the '\\' preceeding this '"', plus one */
518 for (i=0;i<=bcount;i++)
519 *p++='\\';
520 *p++='"';
521 } else {
522 *p++=*a;
524 bcount=0;
526 a++;
528 } else {
529 WCHAR* x = *arg;
530 while ((*p=*x++)) p++;
532 if (has_space)
533 *p++='"';
534 *p++=' ';
536 if (p > rupp->CommandLine.Buffer)
537 p--; /* remove last space */
538 *p = '\0';
540 return TRUE;
544 /* make sure the unicode string doesn't point beyond the end pointer */
545 static inline void fix_unicode_string( UNICODE_STRING *str, char *end_ptr )
547 if ((char *)str->Buffer >= end_ptr)
549 str->Length = str->MaximumLength = 0;
550 str->Buffer = NULL;
551 return;
553 if ((char *)str->Buffer + str->MaximumLength > end_ptr)
555 str->MaximumLength = (end_ptr - (char *)str->Buffer) & ~(sizeof(WCHAR) - 1);
557 if (str->Length >= str->MaximumLength)
559 if (str->MaximumLength >= sizeof(WCHAR))
560 str->Length = str->MaximumLength - sizeof(WCHAR);
561 else
562 str->Length = str->MaximumLength = 0;
567 /***********************************************************************
568 * init_user_process_params
570 * Fill the RTL_USER_PROCESS_PARAMETERS structure from the server.
572 static RTL_USER_PROCESS_PARAMETERS *init_user_process_params( size_t info_size )
574 void *ptr;
575 DWORD size;
576 NTSTATUS status;
577 RTL_USER_PROCESS_PARAMETERS *params;
579 size = info_size;
580 if ((status = NtAllocateVirtualMemory( NtCurrentProcess(), &ptr, NULL, &size,
581 MEM_COMMIT, PAGE_READWRITE )) != STATUS_SUCCESS)
582 return NULL;
584 SERVER_START_REQ( get_startup_info )
586 wine_server_set_reply( req, ptr, info_size );
587 wine_server_call( req );
588 info_size = wine_server_reply_size( reply );
590 SERVER_END_REQ;
592 params = ptr;
593 params->Size = info_size;
594 params->AllocationSize = size;
596 /* make sure the strings are valid */
597 fix_unicode_string( &params->CurrentDirectoryName, (char *)info_size );
598 fix_unicode_string( &params->DllPath, (char *)info_size );
599 fix_unicode_string( &params->ImagePathName, (char *)info_size );
600 fix_unicode_string( &params->CommandLine, (char *)info_size );
601 fix_unicode_string( &params->WindowTitle, (char *)info_size );
602 fix_unicode_string( &params->Desktop, (char *)info_size );
603 fix_unicode_string( &params->ShellInfo, (char *)info_size );
604 fix_unicode_string( &params->RuntimeInfo, (char *)info_size );
606 return RtlNormalizeProcessParams( params );
610 /***********************************************************************
611 * process_init
613 * Main process initialisation code
615 static BOOL process_init( char *argv[], char **environ )
617 static const WCHAR kernel32W[] = {'k','e','r','n','e','l','3','2',0};
618 BOOL ret;
619 size_t info_size = 0;
620 RTL_USER_PROCESS_PARAMETERS *params;
621 PEB *peb = NtCurrentTeb()->Peb;
622 HANDLE hstdin, hstdout, hstderr;
623 extern void __wine_dbg_kernel32_init(void);
625 PTHREAD_Init();
627 __wine_dbg_kernel32_init(); /* hack: register debug channels early */
629 setbuf(stdout,NULL);
630 setbuf(stderr,NULL);
631 setlocale(LC_CTYPE,"");
633 /* Retrieve startup info from the server */
634 SERVER_START_REQ( init_process )
636 req->peb = peb;
637 req->ldt_copy = &wine_ldt_copy;
638 if ((ret = !wine_server_call_err( req )))
640 main_exe_file = reply->exe_file;
641 main_create_flags = reply->create_flags;
642 info_size = reply->info_size;
643 server_startticks = reply->server_start;
644 hstdin = reply->hstdin;
645 hstdout = reply->hstdout;
646 hstderr = reply->hstderr;
649 SERVER_END_REQ;
650 if (!ret) return FALSE;
652 if (info_size == 0)
654 params = peb->ProcessParameters;
656 /* This is wine specific: we have no parent (we're started from unix)
657 * so, create a simple console with bare handles to unix stdio
658 * input & output streams (aka simple console)
660 wine_server_fd_to_handle( 0, GENERIC_READ|SYNCHRONIZE, TRUE, &params->hStdInput );
661 wine_server_fd_to_handle( 1, GENERIC_WRITE|SYNCHRONIZE, TRUE, &params->hStdOutput );
662 wine_server_fd_to_handle( 2, GENERIC_WRITE|SYNCHRONIZE, TRUE, &params->hStdError );
664 /* <hack: to be changed later on> */
665 params->CurrentDirectoryName.Length = 3 * sizeof(WCHAR);
666 params->CurrentDirectoryName.MaximumLength = RtlGetLongestNtPathLength() * sizeof(WCHAR);
667 params->CurrentDirectoryName.Buffer = RtlAllocateHeap( GetProcessHeap(), 0, params->CurrentDirectoryName.MaximumLength);
668 params->CurrentDirectoryName.Buffer[0] = 'C';
669 params->CurrentDirectoryName.Buffer[1] = ':';
670 params->CurrentDirectoryName.Buffer[2] = '\\';
671 params->CurrentDirectoryName.Buffer[3] = '\0';
672 /* </hack: to be changed later on> */
674 else
676 if (!(params = init_user_process_params( info_size ))) return FALSE;
677 peb->ProcessParameters = params;
679 /* convert value from server:
680 * + 0 => INVALID_HANDLE_VALUE
681 * + console handle need to be mapped
683 if (!hstdin)
684 hstdin = INVALID_HANDLE_VALUE;
685 else if (VerifyConsoleIoHandle(console_handle_map(hstdin)))
686 hstdin = console_handle_map(hstdin);
688 if (!hstdout)
689 hstdout = INVALID_HANDLE_VALUE;
690 else if (VerifyConsoleIoHandle(console_handle_map(hstdout)))
691 hstdout = console_handle_map(hstdout);
693 if (!hstderr)
694 hstderr = INVALID_HANDLE_VALUE;
695 else if (VerifyConsoleIoHandle(console_handle_map(hstderr)))
696 hstderr = console_handle_map(hstderr);
698 params->hStdInput = hstdin;
699 params->hStdOutput = hstdout;
700 params->hStdError = hstderr;
703 kernel32_handle = GetModuleHandleW(kernel32W);
705 LOCALE_Init();
707 /* Copy the parent environment */
708 if (!build_initial_environment( environ )) return FALSE;
710 /* Parse command line arguments */
711 OPTIONS_ParseOptions( !info_size ? argv : NULL );
713 /* initialise DOS drives */
714 if (!DRIVE_Init()) return FALSE;
716 /* initialise DOS directories */
717 if (!DIR_Init()) return FALSE;
719 /* registry initialisation */
720 SHELL_LoadRegistry();
722 /* global boot finished, the rest is process-local */
723 SERVER_START_REQ( boot_done )
725 req->debug_level = TRACE_ON(server);
726 wine_server_call( req );
728 SERVER_END_REQ;
730 return TRUE;
734 /***********************************************************************
735 * start_process
737 * Startup routine of a new process. Runs on the new process stack.
739 static void start_process( void *arg )
741 __TRY
743 PEB *peb = NtCurrentTeb()->Peb;
744 IMAGE_NT_HEADERS *nt;
745 LPTHREAD_START_ROUTINE entry;
747 LdrInitializeThunk( main_exe_file, 0, 0, 0 );
749 nt = RtlImageNtHeader( peb->ImageBaseAddress );
750 entry = (LPTHREAD_START_ROUTINE)((char *)peb->ImageBaseAddress +
751 nt->OptionalHeader.AddressOfEntryPoint);
753 if (TRACE_ON(relay))
754 DPRINTF( "%04lx:Starting process %s (entryproc=%p)\n", GetCurrentThreadId(),
755 debugstr_w(peb->ProcessParameters->ImagePathName.Buffer), entry );
757 SetLastError( 0 ); /* clear error code */
758 if (peb->BeingDebugged) DbgBreakPoint();
759 ExitProcess( entry( peb ) );
761 __EXCEPT(UnhandledExceptionFilter)
763 TerminateThread( GetCurrentThread(), GetExceptionCode() );
765 __ENDTRY
769 /***********************************************************************
770 * __wine_kernel_init
772 * Wine initialisation: load and start the main exe file.
774 void __wine_kernel_init(void)
776 WCHAR *main_exe_name, *p;
777 char error[1024];
778 DWORD stack_size = 0;
779 int file_exists;
780 PEB *peb = NtCurrentTeb()->Peb;
782 /* Initialize everything */
783 if (!process_init( __wine_main_argv, __wine_main_environ )) exit(1);
784 /* update argc in case options have been removed */
785 for (__wine_main_argc = 0; __wine_main_argv[__wine_main_argc]; __wine_main_argc++) /*nothing*/;
787 __wine_main_argv++; /* remove argv[0] (wine itself) */
788 __wine_main_argc--;
790 if (!(main_exe_name = peb->ProcessParameters->ImagePathName.Buffer))
792 WCHAR buffer[MAX_PATH];
793 WCHAR exe_nameW[MAX_PATH];
795 if (!__wine_main_argv[0]) OPTIONS_Usage();
797 MultiByteToWideChar( CP_UNIXCP, 0, __wine_main_argv[0], -1, exe_nameW, MAX_PATH );
798 if (!find_exe_file( exe_nameW, buffer, MAX_PATH, &main_exe_file ))
800 MESSAGE( "wine: cannot find '%s'\n", __wine_main_argv[0] );
801 ExitProcess(1);
803 if (main_exe_file == INVALID_HANDLE_VALUE)
805 MESSAGE( "wine: cannot open %s\n", debugstr_w(main_exe_name) );
806 ExitProcess(1);
808 RtlCreateUnicodeString( &peb->ProcessParameters->ImagePathName, buffer );
809 main_exe_name = peb->ProcessParameters->ImagePathName.Buffer;
812 TRACE( "starting process name=%s file=%p argv[0]=%s\n",
813 debugstr_w(main_exe_name), main_exe_file, debugstr_a(__wine_main_argv[0]) );
815 MODULE_InitLoadPath();
816 VERSION_Init( main_exe_name );
818 if (!main_exe_file) /* no file handle -> Winelib app */
820 TRACE( "starting Winelib app %s\n", debugstr_w(main_exe_name) );
821 if (open_builtin_exe_file( main_exe_name, error, sizeof(error), 0, &file_exists ))
822 goto found;
823 MESSAGE( "wine: cannot open builtin library for %s: %s\n",
824 debugstr_w(main_exe_name), error );
825 ExitProcess(1);
828 switch( MODULE_GetBinaryType( main_exe_file ))
830 case BINARY_PE_EXE:
831 TRACE( "starting Win32 binary %s\n", debugstr_w(main_exe_name) );
832 if ((peb->ImageBaseAddress = load_pe_exe( main_exe_name, main_exe_file )))
833 goto found;
834 MESSAGE( "wine: could not load %s as Win32 binary\n", debugstr_w(main_exe_name) );
835 ExitProcess(1);
836 case BINARY_PE_DLL:
837 MESSAGE( "wine: %s is a DLL, not an executable\n", debugstr_w(main_exe_name) );
838 ExitProcess(1);
839 case BINARY_UNKNOWN:
840 /* check for .com extension */
841 if (!(p = strrchrW( main_exe_name, '.' )) || strcmpiW( p, comW ))
843 MESSAGE( "wine: cannot determine executable type for %s\n",
844 debugstr_w(main_exe_name) );
845 ExitProcess(1);
847 /* fall through */
848 case BINARY_WIN16:
849 case BINARY_DOS:
850 TRACE( "starting Win16/DOS binary %s\n", debugstr_w(main_exe_name) );
851 CloseHandle( main_exe_file );
852 main_exe_file = 0;
853 __wine_main_argv--;
854 __wine_main_argc++;
855 __wine_main_argv[0] = "winevdm.exe";
856 if (open_builtin_exe_file( winevdmW, error, sizeof(error), 0, &file_exists ))
857 goto found;
858 MESSAGE( "wine: trying to run %s, cannot open builtin library for 'winevdm.exe': %s\n",
859 debugstr_w(main_exe_name), error );
860 ExitProcess(1);
861 case BINARY_OS216:
862 MESSAGE( "wine: %s is an OS/2 binary, not supported\n", debugstr_w(main_exe_name) );
863 ExitProcess(1);
864 case BINARY_UNIX_EXE:
865 MESSAGE( "wine: %s is a Unix binary, not supported\n", debugstr_w(main_exe_name) );
866 ExitProcess(1);
867 case BINARY_UNIX_LIB:
869 DOS_FULL_NAME full_name;
871 TRACE( "starting Winelib app %s\n", debugstr_w(main_exe_name) );
872 CloseHandle( main_exe_file );
873 main_exe_file = 0;
874 if (DOSFS_GetFullName( main_exe_name, TRUE, &full_name ) &&
875 wine_dlopen( full_name.long_name, RTLD_NOW, error, sizeof(error) ))
877 static const WCHAR soW[] = {'.','s','o',0};
878 if ((p = strrchrW( main_exe_name, '.' )) && !strcmpW( p, soW ))
880 *p = 0;
881 /* update the unicode string */
882 RtlInitUnicodeString( &peb->ProcessParameters->ImagePathName, main_exe_name );
884 goto found;
886 MESSAGE( "wine: could not load %s: %s\n", debugstr_w(main_exe_name), error );
887 ExitProcess(1);
891 found:
892 wine_free_pe_load_area(); /* the main binary is loaded, we don't need this anymore */
894 /* build command line */
895 set_library_wargv( __wine_main_argv );
896 if (!build_command_line( __wine_main_wargv )) goto error;
898 stack_size = RtlImageNtHeader(peb->ImageBaseAddress)->OptionalHeader.SizeOfStackReserve;
900 /* allocate main thread stack */
901 if (!THREAD_InitStack( NtCurrentTeb(), stack_size )) goto error;
903 /* switch to the new stack */
904 wine_switch_to_stack( start_process, NULL, NtCurrentTeb()->Tib.StackBase );
906 error:
907 ExitProcess( GetLastError() );
911 /***********************************************************************
912 * build_argv
914 * Build an argv array from a command-line.
915 * 'reserved' is the number of args to reserve before the first one.
917 static char **build_argv( const WCHAR *cmdlineW, int reserved )
919 int argc;
920 char** argv;
921 char *arg,*s,*d,*cmdline;
922 int in_quotes,bcount,len;
924 len = WideCharToMultiByte( CP_UNIXCP, 0, cmdlineW, -1, NULL, 0, NULL, NULL );
925 if (!(cmdline = malloc(len))) return NULL;
926 WideCharToMultiByte( CP_UNIXCP, 0, cmdlineW, -1, cmdline, len, NULL, NULL );
928 argc=reserved+1;
929 bcount=0;
930 in_quotes=0;
931 s=cmdline;
932 while (1) {
933 if (*s=='\0' || ((*s==' ' || *s=='\t') && !in_quotes)) {
934 /* space */
935 argc++;
936 /* skip the remaining spaces */
937 while (*s==' ' || *s=='\t') {
938 s++;
940 if (*s=='\0')
941 break;
942 bcount=0;
943 continue;
944 } else if (*s=='\\') {
945 /* '\', count them */
946 bcount++;
947 } else if ((*s=='"') && ((bcount & 1)==0)) {
948 /* unescaped '"' */
949 in_quotes=!in_quotes;
950 bcount=0;
951 } else {
952 /* a regular character */
953 bcount=0;
955 s++;
957 argv=malloc(argc*sizeof(*argv));
958 if (!argv)
959 return NULL;
961 arg=d=s=cmdline;
962 bcount=0;
963 in_quotes=0;
964 argc=reserved;
965 while (*s) {
966 if ((*s==' ' || *s=='\t') && !in_quotes) {
967 /* Close the argument and copy it */
968 *d=0;
969 argv[argc++]=arg;
971 /* skip the remaining spaces */
972 do {
973 s++;
974 } while (*s==' ' || *s=='\t');
976 /* Start with a new argument */
977 arg=d=s;
978 bcount=0;
979 } else if (*s=='\\') {
980 /* '\\' */
981 *d++=*s++;
982 bcount++;
983 } else if (*s=='"') {
984 /* '"' */
985 if ((bcount & 1)==0) {
986 /* Preceeded by an even number of '\', this is half that
987 * number of '\', plus a '"' which we discard.
989 d-=bcount/2;
990 s++;
991 in_quotes=!in_quotes;
992 } else {
993 /* Preceeded by an odd number of '\', this is half that
994 * number of '\' followed by a '"'
996 d=d-bcount/2-1;
997 *d++='"';
998 s++;
1000 bcount=0;
1001 } else {
1002 /* a regular character */
1003 *d++=*s++;
1004 bcount=0;
1007 if (*arg) {
1008 *d='\0';
1009 argv[argc++]=arg;
1011 argv[argc]=NULL;
1013 return argv;
1017 /***********************************************************************
1018 * alloc_env_string
1020 * Allocate an environment string; helper for build_envp
1022 static char *alloc_env_string( const char *name, const char *value )
1024 char *ret = malloc( strlen(name) + strlen(value) + 1 );
1025 strcpy( ret, name );
1026 strcat( ret, value );
1027 return ret;
1030 /***********************************************************************
1031 * build_envp
1033 * Build the environment of a new child process.
1035 static char **build_envp( const WCHAR *envW, const WCHAR *extra_envW )
1037 const WCHAR *p;
1038 char **envp;
1039 char *env, *extra_env = NULL;
1040 int count = 0, length;
1042 if (extra_envW)
1044 for (p = extra_envW; *p; count++) p += strlenW(p) + 1;
1045 p++;
1046 length = WideCharToMultiByte( CP_UNIXCP, 0, extra_envW, p - extra_envW,
1047 NULL, 0, NULL, NULL );
1048 if ((extra_env = malloc( length )))
1049 WideCharToMultiByte( CP_UNIXCP, 0, extra_envW, p - extra_envW,
1050 extra_env, length, NULL, NULL );
1052 for (p = envW; *p; count++) p += strlenW(p) + 1;
1053 p++;
1054 length = WideCharToMultiByte( CP_UNIXCP, 0, envW, p - envW, NULL, 0, NULL, NULL );
1055 if (!(env = malloc( length ))) return NULL;
1056 WideCharToMultiByte( CP_UNIXCP, 0, envW, p - envW, env, length, NULL, NULL );
1058 count += 4;
1060 if ((envp = malloc( count * sizeof(*envp) )))
1062 char **envptr = envp;
1063 char *p;
1065 /* first the extra strings */
1066 if (extra_env) for (p = extra_env; *p; p += strlen(p) + 1) *envptr++ = p;
1067 /* then put PATH, HOME and WINEPREFIX from the unix env */
1068 if ((p = getenv("PATH"))) *envptr++ = alloc_env_string( "PATH=", p );
1069 if ((p = getenv("HOME"))) *envptr++ = alloc_env_string( "HOME=", p );
1070 if ((p = getenv("WINEPREFIX"))) *envptr++ = alloc_env_string( "WINEPREFIX=", p );
1071 /* now put the Windows environment strings */
1072 for (p = env; *p; p += strlen(p) + 1)
1074 if (extra_env && p[0]=='=' && 'A'<=p[1] && p[1]<='Z' && p[2]==':' && p[3]=='=')
1075 continue; /* skipped */
1076 if (!memcmp( p, "PATH=", 5 )) /* store PATH as WINEPATH */
1077 *envptr++ = alloc_env_string( "WINEPATH=", p + 5 );
1078 else if (memcmp( p, "HOME=", 5 ) &&
1079 memcmp( p, "WINEPATH=", 9 ) &&
1080 memcmp( p, "WINEPREFIX=", 11 )) *envptr++ = p;
1082 *envptr = 0;
1084 return envp;
1088 /***********************************************************************
1089 * fork_and_exec
1091 * Fork and exec a new Unix binary, checking for errors.
1093 static int fork_and_exec( const char *filename, const WCHAR *cmdline,
1094 const WCHAR *env, const char *newdir )
1096 int fd[2];
1097 int pid, err;
1099 if (!env) env = GetEnvironmentStringsW();
1101 if (pipe(fd) == -1)
1103 FILE_SetDosError();
1104 return -1;
1106 fcntl( fd[1], F_SETFD, 1 ); /* set close on exec */
1107 if (!(pid = fork())) /* child */
1109 char **argv = build_argv( cmdline, 0 );
1110 char **envp = build_envp( env, NULL );
1111 close( fd[0] );
1113 /* Reset signals that we previously set to SIG_IGN */
1114 signal( SIGPIPE, SIG_DFL );
1115 signal( SIGCHLD, SIG_DFL );
1117 if (newdir) chdir(newdir);
1119 if (argv && envp) execve( filename, argv, envp );
1120 err = errno;
1121 write( fd[1], &err, sizeof(err) );
1122 _exit(1);
1124 close( fd[1] );
1125 if ((pid != -1) && (read( fd[0], &err, sizeof(err) ) > 0)) /* exec failed */
1127 errno = err;
1128 pid = -1;
1130 if (pid == -1) FILE_SetDosError();
1131 close( fd[0] );
1132 return pid;
1136 /***********************************************************************
1137 * create_user_params
1139 static RTL_USER_PROCESS_PARAMETERS *create_user_params( LPCWSTR filename, LPCWSTR cmdline,
1140 const STARTUPINFOW *startup )
1142 RTL_USER_PROCESS_PARAMETERS *params;
1143 UNICODE_STRING image_str, cmdline_str, desktop, title;
1144 NTSTATUS status;
1145 WCHAR buffer[MAX_PATH];
1147 if(!GetLongPathNameW( filename, buffer, MAX_PATH ))
1148 lstrcpynW( buffer, filename, MAX_PATH );
1149 if(!GetFullPathNameW( buffer, MAX_PATH, buffer, NULL ))
1150 lstrcpynW( buffer, filename, MAX_PATH );
1151 RtlInitUnicodeString( &image_str, buffer );
1153 RtlInitUnicodeString( &cmdline_str, cmdline );
1154 if (startup->lpDesktop) RtlInitUnicodeString( &desktop, startup->lpDesktop );
1155 if (startup->lpTitle) RtlInitUnicodeString( &title, startup->lpTitle );
1157 status = RtlCreateProcessParameters( &params, &image_str, NULL, NULL, &cmdline_str, NULL,
1158 startup->lpTitle ? &title : NULL,
1159 startup->lpDesktop ? &desktop : NULL,
1160 NULL, NULL );
1161 if (status != STATUS_SUCCESS)
1163 SetLastError( RtlNtStatusToDosError(status) );
1164 return NULL;
1167 params->Environment = NULL; /* we pass it through the Unix environment */
1168 params->hStdInput = startup->hStdInput;
1169 params->hStdOutput = startup->hStdOutput;
1170 params->hStdError = startup->hStdError;
1171 params->dwX = startup->dwX;
1172 params->dwY = startup->dwY;
1173 params->dwXSize = startup->dwXSize;
1174 params->dwYSize = startup->dwYSize;
1175 params->dwXCountChars = startup->dwXCountChars;
1176 params->dwYCountChars = startup->dwYCountChars;
1177 params->dwFillAttribute = startup->dwFillAttribute;
1178 params->dwFlags = startup->dwFlags;
1179 params->wShowWindow = startup->wShowWindow;
1180 return params;
1184 /***********************************************************************
1185 * create_process
1187 * Create a new process. If hFile is a valid handle we have an exe
1188 * file, otherwise it is a Winelib app.
1190 static BOOL create_process( HANDLE hFile, LPCWSTR filename, LPWSTR cmd_line, LPWSTR env,
1191 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1192 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
1193 LPPROCESS_INFORMATION info, LPCSTR unixdir )
1195 BOOL ret, success = FALSE;
1196 HANDLE process_info;
1197 RTL_USER_PROCESS_PARAMETERS *params;
1198 WCHAR *extra_env = NULL;
1199 int startfd[2];
1200 int execfd[2];
1201 pid_t pid;
1202 int err;
1203 char dummy = 0;
1205 if (!env)
1207 env = GetEnvironmentStringsW();
1208 extra_env = DRIVE_BuildEnv();
1211 if (!(params = create_user_params( filename, cmd_line, startup )))
1213 if (extra_env) HeapFree( GetProcessHeap(), 0, extra_env );
1214 return FALSE;
1217 /* create the synchronization pipes */
1219 if (pipe( startfd ) == -1)
1221 FILE_SetDosError();
1222 RtlDestroyProcessParameters( params );
1223 if (extra_env) HeapFree( GetProcessHeap(), 0, extra_env );
1224 return FALSE;
1226 if (pipe( execfd ) == -1)
1228 FILE_SetDosError();
1229 close( startfd[0] );
1230 close( startfd[1] );
1231 RtlDestroyProcessParameters( params );
1232 if (extra_env) HeapFree( GetProcessHeap(), 0, extra_env );
1233 return FALSE;
1235 fcntl( execfd[1], F_SETFD, 1 ); /* set close on exec */
1237 /* create the child process */
1239 if (!(pid = fork())) /* child */
1241 char **argv = build_argv( cmd_line, 1 );
1242 char **envp = build_envp( env, extra_env );
1244 close( startfd[1] );
1245 close( execfd[0] );
1247 /* wait for parent to tell us to start */
1248 if (read( startfd[0], &dummy, 1 ) != 1) _exit(1);
1250 close( startfd[0] );
1251 /* Reset signals that we previously set to SIG_IGN */
1252 signal( SIGPIPE, SIG_DFL );
1253 signal( SIGCHLD, SIG_DFL );
1255 if (unixdir) chdir(unixdir);
1257 if (argv && envp)
1259 /* first, try for a WINELOADER environment variable */
1260 argv[0] = getenv("WINELOADER");
1261 if (argv[0]) execve( argv[0], argv, envp );
1262 /* now use the standard search strategy */
1263 wine_exec_wine_binary( NULL, argv, envp );
1265 err = errno;
1266 write( execfd[1], &err, sizeof(err) );
1267 _exit(1);
1270 /* this is the parent */
1272 close( startfd[0] );
1273 close( execfd[1] );
1274 if (extra_env) HeapFree( GetProcessHeap(), 0, extra_env );
1275 if (pid == -1)
1277 close( startfd[1] );
1278 close( execfd[0] );
1279 FILE_SetDosError();
1280 RtlDestroyProcessParameters( params );
1281 return FALSE;
1284 /* create the process on the server side */
1286 SERVER_START_REQ( new_process )
1288 req->inherit_all = inherit;
1289 req->create_flags = flags;
1290 req->unix_pid = pid;
1291 req->exe_file = hFile;
1292 if (startup->dwFlags & STARTF_USESTDHANDLES)
1294 req->hstdin = startup->hStdInput;
1295 req->hstdout = startup->hStdOutput;
1296 req->hstderr = startup->hStdError;
1298 else
1300 req->hstdin = GetStdHandle( STD_INPUT_HANDLE );
1301 req->hstdout = GetStdHandle( STD_OUTPUT_HANDLE );
1302 req->hstderr = GetStdHandle( STD_ERROR_HANDLE );
1305 if ((flags & (CREATE_NEW_CONSOLE | DETACHED_PROCESS)) != 0)
1307 /* this is temporary (for console handles). We have no way to control that the handle is invalid in child process otherwise */
1308 if (is_console_handle(req->hstdin)) req->hstdin = INVALID_HANDLE_VALUE;
1309 if (is_console_handle(req->hstdout)) req->hstdout = INVALID_HANDLE_VALUE;
1310 if (is_console_handle(req->hstderr)) req->hstderr = INVALID_HANDLE_VALUE;
1312 else
1314 if (is_console_handle(req->hstdin)) req->hstdin = console_handle_unmap(req->hstdin);
1315 if (is_console_handle(req->hstdout)) req->hstdout = console_handle_unmap(req->hstdout);
1316 if (is_console_handle(req->hstderr)) req->hstderr = console_handle_unmap(req->hstderr);
1319 wine_server_add_data( req, params, params->Size );
1320 ret = !wine_server_call_err( req );
1321 process_info = reply->info;
1323 SERVER_END_REQ;
1325 RtlDestroyProcessParameters( params );
1326 if (!ret)
1328 close( startfd[1] );
1329 close( execfd[0] );
1330 return FALSE;
1333 /* tell child to start and wait for it to exec */
1335 write( startfd[1], &dummy, 1 );
1336 close( startfd[1] );
1338 if (read( execfd[0], &err, sizeof(err) ) > 0) /* exec failed */
1340 errno = err;
1341 FILE_SetDosError();
1342 close( execfd[0] );
1343 CloseHandle( process_info );
1344 return FALSE;
1346 close( execfd[0] );
1348 /* wait for the new process info to be ready */
1350 WaitForSingleObject( process_info, INFINITE );
1351 SERVER_START_REQ( get_new_process_info )
1353 req->info = process_info;
1354 req->pinherit = (psa && (psa->nLength >= sizeof(*psa)) && psa->bInheritHandle);
1355 req->tinherit = (tsa && (tsa->nLength >= sizeof(*tsa)) && tsa->bInheritHandle);
1356 if ((ret = !wine_server_call_err( req )))
1358 info->dwProcessId = (DWORD)reply->pid;
1359 info->dwThreadId = (DWORD)reply->tid;
1360 info->hProcess = reply->phandle;
1361 info->hThread = reply->thandle;
1362 success = reply->success;
1365 SERVER_END_REQ;
1367 if (ret && !success) /* new process failed to start */
1369 DWORD exitcode;
1370 if (GetExitCodeProcess( info->hProcess, &exitcode )) SetLastError( exitcode );
1371 CloseHandle( info->hThread );
1372 CloseHandle( info->hProcess );
1373 ret = FALSE;
1375 CloseHandle( process_info );
1376 return ret;
1380 /***********************************************************************
1381 * create_vdm_process
1383 * Create a new VDM process for a 16-bit or DOS application.
1385 static BOOL create_vdm_process( LPCWSTR filename, LPWSTR cmd_line, LPWSTR env,
1386 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1387 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
1388 LPPROCESS_INFORMATION info, LPCSTR unixdir )
1390 static const WCHAR argsW[] = {'%','s',' ','-','-','a','p','p','-','n','a','m','e',' ','"','%','s','"',' ','%','s',0};
1392 BOOL ret;
1393 LPWSTR new_cmd_line = HeapAlloc( GetProcessHeap(), 0,
1394 (strlenW(filename) + strlenW(cmd_line) + 30) * sizeof(WCHAR) );
1396 if (!new_cmd_line)
1398 SetLastError( ERROR_OUTOFMEMORY );
1399 return FALSE;
1401 sprintfW( new_cmd_line, argsW, winevdmW, filename, cmd_line );
1402 ret = create_process( 0, winevdmW, new_cmd_line, env, psa, tsa, inherit,
1403 flags, startup, info, unixdir );
1404 HeapFree( GetProcessHeap(), 0, new_cmd_line );
1405 return ret;
1409 /***********************************************************************
1410 * create_cmd_process
1412 * Create a new cmd shell process for a .BAT file.
1414 static BOOL create_cmd_process( LPCWSTR filename, LPWSTR cmd_line, LPVOID env,
1415 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1416 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
1417 LPPROCESS_INFORMATION info, LPCWSTR cur_dir )
1420 static const WCHAR comspecW[] = {'C','O','M','S','P','E','C',0};
1421 static const WCHAR slashcW[] = {' ','/','c',' ',0};
1422 WCHAR comspec[MAX_PATH];
1423 WCHAR *newcmdline;
1424 BOOL ret;
1426 if (!GetEnvironmentVariableW( comspecW, comspec, sizeof(comspec)/sizeof(WCHAR) ))
1427 return FALSE;
1428 if (!(newcmdline = HeapAlloc( GetProcessHeap(), 0,
1429 (strlenW(comspec) + 4 + strlenW(cmd_line) + 1) * sizeof(WCHAR))))
1430 return FALSE;
1432 strcpyW( newcmdline, comspec );
1433 strcatW( newcmdline, slashcW );
1434 strcatW( newcmdline, cmd_line );
1435 ret = CreateProcessW( comspec, newcmdline, psa, tsa, inherit,
1436 flags, env, cur_dir, startup, info );
1437 HeapFree( GetProcessHeap(), 0, newcmdline );
1438 return ret;
1442 /*************************************************************************
1443 * get_file_name
1445 * Helper for CreateProcess: retrieve the file name to load from the
1446 * app name and command line. Store the file name in buffer, and
1447 * return a possibly modified command line.
1448 * Also returns a handle to the opened file if it's a Windows binary.
1450 static LPWSTR get_file_name( LPCWSTR appname, LPWSTR cmdline, LPWSTR buffer,
1451 int buflen, HANDLE *handle )
1453 static const WCHAR quotesW[] = {'"','%','s','"',0};
1455 WCHAR *name, *pos, *ret = NULL;
1456 const WCHAR *p;
1458 /* if we have an app name, everything is easy */
1460 if (appname)
1462 /* use the unmodified app name as file name */
1463 lstrcpynW( buffer, appname, buflen );
1464 *handle = open_exe_file( buffer );
1465 if (!(ret = cmdline) || !cmdline[0])
1467 /* no command-line, create one */
1468 if ((ret = HeapAlloc( GetProcessHeap(), 0, (strlenW(appname) + 3) * sizeof(WCHAR) )))
1469 sprintfW( ret, quotesW, appname );
1471 return ret;
1474 if (!cmdline)
1476 SetLastError( ERROR_INVALID_PARAMETER );
1477 return NULL;
1480 /* first check for a quoted file name */
1482 if ((cmdline[0] == '"') && ((p = strchrW( cmdline + 1, '"' ))))
1484 int len = p - cmdline - 1;
1485 /* extract the quoted portion as file name */
1486 if (!(name = HeapAlloc( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) ))) return NULL;
1487 memcpy( name, cmdline + 1, len * sizeof(WCHAR) );
1488 name[len] = 0;
1490 if (find_exe_file( name, buffer, buflen, handle ))
1491 ret = cmdline; /* no change necessary */
1492 goto done;
1495 /* now try the command-line word by word */
1497 if (!(name = HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline) + 1) * sizeof(WCHAR) )))
1498 return NULL;
1499 pos = name;
1500 p = cmdline;
1502 while (*p)
1504 do *pos++ = *p++; while (*p && *p != ' ');
1505 *pos = 0;
1506 if (find_exe_file( name, buffer, buflen, handle ))
1508 ret = cmdline;
1509 break;
1513 if (!ret || !strchrW( name, ' ' )) goto done; /* no change necessary */
1515 /* now build a new command-line with quotes */
1517 if (!(ret = HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline) + 3) * sizeof(WCHAR) )))
1518 goto done;
1519 sprintfW( ret, quotesW, name );
1520 strcatW( ret, p );
1522 done:
1523 HeapFree( GetProcessHeap(), 0, name );
1524 return ret;
1528 /**********************************************************************
1529 * CreateProcessA (KERNEL32.@)
1531 BOOL WINAPI CreateProcessA( LPCSTR app_name, LPSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
1532 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit,
1533 DWORD flags, LPVOID env, LPCSTR cur_dir,
1534 LPSTARTUPINFOA startup_info, LPPROCESS_INFORMATION info )
1536 BOOL ret;
1537 UNICODE_STRING app_nameW, cmd_lineW, cur_dirW, desktopW, titleW;
1538 STARTUPINFOW infoW;
1540 if (app_name) RtlCreateUnicodeStringFromAsciiz( &app_nameW, app_name );
1541 else app_nameW.Buffer = NULL;
1542 if (cmd_line) RtlCreateUnicodeStringFromAsciiz( &cmd_lineW, cmd_line );
1543 else cmd_lineW.Buffer = NULL;
1544 if (cur_dir) RtlCreateUnicodeStringFromAsciiz( &cur_dirW, cur_dir );
1545 else cur_dirW.Buffer = NULL;
1546 if (startup_info->lpDesktop) RtlCreateUnicodeStringFromAsciiz( &desktopW, startup_info->lpDesktop );
1547 else desktopW.Buffer = NULL;
1548 if (startup_info->lpTitle) RtlCreateUnicodeStringFromAsciiz( &titleW, startup_info->lpTitle );
1549 else titleW.Buffer = NULL;
1551 memcpy( &infoW, startup_info, sizeof(infoW) );
1552 infoW.lpDesktop = desktopW.Buffer;
1553 infoW.lpTitle = titleW.Buffer;
1555 if (startup_info->lpReserved)
1556 FIXME("StartupInfo.lpReserved is used, please report (%s)\n",
1557 debugstr_a(startup_info->lpReserved));
1559 ret = CreateProcessW( app_nameW.Buffer, cmd_lineW.Buffer, process_attr, thread_attr,
1560 inherit, flags, env, cur_dirW.Buffer, &infoW, info );
1562 RtlFreeUnicodeString( &app_nameW );
1563 RtlFreeUnicodeString( &cmd_lineW );
1564 RtlFreeUnicodeString( &cur_dirW );
1565 RtlFreeUnicodeString( &desktopW );
1566 RtlFreeUnicodeString( &titleW );
1567 return ret;
1571 /**********************************************************************
1572 * CreateProcessW (KERNEL32.@)
1574 BOOL WINAPI CreateProcessW( LPCWSTR app_name, LPWSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
1575 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit, DWORD flags,
1576 LPVOID env, LPCWSTR cur_dir, LPSTARTUPINFOW startup_info,
1577 LPPROCESS_INFORMATION info )
1579 BOOL retv = FALSE;
1580 HANDLE hFile = 0;
1581 const char *unixdir = NULL;
1582 DOS_FULL_NAME full_dir;
1583 WCHAR name[MAX_PATH];
1584 WCHAR *tidy_cmdline, *p, *envW = env;
1586 /* Process the AppName and/or CmdLine to get module name and path */
1588 TRACE("app %s cmdline %s\n", debugstr_w(app_name), debugstr_w(cmd_line) );
1590 if (!(tidy_cmdline = get_file_name( app_name, cmd_line, name, sizeof(name), &hFile )))
1591 return FALSE;
1592 if (hFile == INVALID_HANDLE_VALUE) goto done;
1594 /* Warn if unsupported features are used */
1596 if (flags & (IDLE_PRIORITY_CLASS | HIGH_PRIORITY_CLASS | REALTIME_PRIORITY_CLASS |
1597 CREATE_NEW_PROCESS_GROUP | CREATE_SEPARATE_WOW_VDM | CREATE_SHARED_WOW_VDM |
1598 CREATE_DEFAULT_ERROR_MODE | CREATE_NO_WINDOW |
1599 PROFILE_USER | PROFILE_KERNEL | PROFILE_SERVER))
1600 WARN("(%s,...): ignoring some flags in %lx\n", debugstr_w(name), flags);
1602 if (cur_dir)
1604 if (DOSFS_GetFullName( cur_dir, TRUE, &full_dir )) unixdir = full_dir.long_name;
1606 else
1608 WCHAR buf[MAX_PATH];
1609 if (GetCurrentDirectoryW(MAX_PATH, buf))
1611 if (DOSFS_GetFullName( buf, TRUE, &full_dir )) unixdir = full_dir.long_name;
1615 if (env && !(flags & CREATE_UNICODE_ENVIRONMENT)) /* convert environment to unicode */
1617 char *p = env;
1618 DWORD lenW;
1620 while (*p) p += strlen(p) + 1;
1621 p++; /* final null */
1622 lenW = MultiByteToWideChar( CP_ACP, 0, env, p - (char*)env, NULL, 0 );
1623 envW = HeapAlloc( GetProcessHeap(), 0, lenW * sizeof(WCHAR) );
1624 MultiByteToWideChar( CP_ACP, 0, env, p - (char*)env, envW, lenW );
1625 flags |= CREATE_UNICODE_ENVIRONMENT;
1628 info->hThread = info->hProcess = 0;
1629 info->dwProcessId = info->dwThreadId = 0;
1631 /* Determine executable type */
1633 if (!hFile) /* builtin exe */
1635 TRACE( "starting %s as Winelib app\n", debugstr_w(name) );
1636 retv = create_process( 0, name, tidy_cmdline, envW, process_attr, thread_attr,
1637 inherit, flags, startup_info, info, unixdir );
1638 goto done;
1641 switch( MODULE_GetBinaryType( hFile ))
1643 case BINARY_PE_EXE:
1644 TRACE( "starting %s as Win32 binary\n", debugstr_w(name) );
1645 retv = create_process( hFile, name, tidy_cmdline, envW, process_attr, thread_attr,
1646 inherit, flags, startup_info, info, unixdir );
1647 break;
1648 case BINARY_WIN16:
1649 case BINARY_DOS:
1650 TRACE( "starting %s as Win16/DOS binary\n", debugstr_w(name) );
1651 retv = create_vdm_process( name, tidy_cmdline, envW, process_attr, thread_attr,
1652 inherit, flags, startup_info, info, unixdir );
1653 break;
1654 case BINARY_OS216:
1655 FIXME( "%s is OS/2 binary, not supported\n", debugstr_w(name) );
1656 SetLastError( ERROR_BAD_EXE_FORMAT );
1657 break;
1658 case BINARY_PE_DLL:
1659 TRACE( "not starting %s since it is a dll\n", debugstr_w(name) );
1660 SetLastError( ERROR_BAD_EXE_FORMAT );
1661 break;
1662 case BINARY_UNIX_LIB:
1663 TRACE( "%s is a Unix library, starting as Winelib app\n", debugstr_w(name) );
1664 retv = create_process( hFile, name, tidy_cmdline, envW, process_attr, thread_attr,
1665 inherit, flags, startup_info, info, unixdir );
1666 break;
1667 case BINARY_UNKNOWN:
1668 /* check for .com or .bat extension */
1669 if ((p = strrchrW( name, '.' )))
1671 if (!strcmpiW( p, comW ))
1673 TRACE( "starting %s as DOS binary\n", debugstr_w(name) );
1674 retv = create_vdm_process( name, tidy_cmdline, envW, process_attr, thread_attr,
1675 inherit, flags, startup_info, info, unixdir );
1676 break;
1678 if (!strcmpiW( p, batW ))
1680 TRACE( "starting %s as batch binary\n", debugstr_w(name) );
1681 retv = create_cmd_process( name, tidy_cmdline, envW, process_attr, thread_attr,
1682 inherit, flags, startup_info, info, cur_dir );
1683 break;
1686 /* fall through */
1687 case BINARY_UNIX_EXE:
1689 /* unknown file, try as unix executable */
1690 DOS_FULL_NAME full_name;
1692 TRACE( "starting %s as Unix binary\n", debugstr_w(name) );
1694 if (DOSFS_GetFullName( name, TRUE, &full_name ))
1695 retv = (fork_and_exec( full_name.long_name, tidy_cmdline, envW, unixdir ) != -1);
1697 break;
1699 CloseHandle( hFile );
1701 done:
1702 if (tidy_cmdline != cmd_line) HeapFree( GetProcessHeap(), 0, tidy_cmdline );
1703 if (envW != env) HeapFree( GetProcessHeap(), 0, envW );
1704 return retv;
1708 /***********************************************************************
1709 * wait_input_idle
1711 * Wrapper to call WaitForInputIdle USER function
1713 typedef DWORD (WINAPI *WaitForInputIdle_ptr)( HANDLE hProcess, DWORD dwTimeOut );
1715 static DWORD wait_input_idle( HANDLE process, DWORD timeout )
1717 HMODULE mod = GetModuleHandleA( "user32.dll" );
1718 if (mod)
1720 WaitForInputIdle_ptr ptr = (WaitForInputIdle_ptr)GetProcAddress( mod, "WaitForInputIdle" );
1721 if (ptr) return ptr( process, timeout );
1723 return 0;
1727 /***********************************************************************
1728 * WinExec (KERNEL32.@)
1730 UINT WINAPI WinExec( LPCSTR lpCmdLine, UINT nCmdShow )
1732 PROCESS_INFORMATION info;
1733 STARTUPINFOA startup;
1734 char *cmdline;
1735 UINT ret;
1737 memset( &startup, 0, sizeof(startup) );
1738 startup.cb = sizeof(startup);
1739 startup.dwFlags = STARTF_USESHOWWINDOW;
1740 startup.wShowWindow = nCmdShow;
1742 /* cmdline needs to be writeable for CreateProcess */
1743 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(lpCmdLine)+1 ))) return 0;
1744 strcpy( cmdline, lpCmdLine );
1746 if (CreateProcessA( NULL, cmdline, NULL, NULL, FALSE,
1747 0, NULL, NULL, &startup, &info ))
1749 /* Give 30 seconds to the app to come up */
1750 if (wait_input_idle( info.hProcess, 30000 ) == WAIT_FAILED)
1751 WARN("WaitForInputIdle failed: Error %ld\n", GetLastError() );
1752 ret = 33;
1753 /* Close off the handles */
1754 CloseHandle( info.hThread );
1755 CloseHandle( info.hProcess );
1757 else if ((ret = GetLastError()) >= 32)
1759 FIXME("Strange error set by CreateProcess: %d\n", ret );
1760 ret = 11;
1762 HeapFree( GetProcessHeap(), 0, cmdline );
1763 return ret;
1767 /**********************************************************************
1768 * LoadModule (KERNEL32.@)
1770 HINSTANCE WINAPI LoadModule( LPCSTR name, LPVOID paramBlock )
1772 LOADPARMS32 *params = paramBlock;
1773 PROCESS_INFORMATION info;
1774 STARTUPINFOA startup;
1775 HINSTANCE hInstance;
1776 LPSTR cmdline, p;
1777 char filename[MAX_PATH];
1778 BYTE len;
1780 if (!name) return (HINSTANCE)ERROR_FILE_NOT_FOUND;
1782 if (!SearchPathA( NULL, name, ".exe", sizeof(filename), filename, NULL ) &&
1783 !SearchPathA( NULL, name, NULL, sizeof(filename), filename, NULL ))
1784 return (HINSTANCE)GetLastError();
1786 len = (BYTE)params->lpCmdLine[0];
1787 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(filename) + len + 2 )))
1788 return (HINSTANCE)ERROR_NOT_ENOUGH_MEMORY;
1790 strcpy( cmdline, filename );
1791 p = cmdline + strlen(cmdline);
1792 *p++ = ' ';
1793 memcpy( p, params->lpCmdLine + 1, len );
1794 p[len] = 0;
1796 memset( &startup, 0, sizeof(startup) );
1797 startup.cb = sizeof(startup);
1798 if (params->lpCmdShow)
1800 startup.dwFlags = STARTF_USESHOWWINDOW;
1801 startup.wShowWindow = ((WORD *)params->lpCmdShow)[1];
1804 if (CreateProcessA( filename, cmdline, NULL, NULL, FALSE, 0,
1805 params->lpEnvAddress, NULL, &startup, &info ))
1807 /* Give 30 seconds to the app to come up */
1808 if (wait_input_idle( info.hProcess, 30000 ) == WAIT_FAILED)
1809 WARN("WaitForInputIdle failed: Error %ld\n", GetLastError() );
1810 hInstance = (HINSTANCE)33;
1811 /* Close off the handles */
1812 CloseHandle( info.hThread );
1813 CloseHandle( info.hProcess );
1815 else if ((hInstance = (HINSTANCE)GetLastError()) >= (HINSTANCE)32)
1817 FIXME("Strange error set by CreateProcess: %p\n", hInstance );
1818 hInstance = (HINSTANCE)11;
1821 HeapFree( GetProcessHeap(), 0, cmdline );
1822 return hInstance;
1826 /******************************************************************************
1827 * TerminateProcess (KERNEL32.@)
1829 BOOL WINAPI TerminateProcess( HANDLE handle, DWORD exit_code )
1831 NTSTATUS status = NtTerminateProcess( handle, exit_code );
1832 if (status) SetLastError( RtlNtStatusToDosError(status) );
1833 return !status;
1837 /***********************************************************************
1838 * ExitProcess (KERNEL32.@)
1840 void WINAPI ExitProcess( DWORD status )
1842 LdrShutdownProcess();
1843 SERVER_START_REQ( terminate_process )
1845 /* send the exit code to the server */
1846 req->handle = GetCurrentProcess();
1847 req->exit_code = status;
1848 wine_server_call( req );
1850 SERVER_END_REQ;
1851 exit( status );
1855 /***********************************************************************
1856 * GetExitCodeProcess [KERNEL32.@]
1858 * Gets termination status of specified process
1860 * RETURNS
1861 * Success: TRUE
1862 * Failure: FALSE
1864 BOOL WINAPI GetExitCodeProcess(
1865 HANDLE hProcess, /* [in] handle to the process */
1866 LPDWORD lpExitCode) /* [out] address to receive termination status */
1868 BOOL ret;
1869 SERVER_START_REQ( get_process_info )
1871 req->handle = hProcess;
1872 ret = !wine_server_call_err( req );
1873 if (ret && lpExitCode) *lpExitCode = reply->exit_code;
1875 SERVER_END_REQ;
1876 return ret;
1880 /***********************************************************************
1881 * SetErrorMode (KERNEL32.@)
1883 UINT WINAPI SetErrorMode( UINT mode )
1885 UINT old = process_error_mode;
1886 process_error_mode = mode;
1887 return old;
1891 /**********************************************************************
1892 * TlsAlloc [KERNEL32.@] Allocates a TLS index.
1894 * Allocates a thread local storage index
1896 * RETURNS
1897 * Success: TLS Index
1898 * Failure: 0xFFFFFFFF
1900 DWORD WINAPI TlsAlloc( void )
1902 DWORD index;
1904 RtlAcquirePebLock();
1905 index = RtlFindClearBitsAndSet( NtCurrentTeb()->Peb->TlsBitmap, 1, 0 );
1906 if (index != ~0UL) NtCurrentTeb()->TlsSlots[index] = 0; /* clear the value */
1907 else SetLastError( ERROR_NO_MORE_ITEMS );
1908 RtlReleasePebLock();
1909 return index;
1913 /**********************************************************************
1914 * TlsFree [KERNEL32.@] Releases a TLS index.
1916 * Releases a thread local storage index, making it available for reuse
1918 * RETURNS
1919 * Success: TRUE
1920 * Failure: FALSE
1922 BOOL WINAPI TlsFree(
1923 DWORD index) /* [in] TLS Index to free */
1925 BOOL ret;
1927 RtlAcquirePebLock();
1928 ret = RtlAreBitsSet( NtCurrentTeb()->Peb->TlsBitmap, index, 1 );
1929 if (ret)
1931 RtlClearBits( NtCurrentTeb()->Peb->TlsBitmap, index, 1 );
1932 NtSetInformationThread( GetCurrentThread(), ThreadZeroTlsCell, &index, sizeof(index) );
1934 else SetLastError( ERROR_INVALID_PARAMETER );
1935 RtlReleasePebLock();
1936 return TRUE;
1940 /**********************************************************************
1941 * TlsGetValue [KERNEL32.@] Gets value in a thread's TLS slot
1943 * RETURNS
1944 * Success: Value stored in calling thread's TLS slot for index
1945 * Failure: 0 and GetLastError returns NO_ERROR
1947 LPVOID WINAPI TlsGetValue(
1948 DWORD index) /* [in] TLS index to retrieve value for */
1950 if (index >= NtCurrentTeb()->Peb->TlsBitmap->SizeOfBitMap)
1952 SetLastError( ERROR_INVALID_PARAMETER );
1953 return NULL;
1955 SetLastError( ERROR_SUCCESS );
1956 return NtCurrentTeb()->TlsSlots[index];
1960 /**********************************************************************
1961 * TlsSetValue [KERNEL32.@] Stores a value in the thread's TLS slot.
1963 * RETURNS
1964 * Success: TRUE
1965 * Failure: FALSE
1967 BOOL WINAPI TlsSetValue(
1968 DWORD index, /* [in] TLS index to set value for */
1969 LPVOID value) /* [in] Value to be stored */
1971 if (index >= NtCurrentTeb()->Peb->TlsBitmap->SizeOfBitMap)
1973 SetLastError( ERROR_INVALID_PARAMETER );
1974 return FALSE;
1976 NtCurrentTeb()->TlsSlots[index] = value;
1977 return TRUE;
1981 /***********************************************************************
1982 * GetProcessFlags (KERNEL32.@)
1984 DWORD WINAPI GetProcessFlags( DWORD processid )
1986 IMAGE_NT_HEADERS *nt;
1987 DWORD flags = 0;
1989 if (processid && processid != GetCurrentProcessId()) return 0;
1991 if ((nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress )))
1993 if (nt->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_CUI)
1994 flags |= PDB32_CONSOLE_PROC;
1996 if (!AreFileApisANSI()) flags |= PDB32_FILE_APIS_OEM;
1997 if (IsDebuggerPresent()) flags |= PDB32_DEBUGGED;
1998 return flags;
2002 /***********************************************************************
2003 * GetProcessDword (KERNEL.485)
2004 * GetProcessDword (KERNEL32.18)
2005 * 'Of course you cannot directly access Windows internal structures'
2007 DWORD WINAPI GetProcessDword( DWORD dwProcessID, INT offset )
2009 DWORD x, y;
2010 STARTUPINFOW siw;
2012 TRACE("(%ld, %d)\n", dwProcessID, offset );
2014 if (dwProcessID && dwProcessID != GetCurrentProcessId())
2016 ERR("%d: process %lx not accessible\n", offset, dwProcessID);
2017 return 0;
2020 switch ( offset )
2022 case GPD_APP_COMPAT_FLAGS:
2023 return GetAppCompatFlags16(0);
2024 case GPD_LOAD_DONE_EVENT:
2025 return 0;
2026 case GPD_HINSTANCE16:
2027 return GetTaskDS16();
2028 case GPD_WINDOWS_VERSION:
2029 return GetExeVersion16();
2030 case GPD_THDB:
2031 return (DWORD)NtCurrentTeb() - 0x10 /* FIXME */;
2032 case GPD_PDB:
2033 return (DWORD)NtCurrentTeb()->Peb;
2034 case GPD_STARTF_SHELLDATA: /* return stdoutput handle from startupinfo ??? */
2035 GetStartupInfoW(&siw);
2036 return (DWORD)siw.hStdOutput;
2037 case GPD_STARTF_HOTKEY: /* return stdinput handle from startupinfo ??? */
2038 GetStartupInfoW(&siw);
2039 return (DWORD)siw.hStdInput;
2040 case GPD_STARTF_SHOWWINDOW:
2041 GetStartupInfoW(&siw);
2042 return siw.wShowWindow;
2043 case GPD_STARTF_SIZE:
2044 GetStartupInfoW(&siw);
2045 x = siw.dwXSize;
2046 if ( (INT)x == CW_USEDEFAULT ) x = CW_USEDEFAULT16;
2047 y = siw.dwYSize;
2048 if ( (INT)y == CW_USEDEFAULT ) y = CW_USEDEFAULT16;
2049 return MAKELONG( x, y );
2050 case GPD_STARTF_POSITION:
2051 GetStartupInfoW(&siw);
2052 x = siw.dwX;
2053 if ( (INT)x == CW_USEDEFAULT ) x = CW_USEDEFAULT16;
2054 y = siw.dwY;
2055 if ( (INT)y == CW_USEDEFAULT ) y = CW_USEDEFAULT16;
2056 return MAKELONG( x, y );
2057 case GPD_STARTF_FLAGS:
2058 GetStartupInfoW(&siw);
2059 return siw.dwFlags;
2060 case GPD_PARENT:
2061 return 0;
2062 case GPD_FLAGS:
2063 return GetProcessFlags(0);
2064 case GPD_USERDATA:
2065 return process_dword;
2066 default:
2067 ERR("Unknown offset %d\n", offset );
2068 return 0;
2072 /***********************************************************************
2073 * SetProcessDword (KERNEL.484)
2074 * 'Of course you cannot directly access Windows internal structures'
2076 void WINAPI SetProcessDword( DWORD dwProcessID, INT offset, DWORD value )
2078 TRACE("(%ld, %d)\n", dwProcessID, offset );
2080 if (dwProcessID && dwProcessID != GetCurrentProcessId())
2082 ERR("%d: process %lx not accessible\n", offset, dwProcessID);
2083 return;
2086 switch ( offset )
2088 case GPD_APP_COMPAT_FLAGS:
2089 case GPD_LOAD_DONE_EVENT:
2090 case GPD_HINSTANCE16:
2091 case GPD_WINDOWS_VERSION:
2092 case GPD_THDB:
2093 case GPD_PDB:
2094 case GPD_STARTF_SHELLDATA:
2095 case GPD_STARTF_HOTKEY:
2096 case GPD_STARTF_SHOWWINDOW:
2097 case GPD_STARTF_SIZE:
2098 case GPD_STARTF_POSITION:
2099 case GPD_STARTF_FLAGS:
2100 case GPD_PARENT:
2101 case GPD_FLAGS:
2102 ERR("Not allowed to modify offset %d\n", offset );
2103 break;
2104 case GPD_USERDATA:
2105 process_dword = value;
2106 break;
2107 default:
2108 ERR("Unknown offset %d\n", offset );
2109 break;
2114 /***********************************************************************
2115 * ExitProcess (KERNEL.466)
2117 void WINAPI ExitProcess16( WORD status )
2119 DWORD count;
2120 ReleaseThunkLock( &count );
2121 ExitProcess( status );
2125 /*********************************************************************
2126 * OpenProcess (KERNEL32.@)
2128 HANDLE WINAPI OpenProcess( DWORD access, BOOL inherit, DWORD id )
2130 HANDLE ret = 0;
2131 SERVER_START_REQ( open_process )
2133 req->pid = id;
2134 req->access = access;
2135 req->inherit = inherit;
2136 if (!wine_server_call_err( req )) ret = reply->handle;
2138 SERVER_END_REQ;
2139 return ret;
2143 /*********************************************************************
2144 * MapProcessHandle (KERNEL.483)
2146 DWORD WINAPI MapProcessHandle( HANDLE handle )
2148 DWORD ret = 0;
2149 SERVER_START_REQ( get_process_info )
2151 req->handle = handle;
2152 if (!wine_server_call_err( req )) ret = reply->pid;
2154 SERVER_END_REQ;
2155 return ret;
2159 /*********************************************************************
2160 * CloseW32Handle (KERNEL.474)
2161 * CloseHandle (KERNEL32.@)
2163 BOOL WINAPI CloseHandle( HANDLE handle )
2165 NTSTATUS status;
2167 /* stdio handles need special treatment */
2168 if ((handle == (HANDLE)STD_INPUT_HANDLE) ||
2169 (handle == (HANDLE)STD_OUTPUT_HANDLE) ||
2170 (handle == (HANDLE)STD_ERROR_HANDLE))
2171 handle = GetStdHandle( (DWORD)handle );
2173 if (is_console_handle(handle))
2174 return CloseConsoleHandle(handle);
2176 status = NtClose( handle );
2177 if (status) SetLastError( RtlNtStatusToDosError(status) );
2178 return !status;
2182 /*********************************************************************
2183 * GetHandleInformation (KERNEL32.@)
2185 BOOL WINAPI GetHandleInformation( HANDLE handle, LPDWORD flags )
2187 BOOL ret;
2188 SERVER_START_REQ( set_handle_info )
2190 req->handle = handle;
2191 req->flags = 0;
2192 req->mask = 0;
2193 req->fd = -1;
2194 ret = !wine_server_call_err( req );
2195 if (ret && flags) *flags = reply->old_flags;
2197 SERVER_END_REQ;
2198 return ret;
2202 /*********************************************************************
2203 * SetHandleInformation (KERNEL32.@)
2205 BOOL WINAPI SetHandleInformation( HANDLE handle, DWORD mask, DWORD flags )
2207 BOOL ret;
2208 SERVER_START_REQ( set_handle_info )
2210 req->handle = handle;
2211 req->flags = flags;
2212 req->mask = mask;
2213 req->fd = -1;
2214 ret = !wine_server_call_err( req );
2216 SERVER_END_REQ;
2217 return ret;
2221 /*********************************************************************
2222 * DuplicateHandle (KERNEL32.@)
2224 BOOL WINAPI DuplicateHandle( HANDLE source_process, HANDLE source,
2225 HANDLE dest_process, HANDLE *dest,
2226 DWORD access, BOOL inherit, DWORD options )
2228 NTSTATUS status;
2230 if (is_console_handle(source))
2232 /* FIXME: this test is not sufficient, we need to test process ids, not handles */
2233 if (source_process != dest_process ||
2234 source_process != GetCurrentProcess())
2236 SetLastError(ERROR_INVALID_PARAMETER);
2237 return FALSE;
2239 *dest = DuplicateConsoleHandle( source, access, inherit, options );
2240 return (*dest != INVALID_HANDLE_VALUE);
2242 status = NtDuplicateObject( source_process, source, dest_process, dest,
2243 access, inherit ? OBJ_INHERIT : 0, options );
2244 if (status) SetLastError( RtlNtStatusToDosError(status) );
2245 return !status;
2249 /***********************************************************************
2250 * ConvertToGlobalHandle (KERNEL.476)
2251 * ConvertToGlobalHandle (KERNEL32.@)
2253 HANDLE WINAPI ConvertToGlobalHandle(HANDLE hSrc)
2255 HANDLE ret = INVALID_HANDLE_VALUE;
2256 DuplicateHandle( GetCurrentProcess(), hSrc, GetCurrentProcess(), &ret, 0, FALSE,
2257 DUP_HANDLE_MAKE_GLOBAL | DUP_HANDLE_SAME_ACCESS | DUP_HANDLE_CLOSE_SOURCE );
2258 return ret;
2262 /***********************************************************************
2263 * SetHandleContext (KERNEL32.@)
2265 BOOL WINAPI SetHandleContext(HANDLE hnd,DWORD context)
2267 FIXME("(%p,%ld), stub. In case this got called by WSOCK32/WS2_32: "
2268 "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd,context);
2269 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2270 return FALSE;
2274 /***********************************************************************
2275 * GetHandleContext (KERNEL32.@)
2277 DWORD WINAPI GetHandleContext(HANDLE hnd)
2279 FIXME("(%p), stub. In case this got called by WSOCK32/WS2_32: "
2280 "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd);
2281 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2282 return 0;
2286 /***********************************************************************
2287 * CreateSocketHandle (KERNEL32.@)
2289 HANDLE WINAPI CreateSocketHandle(void)
2291 FIXME("(), stub. In case this got called by WSOCK32/WS2_32: "
2292 "the external WINSOCK DLLs won't work with WINE, don't use them.\n");
2293 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2294 return INVALID_HANDLE_VALUE;
2298 /***********************************************************************
2299 * SetPriorityClass (KERNEL32.@)
2301 BOOL WINAPI SetPriorityClass( HANDLE hprocess, DWORD priorityclass )
2303 BOOL ret;
2304 SERVER_START_REQ( set_process_info )
2306 req->handle = hprocess;
2307 req->priority = priorityclass;
2308 req->mask = SET_PROCESS_INFO_PRIORITY;
2309 ret = !wine_server_call_err( req );
2311 SERVER_END_REQ;
2312 return ret;
2316 /***********************************************************************
2317 * GetPriorityClass (KERNEL32.@)
2319 DWORD WINAPI GetPriorityClass(HANDLE hprocess)
2321 DWORD ret = 0;
2322 SERVER_START_REQ( get_process_info )
2324 req->handle = hprocess;
2325 if (!wine_server_call_err( req )) ret = reply->priority;
2327 SERVER_END_REQ;
2328 return ret;
2332 /***********************************************************************
2333 * SetProcessAffinityMask (KERNEL32.@)
2335 BOOL WINAPI SetProcessAffinityMask( HANDLE hProcess, DWORD affmask )
2337 BOOL ret;
2338 SERVER_START_REQ( set_process_info )
2340 req->handle = hProcess;
2341 req->affinity = affmask;
2342 req->mask = SET_PROCESS_INFO_AFFINITY;
2343 ret = !wine_server_call_err( req );
2345 SERVER_END_REQ;
2346 return ret;
2350 /**********************************************************************
2351 * GetProcessAffinityMask (KERNEL32.@)
2353 BOOL WINAPI GetProcessAffinityMask( HANDLE hProcess,
2354 LPDWORD lpProcessAffinityMask,
2355 LPDWORD lpSystemAffinityMask )
2357 BOOL ret = FALSE;
2358 SERVER_START_REQ( get_process_info )
2360 req->handle = hProcess;
2361 if (!wine_server_call_err( req ))
2363 if (lpProcessAffinityMask) *lpProcessAffinityMask = reply->process_affinity;
2364 if (lpSystemAffinityMask) *lpSystemAffinityMask = reply->system_affinity;
2365 ret = TRUE;
2368 SERVER_END_REQ;
2369 return ret;
2373 /***********************************************************************
2374 * GetProcessVersion (KERNEL32.@)
2376 DWORD WINAPI GetProcessVersion( DWORD processid )
2378 IMAGE_NT_HEADERS *nt;
2380 if (processid && processid != GetCurrentProcessId())
2382 FIXME("should use ReadProcessMemory\n");
2383 return 0;
2385 if ((nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress )))
2386 return ((nt->OptionalHeader.MajorSubsystemVersion << 16) |
2387 nt->OptionalHeader.MinorSubsystemVersion);
2388 return 0;
2392 /***********************************************************************
2393 * SetProcessWorkingSetSize [KERNEL32.@]
2394 * Sets the min/max working set sizes for a specified process.
2396 * PARAMS
2397 * hProcess [I] Handle to the process of interest
2398 * minset [I] Specifies minimum working set size
2399 * maxset [I] Specifies maximum working set size
2401 * RETURNS STD
2403 BOOL WINAPI SetProcessWorkingSetSize(HANDLE hProcess, SIZE_T minset,
2404 SIZE_T maxset)
2406 FIXME("(%p,%ld,%ld): stub - harmless\n",hProcess,minset,maxset);
2407 if(( minset == (SIZE_T)-1) && (maxset == (SIZE_T)-1)) {
2408 /* Trim the working set to zero */
2409 /* Swap the process out of physical RAM */
2411 return TRUE;
2414 /***********************************************************************
2415 * GetProcessWorkingSetSize (KERNEL32.@)
2417 BOOL WINAPI GetProcessWorkingSetSize(HANDLE hProcess, PSIZE_T minset,
2418 PSIZE_T maxset)
2420 FIXME("(%p,%p,%p): stub\n",hProcess,minset,maxset);
2421 /* 32 MB working set size */
2422 if (minset) *minset = 32*1024*1024;
2423 if (maxset) *maxset = 32*1024*1024;
2424 return TRUE;
2428 /***********************************************************************
2429 * SetProcessShutdownParameters (KERNEL32.@)
2431 BOOL WINAPI SetProcessShutdownParameters(DWORD level, DWORD flags)
2433 FIXME("(%08lx, %08lx): partial stub.\n", level, flags);
2434 shutdown_flags = flags;
2435 shutdown_priority = level;
2436 return TRUE;
2440 /***********************************************************************
2441 * GetProcessShutdownParameters (KERNEL32.@)
2444 BOOL WINAPI GetProcessShutdownParameters( LPDWORD lpdwLevel, LPDWORD lpdwFlags )
2446 *lpdwLevel = shutdown_priority;
2447 *lpdwFlags = shutdown_flags;
2448 return TRUE;
2452 /***********************************************************************
2453 * GetProcessPriorityBoost (KERNEL32.@)
2455 BOOL WINAPI GetProcessPriorityBoost(HANDLE hprocess,PBOOL pDisablePriorityBoost)
2457 FIXME("(%p,%p): semi-stub\n", hprocess, pDisablePriorityBoost);
2459 /* Report that no boost is present.. */
2460 *pDisablePriorityBoost = FALSE;
2462 return TRUE;
2465 /***********************************************************************
2466 * SetProcessPriorityBoost (KERNEL32.@)
2468 BOOL WINAPI SetProcessPriorityBoost(HANDLE hprocess,BOOL disableboost)
2470 FIXME("(%p,%d): stub\n",hprocess,disableboost);
2471 /* Say we can do it. I doubt the program will notice that we don't. */
2472 return TRUE;
2476 /***********************************************************************
2477 * ReadProcessMemory (KERNEL32.@)
2479 BOOL WINAPI ReadProcessMemory( HANDLE process, LPCVOID addr, LPVOID buffer, SIZE_T size,
2480 SIZE_T *bytes_read )
2482 NTSTATUS status = NtReadVirtualMemory( process, addr, buffer, size, bytes_read );
2483 if (status) SetLastError( RtlNtStatusToDosError(status) );
2484 return !status;
2488 /***********************************************************************
2489 * WriteProcessMemory (KERNEL32.@)
2491 BOOL WINAPI WriteProcessMemory( HANDLE process, LPVOID addr, LPCVOID buffer, SIZE_T size,
2492 SIZE_T *bytes_written )
2494 NTSTATUS status = NtWriteVirtualMemory( process, addr, buffer, size, bytes_written );
2495 if (status) SetLastError( RtlNtStatusToDosError(status) );
2496 return !status;
2500 /****************************************************************************
2501 * FlushInstructionCache (KERNEL32.@)
2503 BOOL WINAPI FlushInstructionCache(HANDLE hProcess, LPCVOID lpBaseAddress, SIZE_T dwSize)
2505 if (GetVersion() & 0x80000000) return TRUE; /* not NT, always TRUE */
2506 FIXME("(%p,%p,0x%08lx): stub\n",hProcess, lpBaseAddress, dwSize);
2507 return TRUE;
2511 /******************************************************************
2512 * GetProcessIoCounters (KERNEL32.@)
2514 BOOL WINAPI GetProcessIoCounters(HANDLE hProcess, PIO_COUNTERS ioc)
2516 NTSTATUS status;
2518 status = NtQueryInformationProcess(hProcess, ProcessIoCounters,
2519 ioc, sizeof(*ioc), NULL);
2520 if (status) SetLastError( RtlNtStatusToDosError(status) );
2521 return !status;
2524 /***********************************************************************
2525 * ProcessIdToSessionId (KERNEL32.@)
2526 * This function is available on Terminal Server 4SP4 and Windows 2000
2528 BOOL WINAPI ProcessIdToSessionId( DWORD procid, DWORD *sessionid_ptr )
2530 /* According to MSDN, if the calling process is not in a terminal
2531 * services environment, then the sessionid returned is zero.
2533 *sessionid_ptr = 0;
2534 return TRUE;
2538 /***********************************************************************
2539 * RegisterServiceProcess (KERNEL.491)
2540 * RegisterServiceProcess (KERNEL32.@)
2542 * A service process calls this function to ensure that it continues to run
2543 * even after a user logged off.
2545 DWORD WINAPI RegisterServiceProcess(DWORD dwProcessId, DWORD dwType)
2547 /* I don't think that Wine needs to do anything in that function */
2548 return 1; /* success */
2552 /**************************************************************************
2553 * SetFileApisToOEM (KERNEL32.@)
2555 VOID WINAPI SetFileApisToOEM(void)
2557 oem_file_apis = TRUE;
2561 /**************************************************************************
2562 * SetFileApisToANSI (KERNEL32.@)
2564 VOID WINAPI SetFileApisToANSI(void)
2566 oem_file_apis = FALSE;
2570 /******************************************************************************
2571 * AreFileApisANSI [KERNEL32.@] Determines if file functions are using ANSI
2573 * RETURNS
2574 * TRUE: Set of file functions is using ANSI code page
2575 * FALSE: Set of file functions is using OEM code page
2577 BOOL WINAPI AreFileApisANSI(void)
2579 return !oem_file_apis;
2583 /***********************************************************************
2584 * GetSystemMSecCount (SYSTEM.6)
2585 * GetTickCount (KERNEL32.@)
2587 * Returns the number of milliseconds, modulo 2^32, since the start
2588 * of the wineserver.
2590 DWORD WINAPI GetTickCount(void)
2592 struct timeval t;
2593 gettimeofday( &t, NULL );
2594 return ((t.tv_sec * 1000) + (t.tv_usec / 1000)) - server_startticks;
2598 /***********************************************************************
2599 * GetCurrentProcess (KERNEL32.@)
2601 #undef GetCurrentProcess
2602 HANDLE WINAPI GetCurrentProcess(void)
2604 return (HANDLE)0xffffffff;