1 /*
2 * Win32 processes
3 *
4 * Copyright 1996, 1998 Alexandre Julliard
5 *
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.
10 *
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.
15 *
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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
19 */
20
21 #include "config.h"
22 #include "wine/port.h"
23
24 #include <assert.h>
25 #include <ctype.h>
26 #include <errno.h>
27 #include <signal.h>
28 #include <stdio.h>
29 #include <time.h>
30 #ifdef HAVE_SYS_TIME_H
31 # include <sys/time.h>
32 #endif
33 #ifdef HAVE_SYS_IOCTL_H
34 #include <sys/ioctl.h>
35 #endif
36 #ifdef HAVE_SYS_SOCKET_H
37 #include <sys/socket.h>
38 #endif
39 #ifdef HAVE_SYS_PRCTL_H
40 # include <sys/prctl.h>
41 #endif
42 #include <sys/types.h>
43
44 #include "ntstatus.h"
45 #define WIN32_NO_STATUS
46 #include "wine/winbase16.h"
47 #include "wine/winuser16.h"
48 #include "winternl.h"
49 #include "kernel_private.h"
50 #include "wine/exception.h"
51 #include "wine/server.h"
52 #include "wine/unicode.h"
53 #include "wine/debug.h"
54
55 WINE_DEFAULT_DEBUG_CHANNEL(process);
56 WINE_DECLARE_DEBUG_CHANNEL(file);
57 WINE_DECLARE_DEBUG_CHANNEL(relay);
58
59 #ifdef __APPLE__
60 extern char **__wine_get_main_environment(void);
61 #else
62 extern char **__wine_main_environ;
63 static char **__wine_get_main_environment(void) { return __wine_main_environ; }
64 #endif
65
66 typedef struct
67 {
68 LPSTR lpEnvAddress;
69 LPSTR lpCmdLine;
70 LPSTR lpCmdShow;
71 DWORD dwReserved;
72 } LOADPARMS32;
73
74 static UINT process_error_mode;
75
76 static DWORD shutdown_flags = 0;
77 static DWORD shutdown_priority = 0x280;
78 static DWORD process_dword;
79 static BOOL is_wow64;
80
81 HMODULE kernel32_handle = 0;
82
83 const WCHAR *DIR_Windows = NULL;
84 const WCHAR *DIR_System = NULL;
85 const WCHAR *DIR_SysWow64 = NULL;
86
87 /* Process flags */
88 #define PDB32_DEBUGGED 0x0001 /* Process is being debugged */
89 #define PDB32_WIN16_PROC 0x0008 /* Win16 process */
90 #define PDB32_DOS_PROC 0x0010 /* Dos process */
91 #define PDB32_CONSOLE_PROC 0x0020 /* Console process */
92 #define PDB32_FILE_APIS_OEM 0x0040 /* File APIs are OEM */
93 #define PDB32_WIN32S_PROC 0x8000 /* Win32s process */
94
95 static const WCHAR comW[] = {'.','c','o','m',0};
96 static const WCHAR batW[] = {'.','b','a','t',0};
97 static const WCHAR cmdW[] = {'.','c','m','d',0};
98 static const WCHAR pifW[] = {'.','p','i','f',0};
99 static const WCHAR winevdmW[] = {'w','i','n','e','v','d','m','.','e','x','e',0};
100
101 static void exec_process( LPCWSTR name );
102
103 extern void SHELL_LoadRegistry(void);
104
105
106 /***********************************************************************
107 * contains_path
108 */
109 static inline int contains_path( LPCWSTR name )
110 {
111 return ((*name && (name[1] == ':')) || strchrW(name, '/') || strchrW(name, '\\'));
112 }
113
114
115 /***********************************************************************
116 * is_special_env_var
117 *
118 * Check if an environment variable needs to be handled specially when
119 * passed through the Unix environment (i.e. prefixed with "WINE").
120 */
121 static inline int is_special_env_var( const char *var )
122 {
123 return (!strncmp( var, "PATH=", sizeof("PATH=")-1 ) ||
124 !strncmp( var, "HOME=", sizeof("HOME=")-1 ) ||
125 !strncmp( var, "TEMP=", sizeof("TEMP=")-1 ) ||
126 !strncmp( var, "TMP=", sizeof("TMP=")-1 ));
127 }
128
129
130 /***************************************************************************
131 * get_builtin_path
132 *
133 * Get the path of a builtin module when the native file does not exist.
134 */
135 static BOOL get_builtin_path( const WCHAR *libname, const WCHAR *ext, WCHAR *filename, UINT size )
136 {
137 WCHAR *file_part;
138 UINT len = strlenW( DIR_System );
139
140 if (contains_path( libname ))
141 {
142 if (RtlGetFullPathName_U( libname, size * sizeof(WCHAR),
143 filename, &file_part ) > size * sizeof(WCHAR))
144 return FALSE; /* too long */
145
146 if (strncmpiW( filename, DIR_System, len ) || filename[len] != '\\')
147 return FALSE;
148 while (filename[len] == '\\') len++;
149 if (filename + len != file_part) return FALSE;
150 }
151 else
152 {
153 if (strlenW(libname) + len + 2 >= size) return FALSE; /* too long */
154 memcpy( filename, DIR_System, len * sizeof(WCHAR) );
155 file_part = filename + len;
156 if (file_part > filename && file_part[-1] != '\\') *file_part++ = '\\';
157 strcpyW( file_part, libname );
158 }
159 if (ext && !strchrW( file_part, '.' ))
160 {
161 if (file_part + strlenW(file_part) + strlenW(ext) + 1 > filename + size)
162 return FALSE; /* too long */
163 strcatW( file_part, ext );
164 }
165 return TRUE;
166 }
167
168
169 /***********************************************************************
170 * open_builtin_exe_file
171 *
172 * Open an exe file for a builtin exe.
173 */
174 static void *open_builtin_exe_file( const WCHAR *name, char *error, int error_size,
175 int test_only, int *file_exists )
176 {
177 char exename[MAX_PATH];
178 WCHAR *p;
179 UINT i, len;
180
181 *file_exists = 0;
182 if ((p = strrchrW( name, '/' ))) name = p + 1;
183 if ((p = strrchrW( name, '\\' ))) name = p + 1;
184
185 /* we don't want to depend on the current codepage here */
186 len = strlenW( name ) + 1;
187 if (len >= sizeof(exename)) return NULL;
188 for (i = 0; i < len; i++)
189 {
190 if (name[i] > 127) return NULL;
191 exename[i] = (char)name[i];
192 if (exename[i] >= 'A' && exename[i] <= 'Z') exename[i] += 'a' - 'A';
193 }
194 return wine_dll_load_main_exe( exename, error, error_size, test_only, file_exists );
195 }
196
197
198 /***********************************************************************
199 * open_exe_file
200 *
201 * Open a specific exe file, taking load order into account.
202 * Returns the file handle or 0 for a builtin exe.
203 */
204 static HANDLE open_exe_file( const WCHAR *name )
205 {
206 HANDLE handle;
207
208 TRACE("looking for %s\n", debugstr_w(name) );
209
210 if ((handle = CreateFileW( name, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_DELETE,
211 NULL, OPEN_EXISTING, 0, 0 )) == INVALID_HANDLE_VALUE)
212 {
213 WCHAR buffer[MAX_PATH];
214 /* file doesn't exist, check for builtin */
215 if (contains_path( name ) && get_builtin_path( name, NULL, buffer, sizeof(buffer) ))
216 handle = 0;
217 }
218 return handle;
219 }
220
221
222 /***********************************************************************
223 * find_exe_file
224 *
225 * Open an exe file, and return the full name and file handle.
226 * Returns FALSE if file could not be found.
227 * If file exists but cannot be opened, returns TRUE and set handle to INVALID_HANDLE_VALUE.
228 * If file is a builtin exe, returns TRUE and sets handle to 0.
229 */
230 static BOOL find_exe_file( const WCHAR *name, WCHAR *buffer, int buflen, HANDLE *handle )
231 {
232 static const WCHAR exeW[] = {'.','e','x','e',0};
233 int file_exists;
234
235 TRACE("looking for %s\n", debugstr_w(name) );
236
237 if (!SearchPathW( NULL, name, exeW, buflen, buffer, NULL ) &&
238 !get_builtin_path( name, exeW, buffer, buflen ))
239 {
240 /* no builtin found, try native without extension in case it is a Unix app */
241
242 if (SearchPathW( NULL, name, NULL, buflen, buffer, NULL ))
243 {
244 TRACE( "Trying native/Unix binary %s\n", debugstr_w(buffer) );
245 if ((*handle = CreateFileW( buffer, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_DELETE,
246 NULL, OPEN_EXISTING, 0, 0 )) != INVALID_HANDLE_VALUE)
247 return TRUE;
248 }
249 return FALSE;
250 }
251
252 TRACE( "Trying native exe %s\n", debugstr_w(buffer) );
253 if ((*handle = CreateFileW( buffer, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_DELETE,
254 NULL, OPEN_EXISTING, 0, 0 )) != INVALID_HANDLE_VALUE)
255 return TRUE;
256
257 TRACE( "Trying built-in exe %s\n", debugstr_w(buffer) );
258 open_builtin_exe_file( buffer, NULL, 0, 1, &file_exists );
259 if (file_exists)
260 {
261 *handle = 0;
262 return TRUE;
263 }
264
265 return FALSE;
266 }
267
268
269 /***********************************************************************
270 * build_initial_environment
271 *
272 * Build the Win32 environment from the Unix environment
273 */
274 static BOOL build_initial_environment(void)
275 {
276 SIZE_T size = 1;
277 char **e;
278 WCHAR *p, *endptr;
279 void *ptr;
280 char **env = __wine_get_main_environment();
281
282 /* Compute the total size of the Unix environment */
283 for (e = env; *e; e++)
284 {
285 if (is_special_env_var( *e )) continue;
286 size += MultiByteToWideChar( CP_UNIXCP, 0, *e, -1, NULL, 0 );
287 }
288 size *= sizeof(WCHAR);
289
290 /* Now allocate the environment */
291 ptr = NULL;
292 if (NtAllocateVirtualMemory(NtCurrentProcess(), &ptr, 0, &size,
293 MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) != STATUS_SUCCESS)
294 return FALSE;
295
296 NtCurrentTeb()->Peb->ProcessParameters->Environment = p = ptr;
297 endptr = p + size / sizeof(WCHAR);
298
299 /* And fill it with the Unix environment */
300 for (e = env; *e; e++)
301 {
302 char *str = *e;
303
304 /* skip Unix special variables and use the Wine variants instead */
305 if (!strncmp( str, "WINE", 4 ))
306 {
307 if (is_special_env_var( str + 4 )) str += 4;
308 else if (!strncmp( str, "WINEPRELOADRESERVE=", 19 )) continue; /* skip it */
309 }
310 else if (is_special_env_var( str )) continue; /* skip it */
311
312 MultiByteToWideChar( CP_UNIXCP, 0, str, -1, p, endptr - p );
313 p += strlenW(p) + 1;
314 }
315 *p = 0;
316 return TRUE;
317 }
318
319
320 /***********************************************************************
321 * set_registry_variables
322 *
323 * Set environment variables by enumerating the values of a key;
324 * helper for set_registry_environment().
325 * Note that Windows happily truncates the value if it's too big.
326 */
327 static void set_registry_variables( HANDLE hkey, ULONG type )
328 {
329 UNICODE_STRING env_name, env_value;
330 NTSTATUS status;
331 DWORD size;
332 int index;
333 char buffer[1024*sizeof(WCHAR) + sizeof(KEY_VALUE_FULL_INFORMATION)];
334 KEY_VALUE_FULL_INFORMATION *info = (KEY_VALUE_FULL_INFORMATION *)buffer;
335
336 for (index = 0; ; index++)
337 {
338 status = NtEnumerateValueKey( hkey, index, KeyValueFullInformation,
339 buffer, sizeof(buffer), &size );
340 if (status != STATUS_SUCCESS && status != STATUS_BUFFER_OVERFLOW)
341 break;
342 if (info->Type != type)
343 continue;
344 env_name.Buffer = info->Name;
345 env_name.Length = env_name.MaximumLength = info->NameLength;
346 env_value.Buffer = (WCHAR *)(buffer + info->DataOffset);
347 env_value.Length = env_value.MaximumLength = info->DataLength;
348 if (env_value.Length && !env_value.Buffer[env_value.Length/sizeof(WCHAR)-1])
349 env_value.Length -= sizeof(WCHAR); /* don't count terminating null if any */
350 if (info->Type == REG_EXPAND_SZ)
351 {
352 WCHAR buf_expanded[1024];
353 UNICODE_STRING env_expanded;
354 env_expanded.Length = env_expanded.MaximumLength = sizeof(buf_expanded);
355 env_expanded.Buffer=buf_expanded;
356 status = RtlExpandEnvironmentStrings_U(NULL, &env_value, &env_expanded, NULL);
357 if (status == STATUS_SUCCESS || status == STATUS_BUFFER_OVERFLOW)
358 RtlSetEnvironmentVariable( NULL, &env_name, &env_expanded );
359 }
360 else
361 {
362 RtlSetEnvironmentVariable( NULL, &env_name, &env_value );
363 }
364 }
365 }
366
367
368 /***********************************************************************
369 * set_registry_environment
370 *
371 * Set the environment variables specified in the registry.
372 *
373 * Note: Windows handles REG_SZ and REG_EXPAND_SZ in one pass with the
374 * consequence that REG_EXPAND_SZ cannot be used reliably as it depends
375 * on the order in which the variables are processed. But on Windows it
376 * does not really matter since they only use %SystemDrive% and
377 * %SystemRoot% which are predefined. But Wine defines these in the
378 * registry, so we need two passes.
379 */
380 static BOOL set_registry_environment(void)
381 {
382 static const WCHAR env_keyW[] = {'M','a','c','h','i','n','e','\\',
383 'S','y','s','t','e','m','\\',
384 'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
385 'C','o','n','t','r','o','l','\\',
386 'S','e','s','s','i','o','n',' ','M','a','n','a','g','e','r','\\',
387 'E','n','v','i','r','o','n','m','e','n','t',0};
388 static const WCHAR envW[] = {'E','n','v','i','r','o','n','m','e','n','t',0};
389
390 OBJECT_ATTRIBUTES attr;
391 UNICODE_STRING nameW;
392 HANDLE hkey;
393 BOOL ret = FALSE;
394
395 attr.Length = sizeof(attr);
396 attr.RootDirectory = 0;
397 attr.ObjectName = &nameW;
398 attr.Attributes = 0;
399 attr.SecurityDescriptor = NULL;
400 attr.SecurityQualityOfService = NULL;
401
402 /* first the system environment variables */
403 RtlInitUnicodeString( &nameW, env_keyW );
404 if (NtOpenKey( &hkey, KEY_ALL_ACCESS, &attr ) == STATUS_SUCCESS)
405 {
406 set_registry_variables( hkey, REG_SZ );
407 set_registry_variables( hkey, REG_EXPAND_SZ );
408 NtClose( hkey );
409 ret = TRUE;
410 }
411
412 /* then the ones for the current user */
413 if (RtlOpenCurrentUser( KEY_ALL_ACCESS, &attr.RootDirectory ) != STATUS_SUCCESS) return ret;
414 RtlInitUnicodeString( &nameW, envW );
415 if (NtOpenKey( &hkey, KEY_ALL_ACCESS, &attr ) == STATUS_SUCCESS)
416 {
417 set_registry_variables( hkey, REG_SZ );
418 set_registry_variables( hkey, REG_EXPAND_SZ );
419 NtClose( hkey );
420 }
421 NtClose( attr.RootDirectory );
422 return ret;
423 }
424
425
426 /***********************************************************************
427 * get_reg_value
428 */
429 static WCHAR *get_reg_value( HKEY hkey, const WCHAR *name )
430 {
431 char buffer[1024 * sizeof(WCHAR) + sizeof(KEY_VALUE_PARTIAL_INFORMATION)];
432 KEY_VALUE_PARTIAL_INFORMATION *info = (KEY_VALUE_PARTIAL_INFORMATION *)buffer;
433 DWORD len, size = sizeof(buffer);
434 WCHAR *ret = NULL;
435 UNICODE_STRING nameW;
436
437 RtlInitUnicodeString( &nameW, name );
438 if (NtQueryValueKey( hkey, &nameW, KeyValuePartialInformation, buffer, size, &size ))
439 return NULL;
440
441 if (size <= FIELD_OFFSET( KEY_VALUE_PARTIAL_INFORMATION, Data )) return NULL;
442 len = (size - FIELD_OFFSET( KEY_VALUE_PARTIAL_INFORMATION, Data )) / sizeof(WCHAR);
443
444 if (info->Type == REG_EXPAND_SZ)
445 {
446 UNICODE_STRING value, expanded;
447
448 value.MaximumLength = len * sizeof(WCHAR);
449 value.Buffer = (WCHAR *)info->Data;
450 if (!value.Buffer[len - 1]) len--; /* don't count terminating null if any */
451 value.Length = len * sizeof(WCHAR);
452 expanded.Length = expanded.MaximumLength = 1024 * sizeof(WCHAR);
453 if (!(expanded.Buffer = HeapAlloc( GetProcessHeap(), 0, expanded.MaximumLength ))) return NULL;
454 if (!RtlExpandEnvironmentStrings_U( NULL, &value, &expanded, NULL )) ret = expanded.Buffer;
455 else RtlFreeUnicodeString( &expanded );
456 }
457 else if (info->Type == REG_SZ)
458 {
459 if ((ret = HeapAlloc( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) )))
460 {
461 memcpy( ret, info->Data, len * sizeof(WCHAR) );
462 ret[len] = 0;
463 }
464 }
465 return ret;
466 }
467
468
469 /***********************************************************************
470 * set_additional_environment
471 *
472 * Set some additional environment variables not specified in the registry.
473 */
474 static void set_additional_environment(void)
475 {
476 static const WCHAR profile_keyW[] = {'M','a','c','h','i','n','e','\\',
477 'S','o','f','t','w','a','r','e','\\',
478 'M','i','c','r','o','s','o','f','t','\\',
479 'W','i','n','d','o','w','s',' ','N','T','\\',
480 'C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\',
481 'P','r','o','f','i','l','e','L','i','s','t',0};
482 static const WCHAR profiles_valueW[] = {'P','r','o','f','i','l','e','s','D','i','r','e','c','t','o','r','y',0};
483 static const WCHAR all_users_valueW[] = {'A','l','l','U','s','e','r','s','P','r','o','f','i','l','e','\0'};
484 static const WCHAR usernameW[] = {'U','S','E','R','N','A','M','E',0};
485 static const WCHAR userprofileW[] = {'U','S','E','R','P','R','O','F','I','L','E',0};
486 static const WCHAR allusersW[] = {'A','L','L','U','S','E','R','S','P','R','O','F','I','L','E',0};
487 OBJECT_ATTRIBUTES attr;
488 UNICODE_STRING nameW;
489 WCHAR *user_name = NULL, *profile_dir = NULL, *all_users_dir = NULL;
490 HANDLE hkey;
491 const char *name = wine_get_user_name();
492 DWORD len;
493
494 /* set the USERNAME variable */
495
496 len = MultiByteToWideChar( CP_UNIXCP, 0, name, -1, NULL, 0 );
497 if (len)
498 {
499 user_name = HeapAlloc( GetProcessHeap(), 0, len*sizeof(WCHAR) );
500 MultiByteToWideChar( CP_UNIXCP, 0, name, -1, user_name, len );
501 SetEnvironmentVariableW( usernameW, user_name );
502 }
503 else WARN( "user name %s not convertible.\n", debugstr_a(name) );
504
505 /* set the USERPROFILE and ALLUSERSPROFILE variables */
506
507 attr.Length = sizeof(attr);
508 attr.RootDirectory = 0;
509 attr.ObjectName = &nameW;
510 attr.Attributes = 0;
511 attr.SecurityDescriptor = NULL;
512 attr.SecurityQualityOfService = NULL;
513 RtlInitUnicodeString( &nameW, profile_keyW );
514 if (!NtOpenKey( &hkey, KEY_ALL_ACCESS, &attr ))
515 {
516 profile_dir = get_reg_value( hkey, profiles_valueW );
517 all_users_dir = get_reg_value( hkey, all_users_valueW );
518 NtClose( hkey );
519 }
520
521 if (profile_dir)
522 {
523 WCHAR *value, *p;
524
525 if (all_users_dir) len = max( len, strlenW(all_users_dir) + 1 );
526 len += strlenW(profile_dir) + 1;
527 value = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
528 strcpyW( value, profile_dir );
529 p = value + strlenW(value);
530 if (p > value && p[-1] != '\\') *p++ = '\\';
531 if (user_name) {
532 strcpyW( p, user_name );
533 SetEnvironmentVariableW( userprofileW, value );
534 }
535 if (all_users_dir)
536 {
537 strcpyW( p, all_users_dir );
538 SetEnvironmentVariableW( allusersW, value );
539 }
540 HeapFree( GetProcessHeap(), 0, value );
541 }
542
543 HeapFree( GetProcessHeap(), 0, all_users_dir );
544 HeapFree( GetProcessHeap(), 0, profile_dir );
545 HeapFree( GetProcessHeap(), 0, user_name );
546 }
547
548 /***********************************************************************
549 * set_library_wargv
550 *
551 * Set the Wine library Unicode argv global variables.
552 */
553 static void set_library_wargv( char **argv )
554 {
555 int argc;
556 char *q;
557 WCHAR *p;
558 WCHAR **wargv;
559 DWORD total = 0;
560
561 for (argc = 0; argv[argc]; argc++)
562 total += MultiByteToWideChar( CP_UNIXCP, 0, argv[argc], -1, NULL, 0 );
563
564 wargv = RtlAllocateHeap( GetProcessHeap(), 0,
565 total * sizeof(WCHAR) + (argc + 1) * sizeof(*wargv) );
566 p = (WCHAR *)(wargv + argc + 1);
567 for (argc = 0; argv[argc]; argc++)
568 {
569 DWORD reslen = MultiByteToWideChar( CP_UNIXCP, 0, argv[argc], -1, p, total );
570 wargv[argc] = p;
571 p += reslen;
572 total -= reslen;
573 }
574 wargv[argc] = NULL;
575
576 /* convert argv back from Unicode since it has to be in the Ansi codepage not the Unix one */
577
578 for (argc = 0; wargv[argc]; argc++)
579 total += WideCharToMultiByte( CP_ACP, 0, wargv[argc], -1, NULL, 0, NULL, NULL );
580
581 argv = RtlAllocateHeap( GetProcessHeap(), 0, total + (argc + 1) * sizeof(*argv) );
582 q = (char *)(argv + argc + 1);
583 for (argc = 0; wargv[argc]; argc++)
584 {
585 DWORD reslen = WideCharToMultiByte( CP_ACP, 0, wargv[argc], -1, q, total, NULL, NULL );
586 argv[argc] = q;
587 q += reslen;
588 total -= reslen;
589 }
590 argv[argc] = NULL;
591
592 __wine_main_argc = argc;
593 __wine_main_argv = argv;
594 __wine_main_wargv = wargv;
595 }
596
597
598 /***********************************************************************
599 * update_library_argv0
600 *
601 * Update the argv[0] global variable with the binary we have found.
602 */
603 static void update_library_argv0( const WCHAR *argv0 )
604 {
605 DWORD len = strlenW( argv0 );
606
607 if (len > strlenW( __wine_main_wargv[0] ))
608 {
609 __wine_main_wargv[0] = RtlAllocateHeap( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) );
610 }
611 strcpyW( __wine_main_wargv[0], argv0 );
612
613 len = WideCharToMultiByte( CP_ACP, 0, argv0, -1, NULL, 0, NULL, NULL );
614 if (len > strlen( __wine_main_argv[0] ) + 1)
615 {
616 __wine_main_argv[0] = RtlAllocateHeap( GetProcessHeap(), 0, len );
617 }
618 WideCharToMultiByte( CP_ACP, 0, argv0, -1, __wine_main_argv[0], len, NULL, NULL );
619 }
620
621
622 /***********************************************************************
623 * build_command_line
624 *
625 * Build the command line of a process from the argv array.
626 *
627 * Note that it does NOT necessarily include the file name.
628 * Sometimes we don't even have any command line options at all.
629 *
630 * We must quote and escape characters so that the argv array can be rebuilt
631 * from the command line:
632 * - spaces and tabs must be quoted
633 * 'a b' -> '"a b"'
634 * - quotes must be escaped
635 * '"' -> '\"'
636 * - if '\'s are followed by a '"', they must be doubled and followed by '\"',
637 * resulting in an odd number of '\' followed by a '"'
638 * '\"' -> '\\\"'
639 * '\\"' -> '\\\\\"'
640 * - '\'s that are not followed by a '"' can be left as is
641 * 'a\b' == 'a\b'
642 * 'a\\b' == 'a\\b'
643 */
644 static BOOL build_command_line( WCHAR **argv )
645 {
646 int len;
647 WCHAR **arg;
648 LPWSTR p;
649 RTL_USER_PROCESS_PARAMETERS* rupp = NtCurrentTeb()->Peb->ProcessParameters;
650
651 if (rupp->CommandLine.Buffer) return TRUE; /* already got it from the server */
652
653 len = 0;
654 for (arg = argv; *arg; arg++)
655 {
656 int has_space,bcount;
657 WCHAR* a;
658
659 has_space=0;
660 bcount=0;
661 a=*arg;
662 if( !*a ) has_space=1;
663 while (*a!='\0') {
664 if (*a=='\\') {
665 bcount++;
666 } else {
667 if (*a==' ' || *a=='\t') {
668 has_space=1;
669 } else if (*a=='"') {
670 /* doubling of '\' preceding a '"',
671 * plus escaping of said '"'
672 */
673 len+=2*bcount+1;
674 }
675 bcount=0;
676 }
677 a++;
678 }
679 len+=(a-*arg)+1 /* for the separating space */;
680 if (has_space)
681 len+=2; /* for the quotes */
682 }
683
684 if (!(rupp->CommandLine.Buffer = RtlAllocateHeap( GetProcessHeap(), 0, len * sizeof(WCHAR))))
685 return FALSE;
686
687 p = rupp->CommandLine.Buffer;
688 rupp->CommandLine.Length = (len - 1) * sizeof(WCHAR);
689 rupp->CommandLine.MaximumLength = len * sizeof(WCHAR);
690 for (arg = argv; *arg; arg++)
691 {
692 int has_space,has_quote;
693 WCHAR* a;
694
695 /* Check for quotes and spaces in this argument */
696 has_space=has_quote=0;
697 a=*arg;
698 if( !*a ) has_space=1;
699 while (*a!='\0') {
700 if (*a==' ' || *a=='\t') {
701 has_space=1;
702 if (has_quote)
703 break;
704 } else if (*a=='"') {
705 has_quote=1;
706 if (has_space)
707 break;
708 }
709 a++;
710 }
711
712 /* Now transfer it to the command line */
713 if (has_space)
714 *p++='"';
715 if (has_quote) {
716 int bcount;
717 WCHAR* a;
718
719 bcount=0;
720 a=*arg;
721 while (*a!='\0') {
722 if (*a=='\\') {
723 *p++=*a;
724 bcount++;
725 } else {
726 if (*a=='"') {
727 int i;
728
729 /* Double all the '\\' preceding this '"', plus one */
730 for (i=0;i<=bcount;i++)
731 *p++='\\';
732 *p++='"';
733 } else {
734 *p++=*a;
735 }
736 bcount=0;
737 }
738 a++;
739 }
740 } else {
741 WCHAR* x = *arg;
742 while ((*p=*x++)) p++;
743 }
744 if (has_space)
745 *p++='"';
746 *p++=' ';
747 }
748 if (p > rupp->CommandLine.Buffer)
749 p--; /* remove last space */
750 *p = '\0';
751
752 return TRUE;
753 }
754
755
756 /***********************************************************************
757 * init_current_directory
758 *
759 * Initialize the current directory from the Unix cwd or the parent info.
760 */
761 static void init_current_directory( CURDIR *cur_dir )
762 {
763 UNICODE_STRING dir_str;
764 char *cwd;
765 int size;
766
767 /* if we received a cur dir from the parent, try this first */
768
769 if (cur_dir->DosPath.Length)
770 {
771 if (RtlSetCurrentDirectory_U( &cur_dir->DosPath ) == STATUS_SUCCESS) goto done;
772 }
773
774 /* now try to get it from the Unix cwd */
775
776 for (size = 256; ; size *= 2)
777 {
778 if (!(cwd = HeapAlloc( GetProcessHeap(), 0, size ))) break;
779 if (getcwd( cwd, size )) break;
780 HeapFree( GetProcessHeap(), 0, cwd );
781 if (errno == ERANGE) continue;
782 cwd = NULL;
783 break;
784 }
785
786 if (cwd)
787 {
788 WCHAR *dirW;
789 int lenW = MultiByteToWideChar( CP_UNIXCP, 0, cwd, -1, NULL, 0 );
790 if ((dirW = HeapAlloc( GetProcessHeap(), 0, lenW * sizeof(WCHAR) )))
791 {
792 MultiByteToWideChar( CP_UNIXCP, 0, cwd, -1, dirW, lenW );
793 RtlInitUnicodeString( &dir_str, dirW );
794 RtlSetCurrentDirectory_U( &dir_str );
795 RtlFreeUnicodeString( &dir_str );
796 }
797 }
798
799 if (!cur_dir->DosPath.Length) /* still not initialized */
800 {
801 MESSAGE("Warning: could not find DOS drive for current working directory '%s', "
802 "starting in the Windows directory.\n", cwd ? cwd : "" );
803 RtlInitUnicodeString( &dir_str, DIR_Windows );
804 RtlSetCurrentDirectory_U( &dir_str );
805 }
806 HeapFree( GetProcessHeap(), 0, cwd );
807
808 done:
809 if (!cur_dir->Handle) chdir("/"); /* change to root directory so as not to lock cdroms */
810 TRACE( "starting in %s %p\n", debugstr_w( cur_dir->DosPath.Buffer ), cur_dir->Handle );
811 }
812
813
814 /***********************************************************************
815 * init_windows_dirs
816 *
817 * Initialize the windows and system directories from the environment.
818 */
819 static void init_windows_dirs(void)
820 {
821 extern void CDECL __wine_init_windows_dir( const WCHAR *windir, const WCHAR *sysdir );
822
823 static const WCHAR windirW[] = {'w','i','n','d','i','r',0};
824 static const WCHAR winsysdirW[] = {'w','i','n','s','y','s','d','i','r',0};
825 static const WCHAR default_windirW[] = {'C',':','\\','w','i','n','d','o','w','s',0};
826 static const WCHAR default_sysdirW[] = {'\\','s','y','s','t','e','m','3','2',0};
827 static const WCHAR default_syswow64W[] = {'\\','s','y','s','w','o','w','6','4',0};
828
829 DWORD len;
830 WCHAR *buffer;
831
832 if ((len = GetEnvironmentVariableW( windirW, NULL, 0 )))
833 {
834 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
835 GetEnvironmentVariableW( windirW, buffer, len );
836 DIR_Windows = buffer;
837 }
838 else DIR_Windows = default_windirW;
839
840 if ((len = GetEnvironmentVariableW( winsysdirW, NULL, 0 )))
841 {
842 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
843 GetEnvironmentVariableW( winsysdirW, buffer, len );
844 DIR_System = buffer;
845 }
846 else
847 {
848 len = strlenW( DIR_Windows );
849 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) + sizeof(default_sysdirW) );
850 memcpy( buffer, DIR_Windows, len * sizeof(WCHAR) );
851 memcpy( buffer + len, default_sysdirW, sizeof(default_sysdirW) );
852 DIR_System = buffer;
853 }
854
855 #ifndef _WIN64 /* SysWow64 is always defined on 64-bit */
856 if (is_wow64)
857 #endif
858 {
859 len = strlenW( DIR_Windows );
860 buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) + sizeof(default_syswow64W) );
861 memcpy( buffer, DIR_Windows, len * sizeof(WCHAR) );
862 memcpy( buffer + len, default_syswow64W, sizeof(default_syswow64W) );
863 DIR_SysWow64 = buffer;
864 }
865
866 if (!CreateDirectoryW( DIR_Windows, NULL ) && GetLastError() != ERROR_ALREADY_EXISTS)
867 ERR( "directory %s could not be created, error %u\n",
868 debugstr_w(DIR_Windows), GetLastError() );
869 if (!CreateDirectoryW( DIR_System, NULL ) && GetLastError() != ERROR_ALREADY_EXISTS)
870 ERR( "directory %s could not be created, error %u\n",
871 debugstr_w(DIR_System), GetLastError() );
872
873 TRACE_(file)( "WindowsDir = %s\n", debugstr_w(DIR_Windows) );
874 TRACE_(file)( "SystemDir = %s\n", debugstr_w(DIR_System) );
875
876 /* set the directories in ntdll too */
877 __wine_init_windows_dir( DIR_Windows, DIR_System );
878 }
879
880
881 /***********************************************************************
882 * start_wineboot
883 *
884 * Start the wineboot process if necessary. Return the event to wait on.
885 */
886 static HANDLE start_wineboot(void)
887 {
888 static const WCHAR wineboot_eventW[] = {'_','_','w','i','n','e','b','o','o','t','_','e','v','e','n','t',0};
889 HANDLE event;
890
891 if (!(event = CreateEventW( NULL, TRUE, FALSE, wineboot_eventW )))
892 {
893 ERR( "failed to create wineboot event, expect trouble\n" );
894 return 0;
895 }
896 if (GetLastError() != ERROR_ALREADY_EXISTS) /* we created it */
897 {
898 static const WCHAR command_line[] = {'\\','w','i','n','e','b','o','o','t','.','e','x','e',' ','-','-','i','n','i','t',0};
899 STARTUPINFOW si;
900 PROCESS_INFORMATION pi;
901 WCHAR cmdline[MAX_PATH + sizeof(command_line)/sizeof(WCHAR)];
902
903 memset( &si, 0, sizeof(si) );
904 si.cb = sizeof(si);
905 si.dwFlags = STARTF_USESTDHANDLES;
906 si.hStdInput = 0;
907 si.hStdOutput = 0;
908 si.hStdError = GetStdHandle( STD_ERROR_HANDLE );
909
910 GetSystemDirectoryW( cmdline, MAX_PATH );
911 lstrcatW( cmdline, command_line );
912 if (CreateProcessW( NULL, cmdline, NULL, NULL, FALSE, DETACHED_PROCESS, NULL, NULL, &si, &pi ))
913 {
914 TRACE( "started wineboot pid %04x tid %04x\n", pi.dwProcessId, pi.dwThreadId );
915 CloseHandle( pi.hThread );
916 CloseHandle( pi.hProcess );
917
918 }
919 else ERR( "failed to start wineboot, err %u\n", GetLastError() );
920 }
921 return event;
922 }
923
924
925 /***********************************************************************
926 * start_process
927 *
928 * Startup routine of a new process. Runs on the new process stack.
929 */
930 static void start_process( void *arg )
931 {
932 __TRY
933 {
934 PEB *peb = NtCurrentTeb()->Peb;
935 IMAGE_NT_HEADERS *nt;
936 LPTHREAD_START_ROUTINE entry;
937
938 nt = RtlImageNtHeader( peb->ImageBaseAddress );
939 entry = (LPTHREAD_START_ROUTINE)((char *)peb->ImageBaseAddress +
940 nt->OptionalHeader.AddressOfEntryPoint);
941
942 if (!nt->OptionalHeader.AddressOfEntryPoint)
943 {
944 ERR( "%s doesn't have an entry point, it cannot be executed\n",
945 debugstr_w(peb->ProcessParameters->ImagePathName.Buffer) );
946 ExitThread( 1 );
947 }
948
949 if (TRACE_ON(relay))
950 DPRINTF( "%04x:Starting process %s (entryproc=%p)\n", GetCurrentThreadId(),
951 debugstr_w(peb->ProcessParameters->ImagePathName.Buffer), entry );
952
953 SetLastError( 0 ); /* clear error code */
954 if (peb->BeingDebugged) DbgBreakPoint();
955 ExitThread( entry( peb ) );
956 }
957 __EXCEPT(UnhandledExceptionFilter)
958 {
959 TerminateThread( GetCurrentThread(), GetExceptionCode() );
960 }
961 __ENDTRY
962 }
963
964
965 /***********************************************************************
966 * set_process_name
967 *
968 * Change the process name in the ps output.
969 */
970 static void set_process_name( int argc, char *argv[] )
971 {
972 #ifdef HAVE_SETPROCTITLE
973 setproctitle("-%s", argv[1]);
974 #endif
975
976 #ifdef HAVE_PRCTL
977 int i, offset;
978 char *p, *prctl_name = argv[1];
979 char *end = argv[argc-1] + strlen(argv[argc-1]) + 1;
980
981 #ifndef PR_SET_NAME
982 # define PR_SET_NAME 15
983 #endif
984
985 if ((p = strrchr( prctl_name, '\\' ))) prctl_name = p + 1;
986 if ((p = strrchr( prctl_name, '/' ))) prctl_name = p + 1;
987
988 if (prctl( PR_SET_NAME, prctl_name ) != -1)
989 {
990 offset = argv[1] - argv[0];
991 memmove( argv[1] - offset, argv[1], end - argv[1] );
992 memset( end - offset, 0, offset );
993 for (i = 1; i < argc; i++) argv[i-1] = argv[i] - offset;
994 argv[i-1] = NULL;
995 }
996 else
997 #endif /* HAVE_PRCTL */
998 {
999 /* remove argv[0] */
1000 memmove( argv, argv + 1, argc * sizeof(argv[0]) );
1001 }
1002 }
1003
1004
1005 /***********************************************************************
1006 * __wine_kernel_init
1007 *
1008 * Wine initialisation: load and start the main exe file.
1009 */
1010 void CDECL __wine_kernel_init(void)
1011 {
1012 static const WCHAR kernel32W[] = {'k','e','r','n','e','l','3','2',0};
1013 static const WCHAR dotW[] = {'.',0};
1014 static const WCHAR exeW[] = {'.','e','x','e',0};
1015
1016 WCHAR *p, main_exe_name[MAX_PATH+1];
1017 PEB *peb = NtCurrentTeb()->Peb;
1018 RTL_USER_PROCESS_PARAMETERS *params = peb->ProcessParameters;
1019 HANDLE boot_event = 0;
1020 BOOL got_environment = TRUE;
1021
1022 /* Initialize everything */
1023
1024 setbuf(stdout,NULL);
1025 setbuf(stderr,NULL);
1026 kernel32_handle = GetModuleHandleW(kernel32W);
1027 IsWow64Process( GetCurrentProcess(), &is_wow64 );
1028
1029 LOCALE_Init();
1030
1031 if (!params->Environment)
1032 {
1033 /* Copy the parent environment */
1034 if (!build_initial_environment()) exit(1);
1035
1036 /* convert old configuration to new format */
1037 convert_old_config();
1038
1039 got_environment = set_registry_environment();
1040 set_additional_environment();
1041 }
1042
1043 init_windows_dirs();
1044 init_current_directory( ¶ms->CurrentDirectory );
1045
1046 set_process_name( __wine_main_argc, __wine_main_argv );
1047 set_library_wargv( __wine_main_argv );
1048
1049 if (peb->ProcessParameters->ImagePathName.Buffer)
1050 {
1051 strcpyW( main_exe_name, peb->ProcessParameters->ImagePathName.Buffer );
1052 }
1053 else
1054 {
1055 if (!SearchPathW( NULL, __wine_main_wargv[0], exeW, MAX_PATH, main_exe_name, NULL ) &&
1056 !get_builtin_path( __wine_main_wargv[0], exeW, main_exe_name, MAX_PATH ))
1057 {
1058 MESSAGE( "wine: cannot find '%s'\n", __wine_main_argv[0] );
1059 ExitProcess( GetLastError() );
1060 }
1061 update_library_argv0( main_exe_name );
1062 if (!build_command_line( __wine_main_wargv )) goto error;
1063 boot_event = start_wineboot();
1064 }
1065
1066 /* if there's no extension, append a dot to prevent LoadLibrary from appending .dll */
1067 p = strrchrW( main_exe_name, '.' );
1068 if (!p || strchrW( p, '/' ) || strchrW( p, '\\' )) strcatW( main_exe_name, dotW );
1069
1070 TRACE( "starting process name=%s argv[0]=%s\n",
1071 debugstr_w(main_exe_name), debugstr_w(__wine_main_wargv[0]) );
1072
1073 RtlInitUnicodeString( &NtCurrentTeb()->Peb->ProcessParameters->DllPath,
1074 MODULE_get_dll_load_path(main_exe_name) );
1075
1076 if (boot_event)
1077 {
1078 if (WaitForSingleObject( boot_event, 30000 )) ERR( "boot event wait timed out\n" );
1079 CloseHandle( boot_event );
1080 /* if we didn't find environment section, try again now that wineboot has run */
1081 if (!got_environment)
1082 {
1083 set_registry_environment();
1084 set_additional_environment();
1085 }
1086 }
1087
1088 if (!(peb->ImageBaseAddress = LoadLibraryExW( main_exe_name, 0, DONT_RESOLVE_DLL_REFERENCES )))
1089 {
1090 char msg[1024];
1091 DWORD error = GetLastError();
1092
1093 /* if Win16/DOS format, or unavailable address, exec a new process with the proper setup */
1094 if (error == ERROR_BAD_EXE_FORMAT ||
1095 error == ERROR_INVALID_ADDRESS ||
1096 error == ERROR_NOT_ENOUGH_MEMORY)
1097 {
1098 if (!getenv("WINEPRELOADRESERVE")) exec_process( main_exe_name );
1099 /* if we get back here, it failed */
1100 }
1101 else if (error == ERROR_MOD_NOT_FOUND)
1102 {
1103 if ((p = strrchrW( main_exe_name, '\\' ))) p++;
1104 else p = main_exe_name;
1105 if (!strcmpiW( p, winevdmW ) && __wine_main_argc > 3)
1106 {
1107 /* args 1 and 2 are --app-name full_path */
1108 MESSAGE( "wine: could not run %s: 16-bit/DOS support missing\n",
1109 debugstr_w(__wine_main_wargv[3]) );
1110 ExitProcess( ERROR_BAD_EXE_FORMAT );
1111 }
1112 }
1113 FormatMessageA( FORMAT_MESSAGE_FROM_SYSTEM, NULL, error, 0, msg, sizeof(msg), NULL );
1114 MESSAGE( "wine: could not load %s: %s", debugstr_w(main_exe_name), msg );
1115 ExitProcess( error );
1116 }
1117
1118 LdrInitializeThunk( 0, 0, 0, 0 );
1119 /* switch to the new stack */
1120 wine_switch_to_stack( start_process, NULL, NtCurrentTeb()->Tib.StackBase );
1121
1122 error:
1123 ExitProcess( GetLastError() );
1124 }
1125
1126
1127 /***********************************************************************
1128 * build_argv
1129 *
1130 * Build an argv array from a command-line.
1131 * 'reserved' is the number of args to reserve before the first one.
1132 */
1133 static char **build_argv( const WCHAR *cmdlineW, int reserved )
1134 {
1135 int argc;
1136 char** argv;
1137 char *arg,*s,*d,*cmdline;
1138 int in_quotes,bcount,len;
1139
1140 len = WideCharToMultiByte( CP_UNIXCP, 0, cmdlineW, -1, NULL, 0, NULL, NULL );
1141 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, len ))) return NULL;
1142 WideCharToMultiByte( CP_UNIXCP, 0, cmdlineW, -1, cmdline, len, NULL, NULL );
1143
1144 argc=reserved+1;
1145 bcount=0;
1146 in_quotes=0;
1147 s=cmdline;
1148 while (1) {
1149 if (*s=='\0' || ((*s==' ' || *s=='\t') && !in_quotes)) {
1150 /* space */
1151 argc++;
1152 /* skip the remaining spaces */
1153 while (*s==' ' || *s=='\t') {
1154 s++;
1155 }
1156 if (*s=='\0')
1157 break;
1158 bcount=0;
1159 continue;
1160 } else if (*s=='\\') {
1161 /* '\', count them */
1162 bcount++;
1163 } else if ((*s=='"') && ((bcount & 1)==0)) {
1164 /* unescaped '"' */
1165 in_quotes=!in_quotes;
1166 bcount=0;
1167 } else {
1168 /* a regular character */
1169 bcount=0;
1170 }
1171 s++;
1172 }
1173 if (!(argv = HeapAlloc( GetProcessHeap(), 0, argc*sizeof(*argv) + len )))
1174 {
1175 HeapFree( GetProcessHeap(), 0, cmdline );
1176 return NULL;
1177 }
1178
1179 arg = d = s = (char *)(argv + argc);
1180 memcpy( d, cmdline, len );
1181 bcount=0;
1182 in_quotes=0;
1183 argc=reserved;
1184 while (*s) {
1185 if ((*s==' ' || *s=='\t') && !in_quotes) {
1186 /* Close the argument and copy it */
1187 *d=0;
1188 argv[argc++]=arg;
1189
1190 /* skip the remaining spaces */
1191 do {
1192 s++;
1193 } while (*s==' ' || *s=='\t');
1194
1195 /* Start with a new argument */
1196 arg=d=s;
1197 bcount=0;
1198 } else if (*s=='\\') {
1199 /* '\\' */
1200 *d++=*s++;
1201 bcount++;
1202 } else if (*s=='"') {
1203 /* '"' */
1204 if ((bcount & 1)==0) {
1205 /* Preceded by an even number of '\', this is half that
1206 * number of '\', plus a '"' which we discard.
1207 */
1208 d-=bcount/2;
1209 s++;
1210 in_quotes=!in_quotes;
1211 } else {
1212 /* Preceded by an odd number of '\', this is half that
1213 * number of '\' followed by a '"'
1214 */
1215 d=d-bcount/2-1;
1216 *d++='"';
1217 s++;
1218 }
1219 bcount=0;
1220 } else {
1221 /* a regular character */
1222 *d++=*s++;
1223 bcount=0;
1224 }
1225 }
1226 if (*arg) {
1227 *d='\0';
1228 argv[argc++]=arg;
1229 }
1230 argv[argc]=NULL;
1231
1232 HeapFree( GetProcessHeap(), 0, cmdline );
1233 return argv;
1234 }
1235
1236
1237 /***********************************************************************
1238 * build_envp
1239 *
1240 * Build the environment of a new child process.
1241 */
1242 static char **build_envp( const WCHAR *envW )
1243 {
1244 static const char * const unix_vars[] = { "PATH", "TEMP", "TMP", "HOME" };
1245
1246 const WCHAR *end;
1247 char **envp;
1248 char *env, *p;
1249 int count = 1, length;
1250 unsigned int i;
1251
1252 for (end = envW; *end; count++) end += strlenW(end) + 1;
1253 end++;
1254 length = WideCharToMultiByte( CP_UNIXCP, 0, envW, end - envW, NULL, 0, NULL, NULL );
1255 if (!(env = HeapAlloc( GetProcessHeap(), 0, length ))) return NULL;
1256 WideCharToMultiByte( CP_UNIXCP, 0, envW, end - envW, env, length, NULL, NULL );
1257
1258 for (p = env; *p; p += strlen(p) + 1)
1259 if (is_special_env_var( p )) length += 4; /* prefix it with "WINE" */
1260
1261 for (i = 0; i < sizeof(unix_vars)/sizeof(unix_vars[0]); i++)
1262 {
1263 if (!(p = getenv(unix_vars[i]))) continue;
1264 length += strlen(unix_vars[i]) + strlen(p) + 2;
1265 count++;
1266 }
1267
1268 if ((envp = HeapAlloc( GetProcessHeap(), 0, count * sizeof(*envp) + length )))
1269 {
1270 char **envptr = envp;
1271 char *dst = (char *)(envp + count);
1272
1273 /* some variables must not be modified, so we get them directly from the unix env */
1274 for (i = 0; i < sizeof(unix_vars)/sizeof(unix_vars[0]); i++)
1275 {
1276 if (!(p = getenv(unix_vars[i]))) continue;
1277 *envptr++ = strcpy( dst, unix_vars[i] );
1278 strcat( dst, "=" );
1279 strcat( dst, p );
1280 dst += strlen(dst) + 1;
1281 }
1282
1283 /* now put the Windows environment strings */
1284 for (p = env; *p; p += strlen(p) + 1)
1285 {
1286 if (*p == '=') continue; /* skip drive curdirs, this crashes some unix apps */
1287 if (!strncmp( p, "WINEPRELOADRESERVE=", sizeof("WINEPRELOADRESERVE=")-1 )) continue;
1288 if (!strncmp( p, "WINELOADERNOEXEC=", sizeof("WINELOADERNOEXEC=")-1 )) continue;
1289 if (!strncmp( p, "WINESERVERSOCKET=", sizeof("WINESERVERSOCKET=")-1 )) continue;
1290 if (is_special_env_var( p )) /* prefix it with "WINE" */
1291 {
1292 *envptr++ = strcpy( dst, "WINE" );
1293 strcat( dst, p );
1294 }
1295 else
1296 {
1297 *envptr++ = strcpy( dst, p );
1298 }
1299 dst += strlen(dst) + 1;
1300 }
1301 *envptr = 0;
1302 }
1303 HeapFree( GetProcessHeap(), 0, env );
1304 return envp;
1305 }
1306
1307
1308 /***********************************************************************
1309 * fork_and_exec
1310 *
1311 * Fork and exec a new Unix binary, checking for errors.
1312 */
1313 static int fork_and_exec( const char *filename, const WCHAR *cmdline, const WCHAR *env,
1314 const char *newdir, DWORD flags, STARTUPINFOW *startup )
1315 {
1316 int fd[2], stdin_fd = -1, stdout_fd = -1;
1317 int pid, err;
1318 char **argv, **envp;
1319
1320 if (!env) env = GetEnvironmentStringsW();
1321
1322 #ifdef HAVE_PIPE2
1323 if (pipe2( fd, O_CLOEXEC ) == -1)
1324 #endif
1325 {
1326 if (pipe(fd) == -1)
1327 {
1328 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
1329 return -1;
1330 }
1331 fcntl( fd[0], F_SETFD, FD_CLOEXEC );
1332 fcntl( fd[1], F_SETFD, FD_CLOEXEC );
1333 }
1334
1335 if (!(flags & (CREATE_NEW_PROCESS_GROUP | CREATE_NEW_CONSOLE | DETACHED_PROCESS)))
1336 {
1337 HANDLE hstdin, hstdout;
1338
1339 if (startup->dwFlags & STARTF_USESTDHANDLES)
1340 {
1341 hstdin = startup->hStdInput;
1342 hstdout = startup->hStdOutput;
1343 }
1344 else
1345 {
1346 hstdin = GetStdHandle(STD_INPUT_HANDLE);
1347 hstdout = GetStdHandle(STD_OUTPUT_HANDLE);
1348 }
1349
1350 if (is_console_handle( hstdin ))
1351 hstdin = wine_server_ptr_handle( console_handle_unmap( hstdin ));
1352 if (is_console_handle( hstdout ))
1353 hstdout = wine_server_ptr_handle( console_handle_unmap( hstdout ));
1354 wine_server_handle_to_fd( hstdin, FILE_READ_DATA, &stdin_fd, NULL );
1355 wine_server_handle_to_fd( hstdout, FILE_WRITE_DATA, &stdout_fd, NULL );
1356 }
1357
1358 argv = build_argv( cmdline, 0 );
1359 envp = build_envp( env );
1360
1361 if (!(pid = fork())) /* child */
1362 {
1363 close( fd[0] );
1364
1365 if (flags & (CREATE_NEW_PROCESS_GROUP | CREATE_NEW_CONSOLE | DETACHED_PROCESS))
1366 {
1367 int pid;
1368 if (!(pid = fork()))
1369 {
1370 int fd = open( "/dev/null", O_RDWR );
1371 setsid();
1372 /* close stdin and stdout */
1373 if (fd != -1)
1374 {
1375 dup2( fd, 0 );
1376 dup2( fd, 1 );
1377 close( fd );
1378 }
1379 }
1380 else if (pid != -1) _exit(0); /* parent */
1381 }
1382 else
1383 {
1384 if (stdin_fd != -1)
1385 {
1386 dup2( stdin_fd, 0 );
1387 close( stdin_fd );
1388 }
1389 if (stdout_fd != -1)
1390 {
1391 dup2( stdout_fd, 1 );
1392 close( stdout_fd );
1393 }
1394 }
1395
1396 /* Reset signals that we previously set to SIG_IGN */
1397 signal( SIGPIPE, SIG_DFL );
1398 signal( SIGCHLD, SIG_DFL );
1399
1400 if (newdir) chdir(newdir);
1401
1402 if (argv && envp) execve( filename, argv, envp );
1403 err = errno;
1404 write( fd[1], &err, sizeof(err) );
1405 _exit(1);
1406 }
1407 HeapFree( GetProcessHeap(), 0, argv );
1408 HeapFree( GetProcessHeap(), 0, envp );
1409 if (stdin_fd != -1) close( stdin_fd );
1410 if (stdout_fd != -1) close( stdout_fd );
1411 close( fd[1] );
1412 if ((pid != -1) && (read( fd[0], &err, sizeof(err) ) > 0)) /* exec failed */
1413 {
1414 errno = err;
1415 pid = -1;
1416 }
1417 if (pid == -1) FILE_SetDosError();
1418 close( fd[0] );
1419 return pid;
1420 }
1421
1422
1423 /***********************************************************************
1424 * create_user_params
1425 */
1426 static RTL_USER_PROCESS_PARAMETERS *create_user_params( LPCWSTR filename, LPCWSTR cmdline,
1427 LPCWSTR cur_dir, LPWSTR env, DWORD flags,
1428 const STARTUPINFOW *startup )
1429 {
1430 RTL_USER_PROCESS_PARAMETERS *params;
1431 UNICODE_STRING image_str, cmdline_str, curdir_str, desktop, title, runtime, newdir;
1432 NTSTATUS status;
1433 WCHAR buffer[MAX_PATH];
1434
1435 if(!GetLongPathNameW( filename, buffer, MAX_PATH ))
1436 lstrcpynW( buffer, filename, MAX_PATH );
1437 if(!GetFullPathNameW( buffer, MAX_PATH, buffer, NULL ))
1438 lstrcpynW( buffer, filename, MAX_PATH );
1439 RtlInitUnicodeString( &image_str, buffer );
1440
1441 RtlInitUnicodeString( &cmdline_str, cmdline );
1442 newdir.Buffer = NULL;
1443 if (cur_dir)
1444 {
1445 if (RtlDosPathNameToNtPathName_U( cur_dir, &newdir, NULL, NULL ))
1446 {
1447 /* skip \??\ prefix */
1448 curdir_str.Buffer = newdir.Buffer + 4;
1449 curdir_str.Length = newdir.Length - 4 * sizeof(WCHAR);
1450 curdir_str.MaximumLength = newdir.MaximumLength - 4 * sizeof(WCHAR);
1451 }
1452 else cur_dir = NULL;
1453 }
1454 if (startup->lpDesktop) RtlInitUnicodeString( &desktop, startup->lpDesktop );
1455 if (startup->lpTitle) RtlInitUnicodeString( &title, startup->lpTitle );
1456 if (startup->lpReserved2 && startup->cbReserved2)
1457 {
1458 runtime.Length = 0;
1459 runtime.MaximumLength = startup->cbReserved2;
1460 runtime.Buffer = (WCHAR*)startup->lpReserved2;
1461 }
1462
1463 status = RtlCreateProcessParameters( ¶ms, &image_str, NULL,
1464 cur_dir ? &curdir_str : NULL,
1465 &cmdline_str, env,
1466 startup->lpTitle ? &title : NULL,
1467 startup->lpDesktop ? &desktop : NULL,
1468 NULL,
1469 (startup->lpReserved2 && startup->cbReserved2) ? &runtime : NULL );
1470 RtlFreeUnicodeString( &newdir );
1471 if (status != STATUS_SUCCESS)
1472 {
1473 SetLastError( RtlNtStatusToDosError(status) );
1474 return NULL;
1475 }
1476
1477 if (flags & CREATE_NEW_PROCESS_GROUP) params->ConsoleFlags = 1;
1478 if (flags & CREATE_NEW_CONSOLE) params->ConsoleHandle = (HANDLE)1; /* FIXME: cf. kernel_main.c */
1479
1480 if (startup->dwFlags & STARTF_USESTDHANDLES)
1481 {
1482 params->hStdInput = startup->hStdInput;
1483 params->hStdOutput = startup->hStdOutput;
1484 params->hStdError = startup->hStdError;
1485 }
1486 else
1487 {
1488 params->hStdInput = GetStdHandle( STD_INPUT_HANDLE );
1489 params->hStdOutput = GetStdHandle( STD_OUTPUT_HANDLE );
1490 params->hStdError = GetStdHandle( STD_ERROR_HANDLE );
1491 }
1492 params->dwX = startup->dwX;
1493 params->dwY = startup->dwY;
1494 params->dwXSize = startup->dwXSize;
1495 params->dwYSize = startup->dwYSize;
1496 params->dwXCountChars = startup->dwXCountChars;
1497 params->dwYCountChars = startup->dwYCountChars;
1498 params->dwFillAttribute = startup->dwFillAttribute;
1499 params->dwFlags = startup->dwFlags;
1500 params->wShowWindow = startup->wShowWindow;
1501 return params;
1502 }
1503
1504
1505 /***********************************************************************
1506 * create_process
1507 *
1508 * Create a new process. If hFile is a valid handle we have an exe
1509 * file, otherwise it is a Winelib app.
1510 */
1511 static BOOL create_process( HANDLE hFile, LPCWSTR filename, LPWSTR cmd_line, LPWSTR env,
1512 LPCWSTR cur_dir, LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1513 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
1514 LPPROCESS_INFORMATION info, LPCSTR unixdir,
1515 void *res_start, void *res_end, int exec_only )
1516 {
1517 BOOL ret, success = FALSE;
1518 HANDLE process_info, hstdin, hstdout;
1519 WCHAR *env_end;
1520 char *winedebug = NULL;
1521 char **argv;
1522 RTL_USER_PROCESS_PARAMETERS *params;
1523 int socketfd[2], stdin_fd = -1, stdout_fd = -1;
1524 pid_t pid;
1525 int err;
1526
1527 if (!env) RtlAcquirePebLock();
1528
1529 if (!(params = create_user_params( filename, cmd_line, cur_dir, env, flags, startup )))
1530 {
1531 if (!env) RtlReleasePebLock();
1532 return FALSE;
1533 }
1534 env_end = params->Environment;
1535 while (*env_end)
1536 {
1537 static const WCHAR WINEDEBUG[] = {'W','I','N','E','D','E','B','U','G','=',0};
1538 if (!winedebug && !strncmpW( env_end, WINEDEBUG, sizeof(WINEDEBUG)/sizeof(WCHAR) - 1 ))
1539 {
1540 DWORD len = WideCharToMultiByte( CP_UNIXCP, 0, env_end, -1, NULL, 0, NULL, NULL );
1541 if ((winedebug = HeapAlloc( GetProcessHeap(), 0, len )))
1542 WideCharToMultiByte( CP_UNIXCP, 0, env_end, -1, winedebug, len, NULL, NULL );
1543 }
1544 env_end += strlenW(env_end) + 1;
1545 }
1546 env_end++;
1547
1548 /* create the socket for the new process */
1549
1550 if (socketpair( PF_UNIX, SOCK_STREAM, 0, socketfd ) == -1)
1551 {
1552 if (!env) RtlReleasePebLock();
1553 HeapFree( GetProcessHeap(), 0, winedebug );
1554 RtlDestroyProcessParameters( params );
1555 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
1556 return FALSE;
1557 }
1558 wine_server_send_fd( socketfd[1] );
1559 close( socketfd[1] );
1560
1561 /* create the process on the server side */
1562
1563 SERVER_START_REQ( new_process )
1564 {
1565 req->inherit_all = inherit;
1566 req->create_flags = flags;
1567 req->socket_fd = socketfd[1];
1568 req->exe_file = wine_server_obj_handle( hFile );
1569 req->process_access = PROCESS_ALL_ACCESS;
1570 req->process_attr = (psa && (psa->nLength >= sizeof(*psa)) && psa->bInheritHandle) ? OBJ_INHERIT : 0;
1571 req->thread_access = THREAD_ALL_ACCESS;
1572 req->thread_attr = (tsa && (tsa->nLength >= sizeof(*tsa)) && tsa->bInheritHandle) ? OBJ_INHERIT : 0;
1573 req->hstdin = wine_server_obj_handle( params->hStdInput );
1574 req->hstdout = wine_server_obj_handle( params->hStdOutput );
1575 req->hstderr = wine_server_obj_handle( params->hStdError );
1576
1577 if ((flags & (CREATE_NEW_CONSOLE | DETACHED_PROCESS)) != 0)
1578 {
1579 /* this is temporary (for console handles). We have no way to control that the handle is invalid in child process otherwise */
1580 if (is_console_handle(params->hStdInput)) req->hstdin = wine_server_obj_handle( INVALID_HANDLE_VALUE );
1581 if (is_console_handle(params->hStdOutput)) req->hstdout = wine_server_obj_handle( INVALID_HANDLE_VALUE );
1582 if (is_console_handle(params->hStdError)) req->hstderr = wine_server_obj_handle( INVALID_HANDLE_VALUE );
1583 hstdin = hstdout = 0;
1584 }
1585 else
1586 {
1587 if (is_console_handle(params->hStdInput)) req->hstdin = console_handle_unmap(params->hStdInput);
1588 if (is_console_handle(params->hStdOutput)) req->hstdout = console_handle_unmap(params->hStdOutput);
1589 if (is_console_handle(params->hStdError)) req->hstderr = console_handle_unmap(params->hStdError);
1590 hstdin = wine_server_ptr_handle( req->hstdin );
1591 hstdout = wine_server_ptr_handle( req->hstdout );
1592 }
1593
1594 wine_server_add_data( req, params, params->Size );
1595 wine_server_add_data( req, params->Environment, (env_end-params->Environment)*sizeof(WCHAR) );
1596 if ((ret = !wine_server_call_err( req )))
1597 {
1598 info->dwProcessId = (DWORD)reply->pid;
1599 info->dwThreadId = (DWORD)reply->tid;
1600 info->hProcess = wine_server_ptr_handle( reply->phandle );
1601 info->hThread = wine_server_ptr_handle( reply->thandle );
1602 }
1603 process_info = wine_server_ptr_handle( reply->info );
1604 }
1605 SERVER_END_REQ;
1606
1607 if (!env) RtlReleasePebLock();
1608 RtlDestroyProcessParameters( params );
1609 if (!ret)
1610 {
1611 close( socketfd[0] );
1612 HeapFree( GetProcessHeap(), 0, winedebug );
1613 return FALSE;
1614 }
1615
1616 if (hstdin) wine_server_handle_to_fd( hstdin, FILE_READ_DATA, &stdin_fd, NULL );
1617 if (hstdout) wine_server_handle_to_fd( hstdout, FILE_WRITE_DATA, &stdout_fd, NULL );
1618
1619 /* create the child process */
1620 argv = build_argv( cmd_line, 1 );
1621
1622 if (exec_only || !(pid = fork())) /* child */
1623 {
1624 char preloader_reserve[64], socket_env[64];
1625
1626 if (flags & (CREATE_NEW_PROCESS_GROUP | CREATE_NEW_CONSOLE | DETACHED_PROCESS))
1627 {
1628 if (!(pid = fork()))
1629 {
1630 int fd = open( "/dev/null", O_RDWR );
1631 setsid();
1632 /* close stdin and stdout */
1633 if (fd != -1)
1634 {
1635 dup2( fd, 0 );
1636 dup2( fd, 1 );
1637 close( fd );
1638 }
1639 }
1640 else if (pid != -1) _exit(0); /* parent */
1641 }
1642 else
1643 {
1644 if (stdin_fd != -1) dup2( stdin_fd, 0 );
1645 if (stdout_fd != -1) dup2( stdout_fd, 1 );
1646 }
1647
1648 if (stdin_fd != -1) close( stdin_fd );
1649 if (stdout_fd != -1) close( stdout_fd );
1650
1651 /* Reset signals that we previously set to SIG_IGN */
1652 signal( SIGPIPE, SIG_DFL );
1653 signal( SIGCHLD, SIG_DFL );
1654
1655 sprintf( socket_env, "WINESERVERSOCKET=%u", socketfd[0] );
1656 sprintf( preloader_reserve, "WINEPRELOADRESERVE=%lx-%lx",
1657 (unsigned long)res_start, (unsigned long)res_end );
1658
1659 putenv( preloader_reserve );
1660 putenv( socket_env );
1661 if (winedebug) putenv( winedebug );
1662 if (unixdir) chdir(unixdir);
1663
1664 if (argv) wine_exec_wine_binary( NULL, argv, getenv("WINELOADER") );
1665 _exit(1);
1666 }
1667
1668 /* this is the parent */
1669
1670 if (stdin_fd != -1) close( stdin_fd );
1671 if (stdout_fd != -1) close( stdout_fd );
1672 close( socketfd[0] );
1673 HeapFree( GetProcessHeap(), 0, argv );
1674 HeapFree( GetProcessHeap(), 0, winedebug );
1675 if (pid == -1)
1676 {
1677 FILE_SetDosError();
1678 goto error;
1679 }
1680
1681 /* wait for the new process info to be ready */
1682
1683 WaitForSingleObject( process_info, INFINITE );
1684 SERVER_START_REQ( get_new_process_info )
1685 {
1686 req->info = wine_server_obj_handle( process_info );
1687 wine_server_call( req );
1688 success = reply->success;
1689 err = reply->exit_code;
1690 }
1691 SERVER_END_REQ;
1692
1693 if (!success)
1694 {
1695 SetLastError( err ? err : ERROR_INTERNAL_ERROR );
1696 goto error;
1697 }
1698 CloseHandle( process_info );
1699 return success;
1700
1701 error:
1702 CloseHandle( process_info );
1703 CloseHandle( info->hProcess );
1704 CloseHandle( info->hThread );
1705 info->hProcess = info->hThread = 0;
1706 info->dwProcessId = info->dwThreadId = 0;
1707 return FALSE;
1708 }
1709
1710
1711 /***********************************************************************
1712 * create_vdm_process
1713 *
1714 * Create a new VDM process for a 16-bit or DOS application.
1715 */
1716 static BOOL create_vdm_process( LPCWSTR filename, LPWSTR cmd_line, LPWSTR env, LPCWSTR cur_dir,
1717 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1718 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
1719 LPPROCESS_INFORMATION info, LPCSTR unixdir, int exec_only )
1720 {
1721 static const WCHAR argsW[] = {'%','s',' ','-','-','a','p','p','-','n','a','m','e',' ','"','%','s','"',' ','%','s',0};
1722
1723 BOOL ret;
1724 LPWSTR new_cmd_line = HeapAlloc( GetProcessHeap(), 0,
1725 (strlenW(filename) + strlenW(cmd_line) + 30) * sizeof(WCHAR) );
1726
1727 if (!new_cmd_line)
1728 {
1729 SetLastError( ERROR_OUTOFMEMORY );
1730 return FALSE;
1731 }
1732 sprintfW( new_cmd_line, argsW, winevdmW, filename, cmd_line );
1733 ret = create_process( 0, winevdmW, new_cmd_line, env, cur_dir, psa, tsa, inherit,
1734 flags, startup, info, unixdir, NULL, NULL, exec_only );
1735 HeapFree( GetProcessHeap(), 0, new_cmd_line );
1736 return ret;
1737 }
1738
1739
1740 /***********************************************************************
1741 * create_cmd_process
1742 *
1743 * Create a new cmd shell process for a .BAT file.
1744 */
1745 static BOOL create_cmd_process( LPCWSTR filename, LPWSTR cmd_line, LPVOID env, LPCWSTR cur_dir,
1746 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1747 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
1748 LPPROCESS_INFORMATION info )
1749
1750 {
1751 static const WCHAR comspecW[] = {'C','O','M','S','P','E','C',0};
1752 static const WCHAR slashcW[] = {' ','/','c',' ',0};
1753 WCHAR comspec[MAX_PATH];
1754 WCHAR *newcmdline;
1755 BOOL ret;
1756
1757 if (!GetEnvironmentVariableW( comspecW, comspec, sizeof(comspec)/sizeof(WCHAR) ))
1758 return FALSE;
1759 if (!(newcmdline = HeapAlloc( GetProcessHeap(), 0,
1760 (strlenW(comspec) + 4 + strlenW(cmd_line) + 1) * sizeof(WCHAR))))
1761 return FALSE;
1762
1763 strcpyW( newcmdline, comspec );
1764 strcatW( newcmdline, slashcW );
1765 strcatW( newcmdline, cmd_line );
1766 ret = CreateProcessW( comspec, newcmdline, psa, tsa, inherit,
1767 flags, env, cur_dir, startup, info );
1768 HeapFree( GetProcessHeap(), 0, newcmdline );
1769 return ret;
1770 }
1771
1772
1773 /*************************************************************************
1774 * get_file_name
1775 *
1776 * Helper for CreateProcess: retrieve the file name to load from the
1777 * app name and command line. Store the file name in buffer, and
1778 * return a possibly modified command line.
1779 * Also returns a handle to the opened file if it's a Windows binary.
1780 */
1781 static LPWSTR get_file_name( LPCWSTR appname, LPWSTR cmdline, LPWSTR buffer,
1782 int buflen, HANDLE *handle )
1783 {
1784 static const WCHAR quotesW[] = {'"','%','s','"',0};
1785
1786 WCHAR *name, *pos, *ret = NULL;
1787 const WCHAR *p;
1788 BOOL got_space;
1789
1790 /* if we have an app name, everything is easy */
1791
1792 if (appname)
1793 {
1794 /* use the unmodified app name as file name */
1795 lstrcpynW( buffer, appname, buflen );
1796 *handle = open_exe_file( buffer );
1797 if (!(ret = cmdline) || !cmdline[0])
1798 {
1799 /* no command-line, create one */
1800 if ((ret = HeapAlloc( GetProcessHeap(), 0, (strlenW(appname) + 3) * sizeof(WCHAR) )))
1801 sprintfW( ret, quotesW, appname );
1802 }
1803 return ret;
1804 }
1805
1806 /* first check for a quoted file name */
1807
1808 if ((cmdline[0] == '"') && ((p = strchrW( cmdline + 1, '"' ))))
1809 {
1810 int len = p - cmdline - 1;
1811 /* extract the quoted portion as file name */
1812 if (!(name = HeapAlloc( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) ))) return NULL;
1813 memcpy( name, cmdline + 1, len * sizeof(WCHAR) );
1814 name[len] = 0;
1815
1816 if (find_exe_file( name, buffer, buflen, handle ))
1817 ret = cmdline; /* no change necessary */
1818 goto done;
1819 }
1820
1821 /* now try the command-line word by word */
1822
1823 if (!(name = HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline) + 1) * sizeof(WCHAR) )))
1824 return NULL;
1825 pos = name;
1826 p = cmdline;
1827 got_space = FALSE;
1828
1829 while (*p)
1830 {
1831 do *pos++ = *p++; while (*p && *p != ' ' && *p != '\t');
1832 *pos = 0;
1833 if (find_exe_file( name, buffer, buflen, handle ))
1834 {
1835 ret = cmdline;
1836 break;
1837 }
1838 if (*p) got_space = TRUE;
1839 }
1840
1841 if (ret && got_space) /* now build a new command-line with quotes */
1842 {
1843 if (!(ret = HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline) + 3) * sizeof(WCHAR) )))
1844 goto done;
1845 sprintfW( ret, quotesW, name );
1846 strcatW( ret, p );
1847 }
1848 else if (!ret) SetLastError( ERROR_FILE_NOT_FOUND );
1849
1850 done:
1851 HeapFree( GetProcessHeap(), 0, name );
1852 return ret;
1853 }
1854
1855
1856 /**********************************************************************
1857 * CreateProcessA (KERNEL32.@)
1858 */
1859 BOOL WINAPI CreateProcessA( LPCSTR app_name, LPSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
1860 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit,
1861 DWORD flags, LPVOID env, LPCSTR cur_dir,
1862 LPSTARTUPINFOA startup_info, LPPROCESS_INFORMATION info )
1863 {
1864 BOOL ret = FALSE;
1865 WCHAR *app_nameW = NULL, *cmd_lineW = NULL, *cur_dirW = NULL;
1866 UNICODE_STRING desktopW, titleW;
1867 STARTUPINFOW infoW;
1868
1869 desktopW.Buffer = NULL;
1870 titleW.Buffer = NULL;
1871 if (app_name && !(app_nameW = FILE_name_AtoW( app_name, TRUE ))) goto done;
1872 if (cmd_line && !(cmd_lineW = FILE_name_AtoW( cmd_line, TRUE ))) goto done;
1873 if (cur_dir && !(cur_dirW = FILE_name_AtoW( cur_dir, TRUE ))) goto done;
1874
1875 if (startup_info->lpDesktop) RtlCreateUnicodeStringFromAsciiz( &desktopW, startup_info->lpDesktop );
1876 if (startup_info->lpTitle) RtlCreateUnicodeStringFromAsciiz( &titleW, startup_info->lpTitle );
1877
1878 memcpy( &infoW, startup_info, sizeof(infoW) );
1879 infoW.lpDesktop = desktopW.Buffer;
1880 infoW.lpTitle = titleW.Buffer;
1881
1882 if (startup_info->lpReserved)
1883 FIXME("StartupInfo.lpReserved is used, please report (%s)\n",
1884 debugstr_a(startup_info->lpReserved));
1885
1886 ret = CreateProcessW( app_nameW, cmd_lineW, process_attr, thread_attr,
1887 inherit, flags, env, cur_dirW, &infoW, info );
1888 done:
1889 HeapFree( GetProcessHeap(), 0, app_nameW );
1890 HeapFree( GetProcessHeap(), 0, cmd_lineW );
1891 HeapFree( GetProcessHeap(), 0, cur_dirW );
1892 RtlFreeUnicodeString( &desktopW );
1893 RtlFreeUnicodeString( &titleW );
1894 return ret;
1895 }
1896
1897
1898 /**********************************************************************
1899 * CreateProcessW (KERNEL32.@)
1900 */
1901 BOOL WINAPI CreateProcessW( LPCWSTR app_name, LPWSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
1902 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit, DWORD flags,
1903 LPVOID env, LPCWSTR cur_dir, LPSTARTUPINFOW startup_info,
1904 LPPROCESS_INFORMATION info )
1905 {
1906 BOOL retv = FALSE;
1907 HANDLE hFile = 0;
1908 char *unixdir = NULL;
1909 WCHAR name[MAX_PATH];
1910 WCHAR *tidy_cmdline, *p, *envW = env;
1911 void *res_start, *res_end;
1912
1913 /* Process the AppName and/or CmdLine to get module name and path */
1914
1915 TRACE("app %s cmdline %s\n", debugstr_w(app_name), debugstr_w(cmd_line) );
1916
1917 if (!(tidy_cmdline = get_file_name( app_name, cmd_line, name, sizeof(name)/sizeof(WCHAR), &hFile )))
1918 return FALSE;
1919 if (hFile == INVALID_HANDLE_VALUE) goto done;
1920
1921 /* Warn if unsupported features are used */
1922
1923 if (flags & (IDLE_PRIORITY_CLASS | HIGH_PRIORITY_CLASS | REALTIME_PRIORITY_CLASS |
1924 CREATE_NEW_PROCESS_GROUP | CREATE_SEPARATE_WOW_VDM | CREATE_SHARED_WOW_VDM |
1925 CREATE_DEFAULT_ERROR_MODE | CREATE_NO_WINDOW |
1926 PROFILE_USER | PROFILE_KERNEL | PROFILE_SERVER))
1927 WARN("(%s,...): ignoring some flags in %x\n", debugstr_w(name), flags);
1928
1929 if (cur_dir)
1930 {
1931 if (!(unixdir = wine_get_unix_file_name( cur_dir )))
1932 {
1933 SetLastError(ERROR_DIRECTORY);
1934 goto done;
1935 }
1936 }
1937 else
1938 {
1939 WCHAR buf[MAX_PATH];
1940 if (GetCurrentDirectoryW(MAX_PATH, buf)) unixdir = wine_get_unix_file_name( buf );
1941 }
1942
1943 if (env && !(flags & CREATE_UNICODE_ENVIRONMENT)) /* convert environment to unicode */
1944 {
1945 char *p = env;
1946 DWORD lenW;
1947
1948 while (*p) p += strlen(p) + 1;
1949 p++; /* final null */
1950 lenW = MultiByteToWideChar( CP_ACP, 0, env, p - (char*)env, NULL, 0 );
1951 envW = HeapAlloc( GetProcessHeap(), 0, lenW * sizeof(WCHAR) );
1952 MultiByteToWideChar( CP_ACP, 0, env, p - (char*)env, envW, lenW );
1953 flags |= CREATE_UNICODE_ENVIRONMENT;
1954 }
1955
1956 info->hThread = info->hProcess = 0;
1957 info->dwProcessId = info->dwThreadId = 0;
1958
1959 /* Determine executable type */
1960
1961 if (!hFile) /* builtin exe */
1962 {
1963 TRACE( "starting %s as Winelib app\n", debugstr_w(name) );
1964 retv = create_process( 0, name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1965 inherit, flags, startup_info, info, unixdir, NULL, NULL, FALSE );
1966 goto done;
1967 }
1968
1969 switch( MODULE_GetBinaryType( hFile, &res_start, &res_end ))
1970 {
1971 case BINARY_PE_EXE:
1972 TRACE( "starting %s as Win32 binary (%p-%p)\n", debugstr_w(name), res_start, res_end );
1973 retv = create_process( hFile, name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1974 inherit, flags, startup_info, info, unixdir, res_start, res_end, FALSE );
1975 break;
1976 case BINARY_OS216:
1977 case BINARY_WIN16:
1978 case BINARY_DOS:
1979 TRACE( "starting %s as Win16/DOS binary\n", debugstr_w(name) );
1980 retv = create_vdm_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1981 inherit, flags, startup_info, info, unixdir, FALSE );
1982 break;
1983 case BINARY_PE_DLL:
1984 TRACE( "not starting %s since it is a dll\n", debugstr_w(name) );
1985 SetLastError( ERROR_BAD_EXE_FORMAT );
1986 break;
1987 case BINARY_UNIX_LIB:
1988 TRACE( "%s is a Unix library, starting as Winelib app\n", debugstr_w(name) );
1989 retv = create_process( hFile, name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1990 inherit, flags, startup_info, info, unixdir, NULL, NULL, FALSE );
1991 break;
1992 case BINARY_UNKNOWN:
1993 /* check for .com or .bat extension */
1994 if ((p = strrchrW( name, '.' )))
1995 {
1996 if (!strcmpiW( p, comW ) || !strcmpiW( p, pifW ))
1997 {
1998 TRACE( "starting %s as DOS binary\n", debugstr_w(name) );
1999 retv = create_vdm_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2000 inherit, flags, startup_info, info, unixdir, FALSE );
2001 break;
2002 }
2003 if (!strcmpiW( p, batW ) || !strcmpiW( p, cmdW ) )
2004 {
2005 TRACE( "starting %s as batch binary\n", debugstr_w(name) );
2006 retv = create_cmd_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2007 inherit, flags, startup_info, info );
2008 break;
2009 }
2010 }
2011 /* fall through */
2012 case BINARY_UNIX_EXE:
2013 {
2014 /* unknown file, try as unix executable */
2015 char *unix_name;
2016
2017 TRACE( "starting %s as Unix binary\n", debugstr_w(name) );
2018
2019 if ((unix_name = wine_get_unix_file_name( name )))
2020 {
2021 retv = (fork_and_exec( unix_name, tidy_cmdline, envW, unixdir, flags, startup_info ) != -1);
2022 HeapFree( GetProcessHeap(), 0, unix_name );
2023 }
2024 }
2025 break;
2026 }
2027 CloseHandle( hFile );
2028
2029 done:
2030 if (tidy_cmdline != cmd_line) HeapFree( GetProcessHeap(), 0, tidy_cmdline );
2031 if (envW != env) HeapFree( GetProcessHeap(), 0, envW );
2032 HeapFree( GetProcessHeap(), 0, unixdir );
2033 if (retv)
2034 TRACE( "started process pid %04x tid %04x\n", info->dwProcessId, info->dwThreadId );
2035 return retv;
2036 }
2037
2038
2039 /**********************************************************************
2040 * exec_process
2041 */
2042 static void exec_process( LPCWSTR name )
2043 {
2044 HANDLE hFile;
2045 WCHAR *p;
2046 void *res_start, *res_end;
2047 STARTUPINFOW startup_info;
2048 PROCESS_INFORMATION info;
2049
2050 hFile = open_exe_file( name );
2051 if (!hFile || hFile == INVALID_HANDLE_VALUE) return;
2052
2053 memset( &startup_info, 0, sizeof(startup_info) );
2054 startup_info.cb = sizeof(startup_info);
2055
2056 /* Determine executable type */
2057
2058 switch( MODULE_GetBinaryType( hFile, &res_start, &res_end ))
2059 {
2060 case BINARY_PE_EXE:
2061 TRACE( "starting %s as Win32 binary (%p-%p)\n", debugstr_w(name), res_start, res_end );
2062 create_process( hFile, name, GetCommandLineW(), NULL, NULL, NULL, NULL,
2063 FALSE, 0, &startup_info, &info, NULL, res_start, res_end, TRUE );
2064 break;
2065 case BINARY_UNIX_LIB:
2066 TRACE( "%s is a Unix library, starting as Winelib app\n", debugstr_w(name) );
2067 create_process( hFile, name, GetCommandLineW(), NULL, NULL, NULL, NULL,
2068 FALSE, 0, &startup_info, &info, NULL, NULL, NULL, TRUE );
2069 break;
2070 case BINARY_UNKNOWN:
2071 /* check for .com or .pif extension */
2072 if (!(p = strrchrW( name, '.' ))) break;
2073 if (strcmpiW( p, comW ) && strcmpiW( p, pifW )) break;
2074 /* fall through */
2075 case BINARY_OS216:
2076 case BINARY_WIN16:
2077 case BINARY_DOS:
2078 TRACE( "starting %s as Win16/DOS binary\n", debugstr_w(name) );
2079 create_vdm_process( name, GetCommandLineW(), NULL, NULL, NULL, NULL,
2080 FALSE, 0, &startup_info, &info, NULL, TRUE );
2081 break;
2082 default:
2083 break;
2084 }
2085 CloseHandle( hFile );
2086 }
2087
2088
2089 /***********************************************************************
2090 * wait_input_idle
2091 *
2092 * Wrapper to call WaitForInputIdle USER function
2093 */
2094 typedef DWORD (WINAPI *WaitForInputIdle_ptr)( HANDLE hProcess, DWORD dwTimeOut );
2095
2096 static DWORD wait_input_idle( HANDLE process, DWORD timeout )
2097 {
2098 HMODULE mod = GetModuleHandleA( "user32.dll" );
2099 if (mod)
2100 {
2101 WaitForInputIdle_ptr ptr = (WaitForInputIdle_ptr)GetProcAddress( mod, "WaitForInputIdle" );
2102 if (ptr) return ptr( process, timeout );
2103 }
2104 return 0;
2105 }
2106
2107
2108 /***********************************************************************
2109 * WinExec (KERNEL32.@)
2110 */
2111 UINT WINAPI WinExec( LPCSTR lpCmdLine, UINT nCmdShow )
2112 {
2113 PROCESS_INFORMATION info;
2114 STARTUPINFOA startup;
2115 char *cmdline;
2116 UINT ret;
2117
2118 memset( &startup, 0, sizeof(startup) );
2119 startup.cb = sizeof(startup);
2120 startup.dwFlags = STARTF_USESHOWWINDOW;
2121 startup.wShowWindow = nCmdShow;
2122
2123 /* cmdline needs to be writable for CreateProcess */
2124 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(lpCmdLine)+1 ))) return 0;
2125 strcpy( cmdline, lpCmdLine );
2126
2127 if (CreateProcessA( NULL, cmdline, NULL, NULL, FALSE,
2128 0, NULL, NULL, &startup, &info ))
2129 {
2130 /* Give 30 seconds to the app to come up */
2131 if (wait_input_idle( info.hProcess, 30000 ) == WAIT_FAILED)
2132 WARN("WaitForInputIdle failed: Error %d\n", GetLastError() );
2133 ret = 33;
2134 /* Close off the handles */
2135 CloseHandle( info.hThread );
2136 CloseHandle( info.hProcess );
2137 }
2138 else if ((ret = GetLastError()) >= 32)
2139 {
2140 FIXME("Strange error set by CreateProcess: %d\n", ret );
2141 ret = 11;
2142 }
2143 HeapFree( GetProcessHeap(), 0, cmdline );
2144 return ret;
2145 }
2146
2147
2148 /**********************************************************************
2149 * LoadModule (KERNEL32.@)
2150 */
2151 HINSTANCE WINAPI LoadModule( LPCSTR name, LPVOID paramBlock )
2152 {
2153 LOADPARMS32 *params = paramBlock;
2154 PROCESS_INFORMATION info;
2155 STARTUPINFOA startup;
2156 HINSTANCE hInstance;
2157 LPSTR cmdline, p;
2158 char filename[MAX_PATH];
2159 BYTE len;
2160
2161 if (!name) return (HINSTANCE)ERROR_FILE_NOT_FOUND;
2162
2163 if (!SearchPathA( NULL, name, ".exe", sizeof(filename), filename, NULL ) &&
2164 !SearchPathA( NULL, name, NULL, sizeof(filename), filename, NULL ))
2165 return ULongToHandle(GetLastError());
2166
2167 len = (BYTE)params->lpCmdLine[0];
2168 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(filename) + len + 2 )))
2169 return (HINSTANCE)ERROR_NOT_ENOUGH_MEMORY;
2170
2171 strcpy( cmdline, filename );
2172 p = cmdline + strlen(cmdline);
2173 *p++ = ' ';
2174 memcpy( p, params->lpCmdLine + 1, len );
2175 p[len] = 0;
2176
2177 memset( &startup, 0, sizeof(startup) );
2178 startup.cb = sizeof(startup);
2179 if (params->lpCmdShow)
2180 {
2181 startup.dwFlags = STARTF_USESHOWWINDOW;
2182 startup.wShowWindow = ((WORD *)params->lpCmdShow)[1];
2183 }
2184
2185 if (CreateProcessA( filename, cmdline, NULL, NULL, FALSE, 0,
2186 params->lpEnvAddress, NULL, &startup, &info ))
2187 {
2188 /* Give 30 seconds to the app to come up */
2189 if (wait_input_idle( info.hProcess, 30000 ) == WAIT_FAILED)
2190 WARN("WaitForInputIdle failed: Error %d\n", GetLastError() );
2191 hInstance = (HINSTANCE)33;
2192 /* Close off the handles */
2193 CloseHandle( info.hThread );
2194 CloseHandle( info.hProcess );
2195 }
2196 else if ((hInstance = ULongToHandle(GetLastError())) >= (HINSTANCE)32)
2197 {
2198 FIXME("Strange error set by CreateProcess: %p\n", hInstance );
2199 hInstance = (HINSTANCE)11;
2200 }
2201
2202 HeapFree( GetProcessHeap(), 0, cmdline );
2203 return hInstance;
2204 }
2205
2206
2207 /******************************************************************************
2208 * TerminateProcess (KERNEL32.@)
2209 *
2210 * Terminates a process.
2211 *
2212 * PARAMS
2213 * handle [I] Process to terminate.
2214 * exit_code [I] Exit code.
2215 *
2216 * RETURNS
2217 * Success: TRUE.
2218 * Failure: FALSE, check GetLastError().
2219 */
2220 BOOL WINAPI TerminateProcess( HANDLE handle, DWORD exit_code )
2221 {
2222 NTSTATUS status = NtTerminateProcess( handle, exit_code );
2223 if (status) SetLastError( RtlNtStatusToDosError(status) );
2224 return !status;
2225 }
2226
2227 /***********************************************************************
2228 * ExitProcess (KERNEL32.@)
2229 *
2230 * Exits the current process.
2231 *
2232 * PARAMS
2233 * status [I] Status code to exit with.
2234 *
2235 * RETURNS
2236 * Nothing.
2237 */
2238 #ifdef __i386__
2239 __ASM_STDCALL_FUNC( ExitProcess, 4, /* Shrinker depend on this particular ExitProcess implementation */
2240 "pushl %ebp\n\t"
2241 ".byte 0x8B, 0xEC\n\t" /* movl %esp, %ebp */
2242 ".byte 0x6A, 0x00\n\t" /* pushl $0 */
2243 ".byte 0x68, 0x00, 0x00, 0x00, 0x00\n\t" /* pushl $0 - 4 bytes immediate */
2244 "pushl 8(%ebp)\n\t"
2245 "call " __ASM_NAME("process_ExitProcess") __ASM_STDCALL(4) "\n\t"
2246 "leave\n\t"
2247 "ret $4" )
2248
2249 void WINAPI process_ExitProcess( DWORD status )
2250 {
2251 LdrShutdownProcess();
2252 NtTerminateProcess(GetCurrentProcess(), status);
2253 exit(status);
2254 }
2255
2256 #else
2257
2258 void WINAPI ExitProcess( DWORD status )
2259 {
2260 LdrShutdownProcess();
2261 NtTerminateProcess(GetCurrentProcess(), status);
2262 exit(status);
2263 }
2264
2265 #endif
2266
2267 /***********************************************************************
2268 * GetExitCodeProcess [KERNEL32.@]
2269 *
2270 * Gets termination status of specified process.
2271 *
2272 * PARAMS
2273 * hProcess [in] Handle to the process.
2274 * lpExitCode [out] Address to receive termination status.
2275 *
2276 * RETURNS
2277 * Success: TRUE
2278 * Failure: FALSE
2279 */
2280 BOOL WINAPI GetExitCodeProcess( HANDLE hProcess, LPDWORD lpExitCode )
2281 {
2282 NTSTATUS status;
2283 PROCESS_BASIC_INFORMATION pbi;
2284
2285 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
2286 sizeof(pbi), NULL);
2287 if (status == STATUS_SUCCESS)
2288 {
2289 if (lpExitCode) *lpExitCode = pbi.ExitStatus;
2290 return TRUE;
2291 }
2292 SetLastError( RtlNtStatusToDosError(status) );
2293 return FALSE;
2294 }
2295
2296
2297 /***********************************************************************
2298 * SetErrorMode (KERNEL32.@)
2299 */
2300 UINT WINAPI SetErrorMode( UINT mode )
2301 {
2302 UINT old = process_error_mode;
2303 process_error_mode = mode;
2304 return old;
2305 }
2306
2307 /***********************************************************************
2308 * GetErrorMode (KERNEL32.@)
2309 */
2310 UINT WINAPI GetErrorMode( void )
2311 {
2312 return process_error_mode;
2313 }
2314
2315 /**********************************************************************
2316 * TlsAlloc [KERNEL32.@]
2317 *
2318 * Allocates a thread local storage index.
2319 *
2320 * RETURNS
2321 * Success: TLS index.
2322 * Failure: 0xFFFFFFFF
2323 */
2324 DWORD WINAPI TlsAlloc( void )
2325 {
2326 DWORD index;
2327 PEB * const peb = NtCurrentTeb()->Peb;
2328
2329 RtlAcquirePebLock();
2330 index = RtlFindClearBitsAndSet( peb->TlsBitmap, 1, 0 );
2331 if (index != ~0U) NtCurrentTeb()->TlsSlots[index] = 0; /* clear the value */
2332 else
2333 {
2334 index = RtlFindClearBitsAndSet( peb->TlsExpansionBitmap, 1, 0 );
2335 if (index != ~0U)
2336 {
2337 if (!NtCurrentTeb()->TlsExpansionSlots &&
2338 !(NtCurrentTeb()->TlsExpansionSlots = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY,
2339 8 * sizeof(peb->TlsExpansionBitmapBits) * sizeof(void*) )))
2340 {
2341 RtlClearBits( peb->TlsExpansionBitmap, index, 1 );
2342 index = ~0U;
2343 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
2344 }
2345 else
2346 {
2347 NtCurrentTeb()->TlsExpansionSlots[index] = 0; /* clear the value */
2348 index += TLS_MINIMUM_AVAILABLE;
2349 }
2350 }
2351 else SetLastError( ERROR_NO_MORE_ITEMS );
2352 }
2353 RtlReleasePebLock();
2354 return index;
2355 }
2356
2357
2358 /**********************************************************************
2359 * TlsFree [KERNEL32.@]
2360 *
2361 * Releases a thread local storage index, making it available for reuse.
2362 *
2363 * PARAMS
2364 * index [in] TLS index to free.
2365 *
2366 * RETURNS
2367 * Success: TRUE
2368 * Failure: FALSE
2369 */
2370 BOOL WINAPI TlsFree( DWORD index )
2371 {
2372 BOOL ret;
2373
2374 RtlAcquirePebLock();
2375 if (index >= TLS_MINIMUM_AVAILABLE)
2376 {
2377 ret = RtlAreBitsSet( NtCurrentTeb()->Peb->TlsExpansionBitmap, index - TLS_MINIMUM_AVAILABLE, 1 );
2378 if (ret) RtlClearBits( NtCurrentTeb()->Peb->TlsExpansionBitmap, index - TLS_MINIMUM_AVAILABLE, 1 );
2379 }
2380 else
2381 {
2382 ret = RtlAreBitsSet( NtCurrentTeb()->Peb->TlsBitmap, index, 1 );
2383 if (ret) RtlClearBits( NtCurrentTeb()->Peb->TlsBitmap, index, 1 );
2384 }
2385 if (ret) NtSetInformationThread( GetCurrentThread(), ThreadZeroTlsCell, &index, sizeof(index) );
2386 else SetLastError( ERROR_INVALID_PARAMETER );
2387 RtlReleasePebLock();
2388 return TRUE;
2389 }
2390
2391
2392 /**********************************************************************
2393 * TlsGetValue [KERNEL32.@]
2394 *
2395 * Gets value in a thread's TLS slot.
2396 *
2397 * PARAMS
2398 * index [in] TLS index to retrieve value for.
2399 *
2400 * RETURNS
2401 * Success: Value stored in calling thread's TLS slot for index.
2402 * Failure: 0 and GetLastError() returns NO_ERROR.
2403 */
2404 LPVOID WINAPI TlsGetValue( DWORD index )
2405 {
2406 LPVOID ret;
2407
2408 if (index < TLS_MINIMUM_AVAILABLE)
2409 {
2410 ret = NtCurrentTeb()->TlsSlots[index];
2411 }
2412 else
2413 {
2414 index -= TLS_MINIMUM_AVAILABLE;
2415 if (index >= 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits))
2416 {
2417 SetLastError( ERROR_INVALID_PARAMETER );
2418 return NULL;
2419 }
2420 if (!NtCurrentTeb()->TlsExpansionSlots) ret = NULL;
2421 else ret = NtCurrentTeb()->TlsExpansionSlots[index];
2422 }
2423 SetLastError( ERROR_SUCCESS );
2424 return ret;
2425 }
2426
2427
2428 /**********************************************************************
2429 * TlsSetValue [KERNEL32.@]
2430 *
2431 * Stores a value in the thread's TLS slot.
2432 *
2433 * PARAMS
2434 * index [in] TLS index to set value for.
2435 * value [in] Value to be stored.
2436 *
2437 * RETURNS
2438 * Success: TRUE
2439 * Failure: FALSE
2440 */
2441 BOOL WINAPI TlsSetValue( DWORD index, LPVOID value )
2442 {
2443 if (index < TLS_MINIMUM_AVAILABLE)
2444 {
2445 NtCurrentTeb()->TlsSlots[index] = value;
2446 }
2447 else
2448 {
2449 index -= TLS_MINIMUM_AVAILABLE;
2450 if (index >= 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits))
2451 {
2452 SetLastError( ERROR_INVALID_PARAMETER );
2453 return FALSE;
2454 }
2455 if (!NtCurrentTeb()->TlsExpansionSlots &&
2456 !(NtCurrentTeb()->TlsExpansionSlots = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY,
2457 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits) * sizeof(void*) )))
2458 {
2459 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
2460 return FALSE;
2461 }
2462 NtCurrentTeb()->TlsExpansionSlots[index] = value;
2463 }
2464 return TRUE;
2465 }
2466
2467
2468 /***********************************************************************
2469 * GetProcessFlags (KERNEL32.@)
2470 */
2471 DWORD WINAPI GetProcessFlags( DWORD processid )
2472 {
2473 IMAGE_NT_HEADERS *nt;
2474 DWORD flags = 0;
2475
2476 if (processid && processid != GetCurrentProcessId()) return 0;
2477
2478 if ((nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress )))
2479 {
2480 if (nt->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_CUI)
2481 flags |= PDB32_CONSOLE_PROC;
2482 }
2483 if (!AreFileApisANSI()) flags |= PDB32_FILE_APIS_OEM;
2484 if (IsDebuggerPresent()) flags |= PDB32_DEBUGGED;
2485 return flags;
2486 }
2487
2488
2489 /***********************************************************************
2490 * GetProcessDword (KERNEL.485)
2491 * GetProcessDword (KERNEL32.18)
2492 * 'Of course you cannot directly access Windows internal structures'
2493 */
2494 DWORD WINAPI GetProcessDword( DWORD dwProcessID, INT offset )
2495 {
2496 DWORD x, y;
2497 STARTUPINFOW siw;
2498
2499 TRACE("(%d, %d)\n", dwProcessID, offset );
2500
2501 if (dwProcessID && dwProcessID != GetCurrentProcessId())
2502 {
2503 ERR("%d: process %x not accessible\n", offset, dwProcessID);
2504 return 0;
2505 }
2506
2507 switch ( offset )
2508 {
2509 case GPD_APP_COMPAT_FLAGS:
2510 return GetAppCompatFlags16(0);
2511 case GPD_LOAD_DONE_EVENT:
2512 return 0;
2513 case GPD_HINSTANCE16:
2514 return GetTaskDS16();
2515 case GPD_WINDOWS_VERSION:
2516 return GetExeVersion16();
2517 case GPD_THDB:
2518 return (DWORD_PTR)NtCurrentTeb() - 0x10 /* FIXME */;
2519 case GPD_PDB:
2520 return (DWORD_PTR)NtCurrentTeb()->Peb; /* FIXME: truncating a pointer */
2521 case GPD_STARTF_SHELLDATA: /* return stdoutput handle from startupinfo ??? */
2522 GetStartupInfoW(&siw);
2523 return HandleToULong(siw.hStdOutput);
2524 case GPD_STARTF_HOTKEY: /* return stdinput handle from startupinfo ??? */
2525 GetStartupInfoW(&siw);
2526 return HandleToULong(siw.hStdInput);
2527 case GPD_STARTF_SHOWWINDOW:
2528 GetStartupInfoW(&siw);
2529 return siw.wShowWindow;
2530 case GPD_STARTF_SIZE:
2531 GetStartupInfoW(&siw);
2532 x = siw.dwXSize;
2533 if ( (INT)x == CW_USEDEFAULT ) x = CW_USEDEFAULT16;
2534 y = siw.dwYSize;
2535 if ( (INT)y == CW_USEDEFAULT ) y = CW_USEDEFAULT16;
2536 return MAKELONG( x, y );
2537 case GPD_STARTF_POSITION:
2538 GetStartupInfoW(&siw);
2539 x = siw.dwX;
2540 if ( (INT)x == CW_USEDEFAULT ) x = CW_USEDEFAULT16;
2541 y = siw.dwY;
2542 if ( (INT)y == CW_USEDEFAULT ) y = CW_USEDEFAULT16;
2543 return MAKELONG( x, y );
2544 case GPD_STARTF_FLAGS:
2545 GetStartupInfoW(&siw);
2546 return siw.dwFlags;
2547 case GPD_PARENT:
2548 return 0;
2549 case GPD_FLAGS:
2550 return GetProcessFlags(0);
2551 case GPD_USERDATA:
2552 return process_dword;
2553 default:
2554 ERR("Unknown offset %d\n", offset );
2555 return 0;
2556 }
2557 }
2558
2559 /***********************************************************************
2560 * SetProcessDword (KERNEL.484)
2561 * 'Of course you cannot directly access Windows internal structures'
2562 */
2563 void WINAPI SetProcessDword( DWORD dwProcessID, INT offset, DWORD value )
2564 {
2565 TRACE("(%d, %d)\n", dwProcessID, offset );
2566
2567 if (dwProcessID && dwProcessID != GetCurrentProcessId())
2568 {
2569 ERR("%d: process %x not accessible\n", offset, dwProcessID);
2570 return;
2571 }
2572
2573 switch ( offset )
2574 {
2575 case GPD_APP_COMPAT_FLAGS:
2576 case GPD_LOAD_DONE_EVENT:
2577 case GPD_HINSTANCE16:
2578 case GPD_WINDOWS_VERSION:
2579 case GPD_THDB:
2580 case GPD_PDB:
2581 case GPD_STARTF_SHELLDATA:
2582 case GPD_STARTF_HOTKEY:
2583 case GPD_STARTF_SHOWWINDOW:
2584 case GPD_STARTF_SIZE:
2585 case GPD_STARTF_POSITION:
2586 case GPD_STARTF_FLAGS:
2587 case GPD_PARENT:
2588 case GPD_FLAGS:
2589 ERR("Not allowed to modify offset %d\n", offset );
2590 break;
2591 case GPD_USERDATA:
2592 process_dword = value;
2593 break;
2594 default:
2595 ERR("Unknown offset %d\n", offset );
2596 break;
2597 }
2598 }
2599
2600
2601 /***********************************************************************
2602 * ExitProcess (KERNEL.466)
2603 */
2604 void WINAPI ExitProcess16( WORD status )
2605 {
2606 DWORD count;
2607 ReleaseThunkLock( &count );
2608 ExitProcess( status );
2609 }
2610
2611
2612 /*********************************************************************
2613 * OpenProcess (KERNEL32.@)
2614 *
2615 * Opens a handle to a process.
2616 *
2617 * PARAMS
2618 * access [I] Desired access rights assigned to the returned handle.
2619 * inherit [I] Determines whether or not child processes will inherit the handle.
2620 * id [I] Process identifier of the process to get a handle to.
2621 *
2622 * RETURNS
2623 * Success: Valid handle to the specified process.
2624 * Failure: NULL, check GetLastError().
2625 */
2626 HANDLE WINAPI OpenProcess( DWORD access, BOOL inherit, DWORD id )
2627 {
2628 NTSTATUS status;
2629 HANDLE handle;
2630 OBJECT_ATTRIBUTES attr;
2631 CLIENT_ID cid;
2632
2633 cid.UniqueProcess = ULongToHandle(id);
2634 cid.UniqueThread = 0; /* FIXME ? */
2635
2636 attr.Length = sizeof(OBJECT_ATTRIBUTES);
2637 attr.RootDirectory = NULL;
2638 attr.Attributes = inherit ? OBJ_INHERIT : 0;
2639 attr.SecurityDescriptor = NULL;
2640 attr.SecurityQualityOfService = NULL;
2641 attr.ObjectName = NULL;
2642
2643 if (GetVersion() & 0x80000000) access = PROCESS_ALL_ACCESS;
2644
2645 status = NtOpenProcess(&handle, access, &attr, &cid);
2646 if (status != STATUS_SUCCESS)
2647 {
2648 SetLastError( RtlNtStatusToDosError(status) );
2649 return NULL;
2650 }
2651 return handle;
2652 }
2653
2654
2655 /*********************************************************************
2656 * MapProcessHandle (KERNEL.483)
2657 * GetProcessId (KERNEL32.@)
2658 *
2659 * Gets the a unique identifier of a process.
2660 *
2661 * PARAMS
2662 * hProcess [I] Handle to the process.
2663 *
2664 * RETURNS
2665 * Success: TRUE.
2666 * Failure: FALSE, check GetLastError().
2667 *
2668 * NOTES
2669 *
2670 * The identifier is unique only on the machine and only until the process
2671 * exits (including system shutdown).
2672 */
2673 DWORD WINAPI GetProcessId( HANDLE hProcess )
2674 {
2675 NTSTATUS status;
2676 PROCESS_BASIC_INFORMATION pbi;
2677
2678 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
2679 sizeof(pbi), NULL);
2680 if (status == STATUS_SUCCESS) return pbi.UniqueProcessId;
2681 SetLastError( RtlNtStatusToDosError(status) );
2682 return 0;
2683 }
2684
2685
2686 /*********************************************************************
2687 * CloseW32Handle (KERNEL.474)
2688 * CloseHandle (KERNEL32.@)
2689 *
2690 * Closes a handle.
2691 *
2692 * PARAMS
2693 * handle [I] Handle to close.
2694 *
2695 * RETURNS
2696 * Success: TRUE.
2697 * Failure: FALSE, check GetLastError().
2698 */
2699 BOOL WINAPI CloseHandle( HANDLE handle )
2700 {
2701 NTSTATUS status;
2702
2703 /* stdio handles need special treatment */
2704 if ((handle == (HANDLE)STD_INPUT_HANDLE) ||
2705 (handle == (HANDLE)STD_OUTPUT_HANDLE) ||
2706 (handle == (HANDLE)STD_ERROR_HANDLE))
2707 handle = GetStdHandle( HandleToULong(handle) );
2708
2709 if (is_console_handle(handle))
2710 return CloseConsoleHandle(handle);
2711
2712 status = NtClose( handle );
2713 if (status) SetLastError( RtlNtStatusToDosError(status) );
2714 return !status;
2715 }
2716
2717
2718 /*********************************************************************
2719 * GetHandleInformation (KERNEL32.@)
2720 */
2721 BOOL WINAPI GetHandleInformation( HANDLE handle, LPDWORD flags )
2722 {
2723 OBJECT_DATA_INFORMATION info;
2724 NTSTATUS status = NtQueryObject( handle, ObjectDataInformation, &info, sizeof(info), NULL );
2725
2726 if (status) SetLastError( RtlNtStatusToDosError(status) );
2727 else if (flags)
2728 {
2729 *flags = 0;
2730 if (info.InheritHandle) *flags |= HANDLE_FLAG_INHERIT;
2731 if (info.ProtectFromClose) *flags |= HANDLE_FLAG_PROTECT_FROM_CLOSE;
2732 }
2733 return !status;
2734 }
2735
2736
2737 /*********************************************************************
2738 * SetHandleInformation (KERNEL32.@)
2739 */
2740 BOOL WINAPI SetHandleInformation( HANDLE handle, DWORD mask, DWORD flags )
2741 {
2742 OBJECT_DATA_INFORMATION info;
2743 NTSTATUS status;
2744
2745 /* if not setting both fields, retrieve current value first */
2746 if ((mask & (HANDLE_FLAG_INHERIT | HANDLE_FLAG_PROTECT_FROM_CLOSE)) !=
2747 (HANDLE_FLAG_INHERIT | HANDLE_FLAG_PROTECT_FROM_CLOSE))
2748 {
2749 if ((status = NtQueryObject( handle, ObjectDataInformation, &info, sizeof(info), NULL )))
2750 {
2751 SetLastError( RtlNtStatusToDosError(status) );
2752 return FALSE;
2753 }
2754 }
2755 if (mask & HANDLE_FLAG_INHERIT)
2756 info.InheritHandle = (flags & HANDLE_FLAG_INHERIT) != 0;
2757 if (mask & HANDLE_FLAG_PROTECT_FROM_CLOSE)
2758 info.ProtectFromClose = (flags & HANDLE_FLAG_PROTECT_FROM_CLOSE) != 0;
2759
2760 status = NtSetInformationObject( handle, ObjectDataInformation, &info, sizeof(info) );
2761 if (status) SetLastError( RtlNtStatusToDosError(status) );
2762 return !status;
2763 }
2764
2765
2766 /*********************************************************************
2767 * DuplicateHandle (KERNEL32.@)
2768 */
2769 BOOL WINAPI DuplicateHandle( HANDLE source_process, HANDLE source,
2770 HANDLE dest_process, HANDLE *dest,
2771 DWORD access, BOOL inherit, DWORD options )
2772 {
2773 NTSTATUS status;
2774
2775 if (is_console_handle(source))
2776 {
2777 /* FIXME: this test is not sufficient, we need to test process ids, not handles */
2778 if (source_process != dest_process ||
2779 source_process != GetCurrentProcess())
2780 {
2781 SetLastError(ERROR_INVALID_PARAMETER);
2782 return FALSE;
2783 }
2784 *dest = DuplicateConsoleHandle( source, access, inherit, options );
2785 return (*dest != INVALID_HANDLE_VALUE);
2786 }
2787 status = NtDuplicateObject( source_process, source, dest_process, dest,
2788 access, inherit ? OBJ_INHERIT : 0, options );
2789 if (status) SetLastError( RtlNtStatusToDosError(status) );
2790 return !status;
2791 }
2792
2793
2794 /***********************************************************************
2795 * ConvertToGlobalHandle (KERNEL.476)
2796 * ConvertToGlobalHandle (KERNEL32.@)
2797 */
2798 HANDLE WINAPI ConvertToGlobalHandle(HANDLE hSrc)
2799 {
2800 HANDLE ret = INVALID_HANDLE_VALUE;
2801 DuplicateHandle( GetCurrentProcess(), hSrc, GetCurrentProcess(), &ret, 0, FALSE,
2802 DUP_HANDLE_MAKE_GLOBAL | DUP_HANDLE_SAME_ACCESS | DUP_HANDLE_CLOSE_SOURCE );
2803 return ret;
2804 }
2805
2806
2807 /***********************************************************************
2808 * SetHandleContext (KERNEL32.@)
2809 */
2810 BOOL WINAPI SetHandleContext(HANDLE hnd,DWORD context)
2811 {
2812 FIXME("(%p,%d), stub. In case this got called by WSOCK32/WS2_32: "
2813 "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd,context);
2814 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2815 return FALSE;
2816 }
2817
2818
2819 /***********************************************************************
2820 * GetHandleContext (KERNEL32.@)
2821 */
2822 DWORD WINAPI GetHandleContext(HANDLE hnd)
2823 {
2824 FIXME("(%p), stub. In case this got called by WSOCK32/WS2_32: "
2825 "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd);
2826 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2827 return 0;
2828 }
2829
2830
2831 /***********************************************************************
2832 * CreateSocketHandle (KERNEL32.@)
2833 */
2834 HANDLE WINAPI CreateSocketHandle(void)
2835 {
2836 FIXME("(), stub. In case this got called by WSOCK32/WS2_32: "
2837 "the external WINSOCK DLLs won't work with WINE, don't use them.\n");
2838 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2839 return INVALID_HANDLE_VALUE;
2840 }
2841
2842
2843 /***********************************************************************
2844 * SetPriorityClass (KERNEL32.@)
2845 */
2846 BOOL WINAPI SetPriorityClass( HANDLE hprocess, DWORD priorityclass )
2847 {
2848 NTSTATUS status;
2849 PROCESS_PRIORITY_CLASS ppc;
2850
2851 ppc.Foreground = FALSE;
2852 switch (priorityclass)
2853 {
2854 case IDLE_PRIORITY_CLASS:
2855 ppc.PriorityClass = PROCESS_PRIOCLASS_IDLE; break;
2856 case BELOW_NORMAL_PRIORITY_CLASS:
2857 ppc.PriorityClass = PROCESS_PRIOCLASS_BELOW_NORMAL; break;
2858 case NORMAL_PRIORITY_CLASS:
2859 ppc.PriorityClass = PROCESS_PRIOCLASS_NORMAL; break;
2860 case ABOVE_NORMAL_PRIORITY_CLASS:
2861 ppc.PriorityClass = PROCESS_PRIOCLASS_ABOVE_NORMAL; break;
2862 case HIGH_PRIORITY_CLASS:
2863 ppc.PriorityClass = PROCESS_PRIOCLASS_HIGH; break;
2864 case REALTIME_PRIORITY_CLASS:
2865 ppc.PriorityClass = PROCESS_PRIOCLASS_REALTIME; break;
2866 default:
2867 SetLastError(ERROR_INVALID_PARAMETER);
2868 return FALSE;
2869 }
2870
2871 status = NtSetInformationProcess(hprocess, ProcessPriorityClass,
2872 &ppc, sizeof(ppc));
2873
2874 if (status != STATUS_SUCCESS)
2875 {
2876 SetLastError( RtlNtStatusToDosError(status) );
2877 return FALSE;
2878 }
2879 return TRUE;
2880 }
2881
2882
2883 /***********************************************************************
2884 * GetPriorityClass (KERNEL32.@)
2885 */
2886 DWORD WINAPI GetPriorityClass(HANDLE hProcess)
2887 {
2888 NTSTATUS status;
2889 PROCESS_BASIC_INFORMATION pbi;
2890
2891 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
2892 sizeof(pbi), NULL);
2893 if (status != STATUS_SUCCESS)
2894 {
2895 SetLastError( RtlNtStatusToDosError(status) );
2896 return 0;
2897 }
2898 switch (pbi.BasePriority)
2899 {
2900 case PROCESS_PRIOCLASS_IDLE: return IDLE_PRIORITY_CLASS;
2901 case PROCESS_PRIOCLASS_BELOW_NORMAL: return BELOW_NORMAL_PRIORITY_CLASS;
2902 case PROCESS_PRIOCLASS_NORMAL: return NORMAL_PRIORITY_CLASS;
2903 case PROCESS_PRIOCLASS_ABOVE_NORMAL: return ABOVE_NORMAL_PRIORITY_CLASS;
2904 case PROCESS_PRIOCLASS_HIGH: return HIGH_PRIORITY_CLASS;
2905 case PROCESS_PRIOCLASS_REALTIME: return REALTIME_PRIORITY_CLASS;
2906 }
2907 SetLastError( ERROR_INVALID_PARAMETER );
2908 return 0;
2909 }
2910
2911
2912 /***********************************************************************
2913 * SetProcessAffinityMask (KERNEL32.@)
2914 */
2915 BOOL WINAPI SetProcessAffinityMask( HANDLE hProcess, DWORD_PTR affmask )
2916 {
2917 NTSTATUS status;
2918
2919 status = NtSetInformationProcess(hProcess, ProcessAffinityMask,
2920 &affmask, sizeof(DWORD_PTR));
2921 if (status)
2922 {
2923 SetLastError( RtlNtStatusToDosError(status) );
2924 return FALSE;
2925 }
2926 return TRUE;
2927 }
2928
2929
2930 /**********************************************************************
2931 * GetProcessAffinityMask (KERNEL32.@)
2932 */
2933 BOOL WINAPI GetProcessAffinityMask( HANDLE hProcess,
2934 PDWORD_PTR lpProcessAffinityMask,
2935 PDWORD_PTR lpSystemAffinityMask )
2936 {
2937 PROCESS_BASIC_INFORMATION pbi;
2938 NTSTATUS status;
2939
2940 status = NtQueryInformationProcess(hProcess,
2941 ProcessBasicInformation,
2942 &pbi, sizeof(pbi), NULL);
2943 if (status)
2944 {
2945 SetLastError( RtlNtStatusToDosError(status) );
2946 return FALSE;
2947 }
2948 if (lpProcessAffinityMask) *lpProcessAffinityMask = pbi.AffinityMask;
2949 if (lpSystemAffinityMask) *lpSystemAffinityMask = (1 << NtCurrentTeb()->Peb->NumberOfProcessors) - 1;
2950 return TRUE;
2951 }
2952
2953
2954 /***********************************************************************
2955 * GetProcessVersion (KERNEL32.@)
2956 */
2957 DWORD WINAPI GetProcessVersion( DWORD pid )
2958 {
2959 HANDLE process;
2960 NTSTATUS status;
2961 PROCESS_BASIC_INFORMATION pbi;
2962 SIZE_T count;
2963 PEB peb;
2964 IMAGE_DOS_HEADER dos;
2965 IMAGE_NT_HEADERS nt;
2966 DWORD ver = 0;
2967
2968 if (!pid || pid == GetCurrentProcessId())
2969 {
2970 IMAGE_NT_HEADERS *nt;
2971
2972 if ((nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress )))
2973 return ((nt->OptionalHeader.MajorSubsystemVersion << 16) |
2974 nt->OptionalHeader.MinorSubsystemVersion);
2975 return 0;
2976 }
2977
2978 process = OpenProcess(PROCESS_VM_READ | PROCESS_QUERY_INFORMATION, FALSE, pid);
2979 if (!process) return 0;
2980
2981 status = NtQueryInformationProcess(process, ProcessBasicInformation, &pbi, sizeof(pbi), NULL);
2982 if (status) goto err;
2983
2984 status = NtReadVirtualMemory(process, pbi.PebBaseAddress, &peb, sizeof(peb), &count);
2985 if (status || count != sizeof(peb)) goto err;
2986
2987 memset(&dos, 0, sizeof(dos));
2988 status = NtReadVirtualMemory(process, peb.ImageBaseAddress, &dos, sizeof(dos), &count);
2989 if (status || count != sizeof(dos)) goto err;
2990 if (dos.e_magic != IMAGE_DOS_SIGNATURE) goto err;
2991
2992 memset(&nt, 0, sizeof(nt));
2993 status = NtReadVirtualMemory(process, (char *)peb.ImageBaseAddress + dos.e_lfanew, &nt, sizeof(nt), &count);
2994 if (status || count != sizeof(nt)) goto err;
2995 if (nt.Signature != IMAGE_NT_SIGNATURE) goto err;
2996
2997 ver = MAKELONG(nt.OptionalHeader.MinorSubsystemVersion, nt.OptionalHeader.MajorSubsystemVersion);
2998
2999 err:
3000 CloseHandle(process);
3001
3002 if (status != STATUS_SUCCESS)
3003 SetLastError(RtlNtStatusToDosError(status));
3004
3005 return ver;
3006 }
3007
3008
3009 /***********************************************************************
3010 * SetProcessWorkingSetSize [KERNEL32.@]
3011 * Sets the min/max working set sizes for a specified process.
3012 *
3013 * PARAMS
3014 * hProcess [I] Handle to the process of interest
3015 * minset [I] Specifies minimum working set size
3016 * maxset [I] Specifies maximum working set size
3017 *
3018 * RETURNS
3019 * Success: TRUE
3020 * Failure: FALSE
3021 */
3022 BOOL WINAPI SetProcessWorkingSetSize(HANDLE hProcess, SIZE_T minset,
3023 SIZE_T maxset)
3024 {
3025 WARN("(%p,%ld,%ld): stub - harmless\n",hProcess,minset,maxset);
3026 if(( minset == (SIZE_T)-1) && (maxset == (SIZE_T)-1)) {
3027 /* Trim the working set to zero */
3028 /* Swap the process out of physical RAM */
3029 }
3030 return TRUE;
3031 }
3032
3033 /***********************************************************************
3034 * GetProcessWorkingSetSize (KERNEL32.@)
3035 */
3036 BOOL WINAPI GetProcessWorkingSetSize(HANDLE hProcess, PSIZE_T minset,
3037 PSIZE_T maxset)
3038 {
3039 FIXME("(%p,%p,%p): stub\n",hProcess,minset,maxset);
3040 /* 32 MB working set size */
3041 if (minset) *minset = 32*1024*1024;
3042 if (maxset) *maxset = 32*1024*1024;
3043 return TRUE;
3044 }
3045
3046
3047 /***********************************************************************
3048 * SetProcessShutdownParameters (KERNEL32.@)
3049 */
3050 BOOL WINAPI SetProcessShutdownParameters(DWORD level, DWORD flags)
3051 {
3052 FIXME("(%08x, %08x): partial stub.\n", level, flags);
3053 shutdown_flags = flags;
3054 shutdown_priority = level;
3055 return TRUE;
3056 }
3057
3058
3059 /***********************************************************************
3060 * GetProcessShutdownParameters (KERNEL32.@)
3061 *
3062 */
3063 BOOL WINAPI GetProcessShutdownParameters( LPDWORD lpdwLevel, LPDWORD lpdwFlags )
3064 {
3065 *lpdwLevel = shutdown_priority;
3066 *lpdwFlags = shutdown_flags;
3067 return TRUE;
3068 }
3069
3070
3071 /***********************************************************************
3072 * GetProcessPriorityBoost (KERNEL32.@)
3073 */
3074 BOOL WINAPI GetProcessPriorityBoost(HANDLE hprocess,PBOOL pDisablePriorityBoost)
3075 {
3076 FIXME("(%p,%p): semi-stub\n", hprocess, pDisablePriorityBoost);
3077
3078 /* Report that no boost is present.. */
3079 *pDisablePriorityBoost = FALSE;
3080
3081 return TRUE;
3082 }
3083
3084 /***********************************************************************
3085 * SetProcessPriorityBoost (KERNEL32.@)
3086 */
3087 BOOL WINAPI SetProcessPriorityBoost(HANDLE hprocess,BOOL disableboost)
3088 {
3089 FIXME("(%p,%d): stub\n",hprocess,disableboost);
3090 /* Say we can do it. I doubt the program will notice that we don't. */
3091 return TRUE;
3092 }
3093
3094
3095 /***********************************************************************
3096 * ReadProcessMemory (KERNEL32.@)
3097 */
3098 BOOL WINAPI ReadProcessMemory( HANDLE process, LPCVOID addr, LPVOID buffer, SIZE_T size,
3099 SIZE_T *bytes_read )
3100 {
3101 NTSTATUS status = NtReadVirtualMemory( process, addr, buffer, size, bytes_read );
3102 if (status) SetLastError( RtlNtStatusToDosError(status) );
3103 return !status;
3104 }
3105
3106
3107 /***********************************************************************
3108 * WriteProcessMemory (KERNEL32.@)
3109 */
3110 BOOL WINAPI WriteProcessMemory( HANDLE process, LPVOID addr, LPCVOID buffer, SIZE_T size,
3111 SIZE_T *bytes_written )
3112 {
3113 NTSTATUS status = NtWriteVirtualMemory( process, addr, buffer, size, bytes_written );
3114 if (status) SetLastError( RtlNtStatusToDosError(status) );
3115 return !status;
3116 }
3117
3118
3119 /****************************************************************************
3120 * FlushInstructionCache (KERNEL32.@)
3121 */
3122 BOOL WINAPI FlushInstructionCache(HANDLE hProcess, LPCVOID lpBaseAddress, SIZE_T dwSize)
3123 {
3124 NTSTATUS status;
3125 status = NtFlushInstructionCache( hProcess, lpBaseAddress, dwSize );
3126 if (status) SetLastError( RtlNtStatusToDosError(status) );
3127 return !status;
3128 }
3129
3130
3131 /******************************************************************
3132 * GetProcessIoCounters (KERNEL32.@)
3133 */
3134 BOOL WINAPI GetProcessIoCounters(HANDLE hProcess, PIO_COUNTERS ioc)
3135 {
3136 NTSTATUS status;
3137
3138 status = NtQueryInformationProcess(hProcess, ProcessIoCounters,
3139 ioc, sizeof(*ioc), NULL);
3140 if (status) SetLastError( RtlNtStatusToDosError(status) );
3141 return !status;
3142 }
3143
3144 /******************************************************************
3145 * GetProcessHandleCount (KERNEL32.@)
3146 */
3147 BOOL WINAPI GetProcessHandleCount(HANDLE hProcess, DWORD *cnt)
3148 {
3149 NTSTATUS status;
3150
3151 status = NtQueryInformationProcess(hProcess, ProcessHandleCount,
3152 cnt, sizeof(*cnt), NULL);
3153 if (status) SetLastError( RtlNtStatusToDosError(status) );
3154 return !status;
3155 }
3156
3157 /******************************************************************
3158 * QueryFullProcessImageNameA (KERNEL32.@)
3159 */
3160 BOOL WINAPI QueryFullProcessImageNameA(HANDLE hProcess, DWORD dwFlags, LPSTR lpExeName, PDWORD pdwSize)
3161 {
3162 BOOL retval;
3163 DWORD pdwSizeW = *pdwSize;
3164 LPWSTR lpExeNameW = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, *pdwSize * sizeof(WCHAR));
3165
3166 retval = QueryFullProcessImageNameW(hProcess, dwFlags, lpExeNameW, &pdwSizeW);
3167
3168 if(retval)
3169 retval = (0 != WideCharToMultiByte(CP_ACP, 0, lpExeNameW, -1,
3170 lpExeName, *pdwSize, NULL, NULL));
3171 if(retval)
3172 *pdwSize = strlen(lpExeName);
3173
3174 HeapFree(GetProcessHeap(), 0, lpExeNameW);
3175 return retval;
3176 }
3177
3178 /******************************************************************
3179 * QueryFullProcessImageNameW (KERNEL32.@)
3180 */
3181 BOOL WINAPI QueryFullProcessImageNameW(HANDLE hProcess, DWORD dwFlags, LPWSTR lpExeName, PDWORD pdwSize)
3182 {
3183 BYTE buffer[sizeof(UNICODE_STRING) + MAX_PATH*sizeof(WCHAR)]; /* this buffer should be enough */
3184 UNICODE_STRING *dynamic_buffer = NULL;
3185 UNICODE_STRING nt_path;
3186 UNICODE_STRING *result = NULL;
3187 NTSTATUS status;
3188 DWORD needed;
3189
3190 RtlInitUnicodeStringEx(&nt_path, NULL);
3191 /* FIXME: On Windows, ProcessImageFileName return an NT path. We rely that it being a DOS path,
3192 * as this is on Wine. */
3193 status = NtQueryInformationProcess(hProcess, ProcessImageFileName, buffer,
3194 sizeof(buffer) - sizeof(WCHAR), &needed);
3195 if (status == STATUS_INFO_LENGTH_MISMATCH)
3196 {
3197 dynamic_buffer = HeapAlloc(GetProcessHeap(), 0, needed + sizeof(WCHAR));
3198 status = NtQueryInformationProcess(hProcess, ProcessImageFileName, (LPBYTE)dynamic_buffer, needed, &needed);
3199 result = dynamic_buffer;
3200 }
3201 else
3202 result = (PUNICODE_STRING)buffer;
3203
3204 if (status) goto cleanup;
3205
3206 if (dwFlags & PROCESS_NAME_NATIVE)
3207 {
3208 result->Buffer[result->Length / sizeof(WCHAR)] = 0;
3209 if (!RtlDosPathNameToNtPathName_U(result->Buffer, &nt_path, NULL, NULL))
3210 {
3211 status = STATUS_OBJECT_PATH_NOT_FOUND;
3212 goto cleanup;
3213 }
3214 result = &nt_path;
3215 }
3216
3217 if (result->Length/sizeof(WCHAR) + 1 > *pdwSize)
3218 {
3219 status = STATUS_BUFFER_TOO_SMALL;
3220 goto cleanup;
3221 }
3222
3223 *pdwSize = result->Length/sizeof(WCHAR);
3224 memcpy( lpExeName, result->Buffer, result->Length );
3225 lpExeName[*pdwSize] = 0;
3226
3227 cleanup:
3228 HeapFree(GetProcessHeap(), 0, dynamic_buffer);
3229 RtlFreeUnicodeString(&nt_path);
3230 if (status) SetLastError( RtlNtStatusToDosError(status) );
3231 return !status;
3232 }
3233
3234 /***********************************************************************
3235 * ProcessIdToSessionId (KERNEL32.@)
3236 * This function is available on Terminal Server 4SP4 and Windows 2000
3237 */
3238 BOOL WINAPI ProcessIdToSessionId( DWORD procid, DWORD *sessionid_ptr )
3239 {
3240 /* According to MSDN, if the calling process is not in a terminal
3241 * services environment, then the sessionid returned is zero.
3242 */
3243 *sessionid_ptr = 0;
3244 return TRUE;
3245 }
3246