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