install.c 55.6 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
/*
 * Setupapi install routines
 *
 * Copyright 2002 Alexandre Julliard for CodeWeavers
 *
 * 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
#include <stdarg.h>
22
#include <stdbool.h>
23

24 25
#define COBJMACROS

26 27
#include "windef.h"
#include "winbase.h"
28
#include "winreg.h"
29
#include "winternl.h"
30
#include "winerror.h"
31 32 33
#include "wingdi.h"
#include "winuser.h"
#include "winnls.h"
34
#include "winsvc.h"
35
#include "shlobj.h"
36
#include "shlwapi.h"
37 38
#include "objidl.h"
#include "objbase.h"
39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
#include "setupapi.h"
#include "setupapi_private.h"
#include "wine/debug.h"

WINE_DEFAULT_DEBUG_CHANNEL(setupapi);

/* info passed to callback functions dealing with files */
struct files_callback_info
{
    HSPFILEQ queue;
    PCWSTR   src_root;
    UINT     copy_flags;
    HINF     layout;
};

/* info passed to callback functions dealing with the registry */
struct registry_callback_info
{
    HKEY default_root;
    BOOL delete;
};

61 62 63 64 65 66
/* info passed to callback functions dealing with registering dlls */
struct register_dll_info
{
    PSP_FILE_CALLBACK_W callback;
    PVOID               callback_context;
    BOOL                unregister;
67 68 69
    int                 modules_size;
    int                 modules_count;
    HMODULE            *modules;
70 71
};

72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
typedef BOOL (*iterate_fields_func)( HINF hinf, PCWSTR field, void *arg );


/***********************************************************************
 *            get_field_string
 *
 * Retrieve the contents of a field, dynamically growing the buffer if necessary.
 */
static WCHAR *get_field_string( INFCONTEXT *context, DWORD index, WCHAR *buffer,
                                WCHAR *static_buffer, DWORD *size )
{
    DWORD required;

    if (SetupGetStringFieldW( context, index, buffer, *size, &required )) return buffer;
    if (GetLastError() == ERROR_INSUFFICIENT_BUFFER)
    {
        /* now grow the buffer */
89 90
        if (buffer != static_buffer) free( buffer );
        if (!(buffer = malloc( required * sizeof(WCHAR) ))) return NULL;
91 92 93
        *size = required;
        if (SetupGetStringFieldW( context, index, buffer, *size, &required )) return buffer;
    }
94
    if (buffer != static_buffer) free( buffer );
95 96 97 98
    return NULL;
}


99 100 101 102 103 104 105 106 107 108 109 110 111
/***********************************************************************
 *            dup_section_line_field
 *
 * Retrieve the contents of a field in a newly-allocated buffer.
 */
static WCHAR *dup_section_line_field( HINF hinf, const WCHAR *section, const WCHAR *line, DWORD index )
{
    INFCONTEXT context;
    DWORD size;
    WCHAR *buffer;

    if (!SetupFindFirstLineW( hinf, section, line, &context )) return NULL;
    if (!SetupGetStringFieldW( &context, index, NULL, 0, &size )) return NULL;
112
    if (!(buffer = malloc( size * sizeof(WCHAR) ))) return NULL;
113 114 115 116
    if (!SetupGetStringFieldW( &context, index, buffer, size, NULL )) buffer[0] = 0;
    return buffer;
}

117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139
static void get_inf_src_path( HINF hinf, WCHAR *path )
{
    const WCHAR *inf_path = PARSER_get_inf_filename( hinf );
    WCHAR pnf_path[MAX_PATH];
    FILE *pnf;

    wcscpy( pnf_path, inf_path );
    PathRemoveExtensionW( pnf_path );
    PathAddExtensionW( pnf_path, L".pnf" );
    if ((pnf = _wfopen( pnf_path, L"r" )))
    {
        if (fgetws( path, MAX_PATH, pnf ) && !wcscmp( path, PNF_HEADER ))
        {
            fgetws( path, MAX_PATH, pnf );
            TRACE("using original source path %s\n", debugstr_w(path));
            fclose( pnf );
            return;
        }
        fclose( pnf );
    }
    wcscpy( path, inf_path );
}

140 141 142 143 144 145 146
/***********************************************************************
 *            copy_files_callback
 *
 * Called once for each CopyFiles entry in a given section.
 */
static BOOL copy_files_callback( HINF hinf, PCWSTR field, void *arg )
{
147
    INFCONTEXT context;
148
    struct files_callback_info *info = arg;
149 150 151 152
    WCHAR src_root[MAX_PATH], *p;

    if (!info->src_root)
    {
153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168
        const WCHAR *build_dir = _wgetenv( L"WINEBUILDDIR" );
        const WCHAR *data_dir = _wgetenv( L"WINEDATADIR" );

        if ((build_dir || data_dir) && SetupFindFirstLineW( hinf, L"WineSourceDirs", field, &context ))
        {
            lstrcpyW( src_root, build_dir ? build_dir : data_dir );
            src_root[1] = '\\';  /* change \??\ to \\?\ */
            p = src_root + lstrlenW(src_root);
            *p++ = '\\';
            if (!build_dir || !SetupGetStringFieldW( &context, 2, p, MAX_PATH - (p - src_root), NULL ))
            {
                if (!SetupGetStringFieldW( &context, 1, p, MAX_PATH - (p - src_root), NULL )) p[-1] = 0;
            }
        }
        else
        {
169
            get_inf_src_path( hinf, src_root );
170 171
            if ((p = wcsrchr( src_root, '\\' ))) *p = 0;
        }
172
    }
173 174

    if (field[0] == '@')  /* special case: copy single file */
175
        SetupQueueDefaultCopyW( info->queue, info->layout ? info->layout : hinf,
176
                info->src_root ? info->src_root : src_root, field+1, field+1, info->copy_flags );
177
    else
178 179
        SetupQueueCopySectionW( info->queue, info->src_root ? info->src_root : src_root,
                info->layout ? info->layout : hinf, hinf, field, info->copy_flags );
180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216
    return TRUE;
}


/***********************************************************************
 *            delete_files_callback
 *
 * Called once for each DelFiles entry in a given section.
 */
static BOOL delete_files_callback( HINF hinf, PCWSTR field, void *arg )
{
    struct files_callback_info *info = arg;
    SetupQueueDeleteSectionW( info->queue, hinf, 0, field );
    return TRUE;
}


/***********************************************************************
 *            rename_files_callback
 *
 * Called once for each RenFiles entry in a given section.
 */
static BOOL rename_files_callback( HINF hinf, PCWSTR field, void *arg )
{
    struct files_callback_info *info = arg;
    SetupQueueRenameSectionW( info->queue, hinf, 0, field );
    return TRUE;
}


/***********************************************************************
 *            get_root_key
 *
 * Retrieve the registry root key from its name.
 */
static HKEY get_root_key( const WCHAR *name, HKEY def_root )
{
217 218 219 220 221
    if (!wcsicmp( name, L"HKCR" )) return HKEY_CLASSES_ROOT;
    if (!wcsicmp( name, L"HKCU" )) return HKEY_CURRENT_USER;
    if (!wcsicmp( name, L"HKLM" )) return HKEY_LOCAL_MACHINE;
    if (!wcsicmp( name, L"HKU" )) return HKEY_USERS;
    if (!wcsicmp( name, L"HKR" )) return def_root;
222 223 224 225 226 227 228 229 230
    return 0;
}


/***********************************************************************
 *            append_multi_sz_value
 *
 * Append a multisz string to a multisz registry value.
 */
