process.c 106 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
/*
 * Win32 processes
 *
 * Copyright 1996, 1998 Alexandre Julliard
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * 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 22 23
 */

#include "config.h"
#include "wine/port.h"

24 25 26 27 28
#include <assert.h>
#include <ctype.h>
#include <errno.h>
#include <signal.h>
#include <stdio.h>
29 30 31 32
#include <time.h>
#ifdef HAVE_SYS_TIME_H
# include <sys/time.h>
#endif
33 34 35 36 37 38
#ifdef HAVE_SYS_IOCTL_H
#include <sys/ioctl.h>
#endif
#ifdef HAVE_SYS_SOCKET_H
#include <sys/socket.h>
#endif
39 40 41
#ifdef HAVE_SYS_PRCTL_H
# include <sys/prctl.h>
#endif
42
#include <sys/types.h>
43

44 45
#include "ntstatus.h"
#define WIN32_NO_STATUS
46 47
#include "wine/winbase16.h"
#include "wine/winuser16.h"
48
#include "winternl.h"
49
#include "kernel_private.h"
Alexandre Julliard's avatar
Alexandre Julliard committed
50
#include "wine/exception.h"
51
#include "wine/server.h"
52
#include "wine/unicode.h"
53 54
#include "wine/debug.h"

55
WINE_DEFAULT_DEBUG_CHANNEL(process);
56
WINE_DECLARE_DEBUG_CHANNEL(file);
57
WINE_DECLARE_DEBUG_CHANNEL(relay);
58

59 60 61
#ifdef __APPLE__
extern char **__wine_get_main_environment(void);
#else
62 63
extern char **__wine_main_environ;
static char **__wine_get_main_environment(void) { return __wine_main_environ; }
64 65
#endif

66 67 68 69 70 71 72 73
typedef struct
{
    LPSTR lpEnvAddress;
    LPSTR lpCmdLine;
    LPSTR lpCmdShow;
    DWORD dwReserved;
} LOADPARMS32;

74
static UINT process_error_mode;
75 76 77 78 79

static DWORD shutdown_flags = 0;
static DWORD shutdown_priority = 0x280;
static DWORD process_dword;

80
HMODULE kernel32_handle = 0;
81

82 83 84
const WCHAR *DIR_Windows = NULL;
const WCHAR *DIR_System = NULL;

85 86 87 88 89 90 91 92
/* Process flags */
#define PDB32_DEBUGGED      0x0001  /* Process is being debugged */
#define PDB32_WIN16_PROC    0x0008  /* Win16 process */
#define PDB32_DOS_PROC      0x0010  /* Dos process */
#define PDB32_CONSOLE_PROC  0x0020  /* Console process */
#define PDB32_FILE_APIS_OEM 0x0040  /* File APIs are OEM */
#define PDB32_WIN32S_PROC   0x8000  /* Win32s process */

93 94
static const WCHAR comW[] = {'.','c','o','m',0};
static const WCHAR batW[] = {'.','b','a','t',0};
95
static const WCHAR cmdW[] = {'.','c','m','d',0};
96
static const WCHAR pifW[] = {'.','p','i','f',0};
97 98
static const WCHAR winevdmW[] = {'w','i','n','e','v','d','m','.','e','x','e',0};

99 100
static void exec_process( LPCWSTR name );

101
extern void SHELL_LoadRegistry(void);
102

103 104

/***********************************************************************
105
 *           contains_path
106
 */
107
static inline int contains_path( LPCWSTR name )
108
{
109 110 111
    return ((*name && (name[1] == ':')) || strchrW(name, '/') || strchrW(name, '\\'));
}

112

113 114 115 116 117 118
/***********************************************************************
 *           is_special_env_var
 *
 * Check if an environment variable needs to be handled specially when
 * passed through the Unix environment (i.e. prefixed with "WINE").
 */
119
static inline int is_special_env_var( const char *var )
120
{
121
    return (!strncmp( var, "PATH=", sizeof("PATH=")-1 ) ||
122
            !strncmp( var, "HOME=", sizeof("HOME=")-1 ) ||
123 124
            !strncmp( var, "TEMP=", sizeof("TEMP=")-1 ) ||
            !strncmp( var, "TMP=", sizeof("TMP=")-1 ));
125 126 127
}


128 129 130 131 132 133 134 135
/***************************************************************************
 *	get_builtin_path
 *
 * Get the path of a builtin module when the native file does not exist.
 */
static BOOL get_builtin_path( const WCHAR *libname, const WCHAR *ext, WCHAR *filename, UINT size )
{
    WCHAR *file_part;
136
    UINT len = strlenW( DIR_System );
137 138 139 140 141 142 143

    if (contains_path( libname ))
    {
        if (RtlGetFullPathName_U( libname, size * sizeof(WCHAR),
                                  filename, &file_part ) > size * sizeof(WCHAR))
            return FALSE;  /* too long */

144
        if (strncmpiW( filename, DIR_System, len ) || filename[len] != '\\')
145 146
            return FALSE;
        while (filename[len] == '\\') len++;
147
        if (filename + len != file_part) return FALSE;
148 149 150 151
    }
    else
    {
        if (strlenW(libname) + len + 2 >= size) return FALSE;  /* too long */
152
        memcpy( filename, DIR_System, len * sizeof(WCHAR) );
153 154 155 156 157 158 159 160 161 162 163
        file_part = filename + len;
        if (file_part > filename && file_part[-1] != '\\') *file_part++ = '\\';
        strcpyW( file_part, libname );
    }
    if (ext && !strchrW( file_part, '.' ))
    {
        if (file_part + strlenW(file_part) + strlenW(ext) + 1 > filename + size)
            return FALSE;  /* too long */
        strcatW( file_part, ext );
    }
    return TRUE;
164 165 166 167 168 169 170 171
}


/***********************************************************************
 *           open_builtin_exe_file
 *
 * Open an exe file for a builtin exe.
 */
172
static void *open_builtin_exe_file( const WCHAR *name, char *error, int error_size,
173 174
                                    int test_only, int *file_exists )
{
175 176 177 178
    char exename[MAX_PATH];
    WCHAR *p;
    UINT i, len;

179
    *file_exists = 0;
180 181
    if ((p = strrchrW( name, '/' ))) name = p + 1;
    if ((p = strrchrW( name, '\\' ))) name = p + 1;
182

183 184 185 186 187 188 189 190 191
    /* we don't want to depend on the current codepage here */
    len = strlenW( name ) + 1;
    if (len >= sizeof(exename)) return NULL;
    for (i = 0; i < len; i++)
    {
        if (name[i] > 127) return NULL;
        exename[i] = (char)name[i];
        if (exename[i] >= 'A' && exename[i] <= 'Z') exename[i] += 'a' - 'A';
    }
192 193 194 195 196 197 198 199 200 201
    return wine_dll_load_main_exe( exename, error, error_size, test_only, file_exists );
}


/***********************************************************************
 *           open_exe_file
 *
 * Open a specific exe file, taking load order into account.
 * Returns the file handle or 0 for a builtin exe.
 */
202
static HANDLE open_exe_file( const WCHAR *name )
203 204 205
{
    HANDLE handle;

206
    TRACE("looking for %s\n", debugstr_w(name) );
207

208
    if ((handle = CreateFileW( name, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_DELETE,
209 210
                               NULL, OPEN_EXISTING, 0, 0 )) == INVALID_HANDLE_VALUE)
    {
211
        WCHAR buffer[MAX_PATH];
212
        /* file doesn't exist, check for builtin */
213 214
        if (!contains_path( name )) goto error;
        if (!get_builtin_path( name, NULL, buffer, sizeof(buffer) )) goto error;
215
        handle = 0;
216
    }
217
    return handle;
218 219 220 221 222 223 224 225 226 227 228 229 230 231 232

 error:
    SetLastError( ERROR_FILE_NOT_FOUND );
    return INVALID_HANDLE_VALUE;
}


/***********************************************************************
 *           find_exe_file
 *
 * Open an exe file, and return the full name and file handle.
 * Returns FALSE if file could not be found.
 * If file exists but cannot be opened, returns TRUE and set handle to INVALID_HANDLE_VALUE.
 * If file is a builtin exe, returns TRUE and sets handle to 0.
 */
233
static BOOL find_exe_file( const WCHAR *name, WCHAR *buffer, int buflen, HANDLE *handle )
234
{
235
    static const WCHAR exeW[] = {'.','e','x','e',0};
236
    int file_exists;
237

238
    TRACE("looking for %s\n", debugstr_w(name) );
239

240 241
    if (!SearchPathW( NULL, name, exeW, buflen, buffer, NULL ) &&
        !get_builtin_path( name, exeW, buffer, buflen ))
242 243 244
    {
        /* no builtin found, try native without extension in case it is a Unix app */

245
        if (SearchPathW( NULL, name, NULL, buflen, buffer, NULL ))
246
        {
247
            TRACE( "Trying native/Unix binary %s\n", debugstr_w(buffer) );
248
            if ((*handle = CreateFileW( buffer, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_DELETE,
249 250 251 252 253 254
                                        NULL, OPEN_EXISTING, 0, 0 )) != INVALID_HANDLE_VALUE)
                return TRUE;
        }
        return FALSE;
    }

255 256 257 258
    TRACE( "Trying native exe %s\n", debugstr_w(buffer) );
    if ((*handle = CreateFileW( buffer, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_DELETE,
                                NULL, OPEN_EXISTING, 0, 0 )) != INVALID_HANDLE_VALUE)
        return TRUE;
259

260 261 262
    TRACE( "Trying built-in exe %s\n", debugstr_w(buffer) );
    open_builtin_exe_file( buffer, NULL, 0, 1, &file_exists );
    if (file_exists)
263
    {
264 265
        *handle = 0;
        return TRUE;
266
    }
267

268 269 270 271
    return FALSE;
}


272
/***********************************************************************
273
 *           build_initial_environment
274 275 276
 *
 * Build the Win32 environment from the Unix environment
 */
277
static BOOL build_initial_environment(void)
278
{
279
    SIZE_T size = 1;
280 281 282
    char **e;
    WCHAR *p, *endptr;
    void *ptr;
283
    char **env = __wine_get_main_environment();
284 285

    /* Compute the total size of the Unix environment */
286
    for (e = env; *e; e++)
287
    {
288
        if (is_special_env_var( *e )) continue;
289 290 291 292 293
        size += MultiByteToWideChar( CP_UNIXCP, 0, *e, -1, NULL, 0 );
    }
    size *= sizeof(WCHAR);

    /* Now allocate the environment */
294
    ptr = NULL;
295 296 297 298 299 300 301 302
    if (NtAllocateVirtualMemory(NtCurrentProcess(), &ptr, 0, &size,
                                MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) != STATUS_SUCCESS)
        return FALSE;

    NtCurrentTeb()->Peb->ProcessParameters->Environment = p = ptr;
    endptr = p + size / sizeof(WCHAR);

    /* And fill it with the Unix environment */
303
    for (e = env; *e; e++)
304 305
    {
        char *str = *e;
306 307

        /* skip Unix special variables and use the Wine variants instead */
308
        if (!strncmp( str, "WINE", 4 ))
309 310
        {
            if (is_special_env_var( str + 4 )) str += 4;
311
            else if (!strncmp( str, "WINEPRELOADRESERVE=", 19 )) continue;  /* skip it */
312 313 314
        }
        else if (is_special_env_var( str )) continue;  /* skip it */

315 316 317 318 319 320 321 322
        MultiByteToWideChar( CP_UNIXCP, 0, str, -1, p, endptr - p );
        p += strlenW(p) + 1;
    }
    *p = 0;
    return TRUE;
}


323 324 325 326 327
/***********************************************************************
 *           set_registry_variables
 *
 * Set environment variables by enumerating the values of a key;
 * helper for set_registry_environment().
328
 * Note that Windows happily truncates the value if it's too big.
329
 */
330
static void set_registry_variables( HANDLE hkey, ULONG type )
331 332 333 334 335
{
    UNICODE_STRING env_name, env_value;
    NTSTATUS status;
    DWORD size;
    int index;
336
    char buffer[1024*sizeof(WCHAR) + sizeof(KEY_VALUE_FULL_INFORMATION)];
337 338 339 340 341 342
    KEY_VALUE_FULL_INFORMATION *info = (KEY_VALUE_FULL_INFORMATION *)buffer;

    for (index = 0; ; index++)
    {
        status = NtEnumerateValueKey( hkey, index, KeyValueFullInformation,
                                      buffer, sizeof(buffer), &size );
343 344 345 346
        if (status != STATUS_SUCCESS && status != STATUS_BUFFER_OVERFLOW)
            break;
        if (info->Type != type)
            continue;
347 348 349 350 351
        env_name.Buffer = info->Name;
        env_name.Length = env_name.MaximumLength = info->NameLength;
        env_value.Buffer = (WCHAR *)(buffer + info->DataOffset);
        env_value.Length = env_value.MaximumLength = info->DataLength;
        if (env_value.Length && !env_value.Buffer[env_value.Length/sizeof(WCHAR)-1])
352
            env_value.Length -= sizeof(WCHAR);  /* don't count terminating null if any */
353 354 355 356 357 358 359 360 361 362 363 364 365 366
        if (info->Type == REG_EXPAND_SZ)
        {
            WCHAR buf_expanded[1024];
            UNICODE_STRING env_expanded;
            env_expanded.Length = env_expanded.MaximumLength = sizeof(buf_expanded);
            env_expanded.Buffer=buf_expanded;
            status = RtlExpandEnvironmentStrings_U(NULL, &env_value, &env_expanded, NULL);
            if (status == STATUS_SUCCESS || status == STATUS_BUFFER_OVERFLOW)
                RtlSetEnvironmentVariable( NULL, &env_name, &env_expanded );
        }
        else
        {
            RtlSetEnvironmentVariable( NULL, &env_name, &env_value );
        }
367 368 369 370
    }
}


371 372 373 374
/***********************************************************************
 *           set_registry_environment
 *
 * Set the environment variables specified in the registry.
375 376 377 378 379 380 381
 *
 * Note: Windows handles REG_SZ and REG_EXPAND_SZ in one pass with the
 * consequence that REG_EXPAND_SZ cannot be used reliably as it depends
 * on the order in which the variables are processed. But on Windows it
 * does not really matter since they only use %SystemDrive% and
 * %SystemRoot% which are predefined. But Wine defines these in the
 * registry, so we need two passes.
382
 */
383
static BOOL set_registry_environment(void)
384 385 386 387 388 389 390
{
    static const WCHAR env_keyW[] = {'M','a','c','h','i','n','e','\\',
                                     'S','y','s','t','e','m','\\',
                                     'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
                                     'C','o','n','t','r','o','l','\\',
                                     'S','e','s','s','i','o','n',' ','M','a','n','a','g','e','r','\\',
                                     'E','n','v','i','r','o','n','m','e','n','t',0};
391 392
    static const WCHAR envW[] = {'E','n','v','i','r','o','n','m','e','n','t',0};

393
    OBJECT_ATTRIBUTES attr;
394
    UNICODE_STRING nameW;
395
    HANDLE hkey;
396
    BOOL ret = FALSE;
397 398 399 400 401 402 403

    attr.Length = sizeof(attr);
    attr.RootDirectory = 0;
    attr.ObjectName = &nameW;
    attr.Attributes = 0;
    attr.SecurityDescriptor = NULL;
    attr.SecurityQualityOfService = NULL;
404 405

    /* first the system environment variables */
406
    RtlInitUnicodeString( &nameW, env_keyW );
407 408
    if (NtOpenKey( &hkey, KEY_ALL_ACCESS, &attr ) == STATUS_SUCCESS)
    {
409 410
        set_registry_variables( hkey, REG_SZ );
        set_registry_variables( hkey, REG_EXPAND_SZ );
411
        NtClose( hkey );
412
        ret = TRUE;
413
    }
414

415
    /* then the ones for the current user */
416
    if (RtlOpenCurrentUser( KEY_ALL_ACCESS, &attr.RootDirectory ) != STATUS_SUCCESS) return ret;
417 418
    RtlInitUnicodeString( &nameW, envW );
    if (NtOpenKey( &hkey, KEY_ALL_ACCESS, &attr ) == STATUS_SUCCESS)
419
    {
420 421
        set_registry_variables( hkey, REG_SZ );
        set_registry_variables( hkey, REG_EXPAND_SZ );
422
        NtClose( hkey );
423
    }
424
    NtClose( attr.RootDirectory );
425
    return ret;
426 427
}

