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 handles to wait on.
885 */
886 static void start_wineboot( HANDLE handles[2] )
887 {
888 static const WCHAR wineboot_eventW[] = {'_','_','w','i','n','e','b','o','o','t','_','e','v','e','n','t',0};
889
890 handles[1] = 0;
891 if (!(handles[0] = CreateEventW( NULL, TRUE, FALSE, wineboot_eventW )))
892 {
893 ERR( "failed to create wineboot event, expect trouble\n" );
894 return;
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 handles[1] = pi.hProcess;
917 }
918 else
919 {
920 ERR( "failed to start wineboot, err %u\n", GetLastError() );
921 CloseHandle( handles[0] );
922 handles[0] = 0;
923 }
924 }
925 }
926
927
928 /***********************************************************************
929 * start_process
930 *
931 * Startup routine of a new process. Runs on the new process stack.
932 */
933 static void start_process( void *arg )
934 {
935 __TRY
936 {
937 PEB *peb = NtCurrentTeb()->Peb;
938 IMAGE_NT_HEADERS *nt;
939 LPTHREAD_START_ROUTINE entry;
940
941 nt = RtlImageNtHeader( peb->ImageBaseAddress );
942 entry = (LPTHREAD_START_ROUTINE)((char *)peb->ImageBaseAddress +
943 nt->OptionalHeader.AddressOfEntryPoint);
944
945 if (!nt->OptionalHeader.AddressOfEntryPoint)
946 {
947 ERR( "%s doesn't have an entry point, it cannot be executed\n",
948 debugstr_w(peb->ProcessParameters->ImagePathName.Buffer) );
949 ExitThread( 1 );
950 }
951
952 if (TRACE_ON(relay))
953 DPRINTF( "%04x:Starting process %s (entryproc=%p)\n", GetCurrentThreadId(),
954 debugstr_w(peb->ProcessParameters->ImagePathName.Buffer), entry );
955
956 SetLastError( 0 ); /* clear error code */
957 if (peb->BeingDebugged) DbgBreakPoint();
958 ExitThread( entry( peb ) );
959 }
960 __EXCEPT(UnhandledExceptionFilter)
961 {
962 TerminateThread( GetCurrentThread(), GetExceptionCode() );
963 }
964 __ENDTRY
965 }
966
967
968 /***********************************************************************
969 * set_process_name
970 *
971 * Change the process name in the ps output.
972 */
973 static void set_process_name( int argc, char *argv[] )
974 {
975 #ifdef HAVE_SETPROCTITLE
976 setproctitle("-%s", argv[1]);
977 #endif
978
979 #ifdef HAVE_PRCTL
980 int i, offset;
981 char *p, *prctl_name = argv[1];
982 char *end = argv[argc-1] + strlen(argv[argc-1]) + 1;
983
984 #ifndef PR_SET_NAME
985 # define PR_SET_NAME 15
986 #endif
987
988 if ((p = strrchr( prctl_name, '\\' ))) prctl_name = p + 1;
989 if ((p = strrchr( prctl_name, '/' ))) prctl_name = p + 1;
990
991 if (prctl( PR_SET_NAME, prctl_name ) != -1)
992 {
993 offset = argv[1] - argv[0];
994 memmove( argv[1] - offset, argv[1], end - argv[1] );
995 memset( end - offset, 0, offset );
996 for (i = 1; i < argc; i++) argv[i-1] = argv[i] - offset;
997 argv[i-1] = NULL;
998 }
999 else
1000 #endif /* HAVE_PRCTL */
1001 {
1002 /* remove argv[0] */
1003 memmove( argv, argv + 1, argc * sizeof(argv[0]) );
1004 }
1005 }
1006
1007
1008 /***********************************************************************
1009 * __wine_kernel_init
1010 *
1011 * Wine initialisation: load and start the main exe file.
1012 */
1013 void CDECL __wine_kernel_init(void)
1014 {
1015 static const WCHAR kernel32W[] = {'k','e','r','n','e','l','3','2',0};
1016 static const WCHAR dotW[] = {'.',0};
1017 static const WCHAR exeW[] = {'.','e','x','e',0};
1018
1019 WCHAR *p, main_exe_name[MAX_PATH+1];
1020 PEB *peb = NtCurrentTeb()->Peb;
1021 RTL_USER_PROCESS_PARAMETERS *params = peb->ProcessParameters;
1022 HANDLE boot_events[2];
1023 BOOL got_environment = TRUE;
1024
1025 /* Initialize everything */
1026
1027 setbuf(stdout,NULL);
1028 setbuf(stderr,NULL);
1029 kernel32_handle = GetModuleHandleW(kernel32W);
1030 IsWow64Process( GetCurrentProcess(), &is_wow64 );
1031
1032 LOCALE_Init();
1033
1034 if (!params->Environment)
1035 {
1036 /* Copy the parent environment */
1037 if (!build_initial_environment()) exit(1);
1038
1039 /* convert old configuration to new format */
1040 convert_old_config();
1041
1042 got_environment = set_registry_environment();
1043 set_additional_environment();
1044 }
1045
1046 init_windows_dirs();
1047 init_current_directory( ¶ms->CurrentDirectory );
1048
1049 set_process_name( __wine_main_argc, __wine_main_argv );
1050 set_library_wargv( __wine_main_argv );
1051 boot_events[0] = boot_events[1] = 0;
1052
1053 if (peb->ProcessParameters->ImagePathName.Buffer)
1054 {
1055 strcpyW( main_exe_name, peb->ProcessParameters->ImagePathName.Buffer );
1056 }
1057 else
1058 {
1059 if (!SearchPathW( NULL, __wine_main_wargv[0], exeW, MAX_PATH, main_exe_name, NULL ) &&
1060 !get_builtin_path( __wine_main_wargv[0], exeW, main_exe_name, MAX_PATH ))
1061 {
1062 MESSAGE( "wine: cannot find '%s'\n", __wine_main_argv[0] );
1063 ExitProcess( GetLastError() );
1064 }
1065 update_library_argv0( main_exe_name );
1066 if (!build_command_line( __wine_main_wargv )) goto error;
1067 start_wineboot( boot_events );
1068 }
1069
1070 /* if there's no extension, append a dot to prevent LoadLibrary from appending .dll */
1071 p = strrchrW( main_exe_name, '.' );
1072 if (!p || strchrW( p, '/' ) || strchrW( p, '\\' )) strcatW( main_exe_name, dotW );
1073
1074 TRACE( "starting process name=%s argv[0]=%s\n",
1075 debugstr_w(main_exe_name), debugstr_w(__wine_main_wargv[0]) );
1076
1077 RtlInitUnicodeString( &NtCurrentTeb()->Peb->ProcessParameters->DllPath,
1078 MODULE_get_dll_load_path(main_exe_name) );
1079
1080 if (boot_events[0])
1081 {
1082 DWORD timeout = 30000, count = 1;
1083
1084 if (boot_events[1]) count++;
1085 if (!got_environment) timeout = 300000; /* initial prefix creation can take longer */
1086 if (WaitForMultipleObjects( count, boot_events, FALSE, timeout ) == WAIT_TIMEOUT)
1087 ERR( "boot event wait timed out\n" );
1088 CloseHandle( boot_events[0] );
1089 if (boot_events[1]) CloseHandle( boot_events[1] );
1090 /* if we didn't find environment section, try again now that wineboot has run */
1091 if (!got_environment)
1092 {
1093 set_registry_environment();
1094 set_additional_environment();
1095 }
1096 }
1097
1098 if (!(peb->ImageBaseAddress = LoadLibraryExW( main_exe_name, 0, DONT_RESOLVE_DLL_REFERENCES )))
1099 {
1100 char msg[1024];
1101 DWORD error = GetLastError();
1102
1103 /* if Win16/DOS format, or unavailable address, exec a new process with the proper setup */
1104 if (error == ERROR_BAD_EXE_FORMAT ||
1105 error == ERROR_INVALID_ADDRESS ||
1106 error == ERROR_NOT_ENOUGH_MEMORY)
1107 {
1108 if (!getenv("WINEPRELOADRESERVE")) exec_process( main_exe_name );
1109 /* if we get back here, it failed */
1110 }
1111 else if (error == ERROR_MOD_NOT_FOUND)
1112 {
1113 if ((p = strrchrW( main_exe_name, '\\' ))) p++;
1114 else p = main_exe_name;
1115 if (!strcmpiW( p, winevdmW ) && __wine_main_argc > 3)
1116 {
1117 /* args 1 and 2 are --app-name full_path */
1118 MESSAGE( "wine: could not run %s: 16-bit/DOS support missing\n",
1119 debugstr_w(__wine_main_wargv[3]) );
1120 ExitProcess( ERROR_BAD_EXE_FORMAT );
1121 }
1122 }
1123 FormatMessageA( FORMAT_MESSAGE_FROM_SYSTEM, NULL, error, 0, msg, sizeof(msg), NULL );
1124 MESSAGE( "wine: could not load %s: %s", debugstr_w(main_exe_name), msg );
1125 ExitProcess( error );
1126 }
1127
1128 LdrInitializeThunk( 0, 0, 0, 0 );
1129 /* switch to the new stack */
1130 wine_switch_to_stack( start_process, NULL, NtCurrentTeb()->Tib.StackBase );
1131
1132 error:
1133 ExitProcess( GetLastError() );
1134 }
1135
1136
1137 /***********************************************************************
1138 * build_argv
1139 *
1140 * Build an argv array from a command-line.
1141 * 'reserved' is the number of args to reserve before the first one.
1142 */
1143 static char **build_argv( const WCHAR *cmdlineW, int reserved )
1144 {
1145 int argc;
1146 char** argv;
1147 char *arg,*s,*d,*cmdline;
1148 int in_quotes,bcount,len;
1149
1150 len = WideCharToMultiByte( CP_UNIXCP, 0, cmdlineW, -1, NULL, 0, NULL, NULL );
1151 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, len ))) return NULL;
1152 WideCharToMultiByte( CP_UNIXCP, 0, cmdlineW, -1, cmdline, len, NULL, NULL );
1153
1154 argc=reserved+1;
1155 bcount=0;
1156 in_quotes=0;
1157 s=cmdline;
1158 while (1) {
1159 if (*s=='\0' || ((*s==' ' || *s=='\t') && !in_quotes)) {
1160 /* space */
1161 argc++;
1162 /* skip the remaining spaces */
1163 while (*s==' ' || *s=='\t') {
1164 s++;
1165 }
1166 if (*s=='\0')
1167 break;
1168 bcount=0;
1169 continue;
1170 } else if (*s=='\\') {
1171 /* '\', count them */
1172 bcount++;
1173 } else if ((*s=='"') && ((bcount & 1)==0)) {
1174 /* unescaped '"' */
1175 in_quotes=!in_quotes;
1176 bcount=0;
1177 } else {
1178 /* a regular character */
1179 bcount=0;
1180 }
1181 s++;
1182 }
1183 if (!(argv = HeapAlloc( GetProcessHeap(), 0, argc*sizeof(*argv) + len )))
1184 {
1185 HeapFree( GetProcessHeap(), 0, cmdline );
1186 return NULL;
1187 }
1188
1189 arg = d = s = (char *)(argv + argc);
1190 memcpy( d, cmdline, len );
1191 bcount=0;
1192 in_quotes=0;
1193 argc=reserved;
1194 while (*s) {
1195 if ((*s==' ' || *s=='\t') && !in_quotes) {
1196 /* Close the argument and copy it */
1197 *d=0;
1198 argv[argc++]=arg;
1199
1200 /* skip the remaining spaces */
1201 do {
1202 s++;
1203 } while (*s==' ' || *s=='\t');
1204
1205 /* Start with a new argument */
1206 arg=d=s;
1207 bcount=0;
1208 } else if (*s=='\\') {
1209 /* '\\' */
1210 *d++=*s++;
1211 bcount++;
1212 } else if (*s=='"') {
1213 /* '"' */
1214 if ((bcount & 1)==0) {
1215 /* Preceded by an even number of '\', this is half that
1216 * number of '\', plus a '"' which we discard.
1217 */
1218 d-=bcount/2;
1219 s++;
1220 in_quotes=!in_quotes;
1221 } else {
1222 /* Preceded by an odd number of '\', this is half that
1223 * number of '\' followed by a '"'
1224 */
1225 d=d-bcount/2-1;
1226 *d++='"';
1227 s++;
1228 }
1229 bcount=0;
1230 } else {
1231 /* a regular character */
1232 *d++=*s++;
1233 bcount=0;
1234 }
1235 }
1236 if (*arg) {
1237 *d='\0';
1238 argv[argc++]=arg;
1239 }
1240 argv[argc]=NULL;
1241
1242 HeapFree( GetProcessHeap(), 0, cmdline );
1243 return argv;
1244 }
1245
1246
1247 /***********************************************************************
1248 * build_envp
1249 *
1250 * Build the environment of a new child process.
1251 */
1252 static char **build_envp( const WCHAR *envW )
1253 {
1254 static const char * const unix_vars[] = { "PATH", "TEMP", "TMP", "HOME" };
1255
1256 const WCHAR *end;
1257 char **envp;
1258 char *env, *p;
1259 int count = 1, length;
1260 unsigned int i;
1261
1262 for (end = envW; *end; count++) end += strlenW(end) + 1;
1263 end++;
1264 length = WideCharToMultiByte( CP_UNIXCP, 0, envW, end - envW, NULL, 0, NULL, NULL );
1265 if (!(env = HeapAlloc( GetProcessHeap(), 0, length ))) return NULL;
1266 WideCharToMultiByte( CP_UNIXCP, 0, envW, end - envW, env, length, NULL, NULL );
1267
1268 for (p = env; *p; p += strlen(p) + 1)
1269 if (is_special_env_var( p )) length += 4; /* prefix it with "WINE" */
1270
1271 for (i = 0; i < sizeof(unix_vars)/sizeof(unix_vars[0]); i++)
1272 {
1273 if (!(p = getenv(unix_vars[i]))) continue;
1274 length += strlen(unix_vars[i]) + strlen(p) + 2;
1275 count++;
1276 }
1277
1278 if ((envp = HeapAlloc( GetProcessHeap(), 0, count * sizeof(*envp) + length )))
1279 {
1280 char **envptr = envp;
1281 char *dst = (char *)(envp + count);
1282
1283 /* some variables must not be modified, so we get them directly from the unix env */
1284 for (i = 0; i < sizeof(unix_vars)/sizeof(unix_vars[0]); i++)
1285 {
1286 if (!(p = getenv(unix_vars[i]))) continue;
1287 *envptr++ = strcpy( dst, unix_vars[i] );
1288 strcat( dst, "=" );
1289 strcat( dst, p );
1290 dst += strlen(dst) + 1;
1291 }
1292
1293 /* now put the Windows environment strings */
1294 for (p = env; *p; p += strlen(p) + 1)
1295 {
1296 if (*p == '=') continue; /* skip drive curdirs, this crashes some unix apps */
1297 if (!strncmp( p, "WINEPRELOADRESERVE=", sizeof("WINEPRELOADRESERVE=")-1 )) continue;
1298 if (!strncmp( p, "WINELOADERNOEXEC=", sizeof("WINELOADERNOEXEC=")-1 )) continue;
1299 if (!strncmp( p, "WINESERVERSOCKET=", sizeof("WINESERVERSOCKET=")-1 )) continue;
1300 if (is_special_env_var( p )) /* prefix it with "WINE" */
1301 {
1302 *envptr++ = strcpy( dst, "WINE" );
1303 strcat( dst, p );
1304 }
1305 else
1306 {
1307 *envptr++ = strcpy( dst, p );
1308 }
1309 dst += strlen(dst) + 1;
1310 }
1311 *envptr = 0;
1312 }
1313 HeapFree( GetProcessHeap(), 0, env );
1314 return envp;
1315 }
1316
1317
1318 /***********************************************************************
1319 * fork_and_exec
1320 *
1321 * Fork and exec a new Unix binary, checking for errors.
1322 */
1323 static int fork_and_exec( const char *filename, const WCHAR *cmdline, const WCHAR *env,
1324 const char *newdir, DWORD flags, STARTUPINFOW *startup )
1325 {
1326 int fd[2], stdin_fd = -1, stdout_fd = -1;
1327 int pid, err;
1328 char **argv, **envp;
1329
1330 if (!env) env = GetEnvironmentStringsW();
1331
1332 #ifdef HAVE_PIPE2
1333 if (pipe2( fd, O_CLOEXEC ) == -1)
1334 #endif
1335 {
1336 if (pipe(fd) == -1)
1337 {
1338 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
1339 return -1;
1340 }
1341 fcntl( fd[0], F_SETFD, FD_CLOEXEC );
1342 fcntl( fd[1], F_SETFD, FD_CLOEXEC );
1343 }
1344
1345 if (!(flags & (CREATE_NEW_PROCESS_GROUP | CREATE_NEW_CONSOLE | DETACHED_PROCESS)))
1346 {
1347 HANDLE hstdin, hstdout;
1348
1349 if (startup->dwFlags & STARTF_USESTDHANDLES)
1350 {
1351 hstdin = startup->hStdInput;
1352 hstdout = startup->hStdOutput;
1353 }
1354 else
1355 {
1356 hstdin = GetStdHandle(STD_INPUT_HANDLE);
1357 hstdout = GetStdHandle(STD_OUTPUT_HANDLE);
1358 }
1359
1360 if (is_console_handle( hstdin ))
1361 hstdin = wine_server_ptr_handle( console_handle_unmap( hstdin ));
1362 if (is_console_handle( hstdout ))
1363 hstdout = wine_server_ptr_handle( console_handle_unmap( hstdout ));
1364 wine_server_handle_to_fd( hstdin, FILE_READ_DATA, &stdin_fd, NULL );
1365 wine_server_handle_to_fd( hstdout, FILE_WRITE_DATA, &stdout_fd, NULL );
1366 }
1367
1368 argv = build_argv( cmdline, 0 );
1369 envp = build_envp( env );
1370
1371 if (!(pid = fork())) /* child */
1372 {
1373 close( fd[0] );
1374
1375 if (flags & (CREATE_NEW_PROCESS_GROUP | CREATE_NEW_CONSOLE | DETACHED_PROCESS))
1376 {
1377 int pid;
1378 if (!(pid = fork()))
1379 {
1380 int fd = open( "/dev/null", O_RDWR );
1381 setsid();
1382 /* close stdin and stdout */
1383 if (fd != -1)
1384 {
1385 dup2( fd, 0 );
1386 dup2( fd, 1 );
1387 close( fd );
1388 }
1389 }
1390 else if (pid != -1) _exit(0); /* parent */
1391 }
1392 else
1393 {
1394 if (stdin_fd != -1)
1395 {
1396 dup2( stdin_fd, 0 );
1397 close( stdin_fd );
1398 }
1399 if (stdout_fd != -1)
1400 {
1401 dup2( stdout_fd, 1 );
1402 close( stdout_fd );
1403 }
1404 }
1405
1406 /* Reset signals that we previously set to SIG_IGN */
1407 signal( SIGPIPE, SIG_DFL );
1408 signal( SIGCHLD, SIG_DFL );
1409
1410 if (newdir) chdir(newdir);
1411
1412 if (argv && envp) execve( filename, argv, envp );
1413 err = errno;
1414 write( fd[1], &err, sizeof(err) );
1415 _exit(1);
1416 }
1417 HeapFree( GetProcessHeap(), 0, argv );
1418 HeapFree( GetProcessHeap(), 0, envp );
1419 if (stdin_fd != -1) close( stdin_fd );
1420 if (stdout_fd != -1) close( stdout_fd );
1421 close( fd[1] );
1422 if ((pid != -1) && (read( fd[0], &err, sizeof(err) ) > 0)) /* exec failed */
1423 {
1424 errno = err;
1425 pid = -1;
1426 }
1427 if (pid == -1) FILE_SetDosError();
1428 close( fd[0] );
1429 return pid;
1430 }
1431
1432
1433 /***********************************************************************
1434 * create_user_params
1435 */
1436 static RTL_USER_PROCESS_PARAMETERS *create_user_params( LPCWSTR filename, LPCWSTR cmdline,
1437 LPCWSTR cur_dir, LPWSTR env, DWORD flags,
1438 const STARTUPINFOW *startup )
1439 {
1440 RTL_USER_PROCESS_PARAMETERS *params;
1441 UNICODE_STRING image_str, cmdline_str, curdir_str, desktop, title, runtime, newdir;
1442 NTSTATUS status;
1443 WCHAR buffer[MAX_PATH];
1444
1445 if(!GetLongPathNameW( filename, buffer, MAX_PATH ))
1446 lstrcpynW( buffer, filename, MAX_PATH );
1447 if(!GetFullPathNameW( buffer, MAX_PATH, buffer, NULL ))
1448 lstrcpynW( buffer, filename, MAX_PATH );
1449 RtlInitUnicodeString( &image_str, buffer );
1450
1451 RtlInitUnicodeString( &cmdline_str, cmdline );
1452 newdir.Buffer = NULL;
1453 if (cur_dir)
1454 {
1455 if (RtlDosPathNameToNtPathName_U( cur_dir, &newdir, NULL, NULL ))
1456 {
1457 /* skip \??\ prefix */
1458 curdir_str.Buffer = newdir.Buffer + 4;
1459 curdir_str.Length = newdir.Length - 4 * sizeof(WCHAR);
1460 curdir_str.MaximumLength = newdir.MaximumLength - 4 * sizeof(WCHAR);
1461 }
1462 else cur_dir = NULL;
1463 }
1464 if (startup->lpDesktop) RtlInitUnicodeString( &desktop, startup->lpDesktop );
1465 if (startup->lpTitle) RtlInitUnicodeString( &title, startup->lpTitle );
1466 if (startup->lpReserved2 && startup->cbReserved2)
1467 {
1468 runtime.Length = 0;
1469 runtime.MaximumLength = startup->cbReserved2;
1470 runtime.Buffer = (WCHAR*)startup->lpReserved2;
1471 }
1472
1473 status = RtlCreateProcessParameters( ¶ms, &image_str, NULL,
1474 cur_dir ? &curdir_str : NULL,
1475 &cmdline_str, env,
1476 startup->lpTitle ? &title : NULL,
1477 startup->lpDesktop ? &desktop : NULL,
1478 NULL,
1479 (startup->lpReserved2 && startup->cbReserved2) ? &runtime : NULL );
1480 RtlFreeUnicodeString( &newdir );
1481 if (status != STATUS_SUCCESS)
1482 {
1483 SetLastError( RtlNtStatusToDosError(status) );
1484 return NULL;
1485 }
1486
1487 if (flags & CREATE_NEW_PROCESS_GROUP) params->ConsoleFlags = 1;
1488 if (flags & CREATE_NEW_CONSOLE) params->ConsoleHandle = (HANDLE)1; /* FIXME: cf. kernel_main.c */
1489
1490 if (startup->dwFlags & STARTF_USESTDHANDLES)
1491 {
1492 params->hStdInput = startup->hStdInput;
1493 params->hStdOutput = startup->hStdOutput;
1494 params->hStdError = startup->hStdError;
1495 }
1496 else
1497 {
1498 params->hStdInput = GetStdHandle( STD_INPUT_HANDLE );
1499 params->hStdOutput = GetStdHandle( STD_OUTPUT_HANDLE );
1500 params->hStdError = GetStdHandle( STD_ERROR_HANDLE );
1501 }
1502 params->dwX = startup->dwX;
1503 params->dwY = startup->dwY;
1504 params->dwXSize = startup->dwXSize;
1505 params->dwYSize = startup->dwYSize;
1506 params->dwXCountChars = startup->dwXCountChars;
1507 params->dwYCountChars = startup->dwYCountChars;
1508 params->dwFillAttribute = startup->dwFillAttribute;
1509 params->dwFlags = startup->dwFlags;
1510 params->wShowWindow = startup->wShowWindow;
1511 return params;
1512 }
1513
1514
1515 /***********************************************************************
1516 * create_process
1517 *
1518 * Create a new process. If hFile is a valid handle we have an exe
1519 * file, otherwise it is a Winelib app.
1520 */
1521 static BOOL create_process( HANDLE hFile, LPCWSTR filename, LPWSTR cmd_line, LPWSTR env,
1522 LPCWSTR cur_dir, LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1523 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
1524 LPPROCESS_INFORMATION info, LPCSTR unixdir,
1525 void *res_start, void *res_end, DWORD binary_type, int exec_only )
1526 {
1527 BOOL ret, success = FALSE;
1528 HANDLE process_info, hstdin, hstdout;
1529 WCHAR *env_end;
1530 char *winedebug = NULL;
1531 char **argv;
1532 RTL_USER_PROCESS_PARAMETERS *params;
1533 int socketfd[2], stdin_fd = -1, stdout_fd = -1;
1534 pid_t pid;
1535 int err;
1536
1537 if (sizeof(void *) == sizeof(int) && !is_wow64 && (binary_type & BINARY_FLAG_64BIT))
1538 {
1539 ERR( "starting 64-bit process %s not supported on this platform\n", debugstr_w(filename) );
1540 SetLastError( ERROR_BAD_EXE_FORMAT );
1541 return FALSE;
1542 }
1543
1544 if (!env) RtlAcquirePebLock();
1545
1546 if (!(params = create_user_params( filename, cmd_line, cur_dir, env, flags, startup )))
1547 {
1548 if (!env) RtlReleasePebLock();
1549 return FALSE;
1550 }
1551 env_end = params->Environment;
1552 while (*env_end)
1553 {
1554 static const WCHAR WINEDEBUG[] = {'W','I','N','E','D','E','B','U','G','=',0};
1555 if (!winedebug && !strncmpW( env_end, WINEDEBUG, sizeof(WINEDEBUG)/sizeof(WCHAR) - 1 ))
1556 {
1557 DWORD len = WideCharToMultiByte( CP_UNIXCP, 0, env_end, -1, NULL, 0, NULL, NULL );
1558 if ((winedebug = HeapAlloc( GetProcessHeap(), 0, len )))
1559 WideCharToMultiByte( CP_UNIXCP, 0, env_end, -1, winedebug, len, NULL, NULL );
1560 }
1561 env_end += strlenW(env_end) + 1;
1562 }
1563 env_end++;
1564
1565 /* create the socket for the new process */
1566
1567 if (socketpair( PF_UNIX, SOCK_STREAM, 0, socketfd ) == -1)
1568 {
1569 if (!env) RtlReleasePebLock();
1570 HeapFree( GetProcessHeap(), 0, winedebug );
1571 RtlDestroyProcessParameters( params );
1572 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
1573 return FALSE;
1574 }
1575 wine_server_send_fd( socketfd[1] );
1576 close( socketfd[1] );
1577
1578 /* create the process on the server side */
1579
1580 SERVER_START_REQ( new_process )
1581 {
1582 req->inherit_all = inherit;
1583 req->create_flags = flags;
1584 req->socket_fd = socketfd[1];
1585 req->exe_file = wine_server_obj_handle( hFile );
1586 req->process_access = PROCESS_ALL_ACCESS;
1587 req->process_attr = (psa && (psa->nLength >= sizeof(*psa)) && psa->bInheritHandle) ? OBJ_INHERIT : 0;
1588 req->thread_access = THREAD_ALL_ACCESS;
1589 req->thread_attr = (tsa && (tsa->nLength >= sizeof(*tsa)) && tsa->bInheritHandle) ? OBJ_INHERIT : 0;
1590 req->hstdin = wine_server_obj_handle( params->hStdInput );
1591 req->hstdout = wine_server_obj_handle( params->hStdOutput );
1592 req->hstderr = wine_server_obj_handle( params->hStdError );
1593
1594 if ((flags & (CREATE_NEW_CONSOLE | DETACHED_PROCESS)) != 0)
1595 {
1596 /* this is temporary (for console handles). We have no way to control that the handle is invalid in child process otherwise */
1597 if (is_console_handle(params->hStdInput)) req->hstdin = wine_server_obj_handle( INVALID_HANDLE_VALUE );
1598 if (is_console_handle(params->hStdOutput)) req->hstdout = wine_server_obj_handle( INVALID_HANDLE_VALUE );
1599 if (is_console_handle(params->hStdError)) req->hstderr = wine_server_obj_handle( INVALID_HANDLE_VALUE );
1600 hstdin = hstdout = 0;
1601 }
1602 else
1603 {
1604 if (is_console_handle(params->hStdInput)) req->hstdin = console_handle_unmap(params->hStdInput);
1605 if (is_console_handle(params->hStdOutput)) req->hstdout = console_handle_unmap(params->hStdOutput);
1606 if (is_console_handle(params->hStdError)) req->hstderr = console_handle_unmap(params->hStdError);
1607 hstdin = wine_server_ptr_handle( req->hstdin );
1608 hstdout = wine_server_ptr_handle( req->hstdout );
1609 }
1610
1611 wine_server_add_data( req, params, params->Size );
1612 wine_server_add_data( req, params->Environment, (env_end-params->Environment)*sizeof(WCHAR) );
1613 if ((ret = !wine_server_call_err( req )))
1614 {
1615 info->dwProcessId = (DWORD)reply->pid;
1616 info->dwThreadId = (DWORD)reply->tid;
1617 info->hProcess = wine_server_ptr_handle( reply->phandle );
1618 info->hThread = wine_server_ptr_handle( reply->thandle );
1619 }
1620 process_info = wine_server_ptr_handle( reply->info );
1621 }
1622 SERVER_END_REQ;
1623
1624 if (!env) RtlReleasePebLock();
1625 RtlDestroyProcessParameters( params );
1626 if (!ret)
1627 {
1628 close( socketfd[0] );
1629 HeapFree( GetProcessHeap(), 0, winedebug );
1630 return FALSE;
1631 }
1632
1633 if (hstdin) wine_server_handle_to_fd( hstdin, FILE_READ_DATA, &stdin_fd, NULL );
1634 if (hstdout) wine_server_handle_to_fd( hstdout, FILE_WRITE_DATA, &stdout_fd, NULL );
1635
1636 /* create the child process */
1637 argv = build_argv( cmd_line, 1 );
1638
1639 if (exec_only || !(pid = fork())) /* child */
1640 {
1641 char preloader_reserve[64], socket_env[64];
1642
1643 if (flags & (CREATE_NEW_PROCESS_GROUP | CREATE_NEW_CONSOLE | DETACHED_PROCESS))
1644 {
1645 if (!(pid = fork()))
1646 {
1647 int fd = open( "/dev/null", O_RDWR );
1648 setsid();
1649 /* close stdin and stdout */
1650 if (fd != -1)
1651 {
1652 dup2( fd, 0 );
1653 dup2( fd, 1 );
1654 close( fd );
1655 }
1656 }
1657 else if (pid != -1) _exit(0); /* parent */
1658 }
1659 else
1660 {
1661 if (stdin_fd != -1) dup2( stdin_fd, 0 );
1662 if (stdout_fd != -1) dup2( stdout_fd, 1 );
1663 }
1664
1665 if (stdin_fd != -1) close( stdin_fd );
1666 if (stdout_fd != -1) close( stdout_fd );
1667
1668 /* Reset signals that we previously set to SIG_IGN */
1669 signal( SIGPIPE, SIG_DFL );
1670 signal( SIGCHLD, SIG_DFL );
1671
1672 sprintf( socket_env, "WINESERVERSOCKET=%u", socketfd[0] );
1673 sprintf( preloader_reserve, "WINEPRELOADRESERVE=%lx-%lx",
1674 (unsigned long)res_start, (unsigned long)res_end );
1675
1676 putenv( preloader_reserve );
1677 putenv( socket_env );
1678 if (winedebug) putenv( winedebug );
1679 if (unixdir) chdir(unixdir);
1680
1681 if (argv) wine_exec_wine_binary( NULL, argv, getenv("WINELOADER") );
1682 _exit(1);
1683 }
1684
1685 /* this is the parent */
1686
1687 if (stdin_fd != -1) close( stdin_fd );
1688 if (stdout_fd != -1) close( stdout_fd );
1689 close( socketfd[0] );
1690 HeapFree( GetProcessHeap(), 0, argv );
1691 HeapFree( GetProcessHeap(), 0, winedebug );
1692 if (pid == -1)
1693 {
1694 FILE_SetDosError();
1695 goto error;
1696 }
1697
1698 /* wait for the new process info to be ready */
1699
1700 WaitForSingleObject( process_info, INFINITE );
1701 SERVER_START_REQ( get_new_process_info )
1702 {
1703 req->info = wine_server_obj_handle( process_info );
1704 wine_server_call( req );
1705 success = reply->success;
1706 err = reply->exit_code;
1707 }
1708 SERVER_END_REQ;
1709
1710 if (!success)
1711 {
1712 SetLastError( err ? err : ERROR_INTERNAL_ERROR );
1713 goto error;
1714 }
1715 CloseHandle( process_info );
1716 return success;
1717
1718 error:
1719 CloseHandle( process_info );
1720 CloseHandle( info->hProcess );
1721 CloseHandle( info->hThread );
1722 info->hProcess = info->hThread = 0;
1723 info->dwProcessId = info->dwThreadId = 0;
1724 return FALSE;
1725 }
1726
1727
1728 /***********************************************************************
1729 * create_vdm_process
1730 *
1731 * Create a new VDM process for a 16-bit or DOS application.
1732 */
1733 static BOOL create_vdm_process( LPCWSTR filename, LPWSTR cmd_line, LPWSTR env, LPCWSTR cur_dir,
1734 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1735 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
1736 LPPROCESS_INFORMATION info, LPCSTR unixdir,
1737 DWORD binary_type, int exec_only )
1738 {
1739 static const WCHAR argsW[] = {'%','s',' ','-','-','a','p','p','-','n','a','m','e',' ','"','%','s','"',' ','%','s',0};
1740
1741 BOOL ret;
1742 LPWSTR new_cmd_line = HeapAlloc( GetProcessHeap(), 0,
1743 (strlenW(filename) + strlenW(cmd_line) + 30) * sizeof(WCHAR) );
1744
1745 if (!new_cmd_line)
1746 {
1747 SetLastError( ERROR_OUTOFMEMORY );
1748 return FALSE;
1749 }
1750 sprintfW( new_cmd_line, argsW, winevdmW, filename, cmd_line );
1751 ret = create_process( 0, winevdmW, new_cmd_line, env, cur_dir, psa, tsa, inherit,
1752 flags, startup, info, unixdir, NULL, NULL, binary_type, exec_only );
1753 HeapFree( GetProcessHeap(), 0, new_cmd_line );
1754 return ret;
1755 }
1756
1757
1758 /***********************************************************************
1759 * create_cmd_process
1760 *
1761 * Create a new cmd shell process for a .BAT file.
1762 */
1763 static BOOL create_cmd_process( LPCWSTR filename, LPWSTR cmd_line, LPVOID env, LPCWSTR cur_dir,
1764 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1765 BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
1766 LPPROCESS_INFORMATION info )
1767
1768 {
1769 static const WCHAR comspecW[] = {'C','O','M','S','P','E','C',0};
1770 static const WCHAR slashcW[] = {' ','/','c',' ',0};
1771 WCHAR comspec[MAX_PATH];
1772 WCHAR *newcmdline;
1773 BOOL ret;
1774
1775 if (!GetEnvironmentVariableW( comspecW, comspec, sizeof(comspec)/sizeof(WCHAR) ))
1776 return FALSE;
1777 if (!(newcmdline = HeapAlloc( GetProcessHeap(), 0,
1778 (strlenW(comspec) + 4 + strlenW(cmd_line) + 1) * sizeof(WCHAR))))
1779 return FALSE;
1780
1781 strcpyW( newcmdline, comspec );
1782 strcatW( newcmdline, slashcW );
1783 strcatW( newcmdline, cmd_line );
1784 ret = CreateProcessW( comspec, newcmdline, psa, tsa, inherit,
1785 flags, env, cur_dir, startup, info );
1786 HeapFree( GetProcessHeap(), 0, newcmdline );
1787 return ret;
1788 }
1789
1790
1791 /*************************************************************************
1792 * get_file_name
1793 *
1794 * Helper for CreateProcess: retrieve the file name to load from the
1795 * app name and command line. Store the file name in buffer, and
1796 * return a possibly modified command line.
1797 * Also returns a handle to the opened file if it's a Windows binary.
1798 */
1799 static LPWSTR get_file_name( LPCWSTR appname, LPWSTR cmdline, LPWSTR buffer,
1800 int buflen, HANDLE *handle )
1801 {
1802 static const WCHAR quotesW[] = {'"','%','s','"',0};
1803
1804 WCHAR *name, *pos, *ret = NULL;
1805 const WCHAR *p;
1806 BOOL got_space;
1807
1808 /* if we have an app name, everything is easy */
1809
1810 if (appname)
1811 {
1812 /* use the unmodified app name as file name */
1813 lstrcpynW( buffer, appname, buflen );
1814 *handle = open_exe_file( buffer );
1815 if (!(ret = cmdline) || !cmdline[0])
1816 {
1817 /* no command-line, create one */
1818 if ((ret = HeapAlloc( GetProcessHeap(), 0, (strlenW(appname) + 3) * sizeof(WCHAR) )))
1819 sprintfW( ret, quotesW, appname );
1820 }
1821 return ret;
1822 }
1823
1824 /* first check for a quoted file name */
1825
1826 if ((cmdline[0] == '"') && ((p = strchrW( cmdline + 1, '"' ))))
1827 {
1828 int len = p - cmdline - 1;
1829 /* extract the quoted portion as file name */
1830 if (!(name = HeapAlloc( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) ))) return NULL;
1831 memcpy( name, cmdline + 1, len * sizeof(WCHAR) );
1832 name[len] = 0;
1833
1834 if (find_exe_file( name, buffer, buflen, handle ))
1835 ret = cmdline; /* no change necessary */
1836 goto done;
1837 }
1838
1839 /* now try the command-line word by word */
1840
1841 if (!(name = HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline) + 1) * sizeof(WCHAR) )))
1842 return NULL;
1843 pos = name;
1844 p = cmdline;
1845 got_space = FALSE;
1846
1847 while (*p)
1848 {
1849 do *pos++ = *p++; while (*p && *p != ' ' && *p != '\t');
1850 *pos = 0;
1851 if (find_exe_file( name, buffer, buflen, handle ))
1852 {
1853 ret = cmdline;
1854 break;
1855 }
1856 if (*p) got_space = TRUE;
1857 }
1858
1859 if (ret && got_space) /* now build a new command-line with quotes */
1860 {
1861 if (!(ret = HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline) + 3) * sizeof(WCHAR) )))
1862 goto done;
1863 sprintfW( ret, quotesW, name );
1864 strcatW( ret, p );
1865 }
1866 else if (!ret) SetLastError( ERROR_FILE_NOT_FOUND );
1867
1868 done:
1869 HeapFree( GetProcessHeap(), 0, name );
1870 return ret;
1871 }
1872
1873
1874 /**********************************************************************
1875 * CreateProcessA (KERNEL32.@)
1876 */
1877 BOOL WINAPI CreateProcessA( LPCSTR app_name, LPSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
1878 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit,
1879 DWORD flags, LPVOID env, LPCSTR cur_dir,
1880 LPSTARTUPINFOA startup_info, LPPROCESS_INFORMATION info )
1881 {
1882 BOOL ret = FALSE;
1883 WCHAR *app_nameW = NULL, *cmd_lineW = NULL, *cur_dirW = NULL;
1884 UNICODE_STRING desktopW, titleW;
1885 STARTUPINFOW infoW;
1886
1887 desktopW.Buffer = NULL;
1888 titleW.Buffer = NULL;
1889 if (app_name && !(app_nameW = FILE_name_AtoW( app_name, TRUE ))) goto done;
1890 if (cmd_line && !(cmd_lineW = FILE_name_AtoW( cmd_line, TRUE ))) goto done;
1891 if (cur_dir && !(cur_dirW = FILE_name_AtoW( cur_dir, TRUE ))) goto done;
1892
1893 if (startup_info->lpDesktop) RtlCreateUnicodeStringFromAsciiz( &desktopW, startup_info->lpDesktop );
1894 if (startup_info->lpTitle) RtlCreateUnicodeStringFromAsciiz( &titleW, startup_info->lpTitle );
1895
1896 memcpy( &infoW, startup_info, sizeof(infoW) );
1897 infoW.lpDesktop = desktopW.Buffer;
1898 infoW.lpTitle = titleW.Buffer;
1899
1900 if (startup_info->lpReserved)
1901 FIXME("StartupInfo.lpReserved is used, please report (%s)\n",
1902 debugstr_a(startup_info->lpReserved));
1903
1904 ret = CreateProcessW( app_nameW, cmd_lineW, process_attr, thread_attr,
1905 inherit, flags, env, cur_dirW, &infoW, info );
1906 done:
1907 HeapFree( GetProcessHeap(), 0, app_nameW );
1908 HeapFree( GetProcessHeap(), 0, cmd_lineW );
1909 HeapFree( GetProcessHeap(), 0, cur_dirW );
1910 RtlFreeUnicodeString( &desktopW );
1911 RtlFreeUnicodeString( &titleW );
1912 return ret;
1913 }
1914
1915
1916 /**********************************************************************
1917 * CreateProcessW (KERNEL32.@)
1918 */
1919 BOOL WINAPI CreateProcessW( LPCWSTR app_name, LPWSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
1920 LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit, DWORD flags,
1921 LPVOID env, LPCWSTR cur_dir, LPSTARTUPINFOW startup_info,
1922 LPPROCESS_INFORMATION info )
1923 {
1924 BOOL retv = FALSE;
1925 HANDLE hFile = 0;
1926 char *unixdir = NULL;
1927 WCHAR name[MAX_PATH];
1928 WCHAR *tidy_cmdline, *p, *envW = env;
1929 void *res_start, *res_end;
1930 DWORD binary_type;
1931
1932 /* Process the AppName and/or CmdLine to get module name and path */
1933
1934 TRACE("app %s cmdline %s\n", debugstr_w(app_name), debugstr_w(cmd_line) );
1935
1936 if (!(tidy_cmdline = get_file_name( app_name, cmd_line, name, sizeof(name)/sizeof(WCHAR), &hFile )))
1937 return FALSE;
1938 if (hFile == INVALID_HANDLE_VALUE) goto done;
1939
1940 /* Warn if unsupported features are used */
1941
1942 if (flags & (IDLE_PRIORITY_CLASS | HIGH_PRIORITY_CLASS | REALTIME_PRIORITY_CLASS |
1943 CREATE_NEW_PROCESS_GROUP | CREATE_SEPARATE_WOW_VDM | CREATE_SHARED_WOW_VDM |
1944 CREATE_DEFAULT_ERROR_MODE | CREATE_NO_WINDOW |
1945 PROFILE_USER | PROFILE_KERNEL | PROFILE_SERVER))
1946 WARN("(%s,...): ignoring some flags in %x\n", debugstr_w(name), flags);
1947
1948 if (cur_dir)
1949 {
1950 if (!(unixdir = wine_get_unix_file_name( cur_dir )))
1951 {
1952 SetLastError(ERROR_DIRECTORY);
1953 goto done;
1954 }
1955 }
1956 else
1957 {
1958 WCHAR buf[MAX_PATH];
1959 if (GetCurrentDirectoryW(MAX_PATH, buf)) unixdir = wine_get_unix_file_name( buf );
1960 }
1961
1962 if (env && !(flags & CREATE_UNICODE_ENVIRONMENT)) /* convert environment to unicode */
1963 {
1964 char *p = env;
1965 DWORD lenW;
1966
1967 while (*p) p += strlen(p) + 1;
1968 p++; /* final null */
1969 lenW = MultiByteToWideChar( CP_ACP, 0, env, p - (char*)env, NULL, 0 );
1970 envW = HeapAlloc( GetProcessHeap(), 0, lenW * sizeof(WCHAR) );
1971 MultiByteToWideChar( CP_ACP, 0, env, p - (char*)env, envW, lenW );
1972 flags |= CREATE_UNICODE_ENVIRONMENT;
1973 }
1974
1975 info->hThread = info->hProcess = 0;
1976 info->dwProcessId = info->dwThreadId = 0;
1977
1978 /* Determine executable type */
1979
1980 if (!hFile) /* builtin exe */
1981 {
1982 TRACE( "starting %s as Winelib app\n", debugstr_w(name) );
1983 retv = create_process( 0, name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1984 inherit, flags, startup_info, info, unixdir, NULL, NULL,
1985 BINARY_UNIX_LIB, FALSE );
1986 goto done;
1987 }
1988
1989 binary_type = MODULE_GetBinaryType( hFile, &res_start, &res_end );
1990 if (binary_type & BINARY_FLAG_DLL)
1991 {
1992 TRACE( "not starting %s since it is a dll\n", debugstr_w(name) );
1993 SetLastError( ERROR_BAD_EXE_FORMAT );
1994 }
1995 else switch (binary_type & BINARY_TYPE_MASK)
1996 {
1997 case BINARY_PE:
1998 TRACE( "starting %s as Win32 binary (%p-%p)\n", debugstr_w(name), res_start, res_end );
1999 retv = create_process( hFile, name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2000 inherit, flags, startup_info, info, unixdir,
2001 res_start, res_end, binary_type, FALSE );
2002 break;
2003 case BINARY_OS216:
2004 case BINARY_WIN16:
2005 case BINARY_DOS:
2006 TRACE( "starting %s as Win16/DOS binary\n", debugstr_w(name) );
2007 retv = create_vdm_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2008 inherit, flags, startup_info, info, unixdir, binary_type, FALSE );
2009 break;
2010 case BINARY_UNIX_LIB:
2011 TRACE( "%s is a Unix library, starting as Winelib app\n", debugstr_w(name) );
2012 retv = create_process( hFile, name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2013 inherit, flags, startup_info, info, unixdir,
2014 NULL, NULL, binary_type, FALSE );
2015 break;
2016 case BINARY_UNKNOWN:
2017 /* check for .com or .bat extension */
2018 if ((p = strrchrW( name, '.' )))
2019 {
2020 if (!strcmpiW( p, comW ) || !strcmpiW( p, pifW ))
2021 {
2022 TRACE( "starting %s as DOS binary\n", debugstr_w(name) );
2023 retv = create_vdm_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2024 inherit, flags, startup_info, info, unixdir,
2025 binary_type, FALSE );
2026 break;
2027 }
2028 if (!strcmpiW( p, batW ) || !strcmpiW( p, cmdW ) )
2029 {
2030 TRACE( "starting %s as batch binary\n", debugstr_w(name) );
2031 retv = create_cmd_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
2032 inherit, flags, startup_info, info );
2033 break;
2034 }
2035 }
2036 /* fall through */
2037 case BINARY_UNIX_EXE:
2038 {
2039 /* unknown file, try as unix executable */
2040 char *unix_name;
2041
2042 TRACE( "starting %s as Unix binary\n", debugstr_w(name) );
2043
2044 if ((unix_name = wine_get_unix_file_name( name )))
2045 {
2046 retv = (fork_and_exec( unix_name, tidy_cmdline, envW, unixdir, flags, startup_info ) != -1);
2047 HeapFree( GetProcessHeap(), 0, unix_name );
2048 }
2049 }
2050 break;
2051 }
2052 CloseHandle( hFile );
2053
2054 done:
2055 if (tidy_cmdline != cmd_line) HeapFree( GetProcessHeap(), 0, tidy_cmdline );
2056 if (envW != env) HeapFree( GetProcessHeap(), 0, envW );
2057 HeapFree( GetProcessHeap(), 0, unixdir );
2058 if (retv)
2059 TRACE( "started process pid %04x tid %04x\n", info->dwProcessId, info->dwThreadId );
2060 return retv;
2061 }
2062
2063
2064 /**********************************************************************
2065 * exec_process
2066 */
2067 static void exec_process( LPCWSTR name )
2068 {
2069 HANDLE hFile;
2070 WCHAR *p;
2071 void *res_start, *res_end;
2072 STARTUPINFOW startup_info;
2073 PROCESS_INFORMATION info;
2074 DWORD binary_type;
2075
2076 hFile = open_exe_file( name );
2077 if (!hFile || hFile == INVALID_HANDLE_VALUE) return;
2078
2079 memset( &startup_info, 0, sizeof(startup_info) );
2080 startup_info.cb = sizeof(startup_info);
2081
2082 /* Determine executable type */
2083
2084 binary_type = MODULE_GetBinaryType( hFile, &res_start, &res_end );
2085 if (binary_type & BINARY_FLAG_DLL) return;
2086 switch (binary_type & BINARY_TYPE_MASK)
2087 {
2088 case BINARY_PE:
2089 TRACE( "starting %s as Win32 binary (%p-%p)\n", debugstr_w(name), res_start, res_end );
2090 create_process( hFile, name, GetCommandLineW(), NULL, NULL, NULL, NULL,
2091 FALSE, 0, &startup_info, &info, NULL, res_start, res_end, binary_type, TRUE );
2092 break;
2093 case BINARY_UNIX_LIB:
2094 TRACE( "%s is a Unix library, starting as Winelib app\n", debugstr_w(name) );
2095 create_process( hFile, name, GetCommandLineW(), NULL, NULL, NULL, NULL,
2096 FALSE, 0, &startup_info, &info, NULL, NULL, NULL, binary_type, TRUE );
2097 break;
2098 case BINARY_UNKNOWN:
2099 /* check for .com or .pif extension */
2100 if (!(p = strrchrW( name, '.' ))) break;
2101 if (strcmpiW( p, comW ) && strcmpiW( p, pifW )) break;
2102 /* fall through */
2103 case BINARY_OS216:
2104 case BINARY_WIN16:
2105 case BINARY_DOS:
2106 TRACE( "starting %s as Win16/DOS binary\n", debugstr_w(name) );
2107 create_vdm_process( name, GetCommandLineW(), NULL, NULL, NULL, NULL,
2108 FALSE, 0, &startup_info, &info, NULL, binary_type, TRUE );
2109 break;
2110 default:
2111 break;
2112 }
2113 CloseHandle( hFile );
2114 }
2115
2116
2117 /***********************************************************************
2118 * wait_input_idle
2119 *
2120 * Wrapper to call WaitForInputIdle USER function
2121 */
2122 typedef DWORD (WINAPI *WaitForInputIdle_ptr)( HANDLE hProcess, DWORD dwTimeOut );
2123
2124 static DWORD wait_input_idle( HANDLE process, DWORD timeout )
2125 {
2126 HMODULE mod = GetModuleHandleA( "user32.dll" );
2127 if (mod)
2128 {
2129 WaitForInputIdle_ptr ptr = (WaitForInputIdle_ptr)GetProcAddress( mod, "WaitForInputIdle" );
2130 if (ptr) return ptr( process, timeout );
2131 }
2132 return 0;
2133 }
2134
2135
2136 /***********************************************************************
2137 * WinExec (KERNEL32.@)
2138 */
2139 UINT WINAPI WinExec( LPCSTR lpCmdLine, UINT nCmdShow )
2140 {
2141 PROCESS_INFORMATION info;
2142 STARTUPINFOA startup;
2143 char *cmdline;
2144 UINT ret;
2145
2146 memset( &startup, 0, sizeof(startup) );
2147 startup.cb = sizeof(startup);
2148 startup.dwFlags = STARTF_USESHOWWINDOW;
2149 startup.wShowWindow = nCmdShow;
2150
2151 /* cmdline needs to be writable for CreateProcess */
2152 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(lpCmdLine)+1 ))) return 0;
2153 strcpy( cmdline, lpCmdLine );
2154
2155 if (CreateProcessA( NULL, cmdline, NULL, NULL, FALSE,
2156 0, NULL, NULL, &startup, &info ))
2157 {
2158 /* Give 30 seconds to the app to come up */
2159 if (wait_input_idle( info.hProcess, 30000 ) == WAIT_FAILED)
2160 WARN("WaitForInputIdle failed: Error %d\n", GetLastError() );
2161 ret = 33;
2162 /* Close off the handles */
2163 CloseHandle( info.hThread );
2164 CloseHandle( info.hProcess );
2165 }
2166 else if ((ret = GetLastError()) >= 32)
2167 {
2168 FIXME("Strange error set by CreateProcess: %d\n", ret );
2169 ret = 11;
2170 }
2171 HeapFree( GetProcessHeap(), 0, cmdline );
2172 return ret;
2173 }
2174
2175
2176 /**********************************************************************
2177 * LoadModule (KERNEL32.@)
2178 */
2179 HINSTANCE WINAPI LoadModule( LPCSTR name, LPVOID paramBlock )
2180 {
2181 LOADPARMS32 *params = paramBlock;
2182 PROCESS_INFORMATION info;
2183 STARTUPINFOA startup;
2184 HINSTANCE hInstance;
2185 LPSTR cmdline, p;
2186 char filename[MAX_PATH];
2187 BYTE len;
2188
2189 if (!name) return (HINSTANCE)ERROR_FILE_NOT_FOUND;
2190
2191 if (!SearchPathA( NULL, name, ".exe", sizeof(filename), filename, NULL ) &&
2192 !SearchPathA( NULL, name, NULL, sizeof(filename), filename, NULL ))
2193 return ULongToHandle(GetLastError());
2194
2195 len = (BYTE)params->lpCmdLine[0];
2196 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(filename) + len + 2 )))
2197 return (HINSTANCE)ERROR_NOT_ENOUGH_MEMORY;
2198
2199 strcpy( cmdline, filename );
2200 p = cmdline + strlen(cmdline);
2201 *p++ = ' ';
2202 memcpy( p, params->lpCmdLine + 1, len );
2203 p[len] = 0;
2204
2205 memset( &startup, 0, sizeof(startup) );
2206 startup.cb = sizeof(startup);
2207 if (params->lpCmdShow)
2208 {
2209 startup.dwFlags = STARTF_USESHOWWINDOW;
2210 startup.wShowWindow = ((WORD *)params->lpCmdShow)[1];
2211 }
2212
2213 if (CreateProcessA( filename, cmdline, NULL, NULL, FALSE, 0,
2214 params->lpEnvAddress, NULL, &startup, &info ))
2215 {
2216 /* Give 30 seconds to the app to come up */
2217 if (wait_input_idle( info.hProcess, 30000 ) == WAIT_FAILED)
2218 WARN("WaitForInputIdle failed: Error %d\n", GetLastError() );
2219 hInstance = (HINSTANCE)33;
2220 /* Close off the handles */
2221 CloseHandle( info.hThread );
2222 CloseHandle( info.hProcess );
2223 }
2224 else if ((hInstance = ULongToHandle(GetLastError())) >= (HINSTANCE)32)
2225 {
2226 FIXME("Strange error set by CreateProcess: %p\n", hInstance );
2227 hInstance = (HINSTANCE)11;
2228 }
2229
2230 HeapFree( GetProcessHeap(), 0, cmdline );
2231 return hInstance;
2232 }
2233
2234
2235 /******************************************************************************
2236 * TerminateProcess (KERNEL32.@)
2237 *
2238 * Terminates a process.
2239 *
2240 * PARAMS
2241 * handle [I] Process to terminate.
2242 * exit_code [I] Exit code.
2243 *
2244 * RETURNS
2245 * Success: TRUE.
2246 * Failure: FALSE, check GetLastError().
2247 */
2248 BOOL WINAPI TerminateProcess( HANDLE handle, DWORD exit_code )
2249 {
2250 NTSTATUS status = NtTerminateProcess( handle, exit_code );
2251 if (status) SetLastError( RtlNtStatusToDosError(status) );
2252 return !status;
2253 }
2254
2255 /***********************************************************************
2256 * ExitProcess (KERNEL32.@)
2257 *
2258 * Exits the current process.
2259 *
2260 * PARAMS
2261 * status [I] Status code to exit with.
2262 *
2263 * RETURNS
2264 * Nothing.
2265 */
2266 #ifdef __i386__
2267 __ASM_STDCALL_FUNC( ExitProcess, 4, /* Shrinker depend on this particular ExitProcess implementation */
2268 "pushl %ebp\n\t"
2269 ".byte 0x8B, 0xEC\n\t" /* movl %esp, %ebp */
2270 ".byte 0x6A, 0x00\n\t" /* pushl $0 */
2271 ".byte 0x68, 0x00, 0x00, 0x00, 0x00\n\t" /* pushl $0 - 4 bytes immediate */
2272 "pushl 8(%ebp)\n\t"
2273 "call " __ASM_NAME("process_ExitProcess") __ASM_STDCALL(4) "\n\t"
2274 "leave\n\t"
2275 "ret $4" )
2276
2277 void WINAPI process_ExitProcess( DWORD status )
2278 {
2279 LdrShutdownProcess();
2280 NtTerminateProcess(GetCurrentProcess(), status);
2281 exit(status);
2282 }
2283
2284 #else
2285
2286 void WINAPI ExitProcess( DWORD status )
2287 {
2288 LdrShutdownProcess();
2289 NtTerminateProcess(GetCurrentProcess(), status);
2290 exit(status);
2291 }
2292
2293 #endif
2294
2295 /***********************************************************************
2296 * GetExitCodeProcess [KERNEL32.@]
2297 *
2298 * Gets termination status of specified process.
2299 *
2300 * PARAMS
2301 * hProcess [in] Handle to the process.
2302 * lpExitCode [out] Address to receive termination status.
2303 *
2304 * RETURNS
2305 * Success: TRUE
2306 * Failure: FALSE
2307 */
2308 BOOL WINAPI GetExitCodeProcess( HANDLE hProcess, LPDWORD lpExitCode )
2309 {
2310 NTSTATUS status;
2311 PROCESS_BASIC_INFORMATION pbi;
2312
2313 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
2314 sizeof(pbi), NULL);
2315 if (status == STATUS_SUCCESS)
2316 {
2317 if (lpExitCode) *lpExitCode = pbi.ExitStatus;
2318 return TRUE;
2319 }
2320 SetLastError( RtlNtStatusToDosError(status) );
2321 return FALSE;
2322 }
2323
2324
2325 /***********************************************************************
2326 * SetErrorMode (KERNEL32.@)
2327 */
2328 UINT WINAPI SetErrorMode( UINT mode )
2329 {
2330 UINT old = process_error_mode;
2331 process_error_mode = mode;
2332 return old;
2333 }
2334
2335 /***********************************************************************
2336 * GetErrorMode (KERNEL32.@)
2337 */
2338 UINT WINAPI GetErrorMode( void )
2339 {
2340 return process_error_mode;
2341 }
2342
2343 /**********************************************************************
2344 * TlsAlloc [KERNEL32.@]
2345 *
2346 * Allocates a thread local storage index.
2347 *
2348 * RETURNS
2349 * Success: TLS index.
2350 * Failure: 0xFFFFFFFF
2351 */
2352 DWORD WINAPI TlsAlloc( void )
2353 {
2354 DWORD index;
2355 PEB * const peb = NtCurrentTeb()->Peb;
2356
2357 RtlAcquirePebLock();
2358 index = RtlFindClearBitsAndSet( peb->TlsBitmap, 1, 0 );
2359 if (index != ~0U) NtCurrentTeb()->TlsSlots[index] = 0; /* clear the value */
2360 else
2361 {
2362 index = RtlFindClearBitsAndSet( peb->TlsExpansionBitmap, 1, 0 );
2363 if (index != ~0U)
2364 {
2365 if (!NtCurrentTeb()->TlsExpansionSlots &&
2366 !(NtCurrentTeb()->TlsExpansionSlots = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY,
2367 8 * sizeof(peb->TlsExpansionBitmapBits) * sizeof(void*) )))
2368 {
2369 RtlClearBits( peb->TlsExpansionBitmap, index, 1 );
2370 index = ~0U;
2371 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
2372 }
2373 else
2374 {
2375 NtCurrentTeb()->TlsExpansionSlots[index] = 0; /* clear the value */
2376 index += TLS_MINIMUM_AVAILABLE;
2377 }
2378 }
2379 else SetLastError( ERROR_NO_MORE_ITEMS );
2380 }
2381 RtlReleasePebLock();
2382 return index;
2383 }
2384
2385
2386 /**********************************************************************
2387 * TlsFree [KERNEL32.@]
2388 *
2389 * Releases a thread local storage index, making it available for reuse.
2390 *
2391 * PARAMS
2392 * index [in] TLS index to free.
2393 *
2394 * RETURNS
2395 * Success: TRUE
2396 * Failure: FALSE
2397 */
2398 BOOL WINAPI TlsFree( DWORD index )
2399 {
2400 BOOL ret;
2401
2402 RtlAcquirePebLock();
2403 if (index >= TLS_MINIMUM_AVAILABLE)
2404 {
2405 ret = RtlAreBitsSet( NtCurrentTeb()->Peb->TlsExpansionBitmap, index - TLS_MINIMUM_AVAILABLE, 1 );
2406 if (ret) RtlClearBits( NtCurrentTeb()->Peb->TlsExpansionBitmap, index - TLS_MINIMUM_AVAILABLE, 1 );
2407 }
2408 else
2409 {
2410 ret = RtlAreBitsSet( NtCurrentTeb()->Peb->TlsBitmap, index, 1 );
2411 if (ret) RtlClearBits( NtCurrentTeb()->Peb->TlsBitmap, index, 1 );
2412 }
2413 if (ret) NtSetInformationThread( GetCurrentThread(), ThreadZeroTlsCell, &index, sizeof(index) );
2414 else SetLastError( ERROR_INVALID_PARAMETER );
2415 RtlReleasePebLock();
2416 return TRUE;
2417 }
2418
2419
2420 /**********************************************************************
2421 * TlsGetValue [KERNEL32.@]
2422 *
2423 * Gets value in a thread's TLS slot.
2424 *
2425 * PARAMS
2426 * index [in] TLS index to retrieve value for.
2427 *
2428 * RETURNS
2429 * Success: Value stored in calling thread's TLS slot for index.
2430 * Failure: 0 and GetLastError() returns NO_ERROR.
2431 */
2432 LPVOID WINAPI TlsGetValue( DWORD index )
2433 {
2434 LPVOID ret;
2435
2436 if (index < TLS_MINIMUM_AVAILABLE)
2437 {
2438 ret = NtCurrentTeb()->TlsSlots[index];
2439 }
2440 else
2441 {
2442 index -= TLS_MINIMUM_AVAILABLE;
2443 if (index >= 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits))
2444 {
2445 SetLastError( ERROR_INVALID_PARAMETER );
2446 return NULL;
2447 }
2448 if (!NtCurrentTeb()->TlsExpansionSlots) ret = NULL;
2449 else ret = NtCurrentTeb()->TlsExpansionSlots[index];
2450 }
2451 SetLastError( ERROR_SUCCESS );
2452 return ret;
2453 }
2454
2455
2456 /**********************************************************************
2457 * TlsSetValue [KERNEL32.@]
2458 *
2459 * Stores a value in the thread's TLS slot.
2460 *
2461 * PARAMS
2462 * index [in] TLS index to set value for.
2463 * value [in] Value to be stored.
2464 *
2465 * RETURNS
2466 * Success: TRUE
2467 * Failure: FALSE
2468 */
2469 BOOL WINAPI TlsSetValue( DWORD index, LPVOID value )
2470 {
2471 if (index < TLS_MINIMUM_AVAILABLE)
2472 {
2473 NtCurrentTeb()->TlsSlots[index] = value;
2474 }
2475 else
2476 {
2477 index -= TLS_MINIMUM_AVAILABLE;
2478 if (index >= 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits))
2479 {
2480 SetLastError( ERROR_INVALID_PARAMETER );
2481 return FALSE;
2482 }
2483 if (!NtCurrentTeb()->TlsExpansionSlots &&
2484 !(NtCurrentTeb()->TlsExpansionSlots = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY,
2485 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits) * sizeof(void*) )))
2486 {
2487 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
2488 return FALSE;
2489 }
2490 NtCurrentTeb()->TlsExpansionSlots[index] = value;
2491 }
2492 return TRUE;
2493 }
2494
2495
2496 /***********************************************************************
2497 * GetProcessFlags (KERNEL32.@)
2498 */
2499 DWORD WINAPI GetProcessFlags( DWORD processid )
2500 {
2501 IMAGE_NT_HEADERS *nt;
2502 DWORD flags = 0;
2503
2504 if (processid && processid != GetCurrentProcessId()) return 0;
2505
2506 if ((nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress )))
2507 {
2508 if (nt->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_CUI)
2509 flags |= PDB32_CONSOLE_PROC;
2510 }
2511 if (!AreFileApisANSI()) flags |= PDB32_FILE_APIS_OEM;
2512 if (IsDebuggerPresent()) flags |= PDB32_DEBUGGED;
2513 return flags;
2514 }
2515
2516
2517 /***********************************************************************
2518 * GetProcessDword (KERNEL.485)
2519 * GetProcessDword (KERNEL32.18)
2520 * 'Of course you cannot directly access Windows internal structures'
2521 */
2522 DWORD WINAPI GetProcessDword( DWORD dwProcessID, INT offset )
2523 {
2524 DWORD x, y;
2525 STARTUPINFOW siw;
2526
2527 TRACE("(%d, %d)\n", dwProcessID, offset );
2528
2529 if (dwProcessID && dwProcessID != GetCurrentProcessId())
2530 {
2531 ERR("%d: process %x not accessible\n", offset, dwProcessID);
2532 return 0;
2533 }
2534
2535 switch ( offset )
2536 {
2537 case GPD_APP_COMPAT_FLAGS:
2538 return GetAppCompatFlags16(0);
2539 case GPD_LOAD_DONE_EVENT:
2540 return 0;
2541 case GPD_HINSTANCE16:
2542 return GetTaskDS16();
2543 case GPD_WINDOWS_VERSION:
2544 return GetExeVersion16();
2545 case GPD_THDB:
2546 return (DWORD_PTR)NtCurrentTeb() - 0x10 /* FIXME */;
2547 case GPD_PDB:
2548 return (DWORD_PTR)NtCurrentTeb()->Peb; /* FIXME: truncating a pointer */
2549 case GPD_STARTF_SHELLDATA: /* return stdoutput handle from startupinfo ??? */
2550 GetStartupInfoW(&siw);
2551 return HandleToULong(siw.hStdOutput);
2552 case GPD_STARTF_HOTKEY: /* return stdinput handle from startupinfo ??? */
2553 GetStartupInfoW(&siw);
2554 return HandleToULong(siw.hStdInput);
2555 case GPD_STARTF_SHOWWINDOW:
2556 GetStartupInfoW(&siw);
2557 return siw.wShowWindow;
2558 case GPD_STARTF_SIZE:
2559 GetStartupInfoW(&siw);
2560 x = siw.dwXSize;
2561 if ( (INT)x == CW_USEDEFAULT ) x = CW_USEDEFAULT16;
2562 y = siw.dwYSize;
2563 if ( (INT)y == CW_USEDEFAULT ) y = CW_USEDEFAULT16;
2564 return MAKELONG( x, y );
2565 case GPD_STARTF_POSITION:
2566 GetStartupInfoW(&siw);
2567 x = siw.dwX;
2568 if ( (INT)x == CW_USEDEFAULT ) x = CW_USEDEFAULT16;
2569 y = siw.dwY;
2570 if ( (INT)y == CW_USEDEFAULT ) y = CW_USEDEFAULT16;
2571 return MAKELONG( x, y );
2572 case GPD_STARTF_FLAGS:
2573 GetStartupInfoW(&siw);
2574 return siw.dwFlags;
2575 case GPD_PARENT:
2576 return 0;
2577 case GPD_FLAGS:
2578 return GetProcessFlags(0);
2579 case GPD_USERDATA:
2580 return process_dword;
2581 default:
2582 ERR("Unknown offset %d\n", offset );
2583 return 0;
2584 }
2585 }
2586
2587 /***********************************************************************
2588 * SetProcessDword (KERNEL.484)
2589 * 'Of course you cannot directly access Windows internal structures'
2590 */
2591 void WINAPI SetProcessDword( DWORD dwProcessID, INT offset, DWORD value )
2592 {
2593 TRACE("(%d, %d)\n", dwProcessID, offset );
2594
2595 if (dwProcessID && dwProcessID != GetCurrentProcessId())
2596 {
2597 ERR("%d: process %x not accessible\n", offset, dwProcessID);
2598 return;
2599 }
2600
2601 switch ( offset )
2602 {
2603 case GPD_APP_COMPAT_FLAGS:
2604 case GPD_LOAD_DONE_EVENT:
2605 case GPD_HINSTANCE16:
2606 case GPD_WINDOWS_VERSION:
2607 case GPD_THDB:
2608 case GPD_PDB:
2609 case GPD_STARTF_SHELLDATA:
2610 case GPD_STARTF_HOTKEY:
2611 case GPD_STARTF_SHOWWINDOW:
2612 case GPD_STARTF_SIZE:
2613 case GPD_STARTF_POSITION:
2614 case GPD_STARTF_FLAGS:
2615 case GPD_PARENT:
2616 case GPD_FLAGS:
2617 ERR("Not allowed to modify offset %d\n", offset );
2618 break;
2619 case GPD_USERDATA:
2620 process_dword = value;
2621 break;
2622 default:
2623 ERR("Unknown offset %d\n", offset );
2624 break;
2625 }
2626 }
2627
2628
2629 /***********************************************************************
2630 * ExitProcess (KERNEL.466)
2631 */
2632 void WINAPI ExitProcess16( WORD status )
2633 {
2634 DWORD count;
2635 ReleaseThunkLock( &count );
2636 ExitProcess( status );
2637 }
2638
2639
2640 /*********************************************************************
2641 * OpenProcess (KERNEL32.@)
2642 *
2643 * Opens a handle to a process.
2644 *
2645 * PARAMS
2646 * access [I] Desired access rights assigned to the returned handle.
2647 * inherit [I] Determines whether or not child processes will inherit the handle.
2648 * id [I] Process identifier of the process to get a handle to.
2649 *
2650 * RETURNS
2651 * Success: Valid handle to the specified process.
2652 * Failure: NULL, check GetLastError().
2653 */
2654 HANDLE WINAPI OpenProcess( DWORD access, BOOL inherit, DWORD id )
2655 {
2656 NTSTATUS status;
2657 HANDLE handle;
2658 OBJECT_ATTRIBUTES attr;
2659 CLIENT_ID cid;
2660
2661 cid.UniqueProcess = ULongToHandle(id);
2662 cid.UniqueThread = 0; /* FIXME ? */
2663
2664 attr.Length = sizeof(OBJECT_ATTRIBUTES);
2665 attr.RootDirectory = NULL;
2666 attr.Attributes = inherit ? OBJ_INHERIT : 0;
2667 attr.SecurityDescriptor = NULL;
2668 attr.SecurityQualityOfService = NULL;
2669 attr.ObjectName = NULL;
2670
2671 if (GetVersion() & 0x80000000) access = PROCESS_ALL_ACCESS;
2672
2673 status = NtOpenProcess(&handle, access, &attr, &cid);
2674 if (status != STATUS_SUCCESS)
2675 {
2676 SetLastError( RtlNtStatusToDosError(status) );
2677 return NULL;
2678 }
2679 return handle;
2680 }
2681
2682
2683 /*********************************************************************
2684 * MapProcessHandle (KERNEL.483)
2685 * GetProcessId (KERNEL32.@)
2686 *
2687 * Gets the a unique identifier of a process.
2688 *
2689 * PARAMS
2690 * hProcess [I] Handle to the process.
2691 *
2692 * RETURNS
2693 * Success: TRUE.
2694 * Failure: FALSE, check GetLastError().
2695 *
2696 * NOTES
2697 *
2698 * The identifier is unique only on the machine and only until the process
2699 * exits (including system shutdown).
2700 */
2701 DWORD WINAPI GetProcessId( HANDLE hProcess )
2702 {
2703 NTSTATUS status;
2704 PROCESS_BASIC_INFORMATION pbi;
2705
2706 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
2707 sizeof(pbi), NULL);
2708 if (status == STATUS_SUCCESS) return pbi.UniqueProcessId;
2709 SetLastError( RtlNtStatusToDosError(status) );
2710 return 0;
2711 }
2712
2713
2714 /*********************************************************************
2715 * CloseW32Handle (KERNEL.474)
2716 * CloseHandle (KERNEL32.@)
2717 *
2718 * Closes a handle.
2719 *
2720 * PARAMS
2721 * handle [I] Handle to close.
2722 *
2723 * RETURNS
2724 * Success: TRUE.
2725 * Failure: FALSE, check GetLastError().
2726 */
2727 BOOL WINAPI CloseHandle( HANDLE handle )
2728 {
2729 NTSTATUS status;
2730
2731 /* stdio handles need special treatment */
2732 if ((handle == (HANDLE)STD_INPUT_HANDLE) ||
2733 (handle == (HANDLE)STD_OUTPUT_HANDLE) ||
2734 (handle == (HANDLE)STD_ERROR_HANDLE))
2735 handle = GetStdHandle( HandleToULong(handle) );
2736
2737 if (is_console_handle(handle))
2738 return CloseConsoleHandle(handle);
2739
2740 status = NtClose( handle );
2741 if (status) SetLastError( RtlNtStatusToDosError(status) );
2742 return !status;
2743 }
2744
2745
2746 /*********************************************************************
2747 * GetHandleInformation (KERNEL32.@)
2748 */
2749 BOOL WINAPI GetHandleInformation( HANDLE handle, LPDWORD flags )
2750 {
2751 OBJECT_DATA_INFORMATION info;
2752 NTSTATUS status = NtQueryObject( handle, ObjectDataInformation, &info, sizeof(info), NULL );
2753
2754 if (status) SetLastError( RtlNtStatusToDosError(status) );
2755 else if (flags)
2756 {
2757 *flags = 0;
2758 if (info.InheritHandle) *flags |= HANDLE_FLAG_INHERIT;
2759 if (info.ProtectFromClose) *flags |= HANDLE_FLAG_PROTECT_FROM_CLOSE;
2760 }
2761 return !status;
2762 }
2763
2764
2765 /*********************************************************************
2766 * SetHandleInformation (KERNEL32.@)
2767 */
2768 BOOL WINAPI SetHandleInformation( HANDLE handle, DWORD mask, DWORD flags )
2769 {
2770 OBJECT_DATA_INFORMATION info;
2771 NTSTATUS status;
2772
2773 /* if not setting both fields, retrieve current value first */
2774 if ((mask & (HANDLE_FLAG_INHERIT | HANDLE_FLAG_PROTECT_FROM_CLOSE)) !=
2775 (HANDLE_FLAG_INHERIT | HANDLE_FLAG_PROTECT_FROM_CLOSE))
2776 {
2777 if ((status = NtQueryObject( handle, ObjectDataInformation, &info, sizeof(info), NULL )))
2778 {
2779 SetLastError( RtlNtStatusToDosError(status) );
2780 return FALSE;
2781 }
2782 }
2783 if (mask & HANDLE_FLAG_INHERIT)
2784 info.InheritHandle = (flags & HANDLE_FLAG_INHERIT) != 0;
2785 if (mask & HANDLE_FLAG_PROTECT_FROM_CLOSE)
2786 info.ProtectFromClose = (flags & HANDLE_FLAG_PROTECT_FROM_CLOSE) != 0;
2787
2788 status = NtSetInformationObject( handle, ObjectDataInformation, &info, sizeof(info) );
2789 if (status) SetLastError( RtlNtStatusToDosError(status) );
2790 return !status;
2791 }
2792
2793
2794 /*********************************************************************
2795 * DuplicateHandle (KERNEL32.@)
2796 */
2797 BOOL WINAPI DuplicateHandle( HANDLE source_process, HANDLE source,
2798 HANDLE dest_process, HANDLE *dest,
2799 DWORD access, BOOL inherit, DWORD options )
2800 {
2801 NTSTATUS status;
2802
2803 if (is_console_handle(source))
2804 {
2805 /* FIXME: this test is not sufficient, we need to test process ids, not handles */
2806 if (source_process != dest_process ||
2807 source_process != GetCurrentProcess())
2808 {
2809 SetLastError(ERROR_INVALID_PARAMETER);
2810 return FALSE;
2811 }
2812 *dest = DuplicateConsoleHandle( source, access, inherit, options );
2813 return (*dest != INVALID_HANDLE_VALUE);
2814 }
2815 status = NtDuplicateObject( source_process, source, dest_process, dest,
2816 access, inherit ? OBJ_INHERIT : 0, options );
2817 if (status) SetLastError( RtlNtStatusToDosError(status) );
2818 return !status;
2819 }
2820
2821
2822 /***********************************************************************
2823 * ConvertToGlobalHandle (KERNEL.476)
2824 * ConvertToGlobalHandle (KERNEL32.@)
2825 */
2826 HANDLE WINAPI ConvertToGlobalHandle(HANDLE hSrc)
2827 {
2828 HANDLE ret = INVALID_HANDLE_VALUE;
2829 DuplicateHandle( GetCurrentProcess(), hSrc, GetCurrentProcess(), &ret, 0, FALSE,
2830 DUP_HANDLE_MAKE_GLOBAL | DUP_HANDLE_SAME_ACCESS | DUP_HANDLE_CLOSE_SOURCE );
2831 return ret;
2832 }
2833
2834
2835 /***********************************************************************
2836 * SetHandleContext (KERNEL32.@)
2837 */
2838 BOOL WINAPI SetHandleContext(HANDLE hnd,DWORD context)
2839 {
2840 FIXME("(%p,%d), stub. In case this got called by WSOCK32/WS2_32: "
2841 "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd,context);
2842 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2843 return FALSE;
2844 }
2845
2846
2847 /***********************************************************************
2848 * GetHandleContext (KERNEL32.@)
2849 */
2850 DWORD WINAPI GetHandleContext(HANDLE hnd)
2851 {
2852 FIXME("(%p), stub. In case this got called by WSOCK32/WS2_32: "
2853 "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd);
2854 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2855 return 0;
2856 }
2857
2858
2859 /***********************************************************************
2860 * CreateSocketHandle (KERNEL32.@)
2861 */
2862 HANDLE WINAPI CreateSocketHandle(void)
2863 {
2864 FIXME("(), stub. In case this got called by WSOCK32/WS2_32: "
2865 "the external WINSOCK DLLs won't work with WINE, don't use them.\n");
2866 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2867 return INVALID_HANDLE_VALUE;
2868 }
2869
2870
2871 /***********************************************************************
2872 * SetPriorityClass (KERNEL32.@)
2873 */
2874 BOOL WINAPI SetPriorityClass( HANDLE hprocess, DWORD priorityclass )
2875 {
2876 NTSTATUS status;
2877 PROCESS_PRIORITY_CLASS ppc;
2878
2879 ppc.Foreground = FALSE;
2880 switch (priorityclass)
2881 {
2882 case IDLE_PRIORITY_CLASS:
2883 ppc.PriorityClass = PROCESS_PRIOCLASS_IDLE; break;
2884 case BELOW_NORMAL_PRIORITY_CLASS:
2885 ppc.PriorityClass = PROCESS_PRIOCLASS_BELOW_NORMAL; break;
2886 case NORMAL_PRIORITY_CLASS:
2887 ppc.PriorityClass = PROCESS_PRIOCLASS_NORMAL; break;
2888 case ABOVE_NORMAL_PRIORITY_CLASS:
2889 ppc.PriorityClass = PROCESS_PRIOCLASS_ABOVE_NORMAL; break;
2890 case HIGH_PRIORITY_CLASS:
2891 ppc.PriorityClass = PROCESS_PRIOCLASS_HIGH; break;
2892 case REALTIME_PRIORITY_CLASS:
2893 ppc.PriorityClass = PROCESS_PRIOCLASS_REALTIME; break;
2894 default:
2895 SetLastError(ERROR_INVALID_PARAMETER);
2896 return FALSE;
2897 }
2898
2899 status = NtSetInformationProcess(hprocess, ProcessPriorityClass,
2900 &ppc, sizeof(ppc));
2901
2902 if (status != STATUS_SUCCESS)
2903 {
2904 SetLastError( RtlNtStatusToDosError(status) );
2905 return FALSE;
2906 }
2907 return TRUE;
2908 }
2909
2910
2911 /***********************************************************************
2912 * GetPriorityClass (KERNEL32.@)
2913 */
2914 DWORD WINAPI GetPriorityClass(HANDLE hProcess)
2915 {
2916 NTSTATUS status;
2917 PROCESS_BASIC_INFORMATION pbi;
2918
2919 status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
2920 sizeof(pbi), NULL);
2921 if (status != STATUS_SUCCESS)
2922 {
2923 SetLastError( RtlNtStatusToDosError(status) );
2924 return 0;
2925 }
2926 switch (pbi.BasePriority)
2927 {
2928 case PROCESS_PRIOCLASS_IDLE: return IDLE_PRIORITY_CLASS;
2929 case PROCESS_PRIOCLASS_BELOW_NORMAL: return BELOW_NORMAL_PRIORITY_CLASS;
2930 case PROCESS_PRIOCLASS_NORMAL: return NORMAL_PRIORITY_CLASS;
2931 case PROCESS_PRIOCLASS_ABOVE_NORMAL: return ABOVE_NORMAL_PRIORITY_CLASS;
2932 case PROCESS_PRIOCLASS_HIGH: return HIGH_PRIORITY_CLASS;
2933 case PROCESS_PRIOCLASS_REALTIME: return REALTIME_PRIORITY_CLASS;
2934 }
2935 SetLastError( ERROR_INVALID_PARAMETER );
2936 return 0;
2937 }
2938
2939
2940 /***********************************************************************
2941 * SetProcessAffinityMask (KERNEL32.@)
2942 */
2943 BOOL WINAPI SetProcessAffinityMask( HANDLE hProcess, DWORD_PTR affmask )
2944 {
2945 NTSTATUS status;
2946
2947 status = NtSetInformationProcess(hProcess, ProcessAffinityMask,
2948 &affmask, sizeof(DWORD_PTR));
2949 if (status)
2950 {
2951 SetLastError( RtlNtStatusToDosError(status) );
2952 return FALSE;
2953 }
2954 return TRUE;
2955 }
2956
2957
2958 /**********************************************************************
2959 * GetProcessAffinityMask (KERNEL32.@)
2960 */
2961 BOOL WINAPI GetProcessAffinityMask( HANDLE hProcess,
2962 PDWORD_PTR lpProcessAffinityMask,
2963 PDWORD_PTR lpSystemAffinityMask )
2964 {
2965 PROCESS_BASIC_INFORMATION pbi;
2966 NTSTATUS status;
2967
2968 status = NtQueryInformationProcess(hProcess,
2969 ProcessBasicInformation,
2970 &pbi, sizeof(pbi), NULL);
2971 if (status)
2972 {
2973 SetLastError( RtlNtStatusToDosError(status) );
2974 return FALSE;
2975 }
2976 if (lpProcessAffinityMask) *lpProcessAffinityMask = pbi.AffinityMask;
2977 if (lpSystemAffinityMask) *lpSystemAffinityMask = (1 << NtCurrentTeb()->Peb->NumberOfProcessors) - 1;
2978 return TRUE;
2979 }
2980
2981
2982 /***********************************************************************
2983 * GetProcessVersion (KERNEL32.@)
2984 */
2985 DWORD WINAPI GetProcessVersion( DWORD pid )
2986 {
2987 HANDLE process;
2988 NTSTATUS status;
2989 PROCESS_BASIC_INFORMATION pbi;
2990 SIZE_T count;
2991 PEB peb;
2992 IMAGE_DOS_HEADER dos;
2993 IMAGE_NT_HEADERS nt;
2994 DWORD ver = 0;
2995
2996 if (!pid || pid == GetCurrentProcessId())
2997 {
2998 IMAGE_NT_HEADERS *nt;
2999
3000 if ((nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress )))
3001 return ((nt->OptionalHeader.MajorSubsystemVersion << 16) |
3002 nt->OptionalHeader.MinorSubsystemVersion);
3003 return 0;
3004 }
3005
3006 process = OpenProcess(PROCESS_VM_READ | PROCESS_QUERY_INFORMATION, FALSE, pid);
3007 if (!process) return 0;
3008
3009 status = NtQueryInformationProcess(process, ProcessBasicInformation, &pbi, sizeof(pbi), NULL);
3010 if (status) goto err;
3011
3012 status = NtReadVirtualMemory(process, pbi.PebBaseAddress, &peb, sizeof(peb), &count);
3013 if (status || count != sizeof(peb)) goto err;
3014
3015 memset(&dos, 0, sizeof(dos));
3016 status = NtReadVirtualMemory(process, peb.ImageBaseAddress, &dos, sizeof(dos), &count);
3017 if (status || count != sizeof(dos)) goto err;
3018 if (dos.e_magic != IMAGE_DOS_SIGNATURE) goto err;
3019
3020 memset(&nt, 0, sizeof(nt));
3021 status = NtReadVirtualMemory(process, (char *)peb.ImageBaseAddress + dos.e_lfanew, &nt, sizeof(nt), &count);
3022 if (status || count != sizeof(nt)) goto err;
3023 if (nt.Signature != IMAGE_NT_SIGNATURE) goto err;
3024
3025 ver = MAKELONG(nt.OptionalHeader.MinorSubsystemVersion, nt.OptionalHeader.MajorSubsystemVersion);
3026
3027 err:
3028 CloseHandle(process);
3029
3030 if (status != STATUS_SUCCESS)
3031 SetLastError(RtlNtStatusToDosError(status));
3032
3033 return ver;
3034 }
3035
3036
3037 /***********************************************************************
3038 * SetProcessWorkingSetSize [KERNEL32.@]
3039 * Sets the min/max working set sizes for a specified process.
3040 *
3041 * PARAMS
3042 * hProcess [I] Handle to the process of interest
3043 * minset [I] Specifies minimum working set size
3044 * maxset [I] Specifies maximum working set size
3045 *
3046 * RETURNS
3047 * Success: TRUE
3048 * Failure: FALSE
3049 */
3050 BOOL WINAPI SetProcessWorkingSetSize(HANDLE hProcess, SIZE_T minset,
3051 SIZE_T maxset)
3052 {
3053 WARN("(%p,%ld,%ld): stub - harmless\n",hProcess,minset,maxset);
3054 if(( minset == (SIZE_T)-1) && (maxset == (SIZE_T)-1)) {
3055 /* Trim the working set to zero */
3056 /* Swap the process out of physical RAM */
3057 }
3058 return TRUE;
3059 }
3060
3061 /***********************************************************************
3062 * GetProcessWorkingSetSize (KERNEL32.@)
3063 */
3064 BOOL WINAPI GetProcessWorkingSetSize(HANDLE hProcess, PSIZE_T minset,
3065 PSIZE_T maxset)
3066 {
3067 FIXME("(%p,%p,%p): stub\n",hProcess,minset,maxset);
3068 /* 32 MB working set size */
3069 if (minset) *minset = 32*1024*1024;
3070 if (maxset) *maxset = 32*1024*1024;
3071 return TRUE;
3072 }
3073
3074
3075 /***********************************************************************
3076 * SetProcessShutdownParameters (KERNEL32.@)
3077 */
3078 BOOL WINAPI SetProcessShutdownParameters(DWORD level, DWORD flags)
3079 {
3080 FIXME("(%08x, %08x): partial stub.\n", level, flags);
3081 shutdown_flags = flags;
3082 shutdown_priority = level;
3083 return TRUE;
3084 }
3085
3086
3087 /***********************************************************************
3088 * GetProcessShutdownParameters (KERNEL32.@)
3089 *
3090 */
3091 BOOL WINAPI GetProcessShutdownParameters( LPDWORD lpdwLevel, LPDWORD lpdwFlags )
3092 {
3093 *lpdwLevel = shutdown_priority;
3094 *lpdwFlags = shutdown_flags;
3095 return TRUE;
3096 }
3097
3098
3099 /***********************************************************************
3100 * GetProcessPriorityBoost (KERNEL32.@)
3101 */
3102 BOOL WINAPI GetProcessPriorityBoost(HANDLE hprocess,PBOOL pDisablePriorityBoost)
3103 {
3104 FIXME("(%p,%p): semi-stub\n", hprocess, pDisablePriorityBoost);
3105
3106 /* Report that no boost is present.. */
3107 *pDisablePriorityBoost = FALSE;
3108
3109 return TRUE;
3110 }
3111
3112 /***********************************************************************
3113 * SetProcessPriorityBoost (KERNEL32.@)
3114 */
3115 BOOL WINAPI SetProcessPriorityBoost(HANDLE hprocess,BOOL disableboost)
3116 {
3117 FIXME("(%p,%d): stub\n",hprocess,disableboost);
3118 /* Say we can do it. I doubt the program will notice that we don't. */
3119 return TRUE;
3120 }
3121
3122
3123 /***********************************************************************
3124 * ReadProcessMemory (KERNEL32.@)
3125 */
3126 BOOL WINAPI ReadProcessMemory( HANDLE process, LPCVOID addr, LPVOID buffer, SIZE_T size,
3127 SIZE_T *bytes_read )
3128 {
3129 NTSTATUS status = NtReadVirtualMemory( process, addr, buffer, size, bytes_read );
3130 if (status) SetLastError( RtlNtStatusToDosError(status) );
3131 return !status;
3132 }
3133
3134
3135 /***********************************************************************
3136 * WriteProcessMemory (KERNEL32.@)
3137 */
3138 BOOL WINAPI WriteProcessMemory( HANDLE process, LPVOID addr, LPCVOID buffer, SIZE_T size,
3139 SIZE_T *bytes_written )
3140 {
3141 NTSTATUS status = NtWriteVirtualMemory( process, addr, buffer, size, bytes_written );
3142 if (status) SetLastError( RtlNtStatusToDosError(status) );
3143 return !status;
3144 }
3145
3146
3147 /****************************************************************************
3148 * FlushInstructionCache (KERNEL32.@)
3149 */
3150 BOOL WINAPI FlushInstructionCache(HANDLE hProcess, LPCVOID lpBaseAddress, SIZE_T dwSize)
3151 {
3152 NTSTATUS status;
3153 status = NtFlushInstructionCache( hProcess, lpBaseAddress, dwSize );
3154 if (status) SetLastError( RtlNtStatusToDosError(status) );
3155 return !status;
3156 }
3157
3158
3159 /******************************************************************
3160 * GetProcessIoCounters (KERNEL32.@)
3161 */
3162 BOOL WINAPI GetProcessIoCounters(HANDLE hProcess, PIO_COUNTERS ioc)
3163 {
3164 NTSTATUS status;
3165
3166 status = NtQueryInformationProcess(hProcess, ProcessIoCounters,
3167 ioc, sizeof(*ioc), NULL);
3168 if (status) SetLastError( RtlNtStatusToDosError(status) );
3169 return !status;
3170 }
3171
3172 /******************************************************************
3173 * GetProcessHandleCount (KERNEL32.@)
3174 */
3175 BOOL WINAPI GetProcessHandleCount(HANDLE hProcess, DWORD *cnt)
3176 {
3177 NTSTATUS status;
3178
3179 status = NtQueryInformationProcess(hProcess, ProcessHandleCount,
3180 cnt, sizeof(*cnt), NULL);
3181 if (status) SetLastError( RtlNtStatusToDosError(status) );
3182 return !status;
3183 }
3184
3185 /******************************************************************
3186 * QueryFullProcessImageNameA (KERNEL32.@)
3187 */
3188 BOOL WINAPI QueryFullProcessImageNameA(HANDLE hProcess, DWORD dwFlags, LPSTR lpExeName, PDWORD pdwSize)
3189 {
3190 BOOL retval;
3191 DWORD pdwSizeW = *pdwSize;
3192 LPWSTR lpExeNameW = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, *pdwSize * sizeof(WCHAR));
3193
3194 retval = QueryFullProcessImageNameW(hProcess, dwFlags, lpExeNameW, &pdwSizeW);
3195
3196 if(retval)
3197 retval = (0 != WideCharToMultiByte(CP_ACP, 0, lpExeNameW, -1,
3198 lpExeName, *pdwSize, NULL, NULL));
3199 if(retval)
3200 *pdwSize = strlen(lpExeName);
3201
3202 HeapFree(GetProcessHeap(), 0, lpExeNameW);
3203 return retval;
3204 }
3205
3206 /******************************************************************
3207 * QueryFullProcessImageNameW (KERNEL32.@)
3208 */
3209 BOOL WINAPI QueryFullProcessImageNameW(HANDLE hProcess, DWORD dwFlags, LPWSTR lpExeName, PDWORD pdwSize)
3210 {
3211 BYTE buffer[sizeof(UNICODE_STRING) + MAX_PATH*sizeof(WCHAR)]; /* this buffer should be enough */
3212 UNICODE_STRING *dynamic_buffer = NULL;
3213 UNICODE_STRING nt_path;
3214 UNICODE_STRING *result = NULL;
3215 NTSTATUS status;
3216 DWORD needed;
3217
3218 RtlInitUnicodeStringEx(&nt_path, NULL);
3219 /* FIXME: On Windows, ProcessImageFileName return an NT path. We rely that it being a DOS path,
3220 * as this is on Wine. */
3221 status = NtQueryInformationProcess(hProcess, ProcessImageFileName, buffer,
3222 sizeof(buffer) - sizeof(WCHAR), &needed);
3223 if (status == STATUS_INFO_LENGTH_MISMATCH)
3224 {
3225 dynamic_buffer = HeapAlloc(GetProcessHeap(), 0, needed + sizeof(WCHAR));
3226 status = NtQueryInformationProcess(hProcess, ProcessImageFileName, (LPBYTE)dynamic_buffer, needed, &needed);
3227 result = dynamic_buffer;
3228 }
3229 else
3230 result = (PUNICODE_STRING)buffer;
3231
3232 if (status) goto cleanup;
3233
3234 if (dwFlags & PROCESS_NAME_NATIVE)
3235 {
3236 result->Buffer[result->Length / sizeof(WCHAR)] = 0;
3237 if (!RtlDosPathNameToNtPathName_U(result->Buffer, &nt_path, NULL, NULL))
3238 {
3239 status = STATUS_OBJECT_PATH_NOT_FOUND;
3240 goto cleanup;
3241 }
3242 result = &nt_path;
3243 }
3244
3245 if (result->Length/sizeof(WCHAR) + 1 > *pdwSize)
3246 {
3247 status = STATUS_BUFFER_TOO_SMALL;