231
static bool append_multi_sz_value( HKEY hkey, const WCHAR *value, const WCHAR *strings,
232 233 234 235
                                   DWORD str_size )
{
    DWORD size, type, total;
    WCHAR *buffer, *p;
236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255
    LONG ret;

    if ((ret = RegQueryValueExW( hkey, value, NULL, &type, NULL, &size )))
    {
        if (ret != ERROR_FILE_NOT_FOUND)
        {
            ERR( "failed to query value %s, error %lu\n", debugstr_w(value), ret );
            SetLastError( ret );
            return false;
        }

        if ((ret = RegSetValueExW( hkey, value, 0, REG_MULTI_SZ, (BYTE *)strings, str_size * sizeof(WCHAR) )))
        {
            ERR( "failed to set value %s, error %lu\n", debugstr_w(value), ret );
            SetLastError( ret );
            return false;
        }

        return true;
    }
256

257 258 259 260 261 262
    if (type != REG_MULTI_SZ)
    {
        WARN( "value %s exists but has wrong type %#lx\n", debugstr_w(value), type );
        SetLastError( ERROR_INVALID_DATA );
        return false;
    }
263

264
    if (!(buffer = malloc( (size + str_size) * sizeof(WCHAR) ))) return false;
265 266
    if (RegQueryValueExW( hkey, value, NULL, NULL, (BYTE *)buffer, &size ))
    {
267
        free( buffer );
268 269
        return false;
    }
270 271 272 273 274

    /* compare each string against all the existing ones */
    total = size;
    while (*strings)
    {
275
        int len = lstrlenW(strings) + 1;
276

277 278
        for (p = buffer; *p; p += lstrlenW(p) + 1)
            if (!wcsicmp( p, strings )) break;
279 280 281 282 283

        if (!*p)  /* not found, need to append it */
        {
            memcpy( p, strings, len * sizeof(WCHAR) );
            p[len] = 0;
284
            total += len * sizeof(WCHAR);
285 286 287 288 289 290 291 292
        }
        strings += len;
    }
    if (total != size)
    {
        TRACE( "setting value %s to %s\n", debugstr_w(value), debugstr_w(buffer) );
        RegSetValueExW( hkey, value, 0, REG_MULTI_SZ, (BYTE *)buffer, total );
    }
293

294
    free( buffer );
295
    return true;
296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311
}


/***********************************************************************
 *            delete_multi_sz_value
 *
 * Remove a string from a multisz registry value.
 */
static void delete_multi_sz_value( HKEY hkey, const WCHAR *value, const WCHAR *string )
{
    DWORD size, type;
    WCHAR *buffer, *src, *dst;

    if (RegQueryValueExW( hkey, value, NULL, &type, NULL, &size )) return;
    if (type != REG_MULTI_SZ) return;
    /* allocate double the size, one for value before and one for after */
312
    if (!(buffer = malloc( size * 2 * sizeof(WCHAR) ))) return;
313 314 315 316 317
    if (RegQueryValueExW( hkey, value, NULL, NULL, (BYTE *)buffer, &size )) goto done;
    src = buffer;
    dst = buffer + size;
    while (*src)
    {
318 319
        int len = lstrlenW(src) + 1;
        if (wcsicmp( src, string ))
320 321 322 323 324 325 326 327 328 329 330 331 332 333
        {
            memcpy( dst, src, len * sizeof(WCHAR) );
            dst += len;
        }
        src += len;
    }
    *dst++ = 0;
    if (dst != buffer + 2*size)  /* did we remove something? */
    {
        TRACE( "setting value %s to %s\n", debugstr_w(value), debugstr_w(buffer + size) );
        RegSetValueExW( hkey, value, 0, REG_MULTI_SZ,
                        (BYTE *)(buffer + size), dst - (buffer + size) );
    }
 done:
334
    free( buffer );
335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355
}


/***********************************************************************
 *            do_reg_operation
 *
 * Perform an add/delete registry operation depending on the flags.
 */
static BOOL do_reg_operation( HKEY hkey, const WCHAR *value, INFCONTEXT *context, INT flags )
{
    DWORD type, size;

    if (flags & (FLG_ADDREG_DELREG_BIT | FLG_ADDREG_DELVAL))  /* deletion */
    {
        if (*value && !(flags & FLG_DELREG_KEYONLY_COMMON))
        {
            if ((flags & FLG_DELREG_MULTI_SZ_DELSTRING) == FLG_DELREG_MULTI_SZ_DELSTRING)
            {
                WCHAR *str;

                if (!SetupGetStringFieldW( context, 5, NULL, 0, &size ) || !size) return TRUE;
356
                if (!(str = malloc( size * sizeof(WCHAR) ))) return FALSE;
357 358
                SetupGetStringFieldW( context, 5, str, size, NULL );
                delete_multi_sz_value( hkey, value, str );
359
                free( str );
360 361 362
            }
            else RegDeleteValueW( hkey, value );
        }
363 364 365 366 367
        else
        {
            RegDeleteTreeW( hkey, NULL );
            NtDeleteKey( hkey );
        }
368 369 370 371 372 373 374 375 376
        return TRUE;
    }

    if (flags & (FLG_ADDREG_KEYONLY|FLG_ADDREG_KEYONLY_COMMON)) return TRUE;

    if (flags & (FLG_ADDREG_NOCLOBBER|FLG_ADDREG_OVERWRITEONLY))
    {
        BOOL exists = !RegQueryValueExW( hkey, value, NULL, NULL, NULL, NULL );
        if (exists && (flags & FLG_ADDREG_NOCLOBBER)) return TRUE;
Dmitry Timoshkov's avatar
Dmitry Timoshkov committed
377
        if (!exists && (flags & FLG_ADDREG_OVERWRITEONLY)) return TRUE;
378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400
    }

    switch(flags & FLG_ADDREG_TYPE_MASK)
    {
    case FLG_ADDREG_TYPE_SZ:        type = REG_SZ; break;
    case FLG_ADDREG_TYPE_MULTI_SZ:  type = REG_MULTI_SZ; break;
    case FLG_ADDREG_TYPE_EXPAND_SZ: type = REG_EXPAND_SZ; break;
    case FLG_ADDREG_TYPE_BINARY:    type = REG_BINARY; break;
    case FLG_ADDREG_TYPE_DWORD:     type = REG_DWORD; break;
    case FLG_ADDREG_TYPE_NONE:      type = REG_NONE; break;
    default:                        type = flags >> 16; break;
    }

    if (!(flags & FLG_ADDREG_BINVALUETYPE) ||
        (type == REG_DWORD && SetupGetFieldCount(context) == 5))
    {
        WCHAR *str = NULL;

        if (type == REG_MULTI_SZ)
        {
            if (!SetupGetMultiSzFieldW( context, 5, NULL, 0, &size )) size = 0;
            if (size)
            {
401
                if (!(str = malloc( size * sizeof(WCHAR) ))) return FALSE;
402 403 404 405 406
                SetupGetMultiSzFieldW( context, 5, str, size, NULL );
            }
            if (flags & FLG_ADDREG_APPEND)
            {
                if (!str) return TRUE;
407 408
                if (!append_multi_sz_value( hkey, value, str, size ))
                {
409
                    free( str );
410 411
                    return FALSE;
                }
412
                free( str );
413 414 415 416 417 418 419 420 421
                return TRUE;
            }
            /* else fall through to normal string handling */
        }
        else
        {
            if (!SetupGetStringFieldW( context, 5, NULL, 0, &size )) size = 0;
            if (size)
            {
422
                if (!(str = malloc( size * sizeof(WCHAR) ))) return FALSE;
423
                SetupGetStringFieldW( context, 5, str, size, NULL );
424
                if (type == REG_LINK) size--;  /* no terminating null for symlinks */
425 426 427 428 429
            }
        }

        if (type == REG_DWORD)
        {
430
            DWORD dw = str ? wcstoul( str, NULL, 0 ) : 0;
431
            TRACE( "setting dword %s to %lx\n", debugstr_w(value), dw );
432 433 434 435 436 437
            RegSetValueExW( hkey, value, 0, type, (BYTE *)&dw, sizeof(dw) );
        }
        else
        {
            TRACE( "setting value %s to %s\n", debugstr_w(value), debugstr_w(str) );
            if (str) RegSetValueExW( hkey, value, 0, type, (BYTE *)str, size * sizeof(WCHAR) );
438
            else RegSetValueExW( hkey, value, 0, type, (const BYTE *)L"", sizeof(WCHAR) );
439
        }
440
        free( str );
441 442 443 444 445 446 447 448 449
        return TRUE;
    }
    else  /* get the binary data */
    {
        BYTE *data = NULL;

        if (!SetupGetBinaryField( context, 5, NULL, 0, &size )) size = 0;
        if (size)
        {
450
            if (!(data = malloc( size ))) return FALSE;
451
            TRACE( "setting binary data %s len %ld\n", debugstr_w(value), size );
452 453 454
            SetupGetBinaryField( context, 5, data, size, NULL );
        }
        RegSetValueExW( hkey, value, 0, type, data, size );
455
        free( data );
456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475
        return TRUE;
    }
}


/***********************************************************************
 *            registry_callback
 *
 * Called once for each AddReg and DelReg entry in a given section.
 */