428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471

/***********************************************************************
 *           get_reg_value
 */
static WCHAR *get_reg_value( HKEY hkey, const WCHAR *name )
{
    char buffer[1024 * sizeof(WCHAR) + sizeof(KEY_VALUE_PARTIAL_INFORMATION)];
    KEY_VALUE_PARTIAL_INFORMATION *info = (KEY_VALUE_PARTIAL_INFORMATION *)buffer;
    DWORD len, size = sizeof(buffer);
    WCHAR *ret = NULL;
    UNICODE_STRING nameW;

    RtlInitUnicodeString( &nameW, name );
    if (NtQueryValueKey( hkey, &nameW, KeyValuePartialInformation, buffer, size, &size ))
        return NULL;

    if (size <= FIELD_OFFSET( KEY_VALUE_PARTIAL_INFORMATION, Data )) return NULL;
    len = (size - FIELD_OFFSET( KEY_VALUE_PARTIAL_INFORMATION, Data )) / sizeof(WCHAR);

    if (info->Type == REG_EXPAND_SZ)
    {
        UNICODE_STRING value, expanded;

        value.MaximumLength = len * sizeof(WCHAR);
        value.Buffer = (WCHAR *)info->Data;
        if (!value.Buffer[len - 1]) len--;  /* don't count terminating null if any */
        value.Length = len * sizeof(WCHAR);
        expanded.Length = expanded.MaximumLength = 1024 * sizeof(WCHAR);
        if (!(expanded.Buffer = HeapAlloc( GetProcessHeap(), 0, expanded.MaximumLength ))) return NULL;
        if (!RtlExpandEnvironmentStrings_U( NULL, &value, &expanded, NULL )) ret = expanded.Buffer;
        else RtlFreeUnicodeString( &expanded );
    }
    else if (info->Type == REG_SZ)
    {
        if ((ret = HeapAlloc( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) )))
        {
            memcpy( ret, info->Data, len * sizeof(WCHAR) );
            ret[len] = 0;
        }
    }
    return ret;
}


472 473 474 475 476 477 478
/***********************************************************************
 *           set_additional_environment
 *
 * Set some additional environment variables not specified in the registry.
 */
static void set_additional_environment(void)
{
479 480 481 482 483 484 485 486
    static const WCHAR profile_keyW[] = {'M','a','c','h','i','n','e','\\',
                                         'S','o','f','t','w','a','r','e','\\',
                                         'M','i','c','r','o','s','o','f','t','\\',
                                         'W','i','n','d','o','w','s',' ','N','T','\\',
                                         'C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\',
                                         'P','r','o','f','i','l','e','L','i','s','t',0};
    static const WCHAR profiles_valueW[] = {'P','r','o','f','i','l','e','s','D','i','r','e','c','t','o','r','y',0};
    static const WCHAR all_users_valueW[] = {'A','l','l','U','s','e','r','s','P','r','o','f','i','l','e','\0'};
487
    static const WCHAR usernameW[] = {'U','S','E','R','N','A','M','E',0};
488 489 490 491 492 493
    static const WCHAR userprofileW[] = {'U','S','E','R','P','R','O','F','I','L','E',0};
    static const WCHAR allusersW[] = {'A','L','L','U','S','E','R','S','P','R','O','F','I','L','E',0};
    OBJECT_ATTRIBUTES attr;
    UNICODE_STRING nameW;
    WCHAR *user_name = NULL, *profile_dir = NULL, *all_users_dir = NULL;
    HANDLE hkey;
494
    const char *name = wine_get_user_name();
495 496 497 498 499
    DWORD len;

    /* set the USERNAME variable */

    len = MultiByteToWideChar( CP_UNIXCP, 0, name, -1, NULL, 0 );
500 501
    if (len)
    {
502 503 504
        user_name = HeapAlloc( GetProcessHeap(), 0, len*sizeof(WCHAR) );
        MultiByteToWideChar( CP_UNIXCP, 0, name, -1, user_name, len );
        SetEnvironmentVariableW( usernameW, user_name );
505
    }
506
    else WARN( "user name %s not convertible.\n", debugstr_a(name) );
507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533

    /* set the USERPROFILE and ALLUSERSPROFILE variables */

    attr.Length = sizeof(attr);
    attr.RootDirectory = 0;
    attr.ObjectName = &nameW;
    attr.Attributes = 0;
    attr.SecurityDescriptor = NULL;
    attr.SecurityQualityOfService = NULL;
    RtlInitUnicodeString( &nameW, profile_keyW );
    if (!NtOpenKey( &hkey, KEY_ALL_ACCESS, &attr ))
    {
        profile_dir = get_reg_value( hkey, profiles_valueW );
        all_users_dir = get_reg_value( hkey, all_users_valueW );
        NtClose( hkey );
    }

    if (profile_dir)
    {
        WCHAR *value, *p;

        if (all_users_dir) len = max( len, strlenW(all_users_dir) + 1 );
        len += strlenW(profile_dir) + 1;
        value = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
        strcpyW( value, profile_dir );
        p = value + strlenW(value);
        if (p > value && p[-1] != '\\') *p++ = '\\';
534 535 536 537
        if (user_name) {
            strcpyW( p, user_name );
            SetEnvironmentVariableW( userprofileW, value );
        }
538 539 540 541 542 543 544 545 546 547 548
        if (all_users_dir)
        {
            strcpyW( p, all_users_dir );
            SetEnvironmentVariableW( allusersW, value );
        }
        HeapFree( GetProcessHeap(), 0, value );
    }

    HeapFree( GetProcessHeap(), 0, all_users_dir );
    HeapFree( GetProcessHeap(), 0, profile_dir );
    HeapFree( GetProcessHeap(), 0, user_name );
549
}
550

551
/***********************************************************************
552
 *              set_library_wargv
553
 *
554
 * Set the Wine library Unicode argv global variables.
555
 */
556
static void set_library_wargv( char **argv )
557 558
{
    int argc;
559
    char *q;
560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577
    WCHAR *p;
    WCHAR **wargv;
    DWORD total = 0;

    for (argc = 0; argv[argc]; argc++)
        total += MultiByteToWideChar( CP_UNIXCP, 0, argv[argc], -1, NULL, 0 );

    wargv = RtlAllocateHeap( GetProcessHeap(), 0,
                             total * sizeof(WCHAR) + (argc + 1) * sizeof(*wargv) );
    p = (WCHAR *)(wargv + argc + 1);
    for (argc = 0; argv[argc]; argc++)
    {
        DWORD reslen = MultiByteToWideChar( CP_UNIXCP, 0, argv[argc], -1, p, total );
        wargv[argc] = p;
        p += reslen;
        total -= reslen;
    }
    wargv[argc] = NULL;
578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594

    /* convert argv back from Unicode since it has to be in the Ansi codepage not the Unix one */

    for (argc = 0; wargv[argc]; argc++)
        total += WideCharToMultiByte( CP_ACP, 0, wargv[argc], -1, NULL, 0, NULL, NULL );

    argv = RtlAllocateHeap( GetProcessHeap(), 0, total + (argc + 1) * sizeof(*argv) );
    q = (char *)(argv + argc + 1);
    for (argc = 0; wargv[argc]; argc++)
    {
        DWORD reslen = WideCharToMultiByte( CP_ACP, 0, wargv[argc], -1, q, total, NULL, NULL );
        argv[argc] = q;
        q += reslen;
        total -= reslen;
    }
    argv[argc] = NULL;

595
    __wine_main_argc = argc;
596
    __wine_main_argv = argv;
597 598 599 600
    __wine_main_wargv = wargv;
}


601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624
/***********************************************************************
 *              update_library_argv0
 *
 * Update the argv[0] global variable with the binary we have found.
 */
static void update_library_argv0( const WCHAR *argv0 )
{
    DWORD len = strlenW( argv0 );

    if (len > strlenW( __wine_main_wargv[0] ))
    {
        __wine_main_wargv[0] = RtlAllocateHeap( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) );
    }
    strcpyW( __wine_main_wargv[0], argv0 );

    len = WideCharToMultiByte( CP_ACP, 0, argv0, -1, NULL, 0, NULL, NULL );
    if (len > strlen( __wine_main_argv[0] ) + 1)
    {
        __wine_main_argv[0] = RtlAllocateHeap( GetProcessHeap(), 0, len );
    }
    WideCharToMultiByte( CP_ACP, 0, argv0, -1, __wine_main_argv[0], len, NULL, NULL );
}


625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672
/***********************************************************************
 *           build_command_line
 *
 * Build the command line of a process from the argv array.
 *
 * Note that it does NOT necessarily include the file name.
 * Sometimes we don't even have any command line options at all.
 *
 * We must quote and escape characters so that the argv array can be rebuilt
 * from the command line:
 * - spaces and tabs must be quoted
 *   'a b'   -> '"a b"'
 * - quotes must be escaped
 *   '"'     -> '\"'
 * - if '\'s are followed by a '"', they must be doubled and followed by '\"',
 *   resulting in an odd number of '\' followed by a '"'
 *   '\"'    -> '\\\"'
 *   '\\"'   -> '\\\\\"'
 * - '\'s that are not followed by a '"' can be left as is
 *   'a\b'   == 'a\b'
 *   'a\\b'  == 'a\\b'
 */
static BOOL build_command_line( WCHAR **argv )
{
    int len;
    WCHAR **arg;
    LPWSTR p;
    RTL_USER_PROCESS_PARAMETERS* rupp = NtCurrentTeb()->Peb->ProcessParameters;

    if (rupp->CommandLine.Buffer) return TRUE; /* already got it from the server */

    len = 0;
    for (arg = argv; *arg; arg++)
    {
        int has_space,bcount;
        WCHAR* a;

        has_space=0;
        bcount=0;
        a=*arg;
        if( !*a ) has_space=1;
        while (*a!='\0') {
            if (*a=='\\') {
                bcount++;
            } else {
                if (*a==' ' || *a=='\t') {
                    has_space=1;
                } else if (*a=='"') {
673
                    /* doubling of '\' preceding a '"',
674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731
                     * plus escaping of said '"'
                     */
                    len+=2*bcount+1;
                }
                bcount=0;
            }
            a++;
        }
        len+=(a-*arg)+1 /* for the separating space */;
        if (has_space)
            len+=2; /* for the quotes */
    }

    if (!(rupp->CommandLine.Buffer = RtlAllocateHeap( GetProcessHeap(), 0, len * sizeof(WCHAR))))
        return FALSE;

    p = rupp->CommandLine.Buffer;
    rupp->CommandLine.Length = (len - 1) * sizeof(WCHAR);
    rupp->CommandLine.MaximumLength = len * sizeof(WCHAR);
    for (arg = argv; *arg; arg++)
    {
        int has_space,has_quote;
        WCHAR* a;

        /* Check for quotes and spaces in this argument */
        has_space=has_quote=0;
        a=*arg;
        if( !*a ) has_space=1;
        while (*a!='\0') {
            if (*a==' ' || *a=='\t') {
                has_space=1;
                if (has_quote)
                    break;
            } else if (*a=='"') {
                has_quote=1;
                if (has_space)
                    break;
            }
            a++;
        }

        /* Now transfer it to the command line */
        if (has_space)
            *p++='"';
        if (has_quote) {
            int bcount;
            WCHAR* a;

            bcount=0;
            a=*arg;
            while (*a!='\0') {
                if (*a=='\\') {
                    *p++=*a;
                    bcount++;
                } else {
                    if (*a=='"') {
                        int i;

732
                        /* Double all the '\\' preceding this '"', plus one */
733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758
                        for (i=0;i<=bcount;i++)
                            *p++='\\';
                        *p++='"';
                    } else {
                        *p++=*a;
                    }
                    bcount=0;
                }
                a++;
            }
        } else {
            WCHAR* x = *arg;
            while ((*p=*x++)) p++;
        }
        if (has_space)
            *p++='"';
        *p++=' ';
    }
    if (p > rupp->CommandLine.Buffer)
        p--;  /* remove last space */
    *p = '\0';

    return TRUE;
}


759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808
/***********************************************************************
 *           init_current_directory
 *
 * Initialize the current directory from the Unix cwd or the parent info.
 */
static void init_current_directory( CURDIR *cur_dir )
{
    UNICODE_STRING dir_str;
    char *cwd;
    int size;

    /* if we received a cur dir from the parent, try this first */

    if (cur_dir->DosPath.Length)
    {
        if (RtlSetCurrentDirectory_U( &cur_dir->DosPath ) == STATUS_SUCCESS) goto done;
    }

    /* now try to get it from the Unix cwd */

    for (size = 256; ; size *= 2)
    {
        if (!(cwd = HeapAlloc( GetProcessHeap(), 0, size ))) break;
        if (getcwd( cwd, size )) break;
        HeapFree( GetProcessHeap(), 0, cwd );
        if (errno == ERANGE) continue;
        cwd = NULL;
        break;
    }

    if (cwd)
    {
        WCHAR *dirW;
        int lenW = MultiByteToWideChar( CP_UNIXCP, 0, cwd, -1, NULL, 0 );
        if ((dirW = HeapAlloc( GetProcessHeap(), 0, lenW * sizeof(WCHAR) )))
        {
            MultiByteToWideChar( CP_UNIXCP, 0, cwd, -1, dirW, lenW );
            RtlInitUnicodeString( &dir_str, dirW );
            RtlSetCurrentDirectory_U( &dir_str );
            RtlFreeUnicodeString( &dir_str );
        }
    }

    if (!cur_dir->DosPath.Length)  /* still not initialized */
    {
        MESSAGE("Warning: could not find DOS drive for current working directory '%s', "
                "starting in the Windows directory.\n", cwd ? cwd : "" );
        RtlInitUnicodeString( &dir_str, DIR_Windows );
        RtlSetCurrentDirectory_U( &dir_str );
    }
809
    HeapFree( GetProcessHeap(), 0, cwd );
810 811 812 813 814 815 816

done:
    if (!cur_dir->Handle) chdir("/"); /* change to root directory so as not to lock cdroms */
    TRACE( "starting in %s %p\n", debugstr_w( cur_dir->DosPath.Buffer ), cur_dir->Handle );
}


817 818 819 820 821 822 823
/***********************************************************************
 *           init_windows_dirs
 *
 * Initialize the windows and system directories from the environment.
 */
static void init_windows_dirs(void)
{
824
    extern void CDECL __wine_init_windows_dir( const WCHAR *windir, const WCHAR *sysdir );
825

826 827
    static const WCHAR windirW[] = {'w','i','n','d','i','r',0};
    static const WCHAR winsysdirW[] = {'w','i','n','s','y','s','d','i','r',0};
828
    static const WCHAR default_windirW[] = {'C',':','\\','w','i','n','d','o','w','s',0};
829
    static const WCHAR default_sysdirW[] = {'\\','s','y','s','t','e','m','3','2',0};
830 831 832 833 834 835 836 837 838 839

    DWORD len;
    WCHAR *buffer;

    if ((len = GetEnvironmentVariableW( windirW, NULL, 0 )))
    {
        buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
        GetEnvironmentVariableW( windirW, buffer, len );
        DIR_Windows = buffer;
    }
840
    else DIR_Windows = default_windirW;
841 842 843 844 845 846 847 848 849

    if ((len = GetEnvironmentVariableW( winsysdirW, NULL, 0 )))
    {
        buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
        GetEnvironmentVariableW( winsysdirW, buffer, len );
        DIR_System = buffer;
    }
    else
    {
850 851 852 853 854
        len = strlenW( DIR_Windows );
        buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) + sizeof(default_sysdirW) );
        memcpy( buffer, DIR_Windows, len * sizeof(WCHAR) );
        memcpy( buffer + len, default_sysdirW, sizeof(default_sysdirW) );
        DIR_System = buffer;
855 856
    }

857 858 859 860 861 862
    if (!CreateDirectoryW( DIR_Windows, NULL ) && GetLastError() != ERROR_ALREADY_EXISTS)
        ERR( "directory %s could not be created, error %u\n",
             debugstr_w(DIR_Windows), GetLastError() );
    if (!CreateDirectoryW( DIR_System, NULL ) && GetLastError() != ERROR_ALREADY_EXISTS)
        ERR( "directory %s could not be created, error %u\n",
             debugstr_w(DIR_System), GetLastError() );
