dsound: Added missing LeaveCriticalSection (Coverity).
[wine] / dlls / setupapi / install.c
1 /*
2  * Setupapi install routines
3  *
4  * Copyright 2002 Alexandre Julliard for CodeWeavers
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this library; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
19  */
20
21 #include <stdarg.h>
22
23 #define COBJMACROS
24
25 #include "windef.h"
26 #include "winbase.h"
27 #include "winreg.h"
28 #include "winternl.h"
29 #include "winerror.h"
30 #include "wingdi.h"
31 #include "winuser.h"
32 #include "winnls.h"
33 #include "winsvc.h"
34 #include "shlobj.h"
35 #include "objidl.h"
36 #include "objbase.h"
37 #include "setupapi.h"
38 #include "setupapi_private.h"
39 #include "wine/unicode.h"
40 #include "wine/debug.h"
41
42 WINE_DEFAULT_DEBUG_CHANNEL(setupapi);
43
44 /* info passed to callback functions dealing with files */
45 struct files_callback_info
46 {
47     HSPFILEQ queue;
48     PCWSTR   src_root;
49     UINT     copy_flags;
50     HINF     layout;
51 };
52
53 /* info passed to callback functions dealing with the registry */
54 struct registry_callback_info
55 {
56     HKEY default_root;
57     BOOL delete;
58 };
59
60 /* info passed to callback functions dealing with registering dlls */
61 struct register_dll_info
62 {
63     PSP_FILE_CALLBACK_W callback;
64     PVOID               callback_context;
65     BOOL                unregister;
66     int                 modules_size;
67     int                 modules_count;
68     HMODULE            *modules;
69 };
70
71 typedef BOOL (*iterate_fields_func)( HINF hinf, PCWSTR field, void *arg );
72
73 /* Unicode constants */
74 static const WCHAR CopyFiles[]  = {'C','o','p','y','F','i','l','e','s',0};
75 static const WCHAR DelFiles[]   = {'D','e','l','F','i','l','e','s',0};
76 static const WCHAR RenFiles[]   = {'R','e','n','F','i','l','e','s',0};
77 static const WCHAR Ini2Reg[]    = {'I','n','i','2','R','e','g',0};
78 static const WCHAR LogConf[]    = {'L','o','g','C','o','n','f',0};
79 static const WCHAR AddReg[]     = {'A','d','d','R','e','g',0};
80 static const WCHAR DelReg[]     = {'D','e','l','R','e','g',0};
81 static const WCHAR BitReg[]     = {'B','i','t','R','e','g',0};
82 static const WCHAR UpdateInis[] = {'U','p','d','a','t','e','I','n','i','s',0};
83 static const WCHAR CopyINF[]    = {'C','o','p','y','I','N','F',0};
84 static const WCHAR AddService[] = {'A','d','d','S','e','r','v','i','c','e',0};
85 static const WCHAR DelService[] = {'D','e','l','S','e','r','v','i','c','e',0};
86 static const WCHAR UpdateIniFields[] = {'U','p','d','a','t','e','I','n','i','F','i','e','l','d','s',0};
87 static const WCHAR RegisterDlls[]    = {'R','e','g','i','s','t','e','r','D','l','l','s',0};
88 static const WCHAR UnregisterDlls[]  = {'U','n','r','e','g','i','s','t','e','r','D','l','l','s',0};
89 static const WCHAR ProfileItems[]    = {'P','r','o','f','i','l','e','I','t','e','m','s',0};
90 static const WCHAR Name[]            = {'N','a','m','e',0};
91 static const WCHAR CmdLine[]         = {'C','m','d','L','i','n','e',0};
92 static const WCHAR SubDir[]          = {'S','u','b','D','i','r',0};
93 static const WCHAR WineFakeDlls[]    = {'W','i','n','e','F','a','k','e','D','l','l','s',0};
94 static const WCHAR DisplayName[]     = {'D','i','s','p','l','a','y','N','a','m','e',0};
95 static const WCHAR Description[]     = {'D','e','s','c','r','i','p','t','i','o','n',0};
96 static const WCHAR ServiceBinary[]   = {'S','e','r','v','i','c','e','B','i','n','a','r','y',0};
97 static const WCHAR StartName[]       = {'S','t','a','r','t','N','a','m','e',0};
98 static const WCHAR LoadOrderGroup[]  = {'L','o','a','d','O','r','d','e','r','G','r','o','u','p',0};
99 static const WCHAR ServiceType[]     = {'S','e','r','v','i','c','e','T','y','p','e',0};
100 static const WCHAR StartType[]       = {'S','t','a','r','t','T','y','p','e',0};
101 static const WCHAR ErrorControl[]    = {'E','r','r','o','r','C','o','n','t','r','o','l',0};
102
103 static const WCHAR ServicesKey[] = {'S','y','s','t','e','m','\\',
104                         'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
105                         'S','e','r','v','i','c','e','s',0};
106
107 /***********************************************************************
108  *            get_field_string
109  *
110  * Retrieve the contents of a field, dynamically growing the buffer if necessary.
111  */
112 static WCHAR *get_field_string( INFCONTEXT *context, DWORD index, WCHAR *buffer,
113                                 WCHAR *static_buffer, DWORD *size )
114 {
115     DWORD required;
116
117     if (SetupGetStringFieldW( context, index, buffer, *size, &required )) return buffer;
118     if (GetLastError() == ERROR_INSUFFICIENT_BUFFER)
119     {
120         /* now grow the buffer */
121         if (buffer != static_buffer) HeapFree( GetProcessHeap(), 0, buffer );
122         if (!(buffer = HeapAlloc( GetProcessHeap(), 0, required*sizeof(WCHAR) ))) return NULL;
123         *size = required;
124         if (SetupGetStringFieldW( context, index, buffer, *size, &required )) return buffer;
125     }
126     if (buffer != static_buffer) HeapFree( GetProcessHeap(), 0, buffer );
127     return NULL;
128 }
129
130
131 /***********************************************************************
132  *            dup_section_line_field
133  *
134  * Retrieve the contents of a field in a newly-allocated buffer.
135  */
136 static WCHAR *dup_section_line_field( HINF hinf, const WCHAR *section, const WCHAR *line, DWORD index )
137 {
138     INFCONTEXT context;
139     DWORD size;
140     WCHAR *buffer;
141
142     if (!SetupFindFirstLineW( hinf, section, line, &context )) return NULL;
143     if (!SetupGetStringFieldW( &context, index, NULL, 0, &size )) return NULL;
144     if (!(buffer = HeapAlloc( GetProcessHeap(), 0, size * sizeof(WCHAR) ))) return NULL;
145     if (!SetupGetStringFieldW( &context, index, buffer, size, NULL )) buffer[0] = 0;
146     return buffer;
147 }
148
149 /***********************************************************************
150  *            copy_files_callback
151  *
152  * Called once for each CopyFiles entry in a given section.
153  */
154 static BOOL copy_files_callback( HINF hinf, PCWSTR field, void *arg )
155 {
156     struct files_callback_info *info = arg;
157
158     if (field[0] == '@')  /* special case: copy single file */
159         SetupQueueDefaultCopyW( info->queue, info->layout ? info->layout : hinf, info->src_root, NULL, field+1, info->copy_flags );
160     else
161         SetupQueueCopySectionW( info->queue, info->src_root, info->layout ? info->layout : hinf, hinf, field, info->copy_flags );
162     return TRUE;
163 }
164
165
166 /***********************************************************************
167  *            delete_files_callback
168  *
169  * Called once for each DelFiles entry in a given section.
170  */
171 static BOOL delete_files_callback( HINF hinf, PCWSTR field, void *arg )
172 {
173     struct files_callback_info *info = arg;
174     SetupQueueDeleteSectionW( info->queue, hinf, 0, field );
175     return TRUE;
176 }
177
178
179 /***********************************************************************
180  *            rename_files_callback
181  *
182  * Called once for each RenFiles entry in a given section.
183  */
184 static BOOL rename_files_callback( HINF hinf, PCWSTR field, void *arg )
185 {
186     struct files_callback_info *info = arg;
187     SetupQueueRenameSectionW( info->queue, hinf, 0, field );
188     return TRUE;
189 }
190
191
192 /***********************************************************************
193  *            get_root_key
194  *
195  * Retrieve the registry root key from its name.
196  */
197 static HKEY get_root_key( const WCHAR *name, HKEY def_root )
198 {
199     static const WCHAR HKCR[] = {'H','K','C','R',0};
200     static const WCHAR HKCU[] = {'H','K','C','U',0};
201     static const WCHAR HKLM[] = {'H','K','L','M',0};
202     static const WCHAR HKU[]  = {'H','K','U',0};
203     static const WCHAR HKR[]  = {'H','K','R',0};
204
205     if (!strcmpiW( name, HKCR )) return HKEY_CLASSES_ROOT;
206     if (!strcmpiW( name, HKCU )) return HKEY_CURRENT_USER;
207     if (!strcmpiW( name, HKLM )) return HKEY_LOCAL_MACHINE;
208     if (!strcmpiW( name, HKU )) return HKEY_USERS;
209     if (!strcmpiW( name, HKR )) return def_root;
210     return 0;
211 }
212
213
214 /***********************************************************************
215  *            append_multi_sz_value
216  *
217  * Append a multisz string to a multisz registry value.
218  */
219 static void append_multi_sz_value( HKEY hkey, const WCHAR *value, const WCHAR *strings,
220                                    DWORD str_size )
221 {
222     DWORD size, type, total;
223     WCHAR *buffer, *p;
224
225     if (RegQueryValueExW( hkey, value, NULL, &type, NULL, &size )) return;
226     if (type != REG_MULTI_SZ) return;
227
228     if (!(buffer = HeapAlloc( GetProcessHeap(), 0, (size + str_size) * sizeof(WCHAR) ))) return;
229     if (RegQueryValueExW( hkey, value, NULL, NULL, (BYTE *)buffer, &size )) goto done;
230
231     /* compare each string against all the existing ones */
232     total = size;
233     while (*strings)
234     {
235         int len = strlenW(strings) + 1;
236
237         for (p = buffer; *p; p += strlenW(p) + 1)
238             if (!strcmpiW( p, strings )) break;
239
240         if (!*p)  /* not found, need to append it */
241         {
242             memcpy( p, strings, len * sizeof(WCHAR) );
243             p[len] = 0;
244             total += len;
245         }
246         strings += len;
247     }
248     if (total != size)
249     {
250         TRACE( "setting value %s to %s\n", debugstr_w(value), debugstr_w(buffer) );
251         RegSetValueExW( hkey, value, 0, REG_MULTI_SZ, (BYTE *)buffer, total );
252     }
253  done:
254     HeapFree( GetProcessHeap(), 0, buffer );
255 }
256
257
258 /***********************************************************************
259  *            delete_multi_sz_value
260  *
261  * Remove a string from a multisz registry value.
262  */
263 static void delete_multi_sz_value( HKEY hkey, const WCHAR *value, const WCHAR *string )
264 {
265     DWORD size, type;
266     WCHAR *buffer, *src, *dst;
267
268     if (RegQueryValueExW( hkey, value, NULL, &type, NULL, &size )) return;
269     if (type != REG_MULTI_SZ) return;
270     /* allocate double the size, one for value before and one for after */
271     if (!(buffer = HeapAlloc( GetProcessHeap(), 0, size * 2 * sizeof(WCHAR) ))) return;
272     if (RegQueryValueExW( hkey, value, NULL, NULL, (BYTE *)buffer, &size )) goto done;
273     src = buffer;
274     dst = buffer + size;
275     while (*src)
276     {
277         int len = strlenW(src) + 1;
278         if (strcmpiW( src, string ))
279         {
280             memcpy( dst, src, len * sizeof(WCHAR) );
281             dst += len;
282         }
283         src += len;
284     }
285     *dst++ = 0;
286     if (dst != buffer + 2*size)  /* did we remove something? */
287     {
288         TRACE( "setting value %s to %s\n", debugstr_w(value), debugstr_w(buffer + size) );
289         RegSetValueExW( hkey, value, 0, REG_MULTI_SZ,
290                         (BYTE *)(buffer + size), dst - (buffer + size) );
291     }
292  done:
293     HeapFree( GetProcessHeap(), 0, buffer );
294 }
295
296
297 /***********************************************************************
298  *            do_reg_operation
299  *
300  * Perform an add/delete registry operation depending on the flags.
301  */
302 static BOOL do_reg_operation( HKEY hkey, const WCHAR *value, INFCONTEXT *context, INT flags )
303 {
304     DWORD type, size;
305
306     if (flags & (FLG_ADDREG_DELREG_BIT | FLG_ADDREG_DELVAL))  /* deletion */
307     {
308         if (*value && !(flags & FLG_DELREG_KEYONLY_COMMON))
309         {
310             if ((flags & FLG_DELREG_MULTI_SZ_DELSTRING) == FLG_DELREG_MULTI_SZ_DELSTRING)
311             {
312                 WCHAR *str;
313
314                 if (!SetupGetStringFieldW( context, 5, NULL, 0, &size ) || !size) return TRUE;
315                 if (!(str = HeapAlloc( GetProcessHeap(), 0, size * sizeof(WCHAR) ))) return FALSE;
316                 SetupGetStringFieldW( context, 5, str, size, NULL );
317                 delete_multi_sz_value( hkey, value, str );
318                 HeapFree( GetProcessHeap(), 0, str );
319             }
320             else RegDeleteValueW( hkey, value );
321         }
322         else NtDeleteKey( hkey );
323         return TRUE;
324     }
325
326     if (flags & (FLG_ADDREG_KEYONLY|FLG_ADDREG_KEYONLY_COMMON)) return TRUE;
327
328     if (flags & (FLG_ADDREG_NOCLOBBER|FLG_ADDREG_OVERWRITEONLY))
329     {
330         BOOL exists = !RegQueryValueExW( hkey, value, NULL, NULL, NULL, NULL );
331         if (exists && (flags & FLG_ADDREG_NOCLOBBER)) return TRUE;
332         if (!exists && (flags & FLG_ADDREG_OVERWRITEONLY)) return TRUE;
333     }
334
335     switch(flags & FLG_ADDREG_TYPE_MASK)
336     {
337     case FLG_ADDREG_TYPE_SZ:        type = REG_SZ; break;
338     case FLG_ADDREG_TYPE_MULTI_SZ:  type = REG_MULTI_SZ; break;
339     case FLG_ADDREG_TYPE_EXPAND_SZ: type = REG_EXPAND_SZ; break;
340     case FLG_ADDREG_TYPE_BINARY:    type = REG_BINARY; break;
341     case FLG_ADDREG_TYPE_DWORD:     type = REG_DWORD; break;
342     case FLG_ADDREG_TYPE_NONE:      type = REG_NONE; break;
343     default:                        type = flags >> 16; break;
344     }
345
346     if (!(flags & FLG_ADDREG_BINVALUETYPE) ||
347         (type == REG_DWORD && SetupGetFieldCount(context) == 5))
348     {
349         static const WCHAR empty;
350         WCHAR *str = NULL;
351
352         if (type == REG_MULTI_SZ)
353         {
354             if (!SetupGetMultiSzFieldW( context, 5, NULL, 0, &size )) size = 0;
355             if (size)
356             {
357                 if (!(str = HeapAlloc( GetProcessHeap(), 0, size * sizeof(WCHAR) ))) return FALSE;
358                 SetupGetMultiSzFieldW( context, 5, str, size, NULL );
359             }
360             if (flags & FLG_ADDREG_APPEND)
361             {
362                 if (!str) return TRUE;
363                 append_multi_sz_value( hkey, value, str, size );
364                 HeapFree( GetProcessHeap(), 0, str );
365                 return TRUE;
366             }
367             /* else fall through to normal string handling */
368         }
369         else
370         {
371             if (!SetupGetStringFieldW( context, 5, NULL, 0, &size )) size = 0;
372             if (size)
373             {
374                 if (!(str = HeapAlloc( GetProcessHeap(), 0, size * sizeof(WCHAR) ))) return FALSE;
375                 SetupGetStringFieldW( context, 5, str, size, NULL );
376                 if (type == REG_LINK) size--;  /* no terminating null for symlinks */
377             }
378         }
379
380         if (type == REG_DWORD)
381         {
382             DWORD dw = str ? strtoulW( str, NULL, 0 ) : 0;
383             TRACE( "setting dword %s to %x\n", debugstr_w(value), dw );
384             RegSetValueExW( hkey, value, 0, type, (BYTE *)&dw, sizeof(dw) );
385         }
386         else
387         {
388             TRACE( "setting value %s to %s\n", debugstr_w(value), debugstr_w(str) );
389             if (str) RegSetValueExW( hkey, value, 0, type, (BYTE *)str, size * sizeof(WCHAR) );
390             else RegSetValueExW( hkey, value, 0, type, (const BYTE *)&empty, sizeof(WCHAR) );
391         }
392         HeapFree( GetProcessHeap(), 0, str );
393         return TRUE;
394     }
395     else  /* get the binary data */
396     {
397         BYTE *data = NULL;
398
399         if (!SetupGetBinaryField( context, 5, NULL, 0, &size )) size = 0;
400         if (size)
401         {
402             if (!(data = HeapAlloc( GetProcessHeap(), 0, size ))) return FALSE;
403             TRACE( "setting binary data %s len %d\n", debugstr_w(value), size );
404             SetupGetBinaryField( context, 5, data, size, NULL );
405         }
406         RegSetValueExW( hkey, value, 0, type, data, size );
407         HeapFree( GetProcessHeap(), 0, data );
408         return TRUE;
409     }
410 }
411
412
413 /***********************************************************************
414  *            registry_callback
415  *
416  * Called once for each AddReg and DelReg entry in a given section.
417  */
418 static BOOL registry_callback( HINF hinf, PCWSTR field, void *arg )
419 {
420     struct registry_callback_info *info = arg;
421     INFCONTEXT context;
422     HKEY root_key, hkey;
423
424     BOOL ok = SetupFindFirstLineW( hinf, field, NULL, &context );
425
426     for (; ok; ok = SetupFindNextLine( &context, &context ))
427     {
428         DWORD options = 0;
429         WCHAR buffer[MAX_INF_STRING_LENGTH];
430         INT flags;
431
432         /* get root */
433         if (!SetupGetStringFieldW( &context, 1, buffer, sizeof(buffer)/sizeof(WCHAR), NULL ))
434             continue;
435         if (!(root_key = get_root_key( buffer, info->default_root )))
436             continue;
437
438         /* get key */
439         if (!SetupGetStringFieldW( &context, 2, buffer, sizeof(buffer)/sizeof(WCHAR), NULL ))
440             *buffer = 0;
441
442         /* get flags */
443         if (!SetupGetIntField( &context, 4, &flags )) flags = 0;
444
445         if (!info->delete)
446         {
447             if (flags & FLG_ADDREG_DELREG_BIT) continue;  /* ignore this entry */
448         }
449         else
450         {
451             if (!flags) flags = FLG_ADDREG_DELREG_BIT;
452             else if (!(flags & FLG_ADDREG_DELREG_BIT)) continue;  /* ignore this entry */
453         }
454         /* Wine extension: magic support for symlinks */
455         if (flags >> 16 == REG_LINK) options = REG_OPTION_OPEN_LINK | REG_OPTION_CREATE_LINK;
456
457         if (info->delete || (flags & FLG_ADDREG_OVERWRITEONLY))
458         {
459             if (RegOpenKeyExW( root_key, buffer, options, MAXIMUM_ALLOWED, &hkey ))
460                 continue;  /* ignore if it doesn't exist */
461         }
462         else
463         {
464             DWORD res = RegCreateKeyExW( root_key, buffer, 0, NULL, options,
465                                          MAXIMUM_ALLOWED, NULL, &hkey, NULL );
466             if (res == ERROR_ALREADY_EXISTS && (options & REG_OPTION_CREATE_LINK))
467                 res = RegCreateKeyExW( root_key, buffer, 0, NULL, REG_OPTION_OPEN_LINK,
468                                        MAXIMUM_ALLOWED, NULL, &hkey, NULL );
469             if (res)
470             {
471                 ERR( "could not create key %p %s\n", root_key, debugstr_w(buffer) );
472                 continue;
473             }
474         }
475         TRACE( "key %p %s\n", root_key, debugstr_w(buffer) );
476
477         /* get value name */
478         if (!SetupGetStringFieldW( &context, 3, buffer, sizeof(buffer)/sizeof(WCHAR), NULL ))
479             *buffer = 0;
480
481         /* and now do it */
482         if (!do_reg_operation( hkey, buffer, &context, flags ))
483         {
484             RegCloseKey( hkey );
485             return FALSE;
486         }
487         RegCloseKey( hkey );
488     }
489     return TRUE;
490 }
491
492
493 /***********************************************************************
494  *            do_register_dll
495  *
496  * Register or unregister a dll.
497  */
498 static BOOL do_register_dll( struct register_dll_info *info, const WCHAR *path,
499                              INT flags, INT timeout, const WCHAR *args )
500 {
501     HMODULE module;
502     HRESULT res;
503     SP_REGISTER_CONTROL_STATUSW status;
504     IMAGE_NT_HEADERS *nt;
505
506     status.cbSize = sizeof(status);
507     status.FileName = path;
508     status.FailureCode = SPREG_SUCCESS;
509     status.Win32Error = ERROR_SUCCESS;
510
511     if (info->callback)
512     {
513         switch(info->callback( info->callback_context, SPFILENOTIFY_STARTREGISTRATION,
514                                (UINT_PTR)&status, !info->unregister ))
515         {
516         case FILEOP_ABORT:
517             SetLastError( ERROR_OPERATION_ABORTED );
518             return FALSE;
519         case FILEOP_SKIP:
520             return TRUE;
521         case FILEOP_DOIT:
522             break;
523         }
524     }
525
526     if (!(module = LoadLibraryExW( path, 0, LOAD_WITH_ALTERED_SEARCH_PATH )))
527     {
528         WARN( "could not load %s\n", debugstr_w(path) );
529         status.FailureCode = SPREG_LOADLIBRARY;
530         status.Win32Error = GetLastError();
531         goto done;
532     }
533
534     if ((nt = RtlImageNtHeader( module )) && !(nt->FileHeader.Characteristics & IMAGE_FILE_DLL))
535     {
536         /* file is an executable, not a dll */
537         STARTUPINFOW startup;
538         PROCESS_INFORMATION process_info;
539         WCHAR *cmd_line;
540         BOOL res;
541         static const WCHAR format[] = {'"','%','s','"',' ','%','s',0};
542         static const WCHAR default_args[] = {'/','R','e','g','S','e','r','v','e','r',0};
543
544         FreeLibrary( module );
545         module = NULL;
546         if (!args) args = default_args;
547         cmd_line = HeapAlloc( GetProcessHeap(), 0, (strlenW(path) + strlenW(args) + 4) * sizeof(WCHAR) );
548         sprintfW( cmd_line, format, path, args );
549         memset( &startup, 0, sizeof(startup) );
550         startup.cb = sizeof(startup);
551         TRACE( "executing %s\n", debugstr_w(cmd_line) );
552         res = CreateProcessW( NULL, cmd_line, NULL, NULL, FALSE, 0, NULL, NULL, &startup, &process_info );
553         HeapFree( GetProcessHeap(), 0, cmd_line );
554         if (!res)
555         {
556             status.FailureCode = SPREG_LOADLIBRARY;
557             status.Win32Error = GetLastError();
558             goto done;
559         }
560         CloseHandle( process_info.hThread );
561
562         if (WaitForSingleObject( process_info.hProcess, timeout*1000 ) == WAIT_TIMEOUT)
563         {
564             /* timed out, kill the process */
565             TerminateProcess( process_info.hProcess, 1 );
566             status.FailureCode = SPREG_TIMEOUT;
567             status.Win32Error = ERROR_TIMEOUT;
568         }
569         CloseHandle( process_info.hProcess );
570         goto done;
571     }
572
573     if (flags & FLG_REGSVR_DLLREGISTER)
574     {
575         const char *entry_point = info->unregister ? "DllUnregisterServer" : "DllRegisterServer";
576         HRESULT (WINAPI *func)(void) = (void *)GetProcAddress( module, entry_point );
577
578         if (!func)
579         {
580             status.FailureCode = SPREG_GETPROCADDR;
581             status.Win32Error = GetLastError();
582             goto done;
583         }
584
585         TRACE( "calling %s in %s\n", entry_point, debugstr_w(path) );
586         res = func();
587
588         if (FAILED(res))
589         {
590             WARN( "calling %s in %s returned error %x\n", entry_point, debugstr_w(path), res );
591             status.FailureCode = SPREG_REGSVR;
592             status.Win32Error = res;
593             goto done;
594         }
595     }
596
597     if (flags & FLG_REGSVR_DLLINSTALL)
598     {
599         HRESULT (WINAPI *func)(BOOL,LPCWSTR) = (void *)GetProcAddress( module, "DllInstall" );
600
601         if (!func)
602         {
603             status.FailureCode = SPREG_GETPROCADDR;
604             status.Win32Error = GetLastError();
605             goto done;
606         }
607
608         TRACE( "calling DllInstall(%d,%s) in %s\n",
609                !info->unregister, debugstr_w(args), debugstr_w(path) );
610         res = func( !info->unregister, args );
611
612         if (FAILED(res))
613         {
614             WARN( "calling DllInstall in %s returned error %x\n", debugstr_w(path), res );
615             status.FailureCode = SPREG_REGSVR;
616             status.Win32Error = res;
617             goto done;
618         }
619     }
620
621 done:
622     if (module)
623     {
624         if (info->modules_count >= info->modules_size)
625         {
626             int new_size = max( 32, info->modules_size * 2 );
627             HMODULE *new = info->modules ?
628                 HeapReAlloc( GetProcessHeap(), 0, info->modules, new_size * sizeof(*new) ) :
629                 HeapAlloc( GetProcessHeap(), 0, new_size * sizeof(*new) );
630             if (new)
631             {
632                 info->modules_size = new_size;
633                 info->modules = new;
634             }
635         }
636         if (info->modules_count < info->modules_size) info->modules[info->modules_count++] = module;
637         else FreeLibrary( module );
638     }
639     if (info->callback) info->callback( info->callback_context, SPFILENOTIFY_ENDREGISTRATION,
640                                         (UINT_PTR)&status, !info->unregister );
641     return TRUE;
642 }
643
644
645 /***********************************************************************
646  *            register_dlls_callback
647  *
648  * Called once for each RegisterDlls entry in a given section.
649  */
650 static BOOL register_dlls_callback( HINF hinf, PCWSTR field, void *arg )
651 {
652     struct register_dll_info *info = arg;
653     INFCONTEXT context;
654     BOOL ret = TRUE;
655     BOOL ok = SetupFindFirstLineW( hinf, field, NULL, &context );
656
657     for (; ok; ok = SetupFindNextLine( &context, &context ))
658     {
659         WCHAR *path, *args, *p;
660         WCHAR buffer[MAX_INF_STRING_LENGTH];
661         INT flags, timeout;
662
663         /* get directory */
664         if (!(path = PARSER_get_dest_dir( &context ))) continue;
665
666         /* get dll name */
667         if (!SetupGetStringFieldW( &context, 3, buffer, sizeof(buffer)/sizeof(WCHAR), NULL ))
668             goto done;
669         if (!(p = HeapReAlloc( GetProcessHeap(), 0, path,
670                                (strlenW(path) + strlenW(buffer) + 2) * sizeof(WCHAR) ))) goto done;
671         path = p;
672         p += strlenW(p);
673         if (p == path || p[-1] != '\\') *p++ = '\\';
674         strcpyW( p, buffer );
675
676         /* get flags */
677         if (!SetupGetIntField( &context, 4, &flags )) flags = 0;
678
679         /* get timeout */
680         if (!SetupGetIntField( &context, 5, &timeout )) timeout = 60;
681
682         /* get command line */
683         args = NULL;
684         if (SetupGetStringFieldW( &context, 6, buffer, sizeof(buffer)/sizeof(WCHAR), NULL ))
685             args = buffer;
686
687         ret = do_register_dll( info, path, flags, timeout, args );
688
689     done:
690         HeapFree( GetProcessHeap(), 0, path );
691         if (!ret) break;
692     }
693     return ret;
694 }
695
696 /***********************************************************************
697  *            fake_dlls_callback
698  *
699  * Called once for each WineFakeDlls entry in a given section.
700  */
701 static BOOL fake_dlls_callback( HINF hinf, PCWSTR field, void *arg )
702 {
703     INFCONTEXT context;
704     BOOL ret = TRUE;
705     BOOL ok = SetupFindFirstLineW( hinf, field, NULL, &context );
706
707     for (; ok; ok = SetupFindNextLine( &context, &context ))
708     {
709         WCHAR *path, *p;
710         WCHAR buffer[MAX_INF_STRING_LENGTH];
711
712         /* get directory */
713         if (!(path = PARSER_get_dest_dir( &context ))) continue;
714
715         /* get dll name */
716         if (!SetupGetStringFieldW( &context, 3, buffer, sizeof(buffer)/sizeof(WCHAR), NULL ))
717             goto done;
718         if (!(p = HeapReAlloc( GetProcessHeap(), 0, path,
719                                (strlenW(path) + strlenW(buffer) + 2) * sizeof(WCHAR) ))) goto done;
720         path = p;
721         p += strlenW(p);
722         if (p == path || p[-1] != '\\') *p++ = '\\';
723         strcpyW( p, buffer );
724
725         /* get source dll */
726         if (SetupGetStringFieldW( &context, 4, buffer, sizeof(buffer)/sizeof(WCHAR), NULL ))
727             p = buffer;  /* otherwise use target base name as default source */
728
729         create_fake_dll( path, p );  /* ignore errors */
730
731     done:
732         HeapFree( GetProcessHeap(), 0, path );
733         if (!ret) break;
734     }
735     return ret;
736 }
737
738 /***********************************************************************
739  *            update_ini_callback
740  *
741  * Called once for each UpdateInis entry in a given section.
742  */
743 static BOOL update_ini_callback( HINF hinf, PCWSTR field, void *arg )
744 {
745     INFCONTEXT context;
746
747     BOOL ok = SetupFindFirstLineW( hinf, field, NULL, &context );
748
749     for (; ok; ok = SetupFindNextLine( &context, &context ))
750     {
751         WCHAR buffer[MAX_INF_STRING_LENGTH];
752         WCHAR  filename[MAX_INF_STRING_LENGTH];
753         WCHAR  section[MAX_INF_STRING_LENGTH];
754         WCHAR  entry[MAX_INF_STRING_LENGTH];
755         WCHAR  string[MAX_INF_STRING_LENGTH];
756         LPWSTR divider;
757
758         if (!SetupGetStringFieldW( &context, 1, filename,
759                                    sizeof(filename)/sizeof(WCHAR), NULL ))
760             continue;
761
762         if (!SetupGetStringFieldW( &context, 2, section,
763                                    sizeof(section)/sizeof(WCHAR), NULL ))
764             continue;
765
766         if (!SetupGetStringFieldW( &context, 4, buffer,
767                                    sizeof(buffer)/sizeof(WCHAR), NULL ))
768             continue;
769
770         divider = strchrW(buffer,'=');
771         if (divider)
772         {
773             *divider = 0;
774             strcpyW(entry,buffer);
775             divider++;
776             strcpyW(string,divider);
777         }
778         else
779         {
780             strcpyW(entry,buffer);
781             string[0]=0;
782         }
783
784         TRACE("Writing %s = %s in %s of file %s\n",debugstr_w(entry),
785                debugstr_w(string),debugstr_w(section),debugstr_w(filename));
786         WritePrivateProfileStringW(section,entry,string,filename);
787
788     }
789     return TRUE;
790 }
791
792 static BOOL update_ini_fields_callback( HINF hinf, PCWSTR field, void *arg )
793 {
794     FIXME( "should update ini fields %s\n", debugstr_w(field) );
795     return TRUE;
796 }
797
798 static BOOL ini2reg_callback( HINF hinf, PCWSTR field, void *arg )
799 {
800     FIXME( "should do ini2reg %s\n", debugstr_w(field) );
801     return TRUE;
802 }
803
804 static BOOL logconf_callback( HINF hinf, PCWSTR field, void *arg )
805 {
806     FIXME( "should do logconf %s\n", debugstr_w(field) );
807     return TRUE;
808 }
809
810 static BOOL bitreg_callback( HINF hinf, PCWSTR field, void *arg )
811 {
812     FIXME( "should do bitreg %s\n", debugstr_w(field) );
813     return TRUE;
814 }
815
816 static BOOL profile_items_callback( HINF hinf, PCWSTR field, void *arg )
817 {
818     WCHAR lnkpath[MAX_PATH];
819     LPWSTR cmdline=NULL, lnkpath_end;
820     unsigned int name_size;
821     INFCONTEXT name_context, context;
822     int attrs=0;
823
824     static const WCHAR dotlnk[] = {'.','l','n','k',0};
825
826     TRACE( "(%s)\n", debugstr_w(field) );
827
828     if (SetupFindFirstLineW( hinf, field, Name, &name_context ))
829     {
830         SetupGetIntField( &name_context, 2, &attrs );
831         if (attrs & ~FLG_PROFITEM_GROUP) FIXME( "unhandled attributes: %x\n", attrs );
832     }
833     else return TRUE;
834
835     /* calculate filename */
836     SHGetFolderPathW( NULL, CSIDL_COMMON_PROGRAMS, NULL, SHGFP_TYPE_CURRENT, lnkpath );
837     lnkpath_end = lnkpath + strlenW(lnkpath);
838     if (lnkpath_end[-1] != '\\') *lnkpath_end++ = '\\';
839
840     if (!(attrs & FLG_PROFITEM_GROUP) && SetupFindFirstLineW( hinf, field, SubDir, &context ))
841     {
842         unsigned int subdir_size;
843
844         if (!SetupGetStringFieldW( &context, 1, lnkpath_end, (lnkpath+MAX_PATH)-lnkpath_end, &subdir_size ))
845             return TRUE;
846
847         lnkpath_end += subdir_size - 1;
848         if (lnkpath_end[-1] != '\\') *lnkpath_end++ = '\\';
849     }
850
851     if (!SetupGetStringFieldW( &name_context, 1, lnkpath_end, (lnkpath+MAX_PATH)-lnkpath_end, &name_size ))
852         return TRUE;
853
854     lnkpath_end += name_size - 1;
855
856     if (attrs & FLG_PROFITEM_GROUP)
857     {
858         SHPathPrepareForWriteW( NULL, NULL, lnkpath, SHPPFW_DIRCREATE );
859     }
860     else
861     {
862         IShellLinkW* shelllink=NULL;
863         IPersistFile* persistfile=NULL;
864         HRESULT initresult=E_FAIL;
865
866         if (lnkpath+MAX_PATH < lnkpath_end + 5) return TRUE;
867         strcpyW( lnkpath_end, dotlnk );
868
869         TRACE( "link path: %s\n", debugstr_w(lnkpath) );
870
871         /* calculate command line */
872         if (SetupFindFirstLineW( hinf, field, CmdLine, &context ))
873         {
874             unsigned int dir_len=0, subdir_size=0, filename_size=0;
875             int dirid=0;
876             LPCWSTR dir;
877             LPWSTR cmdline_end;
878
879             SetupGetIntField( &context, 1, &dirid );
880             dir = DIRID_get_string( dirid );
881
882             if (dir) dir_len = strlenW(dir);
883
884             SetupGetStringFieldW( &context, 2, NULL, 0, &subdir_size );
885             SetupGetStringFieldW( &context, 3, NULL, 0, &filename_size );
886
887             if (dir_len && filename_size)
888             {
889                 cmdline = cmdline_end = HeapAlloc( GetProcessHeap(), 0, sizeof(WCHAR) * (dir_len+subdir_size+filename_size+1) );
890
891                 strcpyW( cmdline_end, dir );
892                 cmdline_end += dir_len;
893                 if (cmdline_end[-1] != '\\') *cmdline_end++ = '\\';
894
895                 if (subdir_size)
896                 {
897                     SetupGetStringFieldW( &context, 2, cmdline_end, subdir_size, NULL );
898                     cmdline_end += subdir_size-1;
899                     if (cmdline_end[-1] != '\\') *cmdline_end++ = '\\';
900                 }
901                 SetupGetStringFieldW( &context, 3, cmdline_end, filename_size, NULL );
902                 TRACE( "cmdline: %s\n", debugstr_w(cmdline));
903             }
904         }
905
906         if (!cmdline) return TRUE;
907
908         initresult = CoInitialize(NULL);
909
910         if (FAILED(CoCreateInstance( &CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER,
911                                      &IID_IShellLinkW, (LPVOID*)&shelllink )))
912             goto done;
913
914         IShellLinkW_SetPath( shelllink, cmdline );
915         SHPathPrepareForWriteW( NULL, NULL, lnkpath, SHPPFW_DIRCREATE|SHPPFW_IGNOREFILENAME );
916         if (SUCCEEDED(IShellLinkW_QueryInterface( shelllink, &IID_IPersistFile, (LPVOID*)&persistfile)))
917         {
918             TRACE( "writing link: %s\n", debugstr_w(lnkpath) );
919             IPersistFile_Save( persistfile, lnkpath, FALSE );
920             IPersistFile_Release( persistfile );
921         }
922         IShellLinkW_Release( shelllink );
923
924     done:
925         if (SUCCEEDED(initresult)) CoUninitialize();
926         HeapFree( GetProcessHeap(), 0, cmdline );
927     }
928
929     return TRUE;
930 }
931
932 static BOOL copy_inf_callback( HINF hinf, PCWSTR field, void *arg )
933 {
934     FIXME( "should do copy inf %s\n", debugstr_w(field) );
935     return TRUE;
936 }
937
938
939 /***********************************************************************
940  *            iterate_section_fields
941  *
942  * Iterate over all fields of a certain key of a certain section
943  */
944 static BOOL iterate_section_fields( HINF hinf, PCWSTR section, PCWSTR key,
945                                     iterate_fields_func callback, void *arg )
946 {
947     WCHAR static_buffer[200];
948     WCHAR *buffer = static_buffer;
949     DWORD size = sizeof(static_buffer)/sizeof(WCHAR);
950     INFCONTEXT context;
951     BOOL ret = FALSE;
952
953     BOOL ok = SetupFindFirstLineW( hinf, section, key, &context );
954     while (ok)
955     {
956         UINT i, count = SetupGetFieldCount( &context );
957         for (i = 1; i <= count; i++)
958         {
959             if (!(buffer = get_field_string( &context, i, buffer, static_buffer, &size )))
960                 goto done;
961             if (!callback( hinf, buffer, arg ))
962             {
963                 WARN("callback failed for %s %s err %d\n",
964                      debugstr_w(section), debugstr_w(buffer), GetLastError() );
965                 goto done;
966             }
967         }
968         ok = SetupFindNextMatchLineW( &context, key, &context );
969     }
970     ret = TRUE;
971  done:
972     if (buffer != static_buffer) HeapFree( GetProcessHeap(), 0, buffer );
973     return ret;
974 }
975
976
977 /***********************************************************************
978  *            SetupInstallFilesFromInfSectionA   (SETUPAPI.@)
979  */
980 BOOL WINAPI SetupInstallFilesFromInfSectionA( HINF hinf, HINF hlayout, HSPFILEQ queue,
981                                               PCSTR section, PCSTR src_root, UINT flags )
982 {
983     UNICODE_STRING sectionW;
984     BOOL ret = FALSE;
985
986     if (!RtlCreateUnicodeStringFromAsciiz( &sectionW, section ))
987     {
988         SetLastError( ERROR_NOT_ENOUGH_MEMORY );
989         return FALSE;
990     }
991     if (!src_root)
992         ret = SetupInstallFilesFromInfSectionW( hinf, hlayout, queue, sectionW.Buffer,
993                                                 NULL, flags );
994     else
995     {
996         UNICODE_STRING srcW;
997         if (RtlCreateUnicodeStringFromAsciiz( &srcW, src_root ))
998         {
999             ret = SetupInstallFilesFromInfSectionW( hinf, hlayout, queue, sectionW.Buffer,
1000                                                     srcW.Buffer, flags );
1001             RtlFreeUnicodeString( &srcW );
1002         }
1003         else SetLastError( ERROR_NOT_ENOUGH_MEMORY );
1004     }
1005     RtlFreeUnicodeString( &sectionW );
1006     return ret;
1007 }
1008
1009
1010 /***********************************************************************
1011  *            SetupInstallFilesFromInfSectionW   (SETUPAPI.@)
1012  */
1013 BOOL WINAPI SetupInstallFilesFromInfSectionW( HINF hinf, HINF hlayout, HSPFILEQ queue,
1014                                               PCWSTR section, PCWSTR src_root, UINT flags )
1015 {
1016     struct files_callback_info info;
1017
1018     info.queue      = queue;
1019     info.src_root   = src_root;
1020     info.copy_flags = flags;
1021     info.layout     = hlayout;
1022     return iterate_section_fields( hinf, section, CopyFiles, copy_files_callback, &info );
1023 }
1024
1025
1026 /***********************************************************************
1027  *            SetupInstallFromInfSectionA   (SETUPAPI.@)
1028  */
1029 BOOL WINAPI SetupInstallFromInfSectionA( HWND owner, HINF hinf, PCSTR section, UINT flags,
1030                                          HKEY key_root, PCSTR src_root, UINT copy_flags,
1031                                          PSP_FILE_CALLBACK_A callback, PVOID context,
1032                                          HDEVINFO devinfo, PSP_DEVINFO_DATA devinfo_data )
1033 {
1034     UNICODE_STRING sectionW, src_rootW;
1035     struct callback_WtoA_context ctx;
1036     BOOL ret = FALSE;
1037
1038     src_rootW.Buffer = NULL;
1039     if (src_root && !RtlCreateUnicodeStringFromAsciiz( &src_rootW, src_root ))
1040     {
1041         SetLastError( ERROR_NOT_ENOUGH_MEMORY );
1042         return FALSE;
1043     }
1044
1045     if (RtlCreateUnicodeStringFromAsciiz( &sectionW, section ))
1046     {
1047         ctx.orig_context = context;
1048         ctx.orig_handler = callback;
1049         ret = SetupInstallFromInfSectionW( owner, hinf, sectionW.Buffer, flags, key_root,
1050                                            src_rootW.Buffer, copy_flags, QUEUE_callback_WtoA,
1051                                            &ctx, devinfo, devinfo_data );
1052         RtlFreeUnicodeString( &sectionW );
1053     }
1054     else SetLastError( ERROR_NOT_ENOUGH_MEMORY );
1055
1056     RtlFreeUnicodeString( &src_rootW );
1057     return ret;
1058 }
1059
1060
1061 /***********************************************************************
1062  *            SetupInstallFromInfSectionW   (SETUPAPI.@)
1063  */
1064 BOOL WINAPI SetupInstallFromInfSectionW( HWND owner, HINF hinf, PCWSTR section, UINT flags,
1065                                          HKEY key_root, PCWSTR src_root, UINT copy_flags,
1066                                          PSP_FILE_CALLBACK_W callback, PVOID context,
1067                                          HDEVINFO devinfo, PSP_DEVINFO_DATA devinfo_data )
1068 {
1069     BOOL ret;
1070     int i;
1071
1072     if (flags & SPINST_FILES)
1073     {
1074         struct files_callback_info info;
1075         HSPFILEQ queue;
1076
1077         if (!(queue = SetupOpenFileQueue())) return FALSE;
1078         info.queue      = queue;
1079         info.src_root   = src_root;
1080         info.copy_flags = copy_flags;
1081         info.layout     = hinf;
1082         ret = (iterate_section_fields( hinf, section, CopyFiles, copy_files_callback, &info ) &&
1083                iterate_section_fields( hinf, section, DelFiles, delete_files_callback, &info ) &&
1084                iterate_section_fields( hinf, section, RenFiles, rename_files_callback, &info ) &&
1085                SetupCommitFileQueueW( owner, queue, callback, context ));
1086         SetupCloseFileQueue( queue );
1087         if (!ret) return FALSE;
1088     }
1089     if (flags & SPINST_INIFILES)
1090     {
1091         if (!iterate_section_fields( hinf, section, UpdateInis, update_ini_callback, NULL ) ||
1092             !iterate_section_fields( hinf, section, UpdateIniFields,
1093                                      update_ini_fields_callback, NULL ))
1094             return FALSE;
1095     }
1096     if (flags & SPINST_INI2REG)
1097     {
1098         if (!iterate_section_fields( hinf, section, Ini2Reg, ini2reg_callback, NULL ))
1099             return FALSE;
1100     }
1101     if (flags & SPINST_LOGCONFIG)
1102     {
1103         if (!iterate_section_fields( hinf, section, LogConf, logconf_callback, NULL ))
1104             return FALSE;
1105     }
1106     if (flags & SPINST_REGSVR)
1107     {
1108         struct register_dll_info info;
1109
1110         info.unregister    = FALSE;
1111         info.modules_size  = 0;
1112         info.modules_count = 0;
1113         info.modules       = NULL;
1114         if (flags & SPINST_REGISTERCALLBACKAWARE)
1115         {
1116             info.callback         = callback;
1117             info.callback_context = context;
1118         }
1119         else info.callback = NULL;
1120
1121         if (iterate_section_fields( hinf, section, WineFakeDlls, fake_dlls_callback, NULL ))
1122             cleanup_fake_dlls();
1123         else
1124             return FALSE;
1125
1126         ret = iterate_section_fields( hinf, section, RegisterDlls, register_dlls_callback, &info );
1127         for (i = 0; i < info.modules_count; i++) FreeLibrary( info.modules[i] );
1128         HeapFree( GetProcessHeap(), 0, info.modules );
1129         if (!ret) return FALSE;
1130     }
1131     if (flags & SPINST_UNREGSVR)
1132     {
1133         struct register_dll_info info;
1134
1135         info.unregister    = TRUE;
1136         info.modules_size  = 0;
1137         info.modules_count = 0;
1138         info.modules       = NULL;
1139         if (flags & SPINST_REGISTERCALLBACKAWARE)
1140         {
1141             info.callback         = callback;
1142             info.callback_context = context;
1143         }
1144         else info.callback = NULL;
1145
1146         ret = iterate_section_fields( hinf, section, UnregisterDlls, register_dlls_callback, &info );
1147         for (i = 0; i < info.modules_count; i++) FreeLibrary( info.modules[i] );
1148         HeapFree( GetProcessHeap(), 0, info.modules );
1149         if (!ret) return FALSE;
1150     }
1151     if (flags & SPINST_REGISTRY)
1152     {
1153         struct registry_callback_info info;
1154
1155         info.default_root = key_root;
1156         info.delete = TRUE;
1157         if (!iterate_section_fields( hinf, section, DelReg, registry_callback, &info ))
1158             return FALSE;
1159         info.delete = FALSE;
1160         if (!iterate_section_fields( hinf, section, AddReg, registry_callback, &info ))
1161             return FALSE;
1162     }
1163     if (flags & SPINST_BITREG)
1164     {
1165         if (!iterate_section_fields( hinf, section, BitReg, bitreg_callback, NULL ))
1166             return FALSE;
1167     }
1168     if (flags & SPINST_PROFILEITEMS)
1169     {
1170         if (!iterate_section_fields( hinf, section, ProfileItems, profile_items_callback, NULL ))
1171             return FALSE;
1172     }
1173     if (flags & SPINST_COPYINF)
1174     {
1175         if (!iterate_section_fields( hinf, section, CopyINF, copy_inf_callback, NULL ))
1176             return FALSE;
1177     }
1178
1179     return TRUE;
1180 }
1181
1182
1183 /***********************************************************************
1184  *              InstallHinfSectionW  (SETUPAPI.@)
1185  *
1186  * NOTE: 'cmdline' is <section> <mode> <path> from
1187  *   RUNDLL32.EXE SETUPAPI.DLL,InstallHinfSection <section> <mode> <path>
1188  */
1189 void WINAPI InstallHinfSectionW( HWND hwnd, HINSTANCE handle, LPCWSTR cmdline, INT show )
1190 {
1191 #ifdef __i386__
1192     static const WCHAR nt_platformW[] = {'.','n','t','x','8','6',0};
1193 #elif defined(__x86_64)
1194     static const WCHAR nt_platformW[] = {'.','n','t','a','m','d','6','4',0};
1195 #else  /* FIXME: other platforms */
1196     static const WCHAR nt_platformW[] = {'.','n','t',0};
1197 #endif
1198     static const WCHAR nt_genericW[] = {'.','n','t',0};
1199     static const WCHAR servicesW[] = {'.','S','e','r','v','i','c','e','s',0};
1200
1201     WCHAR *s, *path, section[MAX_PATH + (sizeof(nt_platformW) + sizeof(servicesW)) / sizeof(WCHAR)];
1202     void *callback_context;
1203     UINT mode;
1204     HINF hinf;
1205
1206     TRACE("hwnd %p, handle %p, cmdline %s\n", hwnd, handle, debugstr_w(cmdline));
1207
1208     lstrcpynW( section, cmdline, MAX_PATH );
1209
1210     if (!(s = strchrW( section, ' ' ))) return;
1211     *s++ = 0;
1212     while (*s == ' ') s++;
1213     mode = atoiW( s );
1214
1215     /* quoted paths are not allowed on native, the rest of the command line is taken as the path */
1216     if (!(s = strchrW( s, ' ' ))) return;
1217     while (*s == ' ') s++;
1218     path = s;
1219
1220     hinf = SetupOpenInfFileW( path, NULL, INF_STYLE_WIN4, NULL );
1221     if (hinf == INVALID_HANDLE_VALUE) return;
1222
1223     if (!(GetVersion() & 0x80000000))
1224     {
1225         INFCONTEXT context;
1226
1227         /* check for <section>.ntx86 (or corresponding name for the current platform)
1228          * and then <section>.nt */
1229         s = section + strlenW(section);
1230         memcpy( s, nt_platformW, sizeof(nt_platformW) );
1231         if (!(SetupFindFirstLineW( hinf, section, NULL, &context )))
1232         {
1233             memcpy( s, nt_genericW, sizeof(nt_genericW) );
1234             if (!(SetupFindFirstLineW( hinf, section, NULL, &context ))) *s = 0;
1235         }
1236         if (*s) TRACE( "using section %s instead\n", debugstr_w(section) );
1237     }
1238
1239     callback_context = SetupInitDefaultQueueCallback( hwnd );
1240     SetupInstallFromInfSectionW( hwnd, hinf, section, SPINST_ALL, NULL, NULL, SP_COPY_NEWER,
1241                                  SetupDefaultQueueCallbackW, callback_context,
1242                                  NULL, NULL );
1243     SetupTermDefaultQueueCallback( callback_context );
1244     strcatW( section, servicesW );
1245     SetupInstallServicesFromInfSectionW( hinf, section, 0 );
1246     SetupCloseInfFile( hinf );
1247
1248     /* FIXME: should check the mode and maybe reboot */
1249     /* there isn't much point in doing that since we */
1250     /* don't yet handle deferred file copies anyway. */
1251 }
1252
1253
1254 /***********************************************************************
1255  *              InstallHinfSectionA  (SETUPAPI.@)
1256  */
1257 void WINAPI InstallHinfSectionA( HWND hwnd, HINSTANCE handle, LPCSTR cmdline, INT show )
1258 {
1259     UNICODE_STRING cmdlineW;
1260
1261     if (RtlCreateUnicodeStringFromAsciiz( &cmdlineW, cmdline ))
1262     {
1263         InstallHinfSectionW( hwnd, handle, cmdlineW.Buffer, show );
1264         RtlFreeUnicodeString( &cmdlineW );
1265     }
1266 }
1267
1268
1269 /***********************************************************************
1270  *            add_service
1271  *
1272  * Create a new service. Helper for SetupInstallServicesFromInfSectionW.
1273  */
1274 static BOOL add_service( SC_HANDLE scm, HINF hinf, const WCHAR *name, const WCHAR *section, DWORD flags )
1275 {
1276     struct registry_callback_info info;
1277     SC_HANDLE service;
1278     INFCONTEXT context;
1279     SERVICE_DESCRIPTIONW descr;
1280     WCHAR *display_name, *start_name, *load_order, *binary_path;
1281     INT service_type = 0, start_type = 0, error_control = 0;
1282     DWORD size;
1283     HKEY hkey;
1284
1285     /* first the mandatory fields */
1286
1287     if (!SetupFindFirstLineW( hinf, section, ServiceType, &context ) ||
1288         !SetupGetIntField( &context, 1, &service_type ))
1289     {
1290         SetLastError( ERROR_BAD_SERVICE_INSTALLSECT );
1291         return FALSE;
1292     }
1293     if (!SetupFindFirstLineW( hinf, section, StartType, &context ) ||
1294         !SetupGetIntField( &context, 1, &start_type ))
1295     {
1296         SetLastError( ERROR_BAD_SERVICE_INSTALLSECT );
1297         return FALSE;
1298     }
1299     if (!SetupFindFirstLineW( hinf, section, ErrorControl, &context ) ||
1300         !SetupGetIntField( &context, 1, &error_control ))
1301     {
1302         SetLastError( ERROR_BAD_SERVICE_INSTALLSECT );
1303         return FALSE;
1304     }
1305     if (!(binary_path = dup_section_line_field( hinf, section, ServiceBinary, 1 )))
1306     {
1307         SetLastError( ERROR_BAD_SERVICE_INSTALLSECT );
1308         return FALSE;
1309     }
1310
1311     /* now the optional fields */
1312
1313     display_name = dup_section_line_field( hinf, section, DisplayName, 1 );
1314     start_name = dup_section_line_field( hinf, section, StartName, 1 );
1315     load_order = dup_section_line_field( hinf, section, LoadOrderGroup, 1 );
1316     descr.lpDescription = dup_section_line_field( hinf, section, Description, 1 );
1317
1318     /* FIXME: Dependencies field */
1319     /* FIXME: Security field */
1320
1321     TRACE( "service %s display %s type %x start %x error %x binary %s order %s startname %s flags %x\n",
1322            debugstr_w(name), debugstr_w(display_name), service_type, start_type, error_control,
1323            debugstr_w(binary_path), debugstr_w(load_order), debugstr_w(start_name), flags );
1324
1325     service = CreateServiceW( scm, name, display_name, SERVICE_ALL_ACCESS,
1326                               service_type, start_type, error_control, binary_path,
1327                               load_order, NULL, NULL, start_name, NULL );
1328     if (service)
1329     {
1330         if (descr.lpDescription) ChangeServiceConfig2W( service, SERVICE_CONFIG_DESCRIPTION, &descr );
1331     }
1332     else
1333     {
1334         if (GetLastError() != ERROR_SERVICE_EXISTS) goto done;
1335         service = OpenServiceW( scm, name, SERVICE_QUERY_CONFIG|SERVICE_CHANGE_CONFIG|SERVICE_START );
1336         if (!service) goto done;
1337
1338         if (flags & (SPSVCINST_NOCLOBBER_DISPLAYNAME | SPSVCINST_NOCLOBBER_STARTTYPE |
1339                      SPSVCINST_NOCLOBBER_ERRORCONTROL | SPSVCINST_NOCLOBBER_LOADORDERGROUP))
1340         {
1341             QUERY_SERVICE_CONFIGW *config = NULL;
1342
1343             if (!QueryServiceConfigW( service, NULL, 0, &size ) &&
1344                 GetLastError() == ERROR_INSUFFICIENT_BUFFER)
1345                 config = HeapAlloc( GetProcessHeap(), 0, size );
1346             if (config && QueryServiceConfigW( service, config, size, &size ))
1347             {
1348                 if (flags & SPSVCINST_NOCLOBBER_STARTTYPE) start_type = config->dwStartType;
1349                 if (flags & SPSVCINST_NOCLOBBER_ERRORCONTROL) error_control = config->dwErrorControl;
1350                 if (flags & SPSVCINST_NOCLOBBER_DISPLAYNAME)
1351                 {
1352                     HeapFree( GetProcessHeap(), 0, display_name );
1353                     display_name = strdupW( config->lpDisplayName );
1354                 }
1355                 if (flags & SPSVCINST_NOCLOBBER_LOADORDERGROUP)
1356                 {
1357                     HeapFree( GetProcessHeap(), 0, load_order );
1358                     load_order = strdupW( config->lpLoadOrderGroup );
1359                 }
1360             }
1361             HeapFree( GetProcessHeap(), 0, config );
1362         }
1363         TRACE( "changing %s display %s type %x start %x error %x binary %s loadorder %s startname %s\n",
1364                debugstr_w(name), debugstr_w(display_name), service_type, start_type, error_control,
1365                debugstr_w(binary_path), debugstr_w(load_order), debugstr_w(start_name) );
1366
1367         ChangeServiceConfigW( service, service_type, start_type, error_control, binary_path,
1368                               load_order, NULL, NULL, start_name, NULL, display_name );
1369
1370         if (!(flags & SPSVCINST_NOCLOBBER_DESCRIPTION))
1371             ChangeServiceConfig2W( service, SERVICE_CONFIG_DESCRIPTION, &descr );
1372     }
1373
1374     /* execute the AddReg, DelReg and BitReg entries */
1375
1376     info.default_root = 0;
1377     if (!RegOpenKeyW( HKEY_LOCAL_MACHINE, ServicesKey, &hkey ))
1378     {
1379         RegOpenKeyW( hkey, name, &info.default_root );
1380         RegCloseKey( hkey );
1381     }
1382     if (info.default_root)
1383     {
1384         info.delete = TRUE;
1385         iterate_section_fields( hinf, section, DelReg, registry_callback, &info );
1386         info.delete = FALSE;
1387         iterate_section_fields( hinf, section, AddReg, registry_callback, &info );
1388         RegCloseKey( info.default_root );
1389     }
1390     iterate_section_fields( hinf, section, BitReg, bitreg_callback, NULL );
1391
1392     if (flags & SPSVCINST_STARTSERVICE) StartServiceW( service, 0, NULL );
1393     CloseServiceHandle( service );
1394
1395 done:
1396     if (!service) WARN( "failed err %u\n", GetLastError() );
1397     HeapFree( GetProcessHeap(), 0, binary_path );
1398     HeapFree( GetProcessHeap(), 0, display_name );
1399     HeapFree( GetProcessHeap(), 0, start_name );
1400     HeapFree( GetProcessHeap(), 0, load_order );
1401     HeapFree( GetProcessHeap(), 0, descr.lpDescription );
1402     return service != 0;
1403 }
1404
1405
1406 /***********************************************************************
1407  *            del_service
1408  *
1409  * Delete service. Helper for SetupInstallServicesFromInfSectionW.
1410  */
1411 static BOOL del_service( SC_HANDLE scm, HINF hinf, const WCHAR *name, DWORD flags )
1412 {
1413     BOOL ret;
1414     SC_HANDLE service;
1415     SERVICE_STATUS status;
1416
1417     if (!(service = OpenServiceW( scm, name, SERVICE_STOP | DELETE )))
1418     {
1419         if (GetLastError() == ERROR_SERVICE_DOES_NOT_EXIST) return TRUE;
1420         WARN( "cannot open %s err %u\n", debugstr_w(name), GetLastError() );
1421         return FALSE;
1422     }
1423     if (flags & SPSVCINST_STOPSERVICE) ControlService( service, SERVICE_CONTROL_STOP, &status );
1424     TRACE( "deleting %s\n", debugstr_w(name) );
1425     ret = DeleteService( service );
1426     CloseServiceHandle( service );
1427     return ret;
1428 }
1429
1430
1431 /***********************************************************************
1432  *              SetupInstallServicesFromInfSectionW  (SETUPAPI.@)
1433  */
1434 BOOL WINAPI SetupInstallServicesFromInfSectionW( HINF hinf, PCWSTR section, DWORD flags )
1435 {
1436     WCHAR service_name[MAX_INF_STRING_LENGTH];
1437     WCHAR service_section[MAX_INF_STRING_LENGTH];
1438     SC_HANDLE scm;
1439     INFCONTEXT context;
1440     INT section_flags;
1441     BOOL ok, ret = FALSE;
1442
1443     if (!(scm = OpenSCManagerW( NULL, NULL, SC_MANAGER_ALL_ACCESS ))) return FALSE;
1444
1445     if (!(ok = SetupFindFirstLineW( hinf, section, AddService, &context )))
1446         SetLastError( ERROR_SECTION_NOT_FOUND );
1447     while (ok)
1448     {
1449         if (!SetupGetStringFieldW( &context, 1, service_name, MAX_INF_STRING_LENGTH, NULL ))
1450             continue;
1451         if (!SetupGetIntField( &context, 2, &section_flags )) section_flags = 0;
1452         if (!SetupGetStringFieldW( &context, 3, service_section, MAX_INF_STRING_LENGTH, NULL ))
1453             continue;
1454         if (!(ret = add_service( scm, hinf, service_name, service_section, section_flags | flags )))
1455             goto done;
1456         ok = SetupFindNextMatchLineW( &context, AddService, &context );
1457     }
1458
1459     if (!(ok = SetupFindFirstLineW( hinf, section, DelService, &context )))
1460         SetLastError( ERROR_SECTION_NOT_FOUND );
1461     while (ok)
1462     {
1463         if (!SetupGetStringFieldW( &context, 1, service_name, MAX_INF_STRING_LENGTH, NULL ))
1464             continue;
1465         if (!SetupGetIntField( &context, 2, &section_flags )) section_flags = 0;
1466         if (!(ret = del_service( scm, hinf, service_name, section_flags | flags ))) goto done;
1467         ok = SetupFindNextMatchLineW( &context, AddService, &context );
1468     }
1469     if (ret) SetLastError( ERROR_SUCCESS );
1470  done:
1471     CloseServiceHandle( scm );
1472     return ret;
1473 }
1474
1475
1476 /***********************************************************************
1477  *              SetupInstallServicesFromInfSectionA  (SETUPAPI.@)
1478  */
1479 BOOL WINAPI SetupInstallServicesFromInfSectionA( HINF Inf, PCSTR SectionName, DWORD Flags)
1480 {
1481     UNICODE_STRING SectionNameW;
1482     BOOL ret = FALSE;
1483
1484     if (RtlCreateUnicodeStringFromAsciiz( &SectionNameW, SectionName ))
1485     {
1486         ret = SetupInstallServicesFromInfSectionW( Inf, SectionNameW.Buffer, Flags );
1487         RtlFreeUnicodeString( &SectionNameW );
1488     }
1489     else
1490         SetLastError( ERROR_NOT_ENOUGH_MEMORY );
1491
1492     return ret;
1493 }
1494
1495
1496 /***********************************************************************
1497  *              SetupGetInfFileListA  (SETUPAPI.@)
1498  */
1499 BOOL WINAPI SetupGetInfFileListA(PCSTR dir, DWORD style, PSTR buffer,
1500                                  DWORD insize, PDWORD outsize)
1501 {
1502     UNICODE_STRING dirW;
1503     PWSTR bufferW = NULL;
1504     BOOL ret = FALSE;
1505     DWORD outsizeA, outsizeW;
1506
1507     if ( dir )
1508         RtlCreateUnicodeStringFromAsciiz( &dirW, dir );
1509     else
1510         dirW.Buffer = NULL;
1511
1512     if ( buffer )
1513         bufferW = HeapAlloc( GetProcessHeap(), 0, insize * sizeof( WCHAR ));
1514
1515     ret = SetupGetInfFileListW( dirW.Buffer, style, bufferW, insize, &outsizeW);
1516
1517     if ( ret )
1518     {
1519         outsizeA = WideCharToMultiByte( CP_ACP, 0, bufferW, outsizeW,
1520                                         buffer, insize, NULL, NULL);
1521         if ( outsize ) *outsize = outsizeA;
1522     }
1523
1524     HeapFree( GetProcessHeap(), 0, bufferW );
1525     RtlFreeUnicodeString( &dirW );
1526     return ret;
1527 }
1528
1529
1530 /***********************************************************************
1531  *              SetupGetInfFileListW  (SETUPAPI.@)
1532  */
1533 BOOL WINAPI SetupGetInfFileListW(PCWSTR dir, DWORD style, PWSTR buffer,
1534                                  DWORD insize, PDWORD outsize)
1535 {
1536     static WCHAR inf[] = {'\\','*','.','i','n','f',0 };
1537     WCHAR *filter, *fullname = NULL, *ptr = buffer;
1538     DWORD dir_len, name_len = 20, size ;
1539     WIN32_FIND_DATAW finddata;
1540     HANDLE hdl;
1541     if (style & ~( INF_STYLE_OLDNT | INF_STYLE_WIN4 |
1542                    INF_STYLE_CACHE_ENABLE | INF_STYLE_CACHE_DISABLE ))
1543     {
1544         FIXME( "unknown inf_style(s) 0x%x\n",
1545                style & ~( INF_STYLE_OLDNT | INF_STYLE_WIN4 |
1546                          INF_STYLE_CACHE_ENABLE | INF_STYLE_CACHE_DISABLE ));
1547         if( outsize ) *outsize = 1;
1548         return TRUE;
1549     }
1550     if ((style & ( INF_STYLE_OLDNT | INF_STYLE_WIN4 )) == INF_STYLE_NONE)
1551     {
1552         FIXME( "inf_style INF_STYLE_NONE not handled\n" );
1553         if( outsize ) *outsize = 1;
1554         return TRUE;
1555     }
1556     if (style & ( INF_STYLE_CACHE_ENABLE | INF_STYLE_CACHE_DISABLE ))
1557         FIXME("ignored inf_style(s) %s %s\n",
1558               ( style & INF_STYLE_CACHE_ENABLE  ) ? "INF_STYLE_CACHE_ENABLE"  : "",
1559               ( style & INF_STYLE_CACHE_DISABLE ) ? "INF_STYLE_CACHE_DISABLE" : "");
1560     if( dir )
1561     {
1562         DWORD att;
1563         DWORD msize;
1564         dir_len = strlenW( dir );
1565         if ( !dir_len ) return FALSE;
1566         msize = ( 7 + dir_len )  * sizeof( WCHAR ); /* \\*.inf\0 */
1567         filter = HeapAlloc( GetProcessHeap(), 0, msize );
1568         if( !filter )
1569         {
1570             SetLastError( ERROR_NOT_ENOUGH_MEMORY );
1571             return FALSE;
1572         }
1573         strcpyW( filter, dir );
1574         if ( '\\' == filter[dir_len - 1] )
1575             filter[--dir_len] = 0;
1576
1577         att = GetFileAttributesW( filter );
1578         if (att != INVALID_FILE_ATTRIBUTES && !(att & FILE_ATTRIBUTE_DIRECTORY))
1579         {
1580             HeapFree( GetProcessHeap(), 0, filter );
1581             SetLastError( ERROR_DIRECTORY );
1582             return FALSE;
1583         }
1584     }
1585     else
1586     {
1587         WCHAR infdir[] = {'\\','i','n','f',0 };
1588         DWORD msize;
1589         dir_len = GetWindowsDirectoryW( NULL, 0 );
1590         msize = ( 7 + 4 + dir_len ) * sizeof( WCHAR );
1591         filter = HeapAlloc( GetProcessHeap(), 0, msize );
1592         if( !filter )
1593         {
1594             SetLastError( ERROR_NOT_ENOUGH_MEMORY );
1595             return FALSE;
1596         }
1597         GetWindowsDirectoryW( filter, msize );
1598         strcatW( filter, infdir );
1599     }
1600     strcatW( filter, inf );
1601
1602     hdl = FindFirstFileW( filter , &finddata );
1603     if ( hdl == INVALID_HANDLE_VALUE )
1604     {
1605         if( outsize ) *outsize = 1;
1606         HeapFree( GetProcessHeap(), 0, filter );
1607         return TRUE;
1608     }
1609     size = 1;
1610     do
1611     {
1612         static const WCHAR key[] =
1613                {'S','i','g','n','a','t','u','r','e',0 };
1614         static const WCHAR section[] =
1615                {'V','e','r','s','i','o','n',0 };
1616         static const WCHAR sig_win4_1[] =
1617                {'$','C','h','i','c','a','g','o','$',0 };
1618         static const WCHAR sig_win4_2[] =
1619                {'$','W','I','N','D','O','W','S',' ','N','T','$',0 };
1620         WCHAR signature[ MAX_PATH ];
1621         BOOL valid = FALSE;
1622         DWORD len = strlenW( finddata.cFileName );
1623         if (!fullname || ( name_len < len ))
1624         {
1625             name_len = ( name_len < len ) ? len : name_len;
1626             HeapFree( GetProcessHeap(), 0, fullname );
1627             fullname = HeapAlloc( GetProcessHeap(), 0,
1628                                   ( 2 + dir_len + name_len) * sizeof( WCHAR ));
1629             if( !fullname )
1630             {
1631                 HeapFree( GetProcessHeap(), 0, filter );
1632                 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
1633                 return FALSE;
1634             }
1635             strcpyW( fullname, filter );
1636         }
1637         fullname[ dir_len + 1] = 0; /* keep '\\' */
1638         strcatW( fullname, finddata.cFileName );
1639         if (!GetPrivateProfileStringW( section, key, NULL, signature, MAX_PATH, fullname ))
1640             signature[0] = 0;
1641         if( INF_STYLE_OLDNT & style )
1642             valid = strcmpiW( sig_win4_1, signature ) &&
1643                     strcmpiW( sig_win4_2, signature );
1644         if( INF_STYLE_WIN4 & style )
1645             valid = valid || !strcmpiW( sig_win4_1, signature ) ||
1646                     !strcmpiW( sig_win4_2, signature );
1647         if( valid )
1648         {
1649             size += 1 + strlenW( finddata.cFileName );
1650             if( ptr && insize >= size )
1651             {
1652                 strcpyW( ptr, finddata.cFileName );
1653                 ptr += 1 + strlenW( finddata.cFileName );
1654                 *ptr = 0;
1655             }
1656         }
1657     }
1658     while( FindNextFileW( hdl, &finddata ));
1659     FindClose( hdl );
1660
1661     HeapFree( GetProcessHeap(), 0, fullname );
1662     HeapFree( GetProcessHeap(), 0, filter );
1663     if( outsize ) *outsize = size;
1664     return TRUE;
1665 }