static BOOL registry_callback( HINF hinf, PCWSTR field, void *arg )
{
    struct registry_callback_info *info = arg;
    INFCONTEXT context;
    HKEY root_key, hkey;

    BOOL ok = SetupFindFirstLineW( hinf, field, NULL, &context );

    for (; ok; ok = SetupFindNextLine( &context, &context ))
    {
476
        DWORD options = 0;
477 478 479 480
        WCHAR buffer[MAX_INF_STRING_LENGTH];
        INT flags;

        /* get root */
481
        if (!SetupGetStringFieldW( &context, 1, buffer, ARRAY_SIZE( buffer ), NULL ))
482 483 484 485 486
            continue;
        if (!(root_key = get_root_key( buffer, info->default_root )))
            continue;

        /* get key */
487
        if (!SetupGetStringFieldW( &context, 2, buffer, ARRAY_SIZE( buffer ), NULL ))
488 489 490 491 492 493 494 495 496 497 498 499 500 501
            *buffer = 0;

        /* get flags */
        if (!SetupGetIntField( &context, 4, &flags )) flags = 0;

        if (!info->delete)
        {
            if (flags & FLG_ADDREG_DELREG_BIT) continue;  /* ignore this entry */
        }
        else
        {
            if (!flags) flags = FLG_ADDREG_DELREG_BIT;
            else if (!(flags & FLG_ADDREG_DELREG_BIT)) continue;  /* ignore this entry */
        }
502 503
        /* Wine extension: magic support for symlinks */
        if (flags >> 16 == REG_LINK) options = REG_OPTION_OPEN_LINK | REG_OPTION_CREATE_LINK;
504 505 506

        if (info->delete || (flags & FLG_ADDREG_OVERWRITEONLY))
        {
507 508
            if (RegOpenKeyExW( root_key, buffer, options, MAXIMUM_ALLOWED, &hkey ))
                continue;  /* ignore if it doesn't exist */
509
        }
510
        else
511
        {
512 513 514 515 516 517 518 519 520 521
            DWORD res = RegCreateKeyExW( root_key, buffer, 0, NULL, options,
                                         MAXIMUM_ALLOWED, NULL, &hkey, NULL );
            if (res == ERROR_ALREADY_EXISTS && (options & REG_OPTION_CREATE_LINK))
                res = RegCreateKeyExW( root_key, buffer, 0, NULL, REG_OPTION_OPEN_LINK,
                                       MAXIMUM_ALLOWED, NULL, &hkey, NULL );
            if (res)
            {
                ERR( "could not create key %p %s\n", root_key, debugstr_w(buffer) );
                continue;
            }
522
        }
523
        TRACE( "key %p %s\n", root_key, debugstr_w(buffer) );
524 525

        /* get value name */
526
        if (!SetupGetStringFieldW( &context, 3, buffer, ARRAY_SIZE( buffer ), NULL ))
527 528 529 530 531 532 533 534 535 536 537 538 539 540
            *buffer = 0;

        /* and now do it */
        if (!do_reg_operation( hkey, buffer, &context, flags ))
        {
            RegCloseKey( hkey );
            return FALSE;
        }
        RegCloseKey( hkey );
    }
    return TRUE;
}


541 542 543 544 545
/***********************************************************************
 *            do_register_dll
 *
 * Register or unregister a dll.
 */
546
static BOOL do_register_dll( struct register_dll_info *info, const WCHAR *path,
547 548 549 550 551
                             INT flags, INT timeout, const WCHAR *args )
{
    HMODULE module;
    HRESULT res;
    SP_REGISTER_CONTROL_STATUSW status;
552
    IMAGE_NT_HEADERS *nt;
553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581

    status.cbSize = sizeof(status);
    status.FileName = path;
    status.FailureCode = SPREG_SUCCESS;
    status.Win32Error = ERROR_SUCCESS;

    if (info->callback)
    {
        switch(info->callback( info->callback_context, SPFILENOTIFY_STARTREGISTRATION,
                               (UINT_PTR)&status, !info->unregister ))
        {
        case FILEOP_ABORT:
            SetLastError( ERROR_OPERATION_ABORTED );
            return FALSE;
        case FILEOP_SKIP:
            return TRUE;
        case FILEOP_DOIT:
            break;
        }
    }

    if (!(module = LoadLibraryExW( path, 0, LOAD_WITH_ALTERED_SEARCH_PATH )))
    {
        WARN( "could not load %s\n", debugstr_w(path) );
        status.FailureCode = SPREG_LOADLIBRARY;
        status.Win32Error = GetLastError();
        goto done;
    }

582 583 584 585
    if ((nt = RtlImageNtHeader( module )) && !(nt->FileHeader.Characteristics & IMAGE_FILE_DLL))
    {
        /* file is an executable, not a dll */
        STARTUPINFOW startup;
586
        PROCESS_INFORMATION process_info;
587 588
        WCHAR *cmd_line;
        BOOL res;
589
        DWORD len;
590 591 592

        FreeLibrary( module );
        module = NULL;
593
        if (!args) args = L"/RegServer";
594
        len = lstrlenW(path) + lstrlenW(args) + 4;
595
        cmd_line = malloc( len * sizeof(WCHAR) );
596
        swprintf( cmd_line, len, L"\"%s\" %s", path, args );
597 598 599
        memset( &startup, 0, sizeof(startup) );
        startup.cb = sizeof(startup);
        TRACE( "executing %s\n", debugstr_w(cmd_line) );
600
        res = CreateProcessW( path, cmd_line, NULL, NULL, FALSE, 0, NULL, NULL, &startup, &process_info );
601
        free( cmd_line );
602 603 604 605 606 607
        if (!res)
        {
            status.FailureCode = SPREG_LOADLIBRARY;
            status.Win32Error = GetLastError();
            goto done;
        }
608
        CloseHandle( process_info.hThread );
609

610
        if (WaitForSingleObject( process_info.hProcess, timeout*1000 ) == WAIT_TIMEOUT)
611 612
        {
            /* timed out, kill the process */
613
            TerminateProcess( process_info.hProcess, 1 );
614 615 616
            status.FailureCode = SPREG_TIMEOUT;
            status.Win32Error = ERROR_TIMEOUT;
        }
617
        CloseHandle( process_info.hProcess );
618 619 620
        goto done;
    }

621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637
    if (flags & FLG_REGSVR_DLLREGISTER)
    {
        const char *entry_point = info->unregister ? "DllUnregisterServer" : "DllRegisterServer";
        HRESULT (WINAPI *func)(void) = (void *)GetProcAddress( module, entry_point );

        if (!func)
        {
            status.FailureCode = SPREG_GETPROCADDR;
            status.Win32Error = GetLastError();
            goto done;
        }

        TRACE( "calling %s in %s\n", entry_point, debugstr_w(path) );
        res = func();

        if (FAILED(res))
        {
638
            WARN( "calling %s in %s returned error %lx\n", entry_point, debugstr_w(path), res );
639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661
            status.FailureCode = SPREG_REGSVR;
            status.Win32Error = res;
            goto done;
        }
    }

    if (flags & FLG_REGSVR_DLLINSTALL)
    {
        HRESULT (WINAPI *func)(BOOL,LPCWSTR) = (void *)GetProcAddress( module, "DllInstall" );

        if (!func)
        {
            status.FailureCode = SPREG_GETPROCADDR;
            status.Win32Error = GetLastError();
            goto done;
        }

        TRACE( "calling DllInstall(%d,%s) in %s\n",
               !info->unregister, debugstr_w(args), debugstr_w(path) );
        res = func( !info->unregister, args );

        if (FAILED(res))
        {
662
            WARN( "calling DllInstall in %s returned error %lx\n", debugstr_w(path), res );
663 664 665 666 667 668 669
            status.FailureCode = SPREG_REGSVR;
            status.Win32Error = res;
            goto done;
        }
    }

done:
670 671 672 673 674
    if (module)
    {
        if (info->modules_count >= info->modules_size)
        {
            int new_size = max( 32, info->modules_size * 2 );
675
            HMODULE *new = realloc( info->modules, new_size * sizeof(*new) );
676 677 678 679 680 681 682 683 684
            if (new)
            {
                info->modules_size = new_size;
                info->modules = new;
            }
        }
        if (info->modules_count < info->modules_size) info->modules[info->modules_count++] = module;
        else FreeLibrary( module );
    }
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
    if (info->callback) info->callback( info->callback_context, SPFILENOTIFY_ENDREGISTRATION,
                                        (UINT_PTR)&status, !info->unregister );
    return TRUE;
}


/***********************************************************************
 *            register_dlls_callback
 *
 * Called once for each RegisterDlls entry in a given section.
 */