863 864 865

    TRACE_(file)( "WindowsDir = %s\n", debugstr_w(DIR_Windows) );
    TRACE_(file)( "SystemDir  = %s\n", debugstr_w(DIR_System) );
866 867 868

    /* set the directories in ntdll too */
    __wine_init_windows_dir( DIR_Windows, DIR_System );
869 870 871
}


872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888
/***********************************************************************
 *           start_wineboot
 *
 * Start the wineboot process if necessary. Return the event to wait on.
 */
static HANDLE start_wineboot(void)
{
    static const WCHAR wineboot_eventW[] = {'_','_','w','i','n','e','b','o','o','t','_','e','v','e','n','t',0};
    HANDLE event;

    if (!(event = CreateEventW( NULL, TRUE, FALSE, wineboot_eventW )))
    {
        ERR( "failed to create wineboot event, expect trouble\n" );
        return 0;
    }
    if (GetLastError() != ERROR_ALREADY_EXISTS)  /* we created it */
    {
889
        static const WCHAR command_line[] = {'\\','w','i','n','e','b','o','o','t','.','e','x','e',' ','-','-','i','n','i','t',0};
890 891 892 893 894 895
        STARTUPINFOW si;
        PROCESS_INFORMATION pi;
        WCHAR cmdline[MAX_PATH + sizeof(command_line)/sizeof(WCHAR)];

        memset( &si, 0, sizeof(si) );
        si.cb = sizeof(si);
896 897 898 899 900
        si.dwFlags = STARTF_USESTDHANDLES;
        si.hStdInput  = 0;
        si.hStdOutput = 0;
        si.hStdError  = GetStdHandle( STD_ERROR_HANDLE );

901 902 903 904 905 906 907 908 909 910 911 912 913 914 915
        GetSystemDirectoryW( cmdline, MAX_PATH );
        lstrcatW( cmdline, command_line );
        if (CreateProcessW( NULL, cmdline, NULL, NULL, FALSE, DETACHED_PROCESS, NULL, NULL, &si, &pi ))
        {
            TRACE( "started wineboot pid %04x tid %04x\n", pi.dwProcessId, pi.dwThreadId );
            CloseHandle( pi.hThread );
            CloseHandle( pi.hProcess );

        }
        else ERR( "failed to start wineboot, err %u\n", GetLastError() );
    }
    return event;
}


916 917 918 919 920 921 922 923 924
/***********************************************************************
 *           start_process
 *
 * Startup routine of a new process. Runs on the new process stack.
 */
static void start_process( void *arg )
{
    __TRY
    {
925 926 927 928 929 930 931 932
        PEB *peb = NtCurrentTeb()->Peb;
        IMAGE_NT_HEADERS *nt;
        LPTHREAD_START_ROUTINE entry;

        nt = RtlImageNtHeader( peb->ImageBaseAddress );
        entry = (LPTHREAD_START_ROUTINE)((char *)peb->ImageBaseAddress +
                                         nt->OptionalHeader.AddressOfEntryPoint);

933 934 935 936 937 938 939
        if (!nt->OptionalHeader.AddressOfEntryPoint)
        {
            ERR( "%s doesn't have an entry point, it cannot be executed\n",
                 debugstr_w(peb->ProcessParameters->ImagePathName.Buffer) );
            ExitThread( 1 );
        }

940
        if (TRACE_ON(relay))
941
            DPRINTF( "%04x:Starting process %s (entryproc=%p)\n", GetCurrentThreadId(),
942 943 944 945
                     debugstr_w(peb->ProcessParameters->ImagePathName.Buffer), entry );

        SetLastError( 0 );  /* clear error code */
        if (peb->BeingDebugged) DbgBreakPoint();
946
        ExitThread( entry( peb ) );
947 948 949 950 951 952 953 954 955
    }
    __EXCEPT(UnhandledExceptionFilter)
    {
        TerminateThread( GetCurrentThread(), GetExceptionCode() );
    }
    __ENDTRY
}


956 957 958 959 960
/***********************************************************************
 *           set_process_name
 *
 * Change the process name in the ps output.
 */
961
static void set_process_name( int argc, char *argv[] )
962
{
963 964 965 966
#ifdef HAVE_SETPROCTITLE
    setproctitle("-%s", argv[1]);
#endif

967 968
#ifdef HAVE_PRCTL
    int i, offset;
969 970
    char *p, *prctl_name = argv[1];
    char *end = argv[argc-1] + strlen(argv[argc-1]) + 1;
971 972 973 974 975

#ifndef PR_SET_NAME
# define PR_SET_NAME 15
#endif

976 977
    if ((p = strrchr( prctl_name, '\\' ))) prctl_name = p + 1;
    if ((p = strrchr( prctl_name, '/' ))) prctl_name = p + 1;
978

979
    if (prctl( PR_SET_NAME, prctl_name ) != -1)
980
    {
981 982 983 984 985
        offset = argv[1] - argv[0];
        memmove( argv[1] - offset, argv[1], end - argv[1] );
        memset( end - offset, 0, offset );
        for (i = 1; i < argc; i++) argv[i-1] = argv[i] - offset;
        argv[i-1] = NULL;
986 987
    }
    else
988
#endif  /* HAVE_PRCTL */
989
    {
990 991
        /* remove argv[0] */
        memmove( argv, argv + 1, argc * sizeof(argv[0]) );
992 993 994 995
    }
}


996
/***********************************************************************
997
 *           __wine_kernel_init
998 999 1000
 *
 * Wine initialisation: load and start the main exe file.
 */
1001
void CDECL __wine_kernel_init(void)
1002
{
1003
    static const WCHAR kernel32W[] = {'k','e','r','n','e','l','3','2',0};
1004 1005 1006
    static const WCHAR dotW[] = {'.',0};
    static const WCHAR exeW[] = {'.','e','x','e',0};

1007
    WCHAR *p, main_exe_name[MAX_PATH+1];
1008
    PEB *peb = NtCurrentTeb()->Peb;
1009
    RTL_USER_PROCESS_PARAMETERS *params = peb->ProcessParameters;
1010
    HANDLE boot_event = 0;
1011
    BOOL got_environment = TRUE;
1012 1013

    /* Initialize everything */
1014 1015 1016 1017 1018 1019 1020 1021 1022 1023

    setbuf(stdout,NULL);
    setbuf(stderr,NULL);
    kernel32_handle = GetModuleHandleW(kernel32W);

    LOCALE_Init();

    if (!params->Environment)
    {
        /* Copy the parent environment */
1024
        if (!build_initial_environment()) exit(1);
1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035

        /* convert old configuration to new format */
        convert_old_config();

        got_environment = set_registry_environment();
        set_additional_environment();
    }

    init_windows_dirs();
    init_current_directory( &params->CurrentDirectory );

1036
    set_process_name( __wine_main_argc, __wine_main_argv );
1037
    set_library_wargv( __wine_main_argv );
1038

1039 1040 1041 1042 1043
    if (peb->ProcessParameters->ImagePathName.Buffer)
    {
        strcpyW( main_exe_name, peb->ProcessParameters->ImagePathName.Buffer );
    }
    else
1044
    {
1045 1046
        if (!SearchPathW( NULL, __wine_main_wargv[0], exeW, MAX_PATH, main_exe_name, NULL ) &&
            !get_builtin_path( __wine_main_wargv[0], exeW, main_exe_name, MAX_PATH ))
1047
        {
1048
            MESSAGE( "wine: cannot find '%s'\n", __wine_main_argv[0] );
1049
            ExitProcess( GetLastError() );
1050
        }
1051
        update_library_argv0( main_exe_name );
1052
        if (!build_command_line( __wine_main_wargv )) goto error;
1053
        boot_event = start_wineboot();
1054 1055
    }

1056 1057 1058 1059
    /* if there's no extension, append a dot to prevent LoadLibrary from appending .dll */
    p = strrchrW( main_exe_name, '.' );
    if (!p || strchrW( p, '/' ) || strchrW( p, '\\' )) strcatW( main_exe_name, dotW );

1060
    TRACE( "starting process name=%s argv[0]=%s\n",
1061
           debugstr_w(main_exe_name), debugstr_w(__wine_main_wargv[0]) );
1062

1063
    RtlInitUnicodeString( &NtCurrentTeb()->Peb->ProcessParameters->DllPath,
1064
                          MODULE_get_dll_load_path(main_exe_name) );
1065

1066 1067
    if (boot_event)
    {
1068
        if (WaitForSingleObject( boot_event, 30000 )) ERR( "boot event wait timed out\n" );
1069 1070 1071 1072 1073 1074 1075 1076 1077
        CloseHandle( boot_event );
        /* if we didn't find environment section, try again now that wineboot has run */
        if (!got_environment)
        {
            set_registry_environment();
            set_additional_environment();
        }
    }

1078
    if (!(peb->ImageBaseAddress = LoadLibraryExW( main_exe_name, 0, DONT_RESOLVE_DLL_REFERENCES )))
1079
    {
1080 1081 1082 1083
        char msg[1024];
        DWORD error = GetLastError();

        /* if Win16/DOS format, or unavailable address, exec a new process with the proper setup */
1084 1085 1086
        if (error == ERROR_BAD_EXE_FORMAT ||
            error == ERROR_INVALID_ADDRESS ||
            error == ERROR_NOT_ENOUGH_MEMORY)
1087
        {
1088 1089
            if (!getenv("WINEPRELOADRESERVE")) exec_process( main_exe_name );
            /* if we get back here, it failed */
1090
        }
1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102
        else if (error == ERROR_MOD_NOT_FOUND)
        {
            if ((p = strrchrW( main_exe_name, '\\' ))) p++;
            else p = main_exe_name;
            if (!strcmpiW( p, winevdmW ) && __wine_main_argc > 3)
            {
                /* args 1 and 2 are --app-name full_path */
                MESSAGE( "wine: could not run %s: 16-bit/DOS support missing\n",
                         debugstr_w(__wine_main_wargv[3]) );
                ExitProcess( ERROR_BAD_EXE_FORMAT );
            }
        }
1103 1104
        FormatMessageA( FORMAT_MESSAGE_FROM_SYSTEM, NULL, error, 0, msg, sizeof(msg), NULL );
        MESSAGE( "wine: could not load %s: %s", debugstr_w(main_exe_name), msg );
1105
        ExitProcess( error );
1106 1107
    }

1108
    LdrInitializeThunk( 0, 0, 0, 0 );
1109
    /* switch to the new stack */
1110
    wine_switch_to_stack( start_process, NULL, NtCurrentTeb()->Tib.StackBase );
1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122

 error:
    ExitProcess( GetLastError() );
}


/***********************************************************************
 *           build_argv
 *
 * Build an argv array from a command-line.
 * 'reserved' is the number of args to reserve before the first one.
 */
1123
static char **build_argv( const WCHAR *cmdlineW, int reserved )
1124 1125 1126
{
    int argc;
    char** argv;
1127 1128 1129 1130
    char *arg,*s,*d,*cmdline;
    int in_quotes,bcount,len;

    len = WideCharToMultiByte( CP_UNIXCP, 0, cmdlineW, -1, NULL, 0, NULL, NULL );
1131
    if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, len ))) return NULL;
1132
    WideCharToMultiByte( CP_UNIXCP, 0, cmdlineW, -1, cmdline, len, NULL, NULL );
1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162

    argc=reserved+1;
    bcount=0;
    in_quotes=0;
    s=cmdline;
    while (1) {
        if (*s=='\0' || ((*s==' ' || *s=='\t') && !in_quotes)) {
            /* space */
            argc++;
            /* skip the remaining spaces */
            while (*s==' ' || *s=='\t') {
                s++;
            }
            if (*s=='\0')
                break;
            bcount=0;
            continue;
        } else if (*s=='\\') {
            /* '\', count them */
            bcount++;
        } else if ((*s=='"') && ((bcount & 1)==0)) {
            /* unescaped '"' */
            in_quotes=!in_quotes;
            bcount=0;
        } else {
            /* a regular character */
            bcount=0;
        }
        s++;
    }
1163 1164 1165
    if (!(argv = HeapAlloc( GetProcessHeap(), 0, argc*sizeof(*argv) + len )))
    {
        HeapFree( GetProcessHeap(), 0, cmdline );
1166
        return NULL;
1167
    }
1168

1169 1170
    arg = d = s = (char *)(argv + argc);
    memcpy( d, cmdline, len );
1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194
    bcount=0;
    in_quotes=0;
    argc=reserved;
    while (*s) {
        if ((*s==' ' || *s=='\t') && !in_quotes) {
            /* Close the argument and copy it */
            *d=0;
            argv[argc++]=arg;

            /* skip the remaining spaces */
            do {
                s++;
            } while (*s==' ' || *s=='\t');

            /* Start with a new argument */
            arg=d=s;
            bcount=0;
        } else if (*s=='\\') {
            /* '\\' */
            *d++=*s++;
            bcount++;
        } else if (*s=='"') {
            /* '"' */
            if ((bcount & 1)==0) {
1195
                /* Preceded by an even number of '\', this is half that
1196 1197 1198 1199 1200 1201
                 * number of '\', plus a '"' which we discard.
                 */
                d-=bcount/2;
                s++;
                in_quotes=!in_quotes;
            } else {
1202
                /* Preceded by an odd number of '\', this is half that
1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221
                 * number of '\' followed by a '"'
                 */
                d=d-bcount/2-1;
                *d++='"';
                s++;
            }
            bcount=0;
        } else {
            /* a regular character */
            *d++=*s++;
            bcount=0;
        }
    }
    if (*arg) {
        *d='\0';
        argv[argc++]=arg;
    }
    argv[argc]=NULL;

1222
    HeapFree( GetProcessHeap(), 0, cmdline );
1223 1224 1225 1226 1227 1228 1229 1230 1231
    return argv;
}


/***********************************************************************
 *           build_envp
 *
 * Build the environment of a new child process.
 */
1232
static char **build_envp( const WCHAR *envW )
1233
{
1234 1235
    static const char * const unix_vars[] = { "PATH", "TEMP", "TMP", "HOME" };

1236
    const WCHAR *end;
1237
    char **envp;
1238
    char *env, *p;
1239
    int count = 1, length;
1240
    unsigned int i;
1241

1242 1243 1244
    for (end = envW; *end; count++) end += strlenW(end) + 1;
    end++;
    length = WideCharToMultiByte( CP_UNIXCP, 0, envW, end - envW, NULL, 0, NULL, NULL );
1245
    if (!(env = HeapAlloc( GetProcessHeap(), 0, length ))) return NULL;
1246
    WideCharToMultiByte( CP_UNIXCP, 0, envW, end - envW, env, length, NULL, NULL );
1247

1248 1249
    for (p = env; *p; p += strlen(p) + 1)
        if (is_special_env_var( p )) length += 4; /* prefix it with "WINE" */
1250

1251 1252 1253 1254 1255 1256 1257 1258
    for (i = 0; i < sizeof(unix_vars)/sizeof(unix_vars[0]); i++)
    {
        if (!(p = getenv(unix_vars[i]))) continue;
        length += strlen(unix_vars[i]) + strlen(p) + 2;
        count++;
    }

    if ((envp = HeapAlloc( GetProcessHeap(), 0, count * sizeof(*envp) + length )))
1259 1260
    {
        char **envptr = envp;
1261
        char *dst = (char *)(envp + count);
1262

1263
        /* some variables must not be modified, so we get them directly from the unix env */
1264 1265 1266 1267 1268 1269 1270 1271 1272
        for (i = 0; i < sizeof(unix_vars)/sizeof(unix_vars[0]); i++)
        {
            if (!(p = getenv(unix_vars[i]))) continue;
            *envptr++ = strcpy( dst, unix_vars[i] );
            strcat( dst, "=" );
            strcat( dst, p );
            dst += strlen(dst) + 1;
        }

1273 1274 1275
        /* now put the Windows environment strings */
        for (p = env; *p; p += strlen(p) + 1)
        {
1276 1277
            if (*p == '=') continue;  /* skip drive curdirs, this crashes some unix apps */
            if (!strncmp( p, "WINEPRELOADRESERVE=", sizeof("WINEPRELOADRESERVE=")-1 )) continue;
1278
            if (!strncmp( p, "WINELOADERNOEXEC=", sizeof("WINELOADERNOEXEC=")-1 )) continue;
1279
            if (!strncmp( p, "WINESERVERSOCKET=", sizeof("WINESERVERSOCKET=")-1 )) continue;
1280
            if (is_special_env_var( p ))  /* prefix it with "WINE" */
1281 1282 1283 1284
            {
                *envptr++ = strcpy( dst, "WINE" );
                strcat( dst, p );
            }
1285
            else
1286 1287 1288 1289
            {
                *envptr++ = strcpy( dst, p );
            }
            dst += strlen(dst) + 1;
1290 1291 1292
        }
        *envptr = 0;
    }
1293
    HeapFree( GetProcessHeap(), 0, env );
1294 1295 1296 1297 1298 1299 1300 1301 1302
    return envp;
}