static BOOL register_dlls_callback( HINF hinf, PCWSTR field, void *arg )
{
    struct register_dll_info *info = arg;
    INFCONTEXT context;
    BOOL ret = TRUE;
    BOOL ok = SetupFindFirstLineW( hinf, field, NULL, &context );

    for (; ok; ok = SetupFindNextLine( &context, &context ))
    {
        WCHAR *path, *args, *p;
        WCHAR buffer[MAX_INF_STRING_LENGTH];
        INT flags, timeout;

        /* get directory */
        if (!(path = PARSER_get_dest_dir( &context ))) continue;

        /* get dll name */
713
        if (!SetupGetStringFieldW( &context, 3, buffer, ARRAY_SIZE( buffer ), NULL ))
714
            goto done;
715 716
        if (!(p = realloc( path, (lstrlenW(path) + lstrlenW(buffer) + 2) * sizeof(WCHAR) )))
            goto done;
717
        path = p;
718
        p += lstrlenW(p);
719
        if (p == path || p[-1] != '\\') *p++ = '\\';
720
        lstrcpyW( p, buffer );
721 722 723 724 725 726 727 728 729

        /* get flags */
        if (!SetupGetIntField( &context, 4, &flags )) flags = 0;

        /* get timeout */
        if (!SetupGetIntField( &context, 5, &timeout )) timeout = 60;

        /* get command line */
        args = NULL;
730
        if (SetupGetStringFieldW( &context, 6, buffer, ARRAY_SIZE( buffer ), NULL ))
731 732 733 734 735
            args = buffer;

        ret = do_register_dll( info, path, flags, timeout, args );

    done:
736
        free( path );
737 738 739 740 741
        if (!ret) break;
    }
    return ret;
}

742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760
/***********************************************************************
 *            fake_dlls_callback
 *
 * Called once for each WineFakeDlls entry in a given section.
 */
static BOOL fake_dlls_callback( HINF hinf, PCWSTR field, void *arg )
{
    INFCONTEXT context;
    BOOL ok = SetupFindFirstLineW( hinf, field, NULL, &context );

    for (; ok; ok = SetupFindNextLine( &context, &context ))
    {
        WCHAR *path, *p;
        WCHAR buffer[MAX_INF_STRING_LENGTH];

        /* get directory */
        if (!(path = PARSER_get_dest_dir( &context ))) continue;

        /* get dll name */
761
        if (!SetupGetStringFieldW( &context, 3, buffer, ARRAY_SIZE( buffer ), NULL ))
762
            goto done;
763 764
        if (!(p = realloc( path, (lstrlenW(path) + lstrlenW(buffer) + 2) * sizeof(WCHAR) )))
            goto done;
765
        path = p;
766
        p += lstrlenW(p);
767
        if (p == path || p[-1] != '\\') *p++ = '\\';
768
        lstrcpyW( p, buffer );
769 770

        /* get source dll */
771
        if (SetupGetStringFieldW( &context, 4, buffer, ARRAY_SIZE( buffer ), NULL ))
772 773 774 775 776
            p = buffer;  /* otherwise use target base name as default source */

        create_fake_dll( path, p );  /* ignore errors */

    done:
777
        free( path );
778
    }
779
    return TRUE;
780 781
}

782 783 784 785 786
/***********************************************************************
 *            update_ini_callback
 *
 * Called once for each UpdateInis entry in a given section.
 */
787 788
static BOOL update_ini_callback( HINF hinf, PCWSTR field, void *arg )
{
789 790 791 792 793 794 795 796 797 798 799 800 801
    INFCONTEXT context;

    BOOL ok = SetupFindFirstLineW( hinf, field, NULL, &context );

    for (; ok; ok = SetupFindNextLine( &context, &context ))
    {
        WCHAR buffer[MAX_INF_STRING_LENGTH];
        WCHAR  filename[MAX_INF_STRING_LENGTH];
        WCHAR  section[MAX_INF_STRING_LENGTH];
        WCHAR  entry[MAX_INF_STRING_LENGTH];
        WCHAR  string[MAX_INF_STRING_LENGTH];
        LPWSTR divider;

802
        if (!SetupGetStringFieldW( &context, 1, filename, ARRAY_SIZE( filename ), NULL ))
803 804
            continue;

805
        if (!SetupGetStringFieldW( &context, 2, section, ARRAY_SIZE( section ), NULL ))
806 807
            continue;

808
        if (!SetupGetStringFieldW( &context, 4, buffer, ARRAY_SIZE( buffer ), NULL ))
809 810
            continue;

811
        divider = wcschr(buffer,'=');
812 813 814
        if (divider)
        {
            *divider = 0;
815
            lstrcpyW(entry,buffer);
816
            divider++;
817
            lstrcpyW(string,divider);
818 819 820
        }
        else
        {
821
            lstrcpyW(entry,buffer);
822 823 824 825 826 827 828 829
            string[0]=0;
        }

        TRACE("Writing %s = %s in %s of file %s\n",debugstr_w(entry),
               debugstr_w(string),debugstr_w(section),debugstr_w(filename));
        WritePrivateProfileStringW(section,entry,string,filename);

    }
830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850
    return TRUE;
}

static BOOL update_ini_fields_callback( HINF hinf, PCWSTR field, void *arg )
{
    FIXME( "should update ini fields %s\n", debugstr_w(field) );
    return TRUE;
}

static BOOL ini2reg_callback( HINF hinf, PCWSTR field, void *arg )
{
    FIXME( "should do ini2reg %s\n", debugstr_w(field) );
    return TRUE;
}

static BOOL logconf_callback( HINF hinf, PCWSTR field, void *arg )
{
    FIXME( "should do logconf %s\n", debugstr_w(field) );
    return TRUE;
}

851 852 853 854 855 856 857 858
static BOOL bitreg_callback( HINF hinf, PCWSTR field, void *arg )
{
    FIXME( "should do bitreg %s\n", debugstr_w(field) );
    return TRUE;
}

static BOOL profile_items_callback( HINF hinf, PCWSTR field, void *arg )
{
859 860
    WCHAR lnkpath[MAX_PATH];
    LPWSTR cmdline=NULL, lnkpath_end;
861
    DWORD name_size;
862 863 864 865 866
    INFCONTEXT name_context, context;
    int attrs=0;

    TRACE( "(%s)\n", debugstr_w(field) );

867
    if (SetupFindFirstLineW( hinf, field, L"Name", &name_context ))
868 869
    {
        SetupGetIntField( &name_context, 2, &attrs );
870
        if (attrs & ~FLG_PROFITEM_GROUP) FIXME( "unhandled attributes: %x\n", attrs );
871 872 873 874 875
    }
    else return TRUE;

    /* calculate filename */
    SHGetFolderPathW( NULL, CSIDL_COMMON_PROGRAMS, NULL, SHGFP_TYPE_CURRENT, lnkpath );
876
    lnkpath_end = lnkpath + lstrlenW(lnkpath);
877 878
    if (lnkpath_end[-1] != '\\') *lnkpath_end++ = '\\';

879
    if (!(attrs & FLG_PROFITEM_GROUP) && SetupFindFirstLineW( hinf, field, L"SubDir", &context ))
880
    {
881
        DWORD subdir_size;
882 883 884 885 886 887 888 889 890 891 892 893 894

        if (!SetupGetStringFieldW( &context, 1, lnkpath_end, (lnkpath+MAX_PATH)-lnkpath_end, &subdir_size ))
            return TRUE;

        lnkpath_end += subdir_size - 1;
        if (lnkpath_end[-1] != '\\') *lnkpath_end++ = '\\';
    }

    if (!SetupGetStringFieldW( &name_context, 1, lnkpath_end, (lnkpath+MAX_PATH)-lnkpath_end, &name_size ))
        return TRUE;

    lnkpath_end += name_size - 1;

895
    if (attrs & FLG_PROFITEM_GROUP)
896
    {
897 898 899 900 901 902 903
        SHPathPrepareForWriteW( NULL, NULL, lnkpath, SHPPFW_DIRCREATE );
    }
    else
    {
        IShellLinkW* shelllink=NULL;
        IPersistFile* persistfile=NULL;
        HRESULT initresult=E_FAIL;
904

905
        if (lnkpath+MAX_PATH < lnkpath_end + 5) return TRUE;
906
        lstrcpyW( lnkpath_end, L".lnk" );
907

908
        TRACE( "link path: %s\n", debugstr_w(lnkpath) );
909

910
        /* calculate command line */
911
        if (SetupFindFirstLineW( hinf, field, L"CmdLine", &context ))
912
        {
913 914
            unsigned int dir_len=0;
            DWORD subdir_size=0, filename_size=0;
915 916 917
            int dirid=0;
            LPCWSTR dir;
            LPWSTR cmdline_end;
918

919 920
            SetupGetIntField( &context, 1, &dirid );
            dir = DIRID_get_string( dirid );
921

922
            if (dir) dir_len = lstrlenW(dir);
923 924 925 926 927

            SetupGetStringFieldW( &context, 2, NULL, 0, &subdir_size );
            SetupGetStringFieldW( &context, 3, NULL, 0, &filename_size );

            if (dir_len && filename_size)
928
            {
929
                cmdline = cmdline_end = malloc( sizeof(WCHAR) * (dir_len + subdir_size + filename_size + 1) );
930

931
                lstrcpyW( cmdline_end, dir );
932
                cmdline_end += dir_len;
933
                if (cmdline_end[-1] != '\\') *cmdline_end++ = '\\';
934 935 936 937 938 939 940 941 942

                if (subdir_size)
                {
                    SetupGetStringFieldW( &context, 2, cmdline_end, subdir_size, NULL );
                    cmdline_end += subdir_size-1;
                    if (cmdline_end[-1] != '\\') *cmdline_end++ = '\\';
                }
                SetupGetStringFieldW( &context, 3, cmdline_end, filename_size, NULL );
                TRACE( "cmdline: %s\n", debugstr_w(cmdline));
943 944 945
            }
        }

946
        if (!cmdline) return TRUE;
947

948
        initresult = CoInitialize(NULL);
949

950 951
        if (FAILED(CoCreateInstance( &CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER,
                                     &IID_IShellLinkW, (LPVOID*)&shelllink )))
952
            goto done;
953

954 955 956 957 958 959 960 961 962 963 964 965
        IShellLinkW_SetPath( shelllink, cmdline );
        SHPathPrepareForWriteW( NULL, NULL, lnkpath, SHPPFW_DIRCREATE|SHPPFW_IGNOREFILENAME );
        if (SUCCEEDED(IShellLinkW_QueryInterface( shelllink, &IID_IPersistFile, (LPVOID*)&persistfile)))
        {
            TRACE( "writing link: %s\n", debugstr_w(lnkpath) );
            IPersistFile_Save( persistfile, lnkpath, FALSE );
            IPersistFile_Release( persistfile );
        }
        IShellLinkW_Release( shelllink );

    done:
        if (SUCCEEDED(initresult)) CoUninitialize();
966
        free( cmdline );
967 968
    }

969 970 971 972 973 974 975 976 977
    return TRUE;
}

static BOOL copy_inf_callback( HINF hinf, PCWSTR field, void *arg )
{
    FIXME( "should do copy inf %s\n", debugstr_w(field) );
    return TRUE;
}

978 979 980 981 982 983 984 985 986 987 988

/***********************************************************************
 *            iterate_section_fields
 *
 * Iterate over all fields of a certain key of a certain section
 */
static BOOL iterate_section_fields( HINF hinf, PCWSTR section, PCWSTR key,
                                    iterate_fields_func callback, void *arg )
{
    WCHAR static_buffer[200];
    WCHAR *buffer = static_buffer;
989
    DWORD size = ARRAY_SIZE( static_buffer );
990 991 992 993 994 995 996 997 998 999 1000 1001 1002
    INFCONTEXT context;
    BOOL ret = FALSE;

    BOOL ok = SetupFindFirstLineW( hinf, section, key, &context );
    while (ok)
    {
        UINT i, count = SetupGetFieldCount( &context );
        for (i = 1; i <= count; i++)
        {
            if (!(buffer = get_field_string( &context, i, buffer, static_buffer, &size )))
                goto done;
            if (!callback( hinf, buffer, arg ))
            {
1003
                WARN("callback failed for %s %s err %ld\n",
1004
                     debugstr_w(section), debugstr_w(buffer), GetLastError() );
1005 1006 1007 1008 1009 1010 1011
                goto done;
            }
        }
        ok = SetupFindNextMatchLineW( &context, key, &context );
    }
    ret = TRUE;
 done:
1012
    if (buffer != static_buffer) free( buffer );
1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061
    return ret;
}


/***********************************************************************
 *            SetupInstallFilesFromInfSectionA   (SETUPAPI.@)
 */
BOOL WINAPI SetupInstallFilesFromInfSectionA( HINF hinf, HINF hlayout, HSPFILEQ queue,
                                              PCSTR section, PCSTR src_root, UINT flags )
{
    UNICODE_STRING sectionW;
    BOOL ret = FALSE;

    if (!RtlCreateUnicodeStringFromAsciiz( &sectionW, section ))
    {
        SetLastError( ERROR_NOT_ENOUGH_MEMORY );
        return FALSE;
    }
    if (!src_root)
        ret = SetupInstallFilesFromInfSectionW( hinf, hlayout, queue, sectionW.Buffer,
                                                NULL, flags );
    else
    {
        UNICODE_STRING srcW;
        if (RtlCreateUnicodeStringFromAsciiz( &srcW, src_root ))
        {
            ret = SetupInstallFilesFromInfSectionW( hinf, hlayout, queue, sectionW.Buffer,
                                                    srcW.Buffer, flags );
            RtlFreeUnicodeString( &srcW );
        }
        else SetLastError( ERROR_NOT_ENOUGH_MEMORY );
    }
    RtlFreeUnicodeString( &sectionW );
    return ret;
}


/***********************************************************************
 *            SetupInstallFilesFromInfSectionW   (SETUPAPI.@)
 */
BOOL WINAPI SetupInstallFilesFromInfSectionW( HINF hinf, HINF hlayout, HSPFILEQ queue,
                                              PCWSTR section, PCWSTR src_root, UINT flags )
{
    struct files_callback_info info;

    info.queue      = queue;
    info.src_root   = src_root;
    info.copy_flags = flags;
    info.layout     = hlayout;
1062 1063 1064
    return iterate_section_fields( hinf, section, L"CopyFiles", copy_files_callback, &info ) &&
           iterate_section_fields( hinf, section, L"DelFiles", delete_files_callback, &info ) &&
           iterate_section_fields( hinf, section, L"RenFiles", rename_files_callback, &info );
1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110
}


/***********************************************************************
 *            SetupInstallFromInfSectionA   (SETUPAPI.@)
 */
BOOL WINAPI SetupInstallFromInfSectionA( HWND owner, HINF hinf, PCSTR section, UINT flags,
                                         HKEY key_root, PCSTR src_root, UINT copy_flags,
                                         PSP_FILE_CALLBACK_A callback, PVOID context,
                                         HDEVINFO devinfo, PSP_DEVINFO_DATA devinfo_data )
{
    UNICODE_STRING sectionW, src_rootW;
    struct callback_WtoA_context ctx;
    BOOL ret = FALSE;

    src_rootW.Buffer = NULL;
    if (src_root && !RtlCreateUnicodeStringFromAsciiz( &src_rootW, src_root ))
    {
        SetLastError( ERROR_NOT_ENOUGH_MEMORY );
        return FALSE;
    }

    if (RtlCreateUnicodeStringFromAsciiz( &sectionW, section ))
    {
        ctx.orig_context = context;
        ctx.orig_handler = callback;
        ret = SetupInstallFromInfSectionW( owner, hinf, sectionW.Buffer, flags, key_root,
                                           src_rootW.Buffer, copy_flags, QUEUE_callback_WtoA,
                                           &ctx, devinfo, devinfo_data );
        RtlFreeUnicodeString( &sectionW );
    }
    else SetLastError( ERROR_NOT_ENOUGH_MEMORY );

    RtlFreeUnicodeString( &src_rootW );
    return ret;
}


/***********************************************************************
 *            SetupInstallFromInfSectionW   (SETUPAPI.@)
 */