/***********************************************************************
 *           fork_and_exec
 *
 * Fork and exec a new Unix binary, checking for errors.
 */
1303 1304
static int fork_and_exec( const char *filename, const WCHAR *cmdline, const WCHAR *env,
                          const char *newdir, DWORD flags, STARTUPINFOW *startup )
1305
{
1306
    int fd[2], stdin_fd = -1, stdout_fd = -1;
1307
    int pid, err;
1308
    char **argv, **envp;
1309

1310
    if (!env) env = GetEnvironmentStringsW();
1311 1312 1313

    if (pipe(fd) == -1)
    {
1314
        SetLastError( ERROR_TOO_MANY_OPEN_FILES );
1315 1316 1317
        return -1;
    }
    fcntl( fd[1], F_SETFD, 1 );  /* set close on exec */
1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333

    if (!(flags & (CREATE_NEW_PROCESS_GROUP | CREATE_NEW_CONSOLE | DETACHED_PROCESS)))
    {
        HANDLE hstdin, hstdout;

        if (startup->dwFlags & STARTF_USESTDHANDLES)
        {
            hstdin = startup->hStdInput;
            hstdout = startup->hStdOutput;
        }
        else
        {
            hstdin = GetStdHandle(STD_INPUT_HANDLE);
            hstdout = GetStdHandle(STD_OUTPUT_HANDLE);
        }

1334 1335 1336 1337
        if (is_console_handle( hstdin ))
            hstdin = wine_server_ptr_handle( console_handle_unmap( hstdin ));
        if (is_console_handle( hstdout ))
            hstdout = wine_server_ptr_handle( console_handle_unmap( hstdout ));
1338 1339 1340 1341
        wine_server_handle_to_fd( hstdin, FILE_READ_DATA, &stdin_fd, NULL );
        wine_server_handle_to_fd( hstdout, FILE_WRITE_DATA, &stdout_fd, NULL );
    }

1342
    argv = build_argv( cmdline, 0 );
1343
    envp = build_envp( env );
1344

1345 1346 1347 1348
    if (!(pid = fork()))  /* child */
    {
        close( fd[0] );

1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365
        if (flags & (CREATE_NEW_PROCESS_GROUP | CREATE_NEW_CONSOLE | DETACHED_PROCESS))
        {
            int pid;
            if (!(pid = fork()))
            {
                int fd = open( "/dev/null", O_RDWR );
                setsid();
                /* close stdin and stdout */
                if (fd != -1)
                {
                    dup2( fd, 0 );
                    dup2( fd, 1 );
                    close( fd );
                }
            }
            else if (pid != -1) _exit(0);  /* parent */
        }
1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378
        else
        {
            if (stdin_fd != -1)
            {
                dup2( stdin_fd, 0 );
                close( stdin_fd );
            }
            if (stdout_fd != -1)
            {
                dup2( stdout_fd, 1 );
                close( stdout_fd );
            }
        }
1379

1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390
        /* Reset signals that we previously set to SIG_IGN */
        signal( SIGPIPE, SIG_DFL );
        signal( SIGCHLD, SIG_DFL );

        if (newdir) chdir(newdir);

        if (argv && envp) execve( filename, argv, envp );
        err = errno;
        write( fd[1], &err, sizeof(err) );
        _exit(1);
    }
1391
    HeapFree( GetProcessHeap(), 0, argv );
1392
    HeapFree( GetProcessHeap(), 0, envp );
1393 1394
    if (stdin_fd != -1) close( stdin_fd );
    if (stdout_fd != -1) close( stdout_fd );
1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406
    close( fd[1] );
    if ((pid != -1) && (read( fd[0], &err, sizeof(err) ) > 0))  /* exec failed */
    {
        errno = err;
        pid = -1;
    }
    if (pid == -1) FILE_SetDosError();
    close( fd[0] );
    return pid;
}


1407 1408 1409 1410
/***********************************************************************
 *           create_user_params
 */
static RTL_USER_PROCESS_PARAMETERS *create_user_params( LPCWSTR filename, LPCWSTR cmdline,
1411
                                                        LPCWSTR cur_dir, LPWSTR env, DWORD flags,
1412
                                                        const STARTUPINFOW *startup )
1413 1414
{
    RTL_USER_PROCESS_PARAMETERS *params;
1415
    UNICODE_STRING image_str, cmdline_str, curdir_str, desktop, title, runtime, newdir;
1416 1417 1418
    NTSTATUS status;
    WCHAR buffer[MAX_PATH];

1419 1420 1421 1422 1423
    if(!GetLongPathNameW( filename, buffer, MAX_PATH ))
        lstrcpynW( buffer, filename, MAX_PATH );
    if(!GetFullPathNameW( buffer, MAX_PATH, buffer, NULL ))
        lstrcpynW( buffer, filename, MAX_PATH );
    RtlInitUnicodeString( &image_str, buffer );
1424 1425

    RtlInitUnicodeString( &cmdline_str, cmdline );
1426 1427 1428 1429 1430 1431 1432 1433
    newdir.Buffer = NULL;
    if (cur_dir)
    {
        if (RtlDosPathNameToNtPathName_U( cur_dir, &newdir, NULL, NULL ))
        {
            /* skip \??\ prefix */
            curdir_str.Buffer = newdir.Buffer + 4;
            curdir_str.Length = newdir.Length - 4 * sizeof(WCHAR);
1434
            curdir_str.MaximumLength = newdir.MaximumLength - 4 * sizeof(WCHAR);
1435 1436 1437
        }
        else cur_dir = NULL;
    }
1438 1439
    if (startup->lpDesktop) RtlInitUnicodeString( &desktop, startup->lpDesktop );
    if (startup->lpTitle) RtlInitUnicodeString( &title, startup->lpTitle );
1440 1441
    if (startup->lpReserved2 && startup->cbReserved2)
    {
1442 1443
        runtime.Length = 0;
        runtime.MaximumLength = startup->cbReserved2;
1444 1445
        runtime.Buffer = (WCHAR*)startup->lpReserved2;
    }
1446

1447 1448
    status = RtlCreateProcessParameters( &params, &image_str, NULL,
                                         cur_dir ? &curdir_str : NULL,
1449
                                         &cmdline_str, env,
1450 1451
                                         startup->lpTitle ? &title : NULL,
                                         startup->lpDesktop ? &desktop : NULL,
1452 1453
                                         NULL, 
                                         (startup->lpReserved2 && startup->cbReserved2) ? &runtime : NULL );
1454
    RtlFreeUnicodeString( &newdir );
1455 1456 1457 1458 1459 1460
    if (status != STATUS_SUCCESS)
    {
        SetLastError( RtlNtStatusToDosError(status) );
        return NULL;
    }

1461
    if (flags & CREATE_NEW_PROCESS_GROUP) params->ConsoleFlags = 1;
1462
    if (flags & CREATE_NEW_CONSOLE) params->ConsoleHandle = (HANDLE)1;  /* FIXME: cf. kernel_main.c */
1463

1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475
    if (startup->dwFlags & STARTF_USESTDHANDLES)
    {
        params->hStdInput  = startup->hStdInput;
        params->hStdOutput = startup->hStdOutput;
        params->hStdError  = startup->hStdError;
    }
    else
    {
        params->hStdInput  = GetStdHandle( STD_INPUT_HANDLE );
        params->hStdOutput = GetStdHandle( STD_OUTPUT_HANDLE );
        params->hStdError  = GetStdHandle( STD_ERROR_HANDLE );
    }
1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488
    params->dwX             = startup->dwX;
    params->dwY             = startup->dwY;
    params->dwXSize         = startup->dwXSize;
    params->dwYSize         = startup->dwYSize;
    params->dwXCountChars   = startup->dwXCountChars;
    params->dwYCountChars   = startup->dwYCountChars;
    params->dwFillAttribute = startup->dwFillAttribute;
    params->dwFlags         = startup->dwFlags;
    params->wShowWindow     = startup->wShowWindow;
    return params;
}


1489 1490 1491 1492 1493 1494
/***********************************************************************
 *           create_process
 *
 * Create a new process. If hFile is a valid handle we have an exe
 * file, otherwise it is a Winelib app.
 */
1495
static BOOL create_process( HANDLE hFile, LPCWSTR filename, LPWSTR cmd_line, LPWSTR env,
1496
                            LPCWSTR cur_dir, LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1497
                            BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
1498
                            LPPROCESS_INFORMATION info, LPCSTR unixdir,
1499
                            void *res_start, void *res_end, int exec_only )
1500 1501
{
    BOOL ret, success = FALSE;
1502
    HANDLE process_info, hstdin, hstdout;
1503
    WCHAR *env_end;
1504
    char *winedebug = NULL;
1505
    char **argv;
1506
    RTL_USER_PROCESS_PARAMETERS *params;
1507
    int socketfd[2], stdin_fd = -1, stdout_fd = -1;
1508 1509 1510
    pid_t pid;
    int err;

1511
    if (!env) RtlAcquirePebLock();
1512

1513
    if (!(params = create_user_params( filename, cmd_line, cur_dir, env, flags, startup )))
1514 1515
    {
        if (!env) RtlReleasePebLock();
1516
        return FALSE;
1517 1518
    }
    env_end = params->Environment;
1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529
    while (*env_end)
    {
        static const WCHAR WINEDEBUG[] = {'W','I','N','E','D','E','B','U','G','=',0};
        if (!winedebug && !strncmpW( env_end, WINEDEBUG, sizeof(WINEDEBUG)/sizeof(WCHAR) - 1 ))
        {
            DWORD len = WideCharToMultiByte( CP_UNIXCP, 0, env_end, -1, NULL, 0, NULL, NULL );
            if ((winedebug = HeapAlloc( GetProcessHeap(), 0, len )))
                WideCharToMultiByte( CP_UNIXCP, 0, env_end, -1, winedebug, len, NULL, NULL );
        }
        env_end += strlenW(env_end) + 1;
    }
1530
    env_end++;
1531

1532
    /* create the socket for the new process */
1533

1534
    if (socketpair( PF_UNIX, SOCK_STREAM, 0, socketfd ) == -1)
1535
    {
1536
        if (!env) RtlReleasePebLock();
1537
        HeapFree( GetProcessHeap(), 0, winedebug );
1538
        RtlDestroyProcessParameters( params );
1539
        SetLastError( ERROR_TOO_MANY_OPEN_FILES );
1540 1541
        return FALSE;
    }
1542 1543
    wine_server_send_fd( socketfd[1] );
    close( socketfd[1] );
1544 1545 1546 1547 1548

    /* create the process on the server side */

    SERVER_START_REQ( new_process )
    {
1549 1550 1551
        req->inherit_all    = inherit;
        req->create_flags   = flags;
        req->socket_fd      = socketfd[1];
1552
        req->exe_file       = wine_server_obj_handle( hFile );
1553 1554 1555 1556
        req->process_access = PROCESS_ALL_ACCESS;
        req->process_attr   = (psa && (psa->nLength >= sizeof(*psa)) && psa->bInheritHandle) ? OBJ_INHERIT : 0;
        req->thread_access  = THREAD_ALL_ACCESS;
        req->thread_attr    = (tsa && (tsa->nLength >= sizeof(*tsa)) && tsa->bInheritHandle) ? OBJ_INHERIT : 0;
1557 1558 1559
        req->hstdin         = wine_server_obj_handle( params->hStdInput );
        req->hstdout        = wine_server_obj_handle( params->hStdOutput );
        req->hstderr        = wine_server_obj_handle( params->hStdError );
1560 1561 1562 1563

        if ((flags & (CREATE_NEW_CONSOLE | DETACHED_PROCESS)) != 0)
        {
            /* this is temporary (for console handles). We have no way to control that the handle is invalid in child process otherwise */
1564 1565 1566
            if (is_console_handle(params->hStdInput))  req->hstdin  = wine_server_obj_handle( INVALID_HANDLE_VALUE );
            if (is_console_handle(params->hStdOutput)) req->hstdout = wine_server_obj_handle( INVALID_HANDLE_VALUE );
            if (is_console_handle(params->hStdError))  req->hstderr = wine_server_obj_handle( INVALID_HANDLE_VALUE );
1567
            hstdin = hstdout = 0;
1568 1569 1570
        }
        else
        {
1571 1572 1573 1574 1575
            if (is_console_handle(params->hStdInput))  req->hstdin  = console_handle_unmap(params->hStdInput);
            if (is_console_handle(params->hStdOutput)) req->hstdout = console_handle_unmap(params->hStdOutput);
            if (is_console_handle(params->hStdError))  req->hstderr = console_handle_unmap(params->hStdError);
            hstdin  = wine_server_ptr_handle( req->hstdin );
            hstdout = wine_server_ptr_handle( req->hstdout );
1576 1577
        }

1578
        wine_server_add_data( req, params, params->Size );
1579
        wine_server_add_data( req, params->Environment, (env_end-params->Environment)*sizeof(WCHAR) );
1580 1581 1582 1583
        if ((ret = !wine_server_call_err( req )))
        {
            info->dwProcessId = (DWORD)reply->pid;
            info->dwThreadId  = (DWORD)reply->tid;
1584 1585
            info->hProcess    = wine_server_ptr_handle( reply->phandle );
            info->hThread     = wine_server_ptr_handle( reply->thandle );
1586
        }
1587
        process_info = wine_server_ptr_handle( reply->info );
1588 1589
    }
    SERVER_END_REQ;
1590

1591
    if (!env) RtlReleasePebLock();
1592
    RtlDestroyProcessParameters( params );
1593 1594
    if (!ret)
    {
1595 1596
        close( socketfd[0] );
        HeapFree( GetProcessHeap(), 0, winedebug );
1597 1598 1599
        return FALSE;
    }

1600 1601 1602
    if (hstdin) wine_server_handle_to_fd( hstdin, FILE_READ_DATA, &stdin_fd, NULL );
    if (hstdout) wine_server_handle_to_fd( hstdout, FILE_WRITE_DATA, &stdout_fd, NULL );

1603
    /* create the child process */
1604
    argv = build_argv( cmd_line, 1 );
1605

1606
    if (exec_only || !(pid = fork()))  /* child */
1607 1608
    {
        char preloader_reserve[64], socket_env[64];
1609

1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625
        if (flags & (CREATE_NEW_PROCESS_GROUP | CREATE_NEW_CONSOLE | DETACHED_PROCESS))
        {
            if (!(pid = fork()))
            {
                int fd = open( "/dev/null", O_RDWR );
                setsid();
                /* close stdin and stdout */
                if (fd != -1)
                {
                    dup2( fd, 0 );
                    dup2( fd, 1 );
                    close( fd );
                }
            }
            else if (pid != -1) _exit(0);  /* parent */
        }
1626 1627 1628 1629 1630 1631 1632 1633
        else
        {
            if (stdin_fd != -1) dup2( stdin_fd, 0 );
            if (stdout_fd != -1) dup2( stdout_fd, 1 );
        }

        if (stdin_fd != -1) close( stdin_fd );
        if (stdout_fd != -1) close( stdout_fd );
1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653

        /* Reset signals that we previously set to SIG_IGN */
        signal( SIGPIPE, SIG_DFL );
        signal( SIGCHLD, SIG_DFL );

        sprintf( socket_env, "WINESERVERSOCKET=%u", socketfd[0] );
        sprintf( preloader_reserve, "WINEPRELOADRESERVE=%lx-%lx",
                 (unsigned long)res_start, (unsigned long)res_end );

        putenv( preloader_reserve );
        putenv( socket_env );
        if (winedebug) putenv( winedebug );
        if (unixdir) chdir(unixdir);

        if (argv) wine_exec_wine_binary( NULL, argv, getenv("WINELOADER") );
        _exit(1);
    }

    /* this is the parent */

1654 1655
    if (stdin_fd != -1) close( stdin_fd );
    if (stdout_fd != -1) close( stdout_fd );
1656
    close( socketfd[0] );
1657
    HeapFree( GetProcessHeap(), 0, argv );
1658 1659
    HeapFree( GetProcessHeap(), 0, winedebug );
    if (pid == -1)
1660 1661
    {
        FILE_SetDosError();
1662
        goto error;
1663 1664 1665 1666 1667 1668 1669
    }

    /* wait for the new process info to be ready */

    WaitForSingleObject( process_info, INFINITE );
    SERVER_START_REQ( get_new_process_info )
    {
1670
        req->info = wine_server_obj_handle( process_info );
1671 1672 1673
        wine_server_call( req );
        success = reply->success;
        err = reply->exit_code;
1674 1675 1676
    }
    SERVER_END_REQ;

1677
    if (!success)
1678
    {
1679 1680
        SetLastError( err ? err : ERROR_INTERNAL_ERROR );
        goto error;
1681 1682
    }
    CloseHandle( process_info );
1683 1684 1685 1686 1687 1688 1689 1690 1691
    return success;

error:
    CloseHandle( process_info );
    CloseHandle( info->hProcess );
    CloseHandle( info->hThread );
    info->hProcess = info->hThread = 0;
    info->dwProcessId = info->dwThreadId = 0;
    return FALSE;
1692 1693 1694 1695 1696 1697 1698 1699
}