BOOL WINAPI SetupInstallFromInfSectionW( HWND owner, HINF hinf, PCWSTR section, UINT flags,
                                         HKEY key_root, PCWSTR src_root, UINT copy_flags,
                                         PSP_FILE_CALLBACK_W callback, PVOID context,
                                         HDEVINFO devinfo, PSP_DEVINFO_DATA devinfo_data )
{
1111 1112 1113
    BOOL ret;
    int i;

1114 1115 1116 1117 1118 1119 1120
    if (flags & SPINST_REGSVR)
    {
        if (iterate_section_fields( hinf, section, L"WineFakeDlls", fake_dlls_callback, NULL ))
            cleanup_fake_dlls();
        else
            return FALSE;
    }
1121 1122 1123 1124 1125
    if (flags & SPINST_FILES)
    {
        HSPFILEQ queue;

        if (!(queue = SetupOpenFileQueue())) return FALSE;
1126
        ret = (SetupInstallFilesFromInfSectionW( hinf, NULL, queue, section, src_root, copy_flags ) &&
1127 1128 1129 1130 1131 1132
               SetupCommitFileQueueW( owner, queue, callback, context ));
        SetupCloseFileQueue( queue );
        if (!ret) return FALSE;
    }
    if (flags & SPINST_INIFILES)
    {
1133 1134
        if (!iterate_section_fields( hinf, section, L"UpdateInis", update_ini_callback, NULL ) ||
            !iterate_section_fields( hinf, section, L"UpdateIniFields",
1135 1136 1137 1138 1139
                                     update_ini_fields_callback, NULL ))
            return FALSE;
    }
    if (flags & SPINST_INI2REG)
    {
1140
        if (!iterate_section_fields( hinf, section, L"Ini2Reg", ini2reg_callback, NULL ))
1141 1142 1143 1144
            return FALSE;
    }
    if (flags & SPINST_LOGCONFIG)
    {
1145
        if (!iterate_section_fields( hinf, section, L"LogConf", logconf_callback, NULL ))
1146 1147
            return FALSE;
    }
1148 1149
    if (flags & SPINST_REGSVR)
    {
1150
        struct register_dll_info info = { .unregister = FALSE };
1151
        HRESULT hr;
1152 1153 1154 1155 1156 1157

        if (flags & SPINST_REGISTERCALLBACKAWARE)
        {
            info.callback         = callback;
            info.callback_context = context;
        }
1158

1159 1160
        hr = CoInitialize(NULL);

1161
        ret = iterate_section_fields( hinf, section, L"RegisterDlls", register_dlls_callback, &info );
1162
        for (i = 0; i < info.modules_count; i++) FreeLibrary( info.modules[i] );
1163 1164 1165 1166

        if (SUCCEEDED(hr))
            CoUninitialize();

1167
        free( info.modules );
1168
        if (!ret) return FALSE;
1169 1170 1171
    }
    if (flags & SPINST_UNREGSVR)
    {
1172
        struct register_dll_info info = { .unregister = TRUE };
1173
        HRESULT hr;
1174 1175 1176 1177 1178 1179 1180

        if (flags & SPINST_REGISTERCALLBACKAWARE)
        {
            info.callback         = callback;
            info.callback_context = context;
        }

1181 1182
        hr = CoInitialize(NULL);

1183
        ret = iterate_section_fields( hinf, section, L"UnregisterDlls", register_dlls_callback, &info );
1184
        for (i = 0; i < info.modules_count; i++) FreeLibrary( info.modules[i] );
1185 1186 1187 1188

        if (SUCCEEDED(hr))
            CoUninitialize();

1189
        free( info.modules );
1190
        if (!ret) return FALSE;
1191
    }
1192 1193 1194 1195 1196 1197
    if (flags & SPINST_REGISTRY)
    {
        struct registry_callback_info info;

        info.default_root = key_root;
        info.delete = TRUE;
1198
        if (!iterate_section_fields( hinf, section, L"DelReg", registry_callback, &info ))
1199
            return FALSE;
1200
        info.delete = FALSE;
1201
        if (!iterate_section_fields( hinf, section, L"AddReg", registry_callback, &info ))
1202
            return FALSE;
1203
    }
1204 1205
    if (flags & SPINST_BITREG)
    {
1206
        if (!iterate_section_fields( hinf, section, L"BitReg", bitreg_callback, NULL ))
1207 1208 1209 1210
            return FALSE;
    }
    if (flags & SPINST_PROFILEITEMS)
    {
1211
        if (!iterate_section_fields( hinf, section, L"ProfileItems", profile_items_callback, NULL ))
1212 1213 1214 1215
            return FALSE;
    }
    if (flags & SPINST_COPYINF)
    {
1216
        if (!iterate_section_fields( hinf, section, L"CopyINF", copy_inf_callback, NULL ))
1217 1218
            return FALSE;
    }
1219

1220
    SetLastError(ERROR_SUCCESS);
1221 1222
    return TRUE;
}
1223 1224 1225 1226 1227 1228 1229 1230 1231 1232


/***********************************************************************
 *		InstallHinfSectionW  (SETUPAPI.@)
 *
 * NOTE: 'cmdline' is <section> <mode> <path> from
 *   RUNDLL32.EXE SETUPAPI.DLL,InstallHinfSection <section> <mode> <path>
 */
void WINAPI InstallHinfSectionW( HWND hwnd, HINSTANCE handle, LPCWSTR cmdline, INT show )
{
1233
#ifdef __i386__
1234
    static const WCHAR nt_platformW[] = L".ntx86";
1235
#elif defined(__x86_64__)
1236
    static const WCHAR nt_platformW[] = L".ntamd64";
1237
#elif defined(__arm__)
1238
    static const WCHAR nt_platformW[] = L".ntarm";
1239
#elif defined(__aarch64__)
1240
    static const WCHAR nt_platformW[] = L".ntarm64";
1241
#else  /* FIXME: other platforms */
1242
    static const WCHAR nt_platformW[] = L".nt";
1243 1244
#endif

1245
    WCHAR *s, *path, section[MAX_PATH + ARRAY_SIZE( nt_platformW ) + ARRAY_SIZE( L".Services" )];
1246
    void *callback_context;
1247
    UINT mode;
1248 1249 1250 1251
    HINF hinf;

    TRACE("hwnd %p, handle %p, cmdline %s\n", hwnd, handle, debugstr_w(cmdline));

1252
    lstrcpynW( section, cmdline, MAX_PATH );
1253

1254
    if (!(s = wcschr( section, ' ' ))) return;
1255 1256
    *s++ = 0;
    while (*s == ' ') s++;
1257
    mode = wcstol( s, NULL, 10 );
1258

1259
    /* quoted paths are not allowed on native, the rest of the command line is taken as the path */
1260
    if (!(s = wcschr( s, ' ' ))) return;
1261
    while (*s == ' ') s++;
1262
    path = s;
1263 1264 1265 1266

    hinf = SetupOpenInfFileW( path, NULL, INF_STYLE_WIN4, NULL );
    if (hinf == INVALID_HANDLE_VALUE) return;

1267 1268 1269 1270 1271 1272
    if (!(GetVersion() & 0x80000000))
    {
        INFCONTEXT context;

        /* check for <section>.ntx86 (or corresponding name for the current platform)
         * and then <section>.nt */
1273
        s = section + lstrlenW(section);
1274
        lstrcpyW( s, nt_platformW );
1275 1276
        if (!(SetupFindFirstLineW( hinf, section, NULL, &context )))
        {
1277
            lstrcpyW( s, L".nt" );
1278
            if (!(SetupFindFirstLineW( hinf, section, NULL, &context ))) *s = 0;
1279
        }
1280
        if (*s) TRACE( "using section %s instead\n", debugstr_w(section) );
1281 1282
    }

1283 1284 1285 1286 1287
    callback_context = SetupInitDefaultQueueCallback( hwnd );
    SetupInstallFromInfSectionW( hwnd, hinf, section, SPINST_ALL, NULL, NULL, SP_COPY_NEWER,
                                 SetupDefaultQueueCallbackW, callback_context,
                                 NULL, NULL );
    SetupTermDefaultQueueCallback( callback_context );
1288
    lstrcatW( section, L".Services" );
1289
    SetupInstallServicesFromInfSectionW( hinf, section, 0 );
1290 1291 1292 1293 1294
    SetupCloseInfFile( hinf );

    /* FIXME: should check the mode and maybe reboot */
    /* there isn't much point in doing that since we */
    /* don't yet handle deferred file copies anyway. */
1295
    if (mode & 7) TRACE( "should consider reboot, mode %u\n", mode );
1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311
}


/***********************************************************************
 *		InstallHinfSectionA  (SETUPAPI.@)
 */
void WINAPI InstallHinfSectionA( HWND hwnd, HINSTANCE handle, LPCSTR cmdline, INT show )
{
    UNICODE_STRING cmdlineW;

    if (RtlCreateUnicodeStringFromAsciiz( &cmdlineW, cmdline ))
    {
        InstallHinfSectionW( hwnd, handle, cmdlineW.Buffer, show );
        RtlFreeUnicodeString( &cmdlineW );
    }
}
1312

1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331

/***********************************************************************
 *            add_service
 *
 * Create a new service. Helper for SetupInstallServicesFromInfSectionW.
 */
static BOOL add_service( SC_HANDLE scm, HINF hinf, const WCHAR *name, const WCHAR *section, DWORD flags )
{
    struct registry_callback_info info;
    SC_HANDLE service;
    INFCONTEXT context;
    SERVICE_DESCRIPTIONW descr;
    WCHAR *display_name, *start_name, *load_order, *binary_path;
    INT service_type = 0, start_type = 0, error_control = 0;
    DWORD size;
    HKEY hkey;

    /* first the mandatory fields */

1332
    if (!SetupFindFirstLineW( hinf, section, L"ServiceType", &context ) ||
1333 1334 1335 1336 1337
        !SetupGetIntField( &context, 1, &service_type ))
    {
        SetLastError( ERROR_BAD_SERVICE_INSTALLSECT );
        return FALSE;
    }
1338
    if (!SetupFindFirstLineW( hinf, section, L"StartType", &context ) ||
1339 1340 1341 1342 1343
        !SetupGetIntField( &context, 1, &start_type ))
    {
        SetLastError( ERROR_BAD_SERVICE_INSTALLSECT );
        return FALSE;
    }
1344
    if (!SetupFindFirstLineW( hinf, section, L"ErrorControl", &context ) ||
1345 1346 1347 1348 1349
        !SetupGetIntField( &context, 1, &error_control ))
    {
        SetLastError( ERROR_BAD_SERVICE_INSTALLSECT );
        return FALSE;
    }
1350
    if (!(binary_path = dup_section_line_field( hinf, section, L"ServiceBinary", 1 )))
1351 1352 1353 1354 1355 1356 1357
    {
        SetLastError( ERROR_BAD_SERVICE_INSTALLSECT );
        return FALSE;
    }

    /* now the optional fields */

1358 1359 1360 1361
    display_name = dup_section_line_field( hinf, section, L"DisplayName", 1 );
    start_name = dup_section_line_field( hinf, section, L"StartName", 1 );
    load_order = dup_section_line_field( hinf, section, L"LoadOrderGroup", 1 );
    descr.lpDescription = dup_section_line_field( hinf, section, L"Description", 1 );
1362 1363 1364 1365

    /* FIXME: Dependencies field */
    /* FIXME: Security field */

1366
    TRACE( "service %s display %s type %x start %x error %x binary %s order %s startname %s flags %lx\n",
1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389
           debugstr_w(name), debugstr_w(display_name), service_type, start_type, error_control,
           debugstr_w(binary_path), debugstr_w(load_order), debugstr_w(start_name), flags );

    service = CreateServiceW( scm, name, display_name, SERVICE_ALL_ACCESS,
                              service_type, start_type, error_control, binary_path,
                              load_order, NULL, NULL, start_name, NULL );
    if (service)
    {
        if (descr.lpDescription) ChangeServiceConfig2W( service, SERVICE_CONFIG_DESCRIPTION, &descr );
    }
    else
    {
        if (GetLastError() != ERROR_SERVICE_EXISTS) goto done;
        service = OpenServiceW( scm, name, SERVICE_QUERY_CONFIG|SERVICE_CHANGE_CONFIG|SERVICE_START );
        if (!service) goto done;

        if (flags & (SPSVCINST_NOCLOBBER_DISPLAYNAME | SPSVCINST_NOCLOBBER_STARTTYPE |
                     SPSVCINST_NOCLOBBER_ERRORCONTROL | SPSVCINST_NOCLOBBER_LOADORDERGROUP))
        {
            QUERY_SERVICE_CONFIGW *config = NULL;

            if (!QueryServiceConfigW( service, NULL, 0, &size ) &&
                GetLastError() == ERROR_INSUFFICIENT_BUFFER)
1390
                config = malloc( size );
1391 1392 1393 1394 1395 1396
            if (config && QueryServiceConfigW( service, config, size, &size ))
            {
                if (flags & SPSVCINST_NOCLOBBER_STARTTYPE) start_type = config->dwStartType;
                if (flags & SPSVCINST_NOCLOBBER_ERRORCONTROL) error_control = config->dwErrorControl;
                if (flags & SPSVCINST_NOCLOBBER_DISPLAYNAME)
                {
1397 1398
                    free( display_name );
                    display_name = wcsdup( config->lpDisplayName );
1399 1400 1401
                }
                if (flags & SPSVCINST_NOCLOBBER_LOADORDERGROUP)
                {
1402 1403
                    free( load_order );
                    load_order = wcsdup( config->lpLoadOrderGroup );
1404 1405
                }
            }
1406
            free( config );
1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421
        }
        TRACE( "changing %s display %s type %x start %x error %x binary %s loadorder %s startname %s\n",
               debugstr_w(name), debugstr_w(display_name), service_type, start_type, error_control,
               debugstr_w(binary_path), debugstr_w(load_order), debugstr_w(start_name) );

        ChangeServiceConfigW( service, service_type, start_type, error_control, binary_path,
                              load_order, NULL, NULL, start_name, NULL, display_name );

        if (!(flags & SPSVCINST_NOCLOBBER_DESCRIPTION))
            ChangeServiceConfig2W( service, SERVICE_CONFIG_DESCRIPTION, &descr );
    }

    /* execute the AddReg, DelReg and BitReg entries */

    info.default_root = 0;
1422
    if (!RegOpenKeyW( HKEY_LOCAL_MACHINE, L"System\\CurrentControlSet\\Services", &hkey ))
1423 1424 1425 1426 1427 1428 1429
    {
        RegOpenKeyW( hkey, name, &info.default_root );
        RegCloseKey( hkey );
    }
    if (info.default_root)
    {
        info.delete = TRUE;
1430
        iterate_section_fields( hinf, section, L"DelReg", registry_callback, &info );
1431
        info.delete = FALSE;
1432
        iterate_section_fields( hinf, section, L"AddReg", registry_callback, &info );
1433 1434
        RegCloseKey( info.default_root );
    }
1435
    iterate_section_fields( hinf, section, L"BitReg", bitreg_callback, NULL );
1436 1437 1438 1439 1440

    if (flags & SPSVCINST_STARTSERVICE) StartServiceW( service, 0, NULL );
    CloseServiceHandle( service );

done:
1441
    if (!service) WARN( "failed err %lu\n", GetLastError() );
1442 1443 1444 1445 1446
    free( binary_path );
    free( display_name );
    free( start_name );
    free( load_order );
    free( descr.lpDescription );
1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464
    return service != 0;
}


/***********************************************************************
 *            del_service
 *
 * Delete service. Helper for SetupInstallServicesFromInfSectionW.
 */
static BOOL del_service( SC_HANDLE scm, HINF hinf, const WCHAR *name, DWORD flags )
{
    BOOL ret;
    SC_HANDLE service;
    SERVICE_STATUS status;

    if (!(service = OpenServiceW( scm, name, SERVICE_STOP | DELETE )))
    {
        if (GetLastError() == ERROR_SERVICE_DOES_NOT_EXIST) return TRUE;
1465
        WARN( "cannot open %s err %lu\n", debugstr_w(name), GetLastError() );
1466 1467 1468 1469 1470 1471 1472 1473 1474 1475
        return FALSE;
    }
    if (flags & SPSVCINST_STOPSERVICE) ControlService( service, SERVICE_CONTROL_STOP, &status );
    TRACE( "deleting %s\n", debugstr_w(name) );
    ret = DeleteService( service );
    CloseServiceHandle( service );
    return ret;
}


1476 1477 1478
/***********************************************************************
 *              SetupInstallServicesFromInfSectionW  (SETUPAPI.@)
 */
1479
BOOL WINAPI SetupInstallServicesFromInfSectionW( HINF hinf, PCWSTR section, DWORD flags )
1480
{
1481 1482 1483 1484 1485
    WCHAR service_name[MAX_INF_STRING_LENGTH];
    WCHAR service_section[MAX_INF_STRING_LENGTH];
    SC_HANDLE scm;
    INFCONTEXT context;
    INT section_flags;
1486
    BOOL ret = TRUE;
1487

1488
    if (!SetupFindFirstLineW( hinf, section, NULL, &context ))
1489 1490 1491 1492
    {
        SetLastError( ERROR_SECTION_NOT_FOUND );
        return FALSE;
    }
1493 1494
    if (!(scm = OpenSCManagerW( NULL, NULL, SC_MANAGER_ALL_ACCESS ))) return FALSE;

1495
    if (SetupFindFirstLineW( hinf, section, L"AddService", &context ))
1496
    {
1497 1498 1499 1500 1501 1502 1503 1504 1505
        do
        {
            if (!SetupGetStringFieldW( &context, 1, service_name, MAX_INF_STRING_LENGTH, NULL ))
                continue;
            if (!SetupGetIntField( &context, 2, &section_flags )) section_flags = 0;
            if (!SetupGetStringFieldW( &context, 3, service_section, MAX_INF_STRING_LENGTH, NULL ))
                continue;
            if (!(ret = add_service( scm, hinf, service_name, service_section, section_flags | flags )))
                goto done;
1506
        } while (SetupFindNextMatchLineW( &context, L"AddService", &context ));
1507 1508
    }

1509
    if (SetupFindFirstLineW( hinf, section, L"DelService", &context ))
1510
    {
1511 1512 1513 1514 1515 1516
        do
        {
            if (!SetupGetStringFieldW( &context, 1, service_name, MAX_INF_STRING_LENGTH, NULL ))
                continue;
            if (!SetupGetIntField( &context, 2, &section_flags )) section_flags = 0;
            if (!(ret = del_service( scm, hinf, service_name, section_flags | flags ))) goto done;
1517
        } while (SetupFindNextMatchLineW( &context, L"AddService", &context ));
1518 1519 1520 1521 1522
    }
    if (ret) SetLastError( ERROR_SUCCESS );
 done:
    CloseServiceHandle( scm );
    return ret;
1523 1524
}