/***********************************************************************
 *           create_vdm_process
 *
 * Create a new VDM process for a 16-bit or DOS application.
 */
1700
static BOOL create_vdm_process( LPCWSTR filename, LPWSTR cmd_line, LPWSTR env, LPCWSTR cur_dir,
1701
                                LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1702
                                BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
1703
                                LPPROCESS_INFORMATION info, LPCSTR unixdir, int exec_only )
1704
{
1705 1706
    static const WCHAR argsW[] = {'%','s',' ','-','-','a','p','p','-','n','a','m','e',' ','"','%','s','"',' ','%','s',0};

1707
    BOOL ret;
1708 1709
    LPWSTR new_cmd_line = HeapAlloc( GetProcessHeap(), 0,
                                     (strlenW(filename) + strlenW(cmd_line) + 30) * sizeof(WCHAR) );
1710 1711 1712 1713 1714 1715

    if (!new_cmd_line)
    {
        SetLastError( ERROR_OUTOFMEMORY );
        return FALSE;
    }
1716
    sprintfW( new_cmd_line, argsW, winevdmW, filename, cmd_line );
1717
    ret = create_process( 0, winevdmW, new_cmd_line, env, cur_dir, psa, tsa, inherit,
1718
                          flags, startup, info, unixdir, NULL, NULL, exec_only );
1719 1720 1721 1722 1723
    HeapFree( GetProcessHeap(), 0, new_cmd_line );
    return ret;
}


1724 1725 1726 1727 1728
/***********************************************************************
 *           create_cmd_process
 *
 * Create a new cmd shell process for a .BAT file.
 */
1729
static BOOL create_cmd_process( LPCWSTR filename, LPWSTR cmd_line, LPVOID env, LPCWSTR cur_dir,
1730 1731
                                LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
                                BOOL inherit, DWORD flags, LPSTARTUPINFOW startup,
1732
                                LPPROCESS_INFORMATION info )
1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756

{
    static const WCHAR comspecW[] = {'C','O','M','S','P','E','C',0};
    static const WCHAR slashcW[] = {' ','/','c',' ',0};
    WCHAR comspec[MAX_PATH];
    WCHAR *newcmdline;
    BOOL ret;

    if (!GetEnvironmentVariableW( comspecW, comspec, sizeof(comspec)/sizeof(WCHAR) ))
        return FALSE;
    if (!(newcmdline = HeapAlloc( GetProcessHeap(), 0,
                                  (strlenW(comspec) + 4 + strlenW(cmd_line) + 1) * sizeof(WCHAR))))
        return FALSE;

    strcpyW( newcmdline, comspec );
    strcatW( newcmdline, slashcW );
    strcatW( newcmdline, cmd_line );
    ret = CreateProcessW( comspec, newcmdline, psa, tsa, inherit,
                          flags, env, cur_dir, startup, info );
    HeapFree( GetProcessHeap(), 0, newcmdline );
    return ret;
}


1757 1758 1759 1760 1761 1762 1763 1764
/*************************************************************************
 *               get_file_name
 *
 * Helper for CreateProcess: retrieve the file name to load from the
 * app name and command line. Store the file name in buffer, and
 * return a possibly modified command line.
 * Also returns a handle to the opened file if it's a Windows binary.
 */
1765 1766
static LPWSTR get_file_name( LPCWSTR appname, LPWSTR cmdline, LPWSTR buffer,
                             int buflen, HANDLE *handle )
1767
{
1768 1769 1770 1771
    static const WCHAR quotesW[] = {'"','%','s','"',0};

    WCHAR *name, *pos, *ret = NULL;
    const WCHAR *p;
1772
    BOOL got_space;
1773 1774 1775 1776 1777 1778

    /* if we have an app name, everything is easy */

    if (appname)
    {
        /* use the unmodified app name as file name */
1779
        lstrcpynW( buffer, appname, buflen );
1780 1781 1782 1783
        *handle = open_exe_file( buffer );
        if (!(ret = cmdline) || !cmdline[0])
        {
            /* no command-line, create one */
1784
            if ((ret = HeapAlloc( GetProcessHeap(), 0, (strlenW(appname) + 3) * sizeof(WCHAR) )))
1785
                sprintfW( ret, quotesW, appname );
1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797
        }
        return ret;
    }

    if (!cmdline)
    {
        SetLastError( ERROR_INVALID_PARAMETER );
        return NULL;
    }

    /* first check for a quoted file name */

1798
    if ((cmdline[0] == '"') && ((p = strchrW( cmdline + 1, '"' ))))
1799 1800 1801
    {
        int len = p - cmdline - 1;
        /* extract the quoted portion as file name */
1802 1803
        if (!(name = HeapAlloc( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) ))) return NULL;
        memcpy( name, cmdline + 1, len * sizeof(WCHAR) );
1804 1805 1806 1807 1808 1809 1810 1811 1812
        name[len] = 0;

        if (find_exe_file( name, buffer, buflen, handle ))
            ret = cmdline;  /* no change necessary */
        goto done;
    }

    /* now try the command-line word by word */

1813 1814
    if (!(name = HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline) + 1) * sizeof(WCHAR) )))
        return NULL;
1815 1816
    pos = name;
    p = cmdline;
1817
    got_space = FALSE;
1818 1819 1820

    while (*p)
    {
1821
        do *pos++ = *p++; while (*p && *p != ' ' && *p != '\t');
1822 1823 1824 1825 1826 1827
        *pos = 0;
        if (find_exe_file( name, buffer, buflen, handle ))
        {
            ret = cmdline;
            break;
        }
1828
        if (*p) got_space = TRUE;
1829 1830
    }

1831 1832 1833 1834 1835 1836 1837
    if (ret && got_space)  /* now build a new command-line with quotes */
    {
        if (!(ret = HeapAlloc( GetProcessHeap(), 0, (strlenW(cmdline) + 3) * sizeof(WCHAR) )))
            goto done;
        sprintfW( ret, quotesW, name );
        strcatW( ret, p );
    }
1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851

 done:
    HeapFree( GetProcessHeap(), 0, name );
    return ret;
}


/**********************************************************************
 *       CreateProcessA          (KERNEL32.@)
 */
BOOL WINAPI CreateProcessA( LPCSTR app_name, LPSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
                            LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit,
                            DWORD flags, LPVOID env, LPCSTR cur_dir,
                            LPSTARTUPINFOA startup_info, LPPROCESS_INFORMATION info )
1852
{
1853 1854 1855
    BOOL ret = FALSE;
    WCHAR *app_nameW = NULL, *cmd_lineW = NULL, *cur_dirW = NULL;
    UNICODE_STRING desktopW, titleW;
1856 1857
    STARTUPINFOW infoW;

1858 1859 1860 1861 1862 1863
    desktopW.Buffer = NULL;
    titleW.Buffer = NULL;
    if (app_name && !(app_nameW = FILE_name_AtoW( app_name, TRUE ))) goto done;
    if (cmd_line && !(cmd_lineW = FILE_name_AtoW( cmd_line, TRUE ))) goto done;
    if (cur_dir && !(cur_dirW = FILE_name_AtoW( cur_dir, TRUE ))) goto done;

1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874
    if (startup_info->lpDesktop) RtlCreateUnicodeStringFromAsciiz( &desktopW, startup_info->lpDesktop );
    if (startup_info->lpTitle) RtlCreateUnicodeStringFromAsciiz( &titleW, startup_info->lpTitle );

    memcpy( &infoW, startup_info, sizeof(infoW) );
    infoW.lpDesktop = desktopW.Buffer;
    infoW.lpTitle = titleW.Buffer;

    if (startup_info->lpReserved)
      FIXME("StartupInfo.lpReserved is used, please report (%s)\n",
            debugstr_a(startup_info->lpReserved));

1875 1876 1877
    ret = CreateProcessW( app_nameW, cmd_lineW, process_attr, thread_attr,
                          inherit, flags, env, cur_dirW, &infoW, info );
done:
1878 1879 1880
    HeapFree( GetProcessHeap(), 0, app_nameW );
    HeapFree( GetProcessHeap(), 0, cmd_lineW );
    HeapFree( GetProcessHeap(), 0, cur_dirW );
1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893
    RtlFreeUnicodeString( &desktopW );
    RtlFreeUnicodeString( &titleW );
    return ret;
}


/**********************************************************************
 *       CreateProcessW          (KERNEL32.@)
 */
BOOL WINAPI CreateProcessW( LPCWSTR app_name, LPWSTR cmd_line, LPSECURITY_ATTRIBUTES process_attr,
                            LPSECURITY_ATTRIBUTES thread_attr, BOOL inherit, DWORD flags,
                            LPVOID env, LPCWSTR cur_dir, LPSTARTUPINFOW startup_info,
                            LPPROCESS_INFORMATION info )
1894 1895 1896
{
    BOOL retv = FALSE;
    HANDLE hFile = 0;
1897
    char *unixdir = NULL;
1898 1899
    WCHAR name[MAX_PATH];
    WCHAR *tidy_cmdline, *p, *envW = env;
1900
    void *res_start, *res_end;
1901 1902 1903

    /* Process the AppName and/or CmdLine to get module name and path */

1904
    TRACE("app %s cmdline %s\n", debugstr_w(app_name), debugstr_w(cmd_line) );
1905

1906
    if (!(tidy_cmdline = get_file_name( app_name, cmd_line, name, sizeof(name)/sizeof(WCHAR), &hFile )))
1907 1908 1909 1910 1911
        return FALSE;
    if (hFile == INVALID_HANDLE_VALUE) goto done;

    /* Warn if unsupported features are used */

1912 1913 1914 1915
    if (flags & (IDLE_PRIORITY_CLASS | HIGH_PRIORITY_CLASS | REALTIME_PRIORITY_CLASS |
                 CREATE_NEW_PROCESS_GROUP | CREATE_SEPARATE_WOW_VDM | CREATE_SHARED_WOW_VDM |
                 CREATE_DEFAULT_ERROR_MODE | CREATE_NO_WINDOW |
                 PROFILE_USER | PROFILE_KERNEL | PROFILE_SERVER))
1916
        WARN("(%s,...): ignoring some flags in %x\n", debugstr_w(name), flags);
1917 1918 1919

    if (cur_dir)
    {
1920 1921 1922 1923 1924
        if (!(unixdir = wine_get_unix_file_name( cur_dir )))
        {
            SetLastError(ERROR_DIRECTORY);
            goto done;
        }
1925 1926 1927 1928
    }
    else
    {
        WCHAR buf[MAX_PATH];
1929
        if (GetCurrentDirectoryW(MAX_PATH, buf)) unixdir = wine_get_unix_file_name( buf );
1930 1931
    }

1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944
    if (env && !(flags & CREATE_UNICODE_ENVIRONMENT))  /* convert environment to unicode */
    {
        char *p = env;
        DWORD lenW;

        while (*p) p += strlen(p) + 1;
        p++;  /* final null */
        lenW = MultiByteToWideChar( CP_ACP, 0, env, p - (char*)env, NULL, 0 );
        envW = HeapAlloc( GetProcessHeap(), 0, lenW * sizeof(WCHAR) );
        MultiByteToWideChar( CP_ACP, 0, env, p - (char*)env, envW, lenW );
        flags |= CREATE_UNICODE_ENVIRONMENT;
    }

1945 1946 1947 1948 1949 1950 1951
    info->hThread = info->hProcess = 0;
    info->dwProcessId = info->dwThreadId = 0;

    /* Determine executable type */

    if (!hFile)  /* builtin exe */
    {
1952
        TRACE( "starting %s as Winelib app\n", debugstr_w(name) );
1953
        retv = create_process( 0, name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1954
                               inherit, flags, startup_info, info, unixdir, NULL, NULL, FALSE );
1955 1956 1957
        goto done;
    }

1958
    switch( MODULE_GetBinaryType( hFile, &res_start, &res_end ))
1959 1960
    {
    case BINARY_PE_EXE:
1961
        TRACE( "starting %s as Win32 binary (%p-%p)\n", debugstr_w(name), res_start, res_end );
1962
        retv = create_process( hFile, name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1963
                               inherit, flags, startup_info, info, unixdir, res_start, res_end, FALSE );
1964
        break;
1965
    case BINARY_OS216:
1966 1967
    case BINARY_WIN16:
    case BINARY_DOS:
1968
        TRACE( "starting %s as Win16/DOS binary\n", debugstr_w(name) );
1969
        retv = create_vdm_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1970
                                   inherit, flags, startup_info, info, unixdir, FALSE );
1971 1972
        break;
    case BINARY_PE_DLL:
1973
        TRACE( "not starting %s since it is a dll\n", debugstr_w(name) );
1974 1975 1976
        SetLastError( ERROR_BAD_EXE_FORMAT );
        break;
    case BINARY_UNIX_LIB:
1977
        TRACE( "%s is a Unix library, starting as Winelib app\n", debugstr_w(name) );
1978
        retv = create_process( hFile, name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1979
                               inherit, flags, startup_info, info, unixdir, NULL, NULL, FALSE );
1980 1981 1982
        break;
    case BINARY_UNKNOWN:
        /* check for .com or .bat extension */
1983
        if ((p = strrchrW( name, '.' )))
1984
        {
1985
            if (!strcmpiW( p, comW ) || !strcmpiW( p, pifW ))
1986
            {
1987
                TRACE( "starting %s as DOS binary\n", debugstr_w(name) );
1988
                retv = create_vdm_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
1989
                                           inherit, flags, startup_info, info, unixdir, FALSE );
1990 1991
                break;
            }
1992
            if (!strcmpiW( p, batW ) || !strcmpiW( p, cmdW ) )
1993
            {
1994
                TRACE( "starting %s as batch binary\n", debugstr_w(name) );
1995 1996
                retv = create_cmd_process( name, tidy_cmdline, envW, cur_dir, process_attr, thread_attr,
                                           inherit, flags, startup_info, info );
1997
                break;
1998 1999 2000 2001 2002 2003
            }
        }
        /* fall through */
    case BINARY_UNIX_EXE:
        {
            /* unknown file, try as unix executable */
2004
            char *unix_name;
2005

2006
            TRACE( "starting %s as Unix binary\n", debugstr_w(name) );
2007

2008 2009
            if ((unix_name = wine_get_unix_file_name( name )))
            {
2010
                retv = (fork_and_exec( unix_name, tidy_cmdline, envW, unixdir, flags, startup_info ) != -1);
2011 2012
                HeapFree( GetProcessHeap(), 0, unix_name );
            }
2013 2014 2015 2016 2017 2018 2019
        }
        break;
    }
    CloseHandle( hFile );

 done:
    if (tidy_cmdline != cmd_line) HeapFree( GetProcessHeap(), 0, tidy_cmdline );