1525

1526 1527 1528 1529 1530
/***********************************************************************
 *              SetupInstallServicesFromInfSectionA  (SETUPAPI.@)
 */
BOOL WINAPI SetupInstallServicesFromInfSectionA( HINF Inf, PCSTR SectionName, DWORD Flags)
{
1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542
    UNICODE_STRING SectionNameW;
    BOOL ret = FALSE;

    if (RtlCreateUnicodeStringFromAsciiz( &SectionNameW, SectionName ))
    {
        ret = SetupInstallServicesFromInfSectionW( Inf, SectionNameW.Buffer, Flags );
        RtlFreeUnicodeString( &SectionNameW );
    }
    else
        SetLastError( ERROR_NOT_ENOUGH_MEMORY );

    return ret;
1543
}
1544 1545


1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562
/***********************************************************************
 *              SetupGetInfFileListA  (SETUPAPI.@)
 */
BOOL WINAPI SetupGetInfFileListA(PCSTR dir, DWORD style, PSTR buffer,
                                 DWORD insize, PDWORD outsize)
{
    UNICODE_STRING dirW;
    PWSTR bufferW = NULL;
    BOOL ret = FALSE;
    DWORD outsizeA, outsizeW;

    if ( dir )
        RtlCreateUnicodeStringFromAsciiz( &dirW, dir );
    else
        dirW.Buffer = NULL;

    if ( buffer )
1563
        bufferW = malloc( insize * sizeof( WCHAR ));
1564 1565 1566 1567 1568 1569 1570 1571 1572 1573

    ret = SetupGetInfFileListW( dirW.Buffer, style, bufferW, insize, &outsizeW);

    if ( ret )
    {
        outsizeA = WideCharToMultiByte( CP_ACP, 0, bufferW, outsizeW,
                                        buffer, insize, NULL, NULL);
        if ( outsize ) *outsize = outsizeA;
    }

1574
    free( bufferW );
1575 1576 1577 1578 1579
    RtlFreeUnicodeString( &dirW );
    return ret;
}


1580 1581 1582 1583 1584 1585
/***********************************************************************
 *              SetupGetInfFileListW  (SETUPAPI.@)
 */
BOOL WINAPI SetupGetInfFileListW(PCWSTR dir, DWORD style, PWSTR buffer,
                                 DWORD insize, PDWORD outsize)
{
1586 1587 1588 1589 1590 1591 1592
    WCHAR *filter, *fullname = NULL, *ptr = buffer;
    DWORD dir_len, name_len = 20, size ;
    WIN32_FIND_DATAW finddata;
    HANDLE hdl;
    if (style & ~( INF_STYLE_OLDNT | INF_STYLE_WIN4 |
                   INF_STYLE_CACHE_ENABLE | INF_STYLE_CACHE_DISABLE ))
    {
1593
        FIXME( "unknown inf_style(s) 0x%lx\n",
1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612
               style & ~( INF_STYLE_OLDNT | INF_STYLE_WIN4 |
                         INF_STYLE_CACHE_ENABLE | INF_STYLE_CACHE_DISABLE ));
        if( outsize ) *outsize = 1;
        return TRUE;
    }
    if ((style & ( INF_STYLE_OLDNT | INF_STYLE_WIN4 )) == INF_STYLE_NONE)
    {
        FIXME( "inf_style INF_STYLE_NONE not handled\n" );
        if( outsize ) *outsize = 1;
        return TRUE;
    }
    if (style & ( INF_STYLE_CACHE_ENABLE | INF_STYLE_CACHE_DISABLE ))
        FIXME("ignored inf_style(s) %s %s\n",
              ( style & INF_STYLE_CACHE_ENABLE  ) ? "INF_STYLE_CACHE_ENABLE"  : "",
              ( style & INF_STYLE_CACHE_DISABLE ) ? "INF_STYLE_CACHE_DISABLE" : "");
    if( dir )
    {
        DWORD att;
        DWORD msize;
1613
        dir_len = lstrlenW( dir );
1614 1615
        if ( !dir_len ) return FALSE;
        msize = ( 7 + dir_len )  * sizeof( WCHAR ); /* \\*.inf\0 */
1616
        filter = malloc( msize );
1617 1618 1619 1620 1621
        if( !filter )
        {
            SetLastError( ERROR_NOT_ENOUGH_MEMORY );
            return FALSE;
        }
1622
        lstrcpyW( filter, dir );
1623 1624 1625 1626 1627 1628
        if ( '\\' == filter[dir_len - 1] )
            filter[--dir_len] = 0;

        att = GetFileAttributesW( filter );
        if (att != INVALID_FILE_ATTRIBUTES && !(att & FILE_ATTRIBUTE_DIRECTORY))
        {
1629
            free( filter );
1630 1631 1632 1633 1634 1635 1636 1637 1638
            SetLastError( ERROR_DIRECTORY );
            return FALSE;
        }
    }
    else
    {
        DWORD msize;
        dir_len = GetWindowsDirectoryW( NULL, 0 );
        msize = ( 7 + 4 + dir_len ) * sizeof( WCHAR );
1639
        filter = malloc( msize );
1640 1641 1642 1643 1644 1645
        if( !filter )
        {
            SetLastError( ERROR_NOT_ENOUGH_MEMORY );
            return FALSE;
        }
        GetWindowsDirectoryW( filter, msize );
1646
        lstrcatW( filter, L"\\inf" );
1647
    }
1648
    lstrcatW( filter, L"\\*.inf" );
1649 1650 1651 1652 1653

    hdl = FindFirstFileW( filter , &finddata );
    if ( hdl == INVALID_HANDLE_VALUE )
    {
        if( outsize ) *outsize = 1;
1654
        free( filter );
1655 1656 1657 1658 1659 1660 1661
        return TRUE;
    }
    size = 1;
    do
    {
        WCHAR signature[ MAX_PATH ];
        BOOL valid = FALSE;
1662
        DWORD len = lstrlenW( finddata.cFileName );
1663 1664 1665
        if (!fullname || ( name_len < len ))
        {
            name_len = ( name_len < len ) ? len : name_len;
1666 1667
            free( fullname );
            fullname = malloc( (2 + dir_len + name_len) * sizeof( WCHAR ) );
1668 1669
            if( !fullname )
            {
1670
                FindClose( hdl );
1671
                free( filter );
1672 1673 1674
                SetLastError( ERROR_NOT_ENOUGH_MEMORY );
                return FALSE;
            }
1675
            lstrcpyW( fullname, filter );
1676 1677
        }
        fullname[ dir_len + 1] = 0; /* keep '\\' */
1678
        lstrcatW( fullname, finddata.cFileName );
1679
        if (!GetPrivateProfileStringW( L"Version", L"Signature", NULL, signature, MAX_PATH, fullname ))
1680 1681
            signature[0] = 0;
        if( INF_STYLE_OLDNT & style )
1682
            valid = wcsicmp( L"$Chicago$", signature ) && wcsicmp( L"$WINDOWS NT$", signature );
1683
        if( INF_STYLE_WIN4 & style )
1684 1685
            valid = valid || !wcsicmp( L"$Chicago$", signature ) ||
                    !wcsicmp( L"$WINDOWS NT$", signature );
1686 1687
        if( valid )
        {
1688
            size += 1 + lstrlenW( finddata.cFileName );
1689 1690
            if( ptr && insize >= size )
            {
1691 1692
                lstrcpyW( ptr, finddata.cFileName );
                ptr += 1 + lstrlenW( finddata.cFileName );
1693 1694 1695 1696 1697 1698 1699
                *ptr = 0;
            }
        }
    }
    while( FindNextFileW( hdl, &finddata ));
    FindClose( hdl );

1700 1701
    free( fullname );
    free( filter );
1702
    if( outsize ) *outsize = size;
1703 1704
    return TRUE;
}