2020
    if (envW != env) HeapFree( GetProcessHeap(), 0, envW );
2021
    HeapFree( GetProcessHeap(), 0, unixdir );
2022 2023
    if (retv)
        TRACE( "started process pid %04x tid %04x\n", info->dwProcessId, info->dwThreadId );
2024 2025 2026 2027
    return retv;
}


2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077
/**********************************************************************
 *       exec_process
 */
static void exec_process( LPCWSTR name )
{
    HANDLE hFile;
    WCHAR *p;
    void *res_start, *res_end;
    STARTUPINFOW startup_info;
    PROCESS_INFORMATION info;

    hFile = open_exe_file( name );
    if (!hFile || hFile == INVALID_HANDLE_VALUE) return;

    memset( &startup_info, 0, sizeof(startup_info) );
    startup_info.cb = sizeof(startup_info);

    /* Determine executable type */

    switch( MODULE_GetBinaryType( hFile, &res_start, &res_end ))
    {
    case BINARY_PE_EXE:
        TRACE( "starting %s as Win32 binary (%p-%p)\n", debugstr_w(name), res_start, res_end );
        create_process( hFile, name, GetCommandLineW(), NULL, NULL, NULL, NULL,
                        FALSE, 0, &startup_info, &info, NULL, res_start, res_end, TRUE );
        break;
    case BINARY_UNIX_LIB:
        TRACE( "%s is a Unix library, starting as Winelib app\n", debugstr_w(name) );
        create_process( hFile, name, GetCommandLineW(), NULL, NULL, NULL, NULL,
                        FALSE, 0, &startup_info, &info, NULL, NULL, NULL, TRUE );
        break;
    case BINARY_UNKNOWN:
        /* check for .com or .pif extension */
        if (!(p = strrchrW( name, '.' ))) break;
        if (strcmpiW( p, comW ) && strcmpiW( p, pifW )) break;
        /* fall through */
    case BINARY_OS216:
    case BINARY_WIN16:
    case BINARY_DOS:
        TRACE( "starting %s as Win16/DOS binary\n", debugstr_w(name) );
        create_vdm_process( name, GetCommandLineW(), NULL, NULL, NULL, NULL,
                            FALSE, 0, &startup_info, &info, NULL, TRUE );
        break;
    default:
        break;
    }
    CloseHandle( hFile );
}


2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111
/***********************************************************************
 *           wait_input_idle
 *
 * Wrapper to call WaitForInputIdle USER function
 */
typedef DWORD (WINAPI *WaitForInputIdle_ptr)( HANDLE hProcess, DWORD dwTimeOut );

static DWORD wait_input_idle( HANDLE process, DWORD timeout )
{
    HMODULE mod = GetModuleHandleA( "user32.dll" );
    if (mod)
    {
        WaitForInputIdle_ptr ptr = (WaitForInputIdle_ptr)GetProcAddress( mod, "WaitForInputIdle" );
        if (ptr) return ptr( process, timeout );
    }
    return 0;
}


/***********************************************************************
 *           WinExec   (KERNEL32.@)
 */
UINT WINAPI WinExec( LPCSTR lpCmdLine, UINT nCmdShow )
{
    PROCESS_INFORMATION info;
    STARTUPINFOA startup;
    char *cmdline;
    UINT ret;

    memset( &startup, 0, sizeof(startup) );
    startup.cb = sizeof(startup);
    startup.dwFlags = STARTF_USESHOWWINDOW;
    startup.wShowWindow = nCmdShow;

2112
    /* cmdline needs to be writable for CreateProcess */
2113 2114 2115 2116 2117 2118 2119
    if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(lpCmdLine)+1 ))) return 0;
    strcpy( cmdline, lpCmdLine );

    if (CreateProcessA( NULL, cmdline, NULL, NULL, FALSE,
                        0, NULL, NULL, &startup, &info ))
    {
        /* Give 30 seconds to the app to come up */
2120
        if (wait_input_idle( info.hProcess, 30000 ) == WAIT_FAILED)
2121
            WARN("WaitForInputIdle failed: Error %d\n", GetLastError() );
2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141
        ret = 33;
        /* Close off the handles */
        CloseHandle( info.hThread );
        CloseHandle( info.hProcess );
    }
    else if ((ret = GetLastError()) >= 32)
    {
        FIXME("Strange error set by CreateProcess: %d\n", ret );
        ret = 11;
    }
    HeapFree( GetProcessHeap(), 0, cmdline );
    return ret;
}


/**********************************************************************
 *	    LoadModule    (KERNEL32.@)
 */
HINSTANCE WINAPI LoadModule( LPCSTR name, LPVOID paramBlock )
{
2142
    LOADPARMS32 *params = paramBlock;
2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153
    PROCESS_INFORMATION info;
    STARTUPINFOA startup;
    HINSTANCE hInstance;
    LPSTR cmdline, p;
    char filename[MAX_PATH];
    BYTE len;

    if (!name) return (HINSTANCE)ERROR_FILE_NOT_FOUND;

    if (!SearchPathA( NULL, name, ".exe", sizeof(filename), filename, NULL ) &&
        !SearchPathA( NULL, name, NULL, sizeof(filename), filename, NULL ))
2154
        return ULongToHandle(GetLastError());
2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170

    len = (BYTE)params->lpCmdLine[0];
    if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(filename) + len + 2 )))
        return (HINSTANCE)ERROR_NOT_ENOUGH_MEMORY;

    strcpy( cmdline, filename );
    p = cmdline + strlen(cmdline);
    *p++ = ' ';
    memcpy( p, params->lpCmdLine + 1, len );
    p[len] = 0;

    memset( &startup, 0, sizeof(startup) );
    startup.cb = sizeof(startup);
    if (params->lpCmdShow)
    {
        startup.dwFlags = STARTF_USESHOWWINDOW;
2171
        startup.wShowWindow = ((WORD *)params->lpCmdShow)[1];
2172 2173 2174 2175 2176 2177
    }

    if (CreateProcessA( filename, cmdline, NULL, NULL, FALSE, 0,
                        params->lpEnvAddress, NULL, &startup, &info ))
    {
        /* Give 30 seconds to the app to come up */
2178
        if (wait_input_idle( info.hProcess, 30000 ) == WAIT_FAILED)
2179
            WARN("WaitForInputIdle failed: Error %d\n", GetLastError() );
2180 2181 2182 2183 2184
        hInstance = (HINSTANCE)33;
        /* Close off the handles */
        CloseHandle( info.hThread );
        CloseHandle( info.hProcess );
    }
2185
    else if ((hInstance = ULongToHandle(GetLastError())) >= (HINSTANCE)32)
2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197
    {
        FIXME("Strange error set by CreateProcess: %p\n", hInstance );
        hInstance = (HINSTANCE)11;
    }

    HeapFree( GetProcessHeap(), 0, cmdline );
    return hInstance;
}


/******************************************************************************
 *           TerminateProcess   (KERNEL32.@)
2198 2199 2200 2201 2202 2203 2204 2205 2206 2207
 *
 * Terminates a process.
 *
 * PARAMS
 *  handle    [I] Process to terminate.
 *  exit_code [I] Exit code.
 *
 * RETURNS
 *  Success: TRUE.
 *  Failure: FALSE, check GetLastError().
2208 2209 2210 2211 2212 2213 2214 2215
 */
BOOL WINAPI TerminateProcess( HANDLE handle, DWORD exit_code )
{
    NTSTATUS status = NtTerminateProcess( handle, exit_code );
    if (status) SetLastError( RtlNtStatusToDosError(status) );
    return !status;
}

2216 2217
/***********************************************************************
 *           ExitProcess   (KERNEL32.@)
2218 2219 2220 2221 2222 2223 2224 2225
 *
 * Exits the current process.
 *
 * PARAMS
 *  status [I] Status code to exit with.
 *
 * RETURNS
 *  Nothing.
2226
 */
2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246
#ifdef __i386__
__ASM_GLOBAL_FUNC( ExitProcess, /* Shrinker depend on this particular ExitProcess implementation */
                   "pushl %ebp\n\t"
                   ".byte 0x8B, 0xEC\n\t" /* movl %esp, %ebp */
                   ".byte 0x6A, 0x00\n\t" /* pushl $0 */
                   ".byte 0x68, 0x00, 0x00, 0x00, 0x00\n\t" /* pushl $0 - 4 bytes immediate */
                   "pushl 8(%ebp)\n\t"
                   "call " __ASM_NAME("process_ExitProcess") "\n\t"
                   "leave\n\t"
                   "ret $4" )

void WINAPI process_ExitProcess( DWORD status )
{
    LdrShutdownProcess();
    NtTerminateProcess(GetCurrentProcess(), status);
    exit(status);
}

#else

2247 2248 2249
void WINAPI ExitProcess( DWORD status )
{
    LdrShutdownProcess();
2250 2251
    NtTerminateProcess(GetCurrentProcess(), status);
    exit(status);
2252 2253
}

2254
#endif
2255

2256
/***********************************************************************
2257
 * GetExitCodeProcess           [KERNEL32.@]
2258
 *
2259 2260 2261 2262 2263
 * Gets termination status of specified process.
 *
 * PARAMS
 *   hProcess   [in]  Handle to the process.
 *   lpExitCode [out] Address to receive termination status.
2264 2265 2266 2267 2268
 *
 * RETURNS
 *   Success: TRUE
 *   Failure: FALSE
 */
2269
BOOL WINAPI GetExitCodeProcess( HANDLE hProcess, LPDWORD lpExitCode )
2270
{
2271 2272 2273 2274 2275 2276
    NTSTATUS status;
    PROCESS_BASIC_INFORMATION pbi;

    status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
                                       sizeof(pbi), NULL);
    if (status == STATUS_SUCCESS)
2277
    {
2278 2279
        if (lpExitCode) *lpExitCode = pbi.ExitStatus;
        return TRUE;
2280
    }
2281 2282
    SetLastError( RtlNtStatusToDosError(status) );
    return FALSE;
2283 2284 2285 2286 2287 2288 2289 2290
}


/***********************************************************************
 *           SetErrorMode   (KERNEL32.@)
 */
UINT WINAPI SetErrorMode( UINT mode )
{
2291 2292
    UINT old = process_error_mode;
    process_error_mode = mode;
2293 2294 2295
    return old;
}

2296 2297 2298 2299 2300 2301 2302
/***********************************************************************
 *           GetErrorMode   (KERNEL32.@)
 */
UINT WINAPI GetErrorMode( void )
{
    return process_error_mode;
}
2303 2304

/**********************************************************************
2305
 * TlsAlloc             [KERNEL32.@]
2306
 *
2307
 * Allocates a thread local storage index.
2308 2309
 *
 * RETURNS
2310
 *    Success: TLS index.
2311 2312 2313 2314
 *    Failure: 0xFFFFFFFF
 */
DWORD WINAPI TlsAlloc( void )
{
2315
    DWORD index;
2316
    PEB * const peb = NtCurrentTeb()->Peb;
2317

2318
    RtlAcquirePebLock();
2319
    index = RtlFindClearBitsAndSet( peb->TlsBitmap, 1, 0 );
2320
    if (index != ~0U) NtCurrentTeb()->TlsSlots[index] = 0; /* clear the value */
2321 2322 2323
    else
    {
        index = RtlFindClearBitsAndSet( peb->TlsExpansionBitmap, 1, 0 );
2324
        if (index != ~0U)
2325 2326 2327 2328 2329 2330
        {
            if (!NtCurrentTeb()->TlsExpansionSlots &&
                !(NtCurrentTeb()->TlsExpansionSlots = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY,
                                         8 * sizeof(peb->TlsExpansionBitmapBits) * sizeof(void*) )))
            {
                RtlClearBits( peb->TlsExpansionBitmap, index, 1 );
2331
                index = ~0U;
2332 2333 2334 2335 2336 2337 2338 2339 2340 2341
                SetLastError( ERROR_NOT_ENOUGH_MEMORY );
            }
            else
            {
                NtCurrentTeb()->TlsExpansionSlots[index] = 0; /* clear the value */
                index += TLS_MINIMUM_AVAILABLE;
            }
        }
        else SetLastError( ERROR_NO_MORE_ITEMS );
    }
2342
    RtlReleasePebLock();
2343
    return index;
2344 2345 2346 2347
}


/**********************************************************************
2348 2349 2350
 * TlsFree              [KERNEL32.@]
 *
 * Releases a thread local storage index, making it available for reuse.
2351
 *
2352 2353
 * PARAMS
 *    index [in] TLS index to free.
2354 2355 2356 2357 2358
 *
 * RETURNS
 *    Success: TRUE
 *    Failure: FALSE
 */
2359
BOOL WINAPI TlsFree( DWORD index )
2360
{
2361 2362
    BOOL ret;

2363
    RtlAcquirePebLock();
2364 2365 2366 2367 2368 2369
    if (index >= TLS_MINIMUM_AVAILABLE)
    {
        ret = RtlAreBitsSet( NtCurrentTeb()->Peb->TlsExpansionBitmap, index - TLS_MINIMUM_AVAILABLE, 1 );
        if (ret) RtlClearBits( NtCurrentTeb()->Peb->TlsExpansionBitmap, index - TLS_MINIMUM_AVAILABLE, 1 );
    }
    else
2370
    {
2371 2372
        ret = RtlAreBitsSet( NtCurrentTeb()->Peb->TlsBitmap, index, 1 );
        if (ret) RtlClearBits( NtCurrentTeb()->Peb->TlsBitmap, index, 1 );
2373
    }
2374
    if (ret) NtSetInformationThread( GetCurrentThread(), ThreadZeroTlsCell, &index, sizeof(index) );
2375
    else SetLastError( ERROR_INVALID_PARAMETER );
2376 2377 2378 2379 2380 2381
    RtlReleasePebLock();
    return TRUE;
}


/**********************************************************************
2382 2383 2384 2385 2386 2387
 * TlsGetValue          [KERNEL32.@]
 *
 * Gets value in a thread's TLS slot.
 *
 * PARAMS
 *    index [in] TLS index to retrieve value for.
2388 2389
 *
 * RETURNS
2390 2391
 *    Success: Value stored in calling thread's TLS slot for index.
 *    Failure: 0 and GetLastError() returns NO_ERROR.
2392
 */
2393
LPVOID WINAPI TlsGetValue( DWORD index )
2394
{
2395 2396 2397
    LPVOID ret;

    if (index < TLS_MINIMUM_AVAILABLE)
2398
    {
2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410
        ret = NtCurrentTeb()->TlsSlots[index];
    }
    else
    {
        index -= TLS_MINIMUM_AVAILABLE;
        if (index >= 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits))
        {
            SetLastError( ERROR_INVALID_PARAMETER );
            return NULL;
        }
        if (!NtCurrentTeb()->TlsExpansionSlots) ret = NULL;
        else ret = NtCurrentTeb()->TlsExpansionSlots[index];
2411 2412
    }
    SetLastError( ERROR_SUCCESS );
2413
    return ret;
2414 2415 2416 2417
}


/**********************************************************************
2418 2419 2420 2421 2422 2423 2424
 * TlsSetValue          [KERNEL32.@]
 *
 * Stores a value in the thread's TLS slot.
 *
 * PARAMS
 *    index [in] TLS index to set value for.
 *    value [in] Value to be stored.
2425 2426 2427 2428 2429
 *
 * RETURNS
 *    Success: TRUE
 *    Failure: FALSE
 */
2430
BOOL WINAPI TlsSetValue( DWORD index, LPVOID value )
2431
{
2432
    if (index < TLS_MINIMUM_AVAILABLE)
2433
    {
2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451
        NtCurrentTeb()->TlsSlots[index] = value;
    }
    else
    {
        index -= TLS_MINIMUM_AVAILABLE;
        if (index >= 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits))
        {
            SetLastError( ERROR_INVALID_PARAMETER );
            return FALSE;
        }
        if (!NtCurrentTeb()->TlsExpansionSlots &&
            !(NtCurrentTeb()->TlsExpansionSlots = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY,
                         8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits) * sizeof(void*) )))
        {
            SetLastError( ERROR_NOT_ENOUGH_MEMORY );
            return FALSE;
        }
        NtCurrentTeb()->TlsExpansionSlots[index] = value;
2452 2453 2454
    }
    return TRUE;
}
2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487


/***********************************************************************
 *           GetProcessFlags    (KERNEL32.@)
 */
DWORD WINAPI GetProcessFlags( DWORD processid )
{
    IMAGE_NT_HEADERS *nt;
    DWORD flags = 0;

    if (processid && processid != GetCurrentProcessId()) return 0;

    if ((nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress )))
    {
        if (nt->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_CUI)
            flags |= PDB32_CONSOLE_PROC;
    }
    if (!AreFileApisANSI()) flags |= PDB32_FILE_APIS_OEM;
    if (IsDebuggerPresent()) flags |= PDB32_DEBUGGED;
    return flags;
}


/***********************************************************************
 *           GetProcessDword    (KERNEL.485)
 *           GetProcessDword    (KERNEL32.18)
 * 'Of course you cannot directly access Windows internal structures'
 */
DWORD WINAPI GetProcessDword( DWORD dwProcessID, INT offset )
{
    DWORD               x, y;
    STARTUPINFOW        siw;

2488
    TRACE("(%d, %d)\n", dwProcessID, offset );
2489 2490 2491

    if (dwProcessID && dwProcessID != GetCurrentProcessId())
    {
2492
        ERR("%d: process %x not accessible\n", offset, dwProcessID);
2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506
        return 0;
    }

    switch ( offset )
    {
    case GPD_APP_COMPAT_FLAGS:
        return GetAppCompatFlags16(0);
    case GPD_LOAD_DONE_EVENT:
        return 0;
    case GPD_HINSTANCE16:
        return GetTaskDS16();
    case GPD_WINDOWS_VERSION:
        return GetExeVersion16();
    case GPD_THDB:
2507
        return (DWORD_PTR)NtCurrentTeb() - 0x10 /* FIXME */;
2508
    case GPD_PDB:
2509
        return (DWORD_PTR)NtCurrentTeb()->Peb; /* FIXME: truncating a pointer */
2510 2511
    case GPD_STARTF_SHELLDATA: /* return stdoutput handle from startupinfo ??? */
        GetStartupInfoW(&siw);
2512
        return HandleToULong(siw.hStdOutput);
2513 2514
    case GPD_STARTF_HOTKEY: /* return stdinput handle from startupinfo ??? */
        GetStartupInfoW(&siw);
2515
        return HandleToULong(siw.hStdInput);
2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553
    case GPD_STARTF_SHOWWINDOW:
        GetStartupInfoW(&siw);
        return siw.wShowWindow;
    case GPD_STARTF_SIZE:
        GetStartupInfoW(&siw);
        x = siw.dwXSize;
        if ( (INT)x == CW_USEDEFAULT ) x = CW_USEDEFAULT16;
        y = siw.dwYSize;
        if ( (INT)y == CW_USEDEFAULT ) y = CW_USEDEFAULT16;
        return MAKELONG( x, y );
    case GPD_STARTF_POSITION:
        GetStartupInfoW(&siw);
        x = siw.dwX;
        if ( (INT)x == CW_USEDEFAULT ) x = CW_USEDEFAULT16;
        y = siw.dwY;
        if ( (INT)y == CW_USEDEFAULT ) y = CW_USEDEFAULT16;
        return MAKELONG( x, y );
    case GPD_STARTF_FLAGS:
        GetStartupInfoW(&siw);
        return siw.dwFlags;
    case GPD_PARENT:
        return 0;
    case GPD_FLAGS:
        return GetProcessFlags(0);
    case GPD_USERDATA:
        return process_dword;
    default:
        ERR("Unknown offset %d\n", offset );
        return 0;
    }
}

/***********************************************************************
 *           SetProcessDword    (KERNEL.484)
 * 'Of course you cannot directly access Windows internal structures'
 */
void WINAPI SetProcessDword( DWORD dwProcessID, INT offset, DWORD value )
{
2554
    TRACE("(%d, %d)\n", dwProcessID, offset );
2555 2556 2557

    if (dwProcessID && dwProcessID != GetCurrentProcessId())
    {
2558
        ERR("%d: process %x not accessible\n", offset, dwProcessID);
2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602
        return;
    }

    switch ( offset )
    {
    case GPD_APP_COMPAT_FLAGS:
    case GPD_LOAD_DONE_EVENT:
    case GPD_HINSTANCE16:
    case GPD_WINDOWS_VERSION:
    case GPD_THDB:
    case GPD_PDB:
    case GPD_STARTF_SHELLDATA:
    case GPD_STARTF_HOTKEY:
    case GPD_STARTF_SHOWWINDOW:
    case GPD_STARTF_SIZE:
    case GPD_STARTF_POSITION:
    case GPD_STARTF_FLAGS:
    case GPD_PARENT:
    case GPD_FLAGS:
        ERR("Not allowed to modify offset %d\n", offset );
        break;
    case GPD_USERDATA:
        process_dword = value;
        break;
    default:
        ERR("Unknown offset %d\n", offset );
        break;
    }
}


/***********************************************************************
 *           ExitProcess   (KERNEL.466)
 */
void WINAPI ExitProcess16( WORD status )
{
    DWORD count;
    ReleaseThunkLock( &count );
    ExitProcess( status );
}


/*********************************************************************
 *           OpenProcess   (KERNEL32.@)
2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613
 *
 * Opens a handle to a process.
 *
 * PARAMS
 *  access  [I] Desired access rights assigned to the returned handle.
 *  inherit [I] Determines whether or not child processes will inherit the handle.
 *  id      [I] Process identifier of the process to get a handle to.
 *
 * RETURNS
 *  Success: Valid handle to the specified process.
 *  Failure: NULL, check GetLastError().
2614 2615 2616
 */
HANDLE WINAPI OpenProcess( DWORD access, BOOL inherit, DWORD id )
{
2617 2618 2619 2620 2621
    NTSTATUS            status;
    HANDLE              handle;
    OBJECT_ATTRIBUTES   attr;
    CLIENT_ID           cid;

2622
    cid.UniqueProcess = ULongToHandle(id);
2623 2624 2625 2626 2627 2628 2629 2630 2631
    cid.UniqueThread = 0; /* FIXME ? */

    attr.Length = sizeof(OBJECT_ATTRIBUTES);
    attr.RootDirectory = NULL;
    attr.Attributes = inherit ? OBJ_INHERIT : 0;
    attr.SecurityDescriptor = NULL;
    attr.SecurityQualityOfService = NULL;
    attr.ObjectName = NULL;

2632 2633
    if (GetVersion() & 0x80000000) access = PROCESS_ALL_ACCESS;

2634 2635
    status = NtOpenProcess(&handle, access, &attr, &cid);
    if (status != STATUS_SUCCESS)
2636
    {
2637 2638
        SetLastError( RtlNtStatusToDosError(status) );
        return NULL;
2639
    }
2640
    return handle;
2641 2642 2643 2644 2645
}


/*********************************************************************
 *           MapProcessHandle   (KERNEL.483)
Robert Shearman's avatar
Robert Shearman committed
2646
 *           GetProcessId       (KERNEL32.@)
2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660
 *
 * Gets the a unique identifier of a process.
 *
 * PARAMS
 *  hProcess [I] Handle to the process.
 *
 * RETURNS
 *  Success: TRUE.
 *  Failure: FALSE, check GetLastError().
 *
 * NOTES
 *
 * The identifier is unique only on the machine and only until the process
 * exits (including system shutdown).
2661
 */
Robert Shearman's avatar
Robert Shearman committed
2662
DWORD WINAPI GetProcessId( HANDLE hProcess )
2663
{
2664 2665 2666 2667 2668 2669 2670 2671
    NTSTATUS status;
    PROCESS_BASIC_INFORMATION pbi;

    status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
                                       sizeof(pbi), NULL);
    if (status == STATUS_SUCCESS) return pbi.UniqueProcessId;
    SetLastError( RtlNtStatusToDosError(status) );
    return 0;
2672 2673 2674
}


2675 2676 2677
/*********************************************************************
 *           CloseW32Handle (KERNEL.474)
 *           CloseHandle    (KERNEL32.@)
2678 2679 2680 2681 2682 2683 2684 2685 2686
 *
 * Closes a handle.
 *
 * PARAMS
 *  handle [I] Handle to close.
 *
 * RETURNS
 *  Success: TRUE.
 *  Failure: FALSE, check GetLastError().
2687 2688 2689 2690 2691 2692 2693 2694 2695
 */
BOOL WINAPI CloseHandle( HANDLE handle )
{
    NTSTATUS status;

    /* stdio handles need special treatment */
    if ((handle == (HANDLE)STD_INPUT_HANDLE) ||
        (handle == (HANDLE)STD_OUTPUT_HANDLE) ||
        (handle == (HANDLE)STD_ERROR_HANDLE))
2696
        handle = GetStdHandle( HandleToULong(handle) );
2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711

    if (is_console_handle(handle))
        return CloseConsoleHandle(handle);

    status = NtClose( handle );
    if (status) SetLastError( RtlNtStatusToDosError(status) );
    return !status;
}


/*********************************************************************
 *           GetHandleInformation   (KERNEL32.@)
 */
BOOL WINAPI GetHandleInformation( HANDLE handle, LPDWORD flags )
{
2712 2713 2714 2715 2716
    OBJECT_DATA_INFORMATION info;
    NTSTATUS status = NtQueryObject( handle, ObjectDataInformation, &info, sizeof(info), NULL );

    if (status) SetLastError( RtlNtStatusToDosError(status) );
    else if (flags)
2717
    {
2718 2719 2720
        *flags = 0;
        if (info.InheritHandle) *flags |= HANDLE_FLAG_INHERIT;
        if (info.ProtectFromClose) *flags |= HANDLE_FLAG_PROTECT_FROM_CLOSE;
2721
    }
2722
    return !status;
2723 2724 2725 2726 2727 2728 2729 2730
}


/*********************************************************************
 *           SetHandleInformation   (KERNEL32.@)
 */
BOOL WINAPI SetHandleInformation( HANDLE handle, DWORD mask, DWORD flags )
{
2731 2732 2733 2734 2735 2736
    OBJECT_DATA_INFORMATION info;
    NTSTATUS status;

    /* if not setting both fields, retrieve current value first */
    if ((mask & (HANDLE_FLAG_INHERIT | HANDLE_FLAG_PROTECT_FROM_CLOSE)) !=
        (HANDLE_FLAG_INHERIT | HANDLE_FLAG_PROTECT_FROM_CLOSE))
2737
    {
2738 2739 2740 2741 2742
        if ((status = NtQueryObject( handle, ObjectDataInformation, &info, sizeof(info), NULL )))
        {
            SetLastError( RtlNtStatusToDosError(status) );
            return FALSE;
        }
2743
    }
2744 2745 2746 2747 2748 2749 2750 2751
    if (mask & HANDLE_FLAG_INHERIT)
        info.InheritHandle = (flags & HANDLE_FLAG_INHERIT) != 0;
    if (mask & HANDLE_FLAG_PROTECT_FROM_CLOSE)
        info.ProtectFromClose = (flags & HANDLE_FLAG_PROTECT_FROM_CLOSE) != 0;

    status = NtSetInformationObject( handle, ObjectDataInformation, &info, sizeof(info) );
    if (status) SetLastError( RtlNtStatusToDosError(status) );
    return !status;
2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800
}


/*********************************************************************
 *           DuplicateHandle   (KERNEL32.@)
 */
BOOL WINAPI DuplicateHandle( HANDLE source_process, HANDLE source,
                             HANDLE dest_process, HANDLE *dest,
                             DWORD access, BOOL inherit, DWORD options )
{
    NTSTATUS status;

    if (is_console_handle(source))
    {
        /* FIXME: this test is not sufficient, we need to test process ids, not handles */
        if (source_process != dest_process ||
            source_process != GetCurrentProcess())
        {
            SetLastError(ERROR_INVALID_PARAMETER);
            return FALSE;
        }
        *dest = DuplicateConsoleHandle( source, access, inherit, options );
        return (*dest != INVALID_HANDLE_VALUE);
    }
    status = NtDuplicateObject( source_process, source, dest_process, dest,
                                access, inherit ? OBJ_INHERIT : 0, options );
    if (status) SetLastError( RtlNtStatusToDosError(status) );
    return !status;
}


/***********************************************************************
 *           ConvertToGlobalHandle   (KERNEL.476)
 *           ConvertToGlobalHandle  (KERNEL32.@)
 */
HANDLE WINAPI ConvertToGlobalHandle(HANDLE hSrc)
{
    HANDLE ret = INVALID_HANDLE_VALUE;
    DuplicateHandle( GetCurrentProcess(), hSrc, GetCurrentProcess(), &ret, 0, FALSE,
                     DUP_HANDLE_MAKE_GLOBAL | DUP_HANDLE_SAME_ACCESS | DUP_HANDLE_CLOSE_SOURCE );
    return ret;
}


/***********************************************************************
 *           SetHandleContext   (KERNEL32.@)
 */
BOOL WINAPI SetHandleContext(HANDLE hnd,DWORD context)
{
2801
    FIXME("(%p,%d), stub. In case this got called by WSOCK32/WS2_32: "
2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831
          "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd,context);
    SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
    return FALSE;
}


/***********************************************************************
 *           GetHandleContext   (KERNEL32.@)
 */
DWORD WINAPI GetHandleContext(HANDLE hnd)
{
    FIXME("(%p), stub. In case this got called by WSOCK32/WS2_32: "
          "the external WINSOCK DLLs won't work with WINE, don't use them.\n",hnd);
    SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
    return 0;
}


/***********************************************************************
 *           CreateSocketHandle   (KERNEL32.@)
 */
HANDLE WINAPI CreateSocketHandle(void)
{
    FIXME("(), stub. In case this got called by WSOCK32/WS2_32: "
          "the external WINSOCK DLLs won't work with WINE, don't use them.\n");
    SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
    return INVALID_HANDLE_VALUE;
}


2832 2833 2834 2835 2836
/***********************************************************************
 *           SetPriorityClass   (KERNEL32.@)
 */
BOOL WINAPI SetPriorityClass( HANDLE hprocess, DWORD priorityclass )
{
2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863
    NTSTATUS                    status;
    PROCESS_PRIORITY_CLASS      ppc;

    ppc.Foreground = FALSE;
    switch (priorityclass)
    {
    case IDLE_PRIORITY_CLASS:
        ppc.PriorityClass = PROCESS_PRIOCLASS_IDLE; break;
    case BELOW_NORMAL_PRIORITY_CLASS:
        ppc.PriorityClass = PROCESS_PRIOCLASS_BELOW_NORMAL; break;
    case NORMAL_PRIORITY_CLASS:
        ppc.PriorityClass = PROCESS_PRIOCLASS_NORMAL; break;
    case ABOVE_NORMAL_PRIORITY_CLASS:
        ppc.PriorityClass = PROCESS_PRIOCLASS_ABOVE_NORMAL; break;
    case HIGH_PRIORITY_CLASS:
        ppc.PriorityClass = PROCESS_PRIOCLASS_HIGH; break;
    case REALTIME_PRIORITY_CLASS:
        ppc.PriorityClass = PROCESS_PRIOCLASS_REALTIME; break;
    default:
        SetLastError(ERROR_INVALID_PARAMETER);
        return FALSE;
    }

    status = NtSetInformationProcess(hprocess, ProcessPriorityClass,
                                     &ppc, sizeof(ppc));

    if (status != STATUS_SUCCESS)
2864
    {
2865 2866
        SetLastError( RtlNtStatusToDosError(status) );
        return FALSE;
2867
    }
2868
    return TRUE;
2869 2870 2871 2872 2873 2874
}


/***********************************************************************
 *           GetPriorityClass   (KERNEL32.@)
 */
2875
DWORD WINAPI GetPriorityClass(HANDLE hProcess)
2876
{
2877 2878 2879 2880 2881
    NTSTATUS status;
    PROCESS_BASIC_INFORMATION pbi;

    status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi,
                                       sizeof(pbi), NULL);
2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896
    if (status != STATUS_SUCCESS)
    {
        SetLastError( RtlNtStatusToDosError(status) );
        return 0;
    }
    switch (pbi.BasePriority)
    {
    case PROCESS_PRIOCLASS_IDLE: return IDLE_PRIORITY_CLASS;
    case PROCESS_PRIOCLASS_BELOW_NORMAL: return BELOW_NORMAL_PRIORITY_CLASS;
    case PROCESS_PRIOCLASS_NORMAL: return NORMAL_PRIORITY_CLASS;
    case PROCESS_PRIOCLASS_ABOVE_NORMAL: return ABOVE_NORMAL_PRIORITY_CLASS;
    case PROCESS_PRIOCLASS_HIGH: return HIGH_PRIORITY_CLASS;
    case PROCESS_PRIOCLASS_REALTIME: return REALTIME_PRIORITY_CLASS;
    }
    SetLastError( ERROR_INVALID_PARAMETER );
2897
    return 0;
2898 2899 2900 2901 2902 2903
}


/***********************************************************************
 *          SetProcessAffinityMask   (KERNEL32.@)
 */
2904
BOOL WINAPI SetProcessAffinityMask( HANDLE hProcess, DWORD_PTR affmask )
2905
{
2906 2907 2908 2909
    NTSTATUS status;

    status = NtSetInformationProcess(hProcess, ProcessAffinityMask,
                                     &affmask, sizeof(DWORD_PTR));
2910
    if (status)
2911
    {
2912 2913
        SetLastError( RtlNtStatusToDosError(status) );
        return FALSE;
2914
    }
2915
    return TRUE;
2916 2917 2918 2919 2920 2921 2922
}


/**********************************************************************
 *          GetProcessAffinityMask    (KERNEL32.@)
 */
BOOL WINAPI GetProcessAffinityMask( HANDLE hProcess,
2923 2924
                                    PDWORD_PTR lpProcessAffinityMask,
                                    PDWORD_PTR lpSystemAffinityMask )
2925
{
2926 2927 2928 2929 2930 2931 2932
    PROCESS_BASIC_INFORMATION   pbi;
    NTSTATUS                    status;

    status = NtQueryInformationProcess(hProcess,
                                       ProcessBasicInformation,
                                       &pbi, sizeof(pbi), NULL);
    if (status)
2933
    {
2934 2935
        SetLastError( RtlNtStatusToDosError(status) );
        return FALSE;
2936
    }
2937
    if (lpProcessAffinityMask) *lpProcessAffinityMask = pbi.AffinityMask;
2938
    if (lpSystemAffinityMask)  *lpSystemAffinityMask = (1 << NtCurrentTeb()->Peb->NumberOfProcessors) - 1;
2939
    return TRUE;
2940 2941 2942 2943 2944 2945
}


/***********************************************************************
 *           GetProcessVersion    (KERNEL32.@)
 */
2946
DWORD WINAPI GetProcessVersion( DWORD pid )
2947
{
2948 2949 2950 2951 2952 2953 2954 2955
    HANDLE process;
    NTSTATUS status;
    PROCESS_BASIC_INFORMATION pbi;
    SIZE_T count;
    PEB peb;
    IMAGE_DOS_HEADER dos;
    IMAGE_NT_HEADERS nt;
    DWORD ver = 0;
2956

2957
    if (!pid || pid == GetCurrentProcessId())
2958
    {
2959 2960 2961 2962 2963
        IMAGE_NT_HEADERS *nt;

        if ((nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress )))
            return ((nt->OptionalHeader.MajorSubsystemVersion << 16) |
                    nt->OptionalHeader.MinorSubsystemVersion);
2964 2965
        return 0;
    }
2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994

    process = OpenProcess(PROCESS_VM_READ | PROCESS_QUERY_INFORMATION, FALSE, pid);
    if (!process) return 0;

    status = NtQueryInformationProcess(process, ProcessBasicInformation, &pbi, sizeof(pbi), NULL);
    if (status) goto err;

    status = NtReadVirtualMemory(process, pbi.PebBaseAddress, &peb, sizeof(peb), &count);
    if (status || count != sizeof(peb)) goto err;

    memset(&dos, 0, sizeof(dos));
    status = NtReadVirtualMemory(process, peb.ImageBaseAddress, &dos, sizeof(dos), &count);
    if (status || count != sizeof(dos)) goto err;
    if (dos.e_magic != IMAGE_DOS_SIGNATURE) goto err;

    memset(&nt, 0, sizeof(nt));
    status = NtReadVirtualMemory(process, (char *)peb.ImageBaseAddress + dos.e_lfanew, &nt, sizeof(nt), &count);
    if (status || count != sizeof(nt)) goto err;
    if (nt.Signature != IMAGE_NT_SIGNATURE) goto err;

    ver = MAKELONG(nt.OptionalHeader.MinorSubsystemVersion, nt.OptionalHeader.MajorSubsystemVersion);

err:
    CloseHandle(process);

    if (status != STATUS_SUCCESS)
        SetLastError(RtlNtStatusToDosError(status));

    return ver;
2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006
}


/***********************************************************************
 *		SetProcessWorkingSetSize	[KERNEL32.@]
 * Sets the min/max working set sizes for a specified process.
 *
 * PARAMS
 *    hProcess [I] Handle to the process of interest
 *    minset   [I] Specifies minimum working set size
 *    maxset   [I] Specifies maximum working set size
 *
Jon Griffiths's avatar
Jon Griffiths committed
3007 3008 3009
 * RETURNS
 *  Success: TRUE
 *  Failure: FALSE
3010 3011 3012 3013
 */
BOOL WINAPI SetProcessWorkingSetSize(HANDLE hProcess, SIZE_T minset,
                                     SIZE_T maxset)
{
3014
    WARN("(%p,%ld,%ld): stub - harmless\n",hProcess,minset,maxset);
3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040
    if(( minset == (SIZE_T)-1) && (maxset == (SIZE_T)-1)) {
        /* Trim the working set to zero */
        /* Swap the process out of physical RAM */
    }
    return TRUE;
}

/***********************************************************************
 *           GetProcessWorkingSetSize    (KERNEL32.@)
 */
BOOL WINAPI GetProcessWorkingSetSize(HANDLE hProcess, PSIZE_T minset,
                                     PSIZE_T maxset)
{
    FIXME("(%p,%p,%p): stub\n",hProcess,minset,maxset);
    /* 32 MB working set size */
    if (minset) *minset = 32*1024*1024;
    if (maxset) *maxset = 32*1024*1024;
    return TRUE;
}


/***********************************************************************
 *           SetProcessShutdownParameters    (KERNEL32.@)
 */
BOOL WINAPI SetProcessShutdownParameters(DWORD level, DWORD flags)
{
3041
    FIXME("(%08x, %08x): partial stub.\n", level, flags);
3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089
    shutdown_flags = flags;
    shutdown_priority = level;
    return TRUE;
}


/***********************************************************************
 * GetProcessShutdownParameters                 (KERNEL32.@)
 *
 */
BOOL WINAPI GetProcessShutdownParameters( LPDWORD lpdwLevel, LPDWORD lpdwFlags )
{
    *lpdwLevel = shutdown_priority;
    *lpdwFlags = shutdown_flags;
    return TRUE;
}


/***********************************************************************
 *           GetProcessPriorityBoost    (KERNEL32.@)
 */
BOOL WINAPI GetProcessPriorityBoost(HANDLE hprocess,PBOOL pDisablePriorityBoost)
{
    FIXME("(%p,%p): semi-stub\n", hprocess, pDisablePriorityBoost);
    
    /* Report that no boost is present.. */
    *pDisablePriorityBoost = FALSE;
    
    return TRUE;
}

/***********************************************************************
 *           SetProcessPriorityBoost    (KERNEL32.@)
 */
BOOL WINAPI SetProcessPriorityBoost(HANDLE hprocess,BOOL disableboost)
{
    FIXME("(%p,%d): stub\n",hprocess,disableboost);
    /* Say we can do it. I doubt the program will notice that we don't. */
    return TRUE;
}


/***********************************************************************
 *		ReadProcessMemory (KERNEL32.@)
 */
BOOL WINAPI ReadProcessMemory( HANDLE process, LPCVOID addr, LPVOID buffer, SIZE_T size,
                               SIZE_T *bytes_read )
{
3090 3091 3092
    NTSTATUS status = NtReadVirtualMemory( process, addr, buffer, size, bytes_read );
    if (status) SetLastError( RtlNtStatusToDosError(status) );
    return !status;
3093 3094 3095 3096 3097 3098 3099 3100 3101
}


/***********************************************************************
 *           WriteProcessMemory    		(KERNEL32.@)
 */
BOOL WINAPI WriteProcessMemory( HANDLE process, LPVOID addr, LPCVOID buffer, SIZE_T size,
                                SIZE_T *bytes_written )
{
3102 3103 3104
    NTSTATUS status = NtWriteVirtualMemory( process, addr, buffer, size, bytes_written );
    if (status) SetLastError( RtlNtStatusToDosError(status) );
    return !status;
3105 3106
}

3107 3108 3109 3110 3111 3112

/****************************************************************************
 *		FlushInstructionCache (KERNEL32.@)
 */
BOOL WINAPI FlushInstructionCache(HANDLE hProcess, LPCVOID lpBaseAddress, SIZE_T dwSize)
{
3113 3114 3115 3116
    NTSTATUS status;
    status = NtFlushInstructionCache( hProcess, lpBaseAddress, dwSize );
    if (status) SetLastError( RtlNtStatusToDosError(status) );
    return !status;
3117 3118 3119
}


3120 3121 3122 3123 3124 3125 3126 3127 3128 3129
/******************************************************************
 *		GetProcessIoCounters (KERNEL32.@)
 */
BOOL WINAPI GetProcessIoCounters(HANDLE hProcess, PIO_COUNTERS ioc)
{
    NTSTATUS    status;

    status = NtQueryInformationProcess(hProcess, ProcessIoCounters, 
                                       ioc, sizeof(*ioc), NULL);
    if (status) SetLastError( RtlNtStatusToDosError(status) );
3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142
    return !status;
}

/******************************************************************
 *		GetProcessHandleCount (KERNEL32.@)
 */
BOOL WINAPI GetProcessHandleCount(HANDLE hProcess, DWORD *cnt)
{
    NTSTATUS status;

    status = NtQueryInformationProcess(hProcess, ProcessHandleCount,
                                       cnt, sizeof(*cnt), NULL);
    if (status) SetLastError( RtlNtStatusToDosError(status) );
3143 3144
    return !status;
}
3145

3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160
/******************************************************************
 *		QueryFullProcessImageNameW (KERNEL32.@)
 */
BOOL WINAPI QueryFullProcessImageNameW(HANDLE hProcess, DWORD dwFlags, LPWSTR lpExeName, PDWORD pdwSize)
{
    BYTE buffer[sizeof(UNICODE_STRING) + MAX_PATH*sizeof(WCHAR)];  /* this buffer should be enough */
    UNICODE_STRING *dynamic_buffer = NULL;
    UNICODE_STRING nt_path;
    UNICODE_STRING *result = NULL;
    NTSTATUS status;
    DWORD needed;

    RtlInitUnicodeStringEx(&nt_path, NULL);
    /* FIXME: On Windows, ProcessImageFileName return an NT path. We rely that it being a DOS path,
     * as this is on Wine. */
3161 3162
    status = NtQueryInformationProcess(hProcess, ProcessImageFileName, buffer,
                                       sizeof(buffer) - sizeof(WCHAR), &needed);
3163 3164
    if (status == STATUS_INFO_LENGTH_MISMATCH)
    {
3165
        dynamic_buffer = HeapAlloc(GetProcessHeap(), 0, needed + sizeof(WCHAR));
3166 3167 3168 3169 3170 3171 3172 3173 3174 3175
        status = NtQueryInformationProcess(hProcess, ProcessImageFileName, (LPBYTE)dynamic_buffer, needed, &needed);
        result = dynamic_buffer;
    }
    else
        result = (PUNICODE_STRING)buffer;

    if (status) goto cleanup;

    if (dwFlags & PROCESS_NAME_NATIVE)
    {
3176
        result->Buffer[result->Length / sizeof(WCHAR)] = 0;
3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191
        if (!RtlDosPathNameToNtPathName_U(result->Buffer, &nt_path, NULL, NULL))
        {
            status = STATUS_OBJECT_PATH_NOT_FOUND;
            goto cleanup;
        }
        result = &nt_path;
    }

    if (result->Length/sizeof(WCHAR) + 1 > *pdwSize)
    {
        status = STATUS_BUFFER_TOO_SMALL;
        goto cleanup;
    }

    *pdwSize = result->Length/sizeof(WCHAR);
3192 3193
    memcpy( lpExeName, result->Buffer, result->Length );
    lpExeName[*pdwSize] = 0;
3194 3195 3196 3197 3198 3199 3200 3201

cleanup:
    HeapFree(GetProcessHeap(), 0, dynamic_buffer);
    RtlFreeUnicodeString(&nt_path);
    if (status) SetLastError( RtlNtStatusToDosError(status) );
    return !status;
}

3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215
/***********************************************************************
 * ProcessIdToSessionId   (KERNEL32.@)
 * This function is available on Terminal Server 4SP4 and Windows 2000
 */
BOOL WINAPI ProcessIdToSessionId( DWORD procid, DWORD *sessionid_ptr )
{
    /* According to MSDN, if the calling process is not in a terminal
     * services environment, then the sessionid returned is zero.
     */
    *sessionid_ptr = 0;
    return TRUE;
}


3216 3217 3218 3219 3220 3221 3222 3223 3224
/***********************************************************************
 *		RegisterServiceProcess (KERNEL.491)
 *		RegisterServiceProcess (KERNEL32.@)
 *
 * A service process calls this function to ensure that it continues to run
 * even after a user logged off.
 */
DWORD WINAPI RegisterServiceProcess(DWORD dwProcessId, DWORD dwType)
{
Jon Griffiths's avatar
Jon Griffiths committed
3225
    /* I don't think that Wine needs to do anything in this function */
3226 3227 3228 3229
    return 1; /* success */
}


3230 3231 3232 3233 3234
/**********************************************************************
 *           IsWow64Process         (KERNEL32.@)
 */
BOOL WINAPI IsWow64Process(HANDLE hProcess, PBOOL Wow64Process)
{
3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245
    ULONG pbi;
    NTSTATUS status;

    status = NtQueryInformationProcess( hProcess, ProcessWow64Information, &pbi, sizeof(pbi), NULL );

    if (status != STATUS_SUCCESS)
    {
        SetLastError( RtlNtStatusToDosError( status ) );
        return FALSE;
    }
    *Wow64Process = (pbi != 0);
3246 3247 3248 3249
    return TRUE;
}


3250 3251
/***********************************************************************
 *           GetCurrentProcess   (KERNEL32.@)
Jon Griffiths's avatar
Jon Griffiths committed
3252 3253 3254 3255 3256 3257 3258 3259
 *
 * Get a handle to the current process.
 *
 * PARAMS
 *  None.
 *
 * RETURNS
 *  A handle representing the current process.
3260 3261 3262 3263
 */
#undef GetCurrentProcess
HANDLE WINAPI GetCurrentProcess(void)
{
3264
    return (HANDLE)~(ULONG_PTR)0;
3265
}
3266 3267 3268 3269

/***********************************************************************
 *           CmdBatNotification   (KERNEL32.@)
 *
3270 3271 3272 3273 3274 3275 3276 3277
 * Notifies the system that a batch file has started or finished.
 *
 * PARAMS
 *  bBatchRunning [I]  TRUE if a batch file has started or 
 *                     FALSE if a batch file has finished executing.
 *
 * RETURNS
 *  Unknown.
3278 3279 3280 3281 3282 3283
 */
BOOL WINAPI CmdBatNotification( BOOL bBatchRunning )
{
    FIXME("%d\n", bBatchRunning);
    return FALSE;
}
3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294


/***********************************************************************
 *           RegisterApplicationRestart       (KERNEL32.@)
 */
HRESULT WINAPI RegisterApplicationRestart(PCWSTR pwzCommandLine, DWORD dwFlags)
{
    FIXME("(%s,%d)\n", debugstr_w(pwzCommandLine), dwFlags);

    return S_OK;
}