mshtml: Added IHTMLAttributeCollection stub.
[wine] / dlls / setupapi / fakedll.c
1 /*
2  * Creation of Wine fake dlls for apps that access the dll file directly.
3  *
4  * Copyright 2006, 2011 Alexandre Julliard
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this library; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
19  */
20
21 #include "config.h"
22 #include "wine/port.h"
23
24 #include <stdarg.h>
25 #include <fcntl.h>
26 #ifdef HAVE_DIRENT_H
27 # include <dirent.h>
28 #endif
29 #ifdef HAVE_SYS_STAT_H
30 # include <sys/stat.h>
31 #endif
32 #ifdef HAVE_UNISTD_H
33 # include <unistd.h>
34 #endif
35
36 #define COBJMACROS
37 #define ATL_INITGUID
38 #define NONAMELESSSTRUCT
39 #define NONAMELESSUNION
40 #include "ntstatus.h"
41 #define WIN32_NO_STATUS
42 #include "windef.h"
43 #include "winbase.h"
44 #include "winuser.h"
45 #include "winnt.h"
46 #include "winternl.h"
47 #include "wine/unicode.h"
48 #include "wine/library.h"
49 #include "wine/debug.h"
50 #include "ole2.h"
51 #include "atliface.h"
52
53 WINE_DEFAULT_DEBUG_CHANNEL(setupapi);
54
55 static const char fakedll_signature[] = "Wine placeholder DLL";
56
57 static const unsigned int file_alignment = 512;
58 static const unsigned int section_alignment = 4096;
59 static const unsigned int max_dll_name_len = 64;
60
61 static void *file_buffer;
62 static SIZE_T file_buffer_size;
63 static unsigned int handled_count;
64 static unsigned int handled_total;
65 static char **handled_dlls;
66 static IRegistrar *registrar;
67
68 struct dll_info
69 {
70     HANDLE            handle;
71     IMAGE_NT_HEADERS *nt;
72     DWORD             file_pos;
73     DWORD             mem_pos;
74 };
75
76 #define ALIGN(size,align) (((size) + (align) - 1) & ~((align) - 1))
77
78 /* contents of the dll sections */
79
80 static const BYTE dll_code_section[] = { 0x31, 0xc0,          /* xor %eax,%eax */
81                                          0xc2, 0x0c, 0x00 };  /* ret $12 */
82
83 static const BYTE exe_code_section[] = { 0xb8, 0x01, 0x00, 0x00, 0x00,  /* movl $1,%eax */
84                                          0xc2, 0x04, 0x00 };            /* ret $4 */
85
86 static const IMAGE_BASE_RELOCATION reloc_section;  /* empty relocs */
87
88
89 /* wrapper for WriteFile */
90 static inline BOOL xwrite( struct dll_info *info, const void *data, DWORD size, DWORD offset )
91 {
92     DWORD res;
93
94     return (SetFilePointer( info->handle, offset, NULL, FILE_BEGIN ) != INVALID_SET_FILE_POINTER &&
95             WriteFile( info->handle, data, size, &res, NULL ) &&
96             res == size);
97 }
98
99 /* add a new section to the dll NT header */
100 static void add_section( struct dll_info *info, const char *name, DWORD size, DWORD flags )
101 {
102     IMAGE_SECTION_HEADER *sec = (IMAGE_SECTION_HEADER *)(info->nt + 1);
103
104     sec += info->nt->FileHeader.NumberOfSections;
105     memcpy( sec->Name, name, min( strlen(name), sizeof(sec->Name)) );
106     sec->Misc.VirtualSize = ALIGN( size, section_alignment );
107     sec->VirtualAddress   = info->mem_pos;
108     sec->SizeOfRawData    = size;
109     sec->PointerToRawData = info->file_pos;
110     sec->Characteristics  = flags;
111     info->file_pos += ALIGN( size, file_alignment );
112     info->mem_pos  += ALIGN( size, section_alignment );
113     info->nt->FileHeader.NumberOfSections++;
114 }
115
116 /* add a data directory to the dll NT header */
117 static inline void add_directory( struct dll_info *info, unsigned int idx, DWORD rva, DWORD size )
118 {
119     info->nt->OptionalHeader.DataDirectory[idx].VirtualAddress = rva;
120     info->nt->OptionalHeader.DataDirectory[idx].Size = size;
121 }
122
123 /* convert a dll name W->A without depending on the current codepage */
124 static char *dll_name_WtoA( char *nameA, const WCHAR *nameW, unsigned int len )
125 {
126     unsigned int i;
127
128     for (i = 0; i < len; i++)
129     {
130         char c = nameW[i];
131         if (nameW[i] > 127) return NULL;
132         if (c >= 'A' && c <= 'Z') c += 'a' - 'A';
133         nameA[i] = c;
134     }
135     nameA[i] = 0;
136     return nameA;
137 }
138
139 /* convert a dll name A->W without depending on the current codepage */
140 static WCHAR *dll_name_AtoW( WCHAR *nameW, const char *nameA, unsigned int len )
141 {
142     unsigned int i;
143
144     for (i = 0; i < len; i++) nameW[i] = nameA[i];
145     nameW[i] = 0;
146     return nameW;
147 }
148
149 /* add a dll to the list of dll that have been taken care of */
150 static BOOL add_handled_dll( const WCHAR *name )
151 {
152     unsigned int len = strlenW( name );
153     int i, min, max, pos, res;
154     char *nameA;
155
156     if (!(nameA = HeapAlloc( GetProcessHeap(), 0, len + 1 ))) return FALSE;
157     if (!dll_name_WtoA( nameA, name, len )) goto failed;
158
159     min = 0;
160     max = handled_count - 1;
161     while (min <= max)
162     {
163         pos = (min + max) / 2;
164         res = strcmp( handled_dlls[pos], nameA );
165         if (!res) goto failed;  /* already in the list */
166         if (res < 0) min = pos + 1;
167         else max = pos - 1;
168     }
169
170     if (handled_count >= handled_total)
171     {
172         char **new_dlls;
173         unsigned int new_count = max( 64, handled_total * 2 );
174
175         if (handled_dlls) new_dlls = HeapReAlloc( GetProcessHeap(), 0, handled_dlls,
176                                                   new_count * sizeof(*handled_dlls) );
177         else new_dlls = HeapAlloc( GetProcessHeap(), 0, new_count * sizeof(*handled_dlls) );
178         if (!new_dlls) goto failed;
179         handled_dlls = new_dlls;
180         handled_total = new_count;
181     }
182
183     for (i = handled_count; i > min; i--) handled_dlls[i] = handled_dlls[i - 1];
184     handled_dlls[i] = nameA;
185     handled_count++;
186     return TRUE;
187
188 failed:
189     HeapFree( GetProcessHeap(), 0, nameA );
190     return FALSE;
191 }
192
193 /* read in the contents of a file into the global file buffer */
194 /* return 1 on success, 0 on nonexistent file, -1 on other error */
195 static int read_file( const char *name, void **data, SIZE_T *size )
196 {
197     struct stat st;
198     int fd, ret = -1;
199     size_t header_size;
200     IMAGE_DOS_HEADER *dos;
201     IMAGE_NT_HEADERS *nt;
202     const size_t min_size = sizeof(*dos) + sizeof(fakedll_signature) +
203         FIELD_OFFSET( IMAGE_NT_HEADERS, OptionalHeader.MajorLinkerVersion );
204
205     if ((fd = open( name, O_RDONLY | O_BINARY )) == -1) return 0;
206     if (fstat( fd, &st ) == -1) goto done;
207     *size = st.st_size;
208     if (!file_buffer || st.st_size > file_buffer_size)
209     {
210         VirtualFree( file_buffer, 0, MEM_RELEASE );
211         file_buffer = NULL;
212         file_buffer_size = st.st_size;
213         if (NtAllocateVirtualMemory( GetCurrentProcess(), &file_buffer, 0, &file_buffer_size,
214                                      MEM_COMMIT, PAGE_READWRITE )) goto done;
215     }
216
217     /* check for valid fake dll file */
218
219     if (st.st_size < min_size) goto done;
220     header_size = min( st.st_size, 4096 );
221     if (pread( fd, file_buffer, header_size, 0 ) != header_size) goto done;
222     dos = file_buffer;
223     if (dos->e_magic != IMAGE_DOS_SIGNATURE) goto done;
224     if (dos->e_lfanew < sizeof(fakedll_signature)) goto done;
225     if (memcmp( dos + 1, fakedll_signature, sizeof(fakedll_signature) )) goto done;
226     if (dos->e_lfanew + FIELD_OFFSET(IMAGE_NT_HEADERS,OptionalHeader.MajorLinkerVersion) > header_size)
227         goto done;
228     nt = (IMAGE_NT_HEADERS *)((char *)file_buffer + dos->e_lfanew);
229     if (nt->Signature == IMAGE_NT_SIGNATURE && nt->OptionalHeader.Magic != IMAGE_NT_OPTIONAL_HDR_MAGIC)
230     {
231         /* wrong 32/64 type, pretend it doesn't exist */
232         ret = 0;
233         goto done;
234     }
235     if (st.st_size == header_size ||
236         pread( fd, (char *)file_buffer + header_size,
237                st.st_size - header_size, header_size ) == st.st_size - header_size)
238     {
239         *data = file_buffer;
240         ret = 1;
241     }
242 done:
243     close( fd );
244     return ret;
245 }
246
247 /* build a complete fake dll from scratch */
248 static BOOL build_fake_dll( HANDLE file )
249 {
250     IMAGE_DOS_HEADER *dos;
251     IMAGE_NT_HEADERS *nt;
252     struct dll_info info;
253     BYTE *buffer;
254     BOOL ret = FALSE;
255     DWORD lfanew = (sizeof(*dos) + sizeof(fakedll_signature) + 15) & ~15;
256     DWORD size, header_size = lfanew + sizeof(*nt);
257
258     info.handle = file;
259     buffer = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, header_size + 8 * sizeof(IMAGE_SECTION_HEADER) );
260
261     dos = (IMAGE_DOS_HEADER *)buffer;
262     dos->e_magic    = IMAGE_DOS_SIGNATURE;
263     dos->e_cblp     = sizeof(*dos);
264     dos->e_cp       = 1;
265     dos->e_cparhdr  = lfanew / 16;
266     dos->e_minalloc = 0;
267     dos->e_maxalloc = 0xffff;
268     dos->e_ss       = 0x0000;
269     dos->e_sp       = 0x00b8;
270     dos->e_lfarlc   = lfanew;
271     dos->e_lfanew   = lfanew;
272     memcpy( dos + 1, fakedll_signature, sizeof(fakedll_signature) );
273
274     nt = info.nt = (IMAGE_NT_HEADERS *)(buffer + lfanew);
275     /* some fields are copied from the source dll */
276 #ifdef _WIN64
277     nt->FileHeader.Machine = IMAGE_FILE_MACHINE_AMD64;
278 #else
279     nt->FileHeader.Machine = IMAGE_FILE_MACHINE_I386;
280 #endif
281     nt->FileHeader.TimeDateStamp = 0;
282     nt->FileHeader.Characteristics = IMAGE_FILE_DLL;
283     nt->OptionalHeader.MajorLinkerVersion = 1;
284     nt->OptionalHeader.MinorLinkerVersion = 0;
285     nt->OptionalHeader.MajorOperatingSystemVersion = 1;
286     nt->OptionalHeader.MinorOperatingSystemVersion = 0;
287     nt->OptionalHeader.MajorImageVersion = 1;
288     nt->OptionalHeader.MinorImageVersion = 0;
289     nt->OptionalHeader.MajorSubsystemVersion = 4;
290     nt->OptionalHeader.MinorSubsystemVersion = 0;
291     nt->OptionalHeader.Win32VersionValue = 0;
292     nt->OptionalHeader.Subsystem = IMAGE_SUBSYSTEM_WINDOWS_GUI;
293     nt->OptionalHeader.DllCharacteristics = 0;
294     nt->OptionalHeader.SizeOfStackReserve = 0;
295     nt->OptionalHeader.SizeOfStackCommit = 0;
296     nt->OptionalHeader.SizeOfHeapReserve = 0;
297     nt->OptionalHeader.SizeOfHeapCommit = 0;
298     /* other fields have fixed values */
299     nt->Signature                              = IMAGE_NT_SIGNATURE;
300     nt->FileHeader.NumberOfSections            = 0;
301     nt->FileHeader.SizeOfOptionalHeader        = IMAGE_SIZEOF_NT_OPTIONAL_HEADER;
302     nt->OptionalHeader.Magic                   = IMAGE_NT_OPTIONAL_HDR_MAGIC;
303     nt->OptionalHeader.ImageBase               = 0x10000000;
304     nt->OptionalHeader.SectionAlignment        = section_alignment;
305     nt->OptionalHeader.FileAlignment           = file_alignment;
306     nt->OptionalHeader.NumberOfRvaAndSizes     = IMAGE_NUMBEROF_DIRECTORY_ENTRIES;
307
308     header_size = (BYTE *)(nt + 1) - buffer;
309     info.mem_pos  = ALIGN( header_size, section_alignment );
310     info.file_pos = ALIGN( header_size, file_alignment );
311
312     nt->OptionalHeader.AddressOfEntryPoint = info.mem_pos;
313     nt->OptionalHeader.BaseOfCode          = info.mem_pos;
314
315     if (nt->FileHeader.Characteristics & IMAGE_FILE_DLL)
316     {
317         size = sizeof(dll_code_section);
318         if (!xwrite( &info, dll_code_section, size, info.file_pos )) goto done;
319     }
320     else
321     {
322         size = sizeof(exe_code_section);
323         if (!xwrite( &info, exe_code_section, size, info.file_pos )) goto done;
324     }
325     nt->OptionalHeader.SizeOfCode = size;
326     add_section( &info, ".text", size, IMAGE_SCN_CNT_CODE | IMAGE_SCN_MEM_EXECUTE | IMAGE_SCN_MEM_READ );
327
328     if (!xwrite( &info, &reloc_section, sizeof(reloc_section), info.file_pos )) goto done;
329     add_directory( &info, IMAGE_DIRECTORY_ENTRY_BASERELOC, info.mem_pos, sizeof(reloc_section) );
330     add_section( &info, ".reloc", sizeof(reloc_section),
331                  IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_DISCARDABLE | IMAGE_SCN_MEM_READ );
332
333     header_size += nt->FileHeader.NumberOfSections * sizeof(IMAGE_SECTION_HEADER);
334     nt->OptionalHeader.SizeOfHeaders = ALIGN( header_size, file_alignment );
335     nt->OptionalHeader.SizeOfImage   = ALIGN( info.mem_pos, section_alignment );
336     ret = xwrite( &info, buffer, header_size, 0 );
337 done:
338     HeapFree( GetProcessHeap(), 0, buffer );
339     return ret;
340 }
341
342 /* check if an existing file is a fake dll so that we can overwrite it */
343 static BOOL is_fake_dll( HANDLE h )
344 {
345     IMAGE_DOS_HEADER *dos;
346     DWORD size;
347     BYTE buffer[sizeof(*dos) + sizeof(fakedll_signature)];
348
349     if (!ReadFile( h, buffer, sizeof(buffer), &size, NULL ) || size != sizeof(buffer))
350         return FALSE;
351     dos = (IMAGE_DOS_HEADER *)buffer;
352     if (dos->e_magic != IMAGE_DOS_SIGNATURE) return FALSE;
353     if (dos->e_lfanew < size) return FALSE;
354     return !memcmp( dos + 1, fakedll_signature, sizeof(fakedll_signature) );
355 }
356
357 /* create directories leading to a given file */
358 static void create_directories( const WCHAR *name )
359 {
360     WCHAR *path, *p;
361
362     /* create the directory/directories */
363     path = HeapAlloc(GetProcessHeap(), 0, (strlenW(name) + 1)*sizeof(WCHAR));
364     strcpyW(path, name);
365
366     p = strchrW(path, '\\');
367     while (p != NULL)
368     {
369         *p = 0;
370         if (!CreateDirectoryW(path, NULL))
371             TRACE("Couldn't create directory %s - error: %d\n", wine_dbgstr_w(path), GetLastError());
372         *p = '\\';
373         p = strchrW(p+1, '\\');
374     }
375     HeapFree(GetProcessHeap(), 0, path);
376 }
377
378 static inline char *prepend( char *buffer, const char *str, size_t len )
379 {
380     return memcpy( buffer - len, str, len );
381 }
382
383 /* try to load a pre-compiled fake dll */
384 static void *load_fake_dll( const WCHAR *name, SIZE_T *size )
385 {
386     const char *build_dir = wine_get_build_dir();
387     const char *path;
388     char *file, *ptr;
389     void *data = NULL;
390     unsigned int i, pos, len, namelen, maxlen = 0;
391     WCHAR *p;
392     int res = 0;
393
394     if ((p = strrchrW( name, '\\' ))) name = p + 1;
395
396     i = 0;
397     if (build_dir) maxlen = strlen(build_dir) + sizeof("/programs/") + strlenW(name);
398     while ((path = wine_dll_enum_load_path( i++ ))) maxlen = max( maxlen, strlen(path) );
399     maxlen += sizeof("/fakedlls") + strlenW(name) + 2;
400
401     if (!(file = HeapAlloc( GetProcessHeap(), 0, maxlen ))) return NULL;
402
403     len = strlenW( name );
404     pos = maxlen - len - sizeof(".fake");
405     if (!dll_name_WtoA( file + pos, name, len )) goto done;
406     file[--pos] = '/';
407
408     if (build_dir)
409     {
410         strcpy( file + pos + len + 1, ".fake" );
411
412         /* try as a dll */
413         ptr = file + pos;
414         namelen = len + 1;
415         if (namelen > 4 && !memcmp( ptr + namelen - 4, ".dll", 4 )) namelen -= 4;
416         ptr = prepend( ptr, ptr, namelen );
417         ptr = prepend( ptr, "/dlls", sizeof("/dlls") - 1 );
418         ptr = prepend( ptr, build_dir, strlen(build_dir) );
419         if ((res = read_file( ptr, &data, size ))) goto done;
420
421         /* now as a program */
422         ptr = file + pos;
423         namelen = len + 1;
424         if (namelen > 4 && !memcmp( ptr + namelen - 4, ".exe", 4 )) namelen -= 4;
425         ptr = prepend( ptr, ptr, namelen );
426         ptr = prepend( ptr, "/programs", sizeof("/programs") - 1 );
427         ptr = prepend( ptr, build_dir, strlen(build_dir) );
428         if ((res = read_file( ptr, &data, size ))) goto done;
429     }
430
431     file[pos + len + 1] = 0;
432     for (i = 0; (path = wine_dll_enum_load_path( i )); i++)
433     {
434         ptr = prepend( file + pos, "/fakedlls", sizeof("/fakedlls") - 1 );
435         ptr = prepend( ptr, path, strlen(path) );
436         if ((res = read_file( ptr, &data, size ))) break;
437     }
438
439 done:
440     HeapFree( GetProcessHeap(), 0, file );
441     if (res == 1) return data;
442     return NULL;
443 }
444
445 /* create the fake dll destination file */
446 static HANDLE create_dest_file( const WCHAR *name )
447 {
448     /* first check for an existing file */
449     HANDLE h = CreateFileW( name, GENERIC_READ|GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL );
450     if (h != INVALID_HANDLE_VALUE)
451     {
452         if (!is_fake_dll( h ))
453         {
454             TRACE( "%s is not a fake dll, not overwriting it\n", debugstr_w(name) );
455             CloseHandle( h );
456             return 0;
457         }
458         /* truncate the file */
459         SetFilePointer( h, 0, NULL, FILE_BEGIN );
460         SetEndOfFile( h );
461     }
462     else
463     {
464         if (GetLastError() == ERROR_PATH_NOT_FOUND) create_directories( name );
465
466         h = CreateFileW( name, GENERIC_WRITE, 0, NULL, CREATE_NEW, 0, NULL );
467         if (h == INVALID_HANDLE_VALUE)
468             ERR( "failed to create %s (error=%u)\n", debugstr_w(name), GetLastError() );
469     }
470     return h;
471 }
472
473 /* XML parsing code copied from ntdll */
474
475 typedef struct
476 {
477     const char  *ptr;
478     unsigned int len;
479 } xmlstr_t;
480
481 typedef struct
482 {
483     const char *ptr;
484     const char *end;
485 } xmlbuf_t;
486
487 static inline BOOL xmlstr_cmp(const xmlstr_t* xmlstr, const char *str)
488 {
489     return !strncmp(xmlstr->ptr, str, xmlstr->len) && !str[xmlstr->len];
490 }
491
492 static inline BOOL isxmlspace( char ch )
493 {
494     return (ch == ' ' || ch == '\r' || ch == '\n' || ch == '\t');
495 }
496
497 static BOOL next_xml_elem( xmlbuf_t *xmlbuf, xmlstr_t *elem )
498 {
499     const char *ptr;
500
501     for (;;)
502     {
503         ptr = memchr(xmlbuf->ptr, '<', xmlbuf->end - xmlbuf->ptr);
504         if (!ptr)
505         {
506             xmlbuf->ptr = xmlbuf->end;
507             return FALSE;
508         }
509         ptr++;
510         if (ptr + 3 < xmlbuf->end && ptr[0] == '!' && ptr[1] == '-' && ptr[2] == '-') /* skip comment */
511         {
512             for (ptr += 3; ptr + 3 <= xmlbuf->end; ptr++)
513                 if (ptr[0] == '-' && ptr[1] == '-' && ptr[2] == '>') break;
514
515             if (ptr + 3 > xmlbuf->end)
516             {
517                 xmlbuf->ptr = xmlbuf->end;
518                 return FALSE;
519             }
520             xmlbuf->ptr = ptr + 3;
521         }
522         else break;
523     }
524
525     xmlbuf->ptr = ptr;
526     while (ptr < xmlbuf->end && !isxmlspace(*ptr) && *ptr != '>' && (*ptr != '/' || ptr == xmlbuf->ptr))
527         ptr++;
528
529     elem->ptr = xmlbuf->ptr;
530     elem->len = ptr - xmlbuf->ptr;
531     xmlbuf->ptr = ptr;
532     return xmlbuf->ptr != xmlbuf->end;
533 }
534
535 static BOOL next_xml_attr(xmlbuf_t* xmlbuf, xmlstr_t* name, xmlstr_t* value,
536                           BOOL* error, BOOL* end)
537 {
538     const char *ptr;
539
540     *error = TRUE;
541
542     while (xmlbuf->ptr < xmlbuf->end && isxmlspace(*xmlbuf->ptr))
543         xmlbuf->ptr++;
544
545     if (xmlbuf->ptr == xmlbuf->end) return FALSE;
546
547     if (*xmlbuf->ptr == '/')
548     {
549         xmlbuf->ptr++;
550         if (xmlbuf->ptr == xmlbuf->end || *xmlbuf->ptr != '>')
551             return FALSE;
552
553         xmlbuf->ptr++;
554         *end = TRUE;
555         *error = FALSE;
556         return FALSE;
557     }
558
559     if (*xmlbuf->ptr == '>')
560     {
561         xmlbuf->ptr++;
562         *error = FALSE;
563         return FALSE;
564     }
565
566     ptr = xmlbuf->ptr;
567     while (ptr < xmlbuf->end && *ptr != '=' && *ptr != '>' && !isxmlspace(*ptr)) ptr++;
568
569     if (ptr == xmlbuf->end || *ptr != '=') return FALSE;
570
571     name->ptr = xmlbuf->ptr;
572     name->len = ptr-xmlbuf->ptr;
573     xmlbuf->ptr = ptr;
574
575     ptr++;
576     if (ptr == xmlbuf->end || (*ptr != '"' && *ptr != '\'')) return FALSE;
577
578     value->ptr = ++ptr;
579     if (ptr == xmlbuf->end) return FALSE;
580
581     ptr = memchr(ptr, ptr[-1], xmlbuf->end - ptr);
582     if (!ptr)
583     {
584         xmlbuf->ptr = xmlbuf->end;
585         return FALSE;
586     }
587
588     value->len = ptr - value->ptr;
589     xmlbuf->ptr = ptr + 1;
590
591     if (xmlbuf->ptr == xmlbuf->end) return FALSE;
592
593     *error = FALSE;
594     return TRUE;
595 }
596
597 static void get_manifest_filename( const xmlstr_t *arch, const xmlstr_t *name, const xmlstr_t *key,
598                                    const xmlstr_t *version, WCHAR *buffer, DWORD size )
599 {
600     static const WCHAR trailerW[] = {'_','n','o','n','e','_','d','e','a','d','b','e','e','f',0};
601     DWORD pos;
602
603     pos = MultiByteToWideChar( CP_UTF8, 0, arch->ptr, arch->len, buffer, size );
604     buffer[pos++] = '_';
605     pos += MultiByteToWideChar( CP_UTF8, 0, name->ptr, name->len, buffer + pos, size - pos );
606     buffer[pos++] = '_';
607     pos += MultiByteToWideChar( CP_UTF8, 0, key->ptr, key->len, buffer + pos, size - pos );
608     buffer[pos++] = '_';
609     pos += MultiByteToWideChar( CP_UTF8, 0, version->ptr, version->len, buffer + pos, size - pos );
610     memcpy( buffer + pos, trailerW, sizeof(trailerW) );
611     strlwrW( buffer );
612 }
613
614 static BOOL create_winsxs_dll( const WCHAR *dll_name, const xmlstr_t *arch, const xmlstr_t *name,
615                                const xmlstr_t *key, const xmlstr_t *version,
616                                const void *dll_data, size_t dll_size )
617 {
618     static const WCHAR winsxsW[] = {'w','i','n','s','x','s','\\'};
619     WCHAR *path;
620     const WCHAR *filename;
621     DWORD pos, written, path_len;
622     HANDLE handle;
623     BOOL ret = FALSE;
624
625     if (!(filename = strrchrW( dll_name, '\\' ))) filename = dll_name;
626     else filename++;
627
628     path_len = GetWindowsDirectoryW( NULL, 0 ) + 1 + sizeof(winsxsW)/sizeof(WCHAR)
629         + arch->len + name->len + key->len + version->len + 18 + strlenW( filename ) + 1;
630
631     path = HeapAlloc( GetProcessHeap(), 0, path_len * sizeof(WCHAR) );
632     pos = GetWindowsDirectoryW( path, path_len );
633     path[pos++] = '\\';
634     memcpy( path + pos, winsxsW, sizeof(winsxsW) );
635     pos += sizeof(winsxsW) / sizeof(WCHAR);
636     get_manifest_filename( arch, name, key, version, path + pos, path_len - pos );
637     pos += strlenW( path + pos );
638     path[pos++] = '\\';
639     strcpyW( path + pos, filename );
640     handle = create_dest_file( path );
641     if (handle && handle != INVALID_HANDLE_VALUE)
642     {
643         TRACE( "creating %s\n", debugstr_w(path) );
644         ret = (WriteFile( handle, dll_data, dll_size, &written, NULL ) && written == dll_size);
645         if (!ret) ERR( "failed to write to %s (error=%u)\n", debugstr_w(path), GetLastError() );
646         CloseHandle( handle );
647         if (!ret) DeleteFileW( path );
648     }
649     HeapFree( GetProcessHeap(), 0, path );
650     return ret;
651 }
652
653 static BOOL create_manifest( const xmlstr_t *arch, const xmlstr_t *name, const xmlstr_t *key,
654                              const xmlstr_t *version, const void *data, DWORD len )
655 {
656     static const WCHAR winsxsW[] = {'w','i','n','s','x','s','\\','m','a','n','i','f','e','s','t','s','\\'};
657     static const WCHAR extensionW[] = {'.','m','a','n','i','f','e','s','t',0};
658     WCHAR *path;
659     DWORD pos, written, path_len;
660     HANDLE handle;
661     BOOL ret = FALSE;
662
663     path_len = GetWindowsDirectoryW( NULL, 0 ) + 1 + sizeof(winsxsW)/sizeof(WCHAR)
664         + arch->len + name->len + key->len + version->len + 18 + sizeof(extensionW)/sizeof(WCHAR);
665
666     path = HeapAlloc( GetProcessHeap(), 0, path_len * sizeof(WCHAR) );
667     pos = GetWindowsDirectoryW( path, MAX_PATH );
668     path[pos++] = '\\';
669     memcpy( path + pos, winsxsW, sizeof(winsxsW) );
670     pos += sizeof(winsxsW) / sizeof(WCHAR);
671     get_manifest_filename( arch, name, key, version, path + pos, MAX_PATH - pos );
672     strcatW( path + pos, extensionW );
673     handle = CreateFileW( path, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, NULL );
674     if (handle == INVALID_HANDLE_VALUE && GetLastError() == ERROR_PATH_NOT_FOUND)
675     {
676         create_directories( path );
677         handle = CreateFileW( path, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, NULL );
678     }
679
680     if (handle != INVALID_HANDLE_VALUE)
681     {
682         TRACE( "creating %s\n", debugstr_w(path) );
683         ret = (WriteFile( handle, data, len, &written, NULL ) && written == len);
684         if (!ret) ERR( "failed to write to %s (error=%u)\n", debugstr_w(path), GetLastError() );
685         CloseHandle( handle );
686         if (!ret) DeleteFileW( path );
687     }
688     HeapFree( GetProcessHeap(), 0, path );
689     return ret;
690 }
691
692 static void register_manifest( const WCHAR *dll_name, const char *manifest, DWORD len,
693                                const void *dll_data, size_t dll_size )
694 {
695 #ifdef __i386__
696     static const char current_arch[] = "x86";
697 #elif defined __x86_64__
698     static const char current_arch[] = "amd64";
699 #else
700     static const char current_arch[] = "none";
701 #endif
702     xmlbuf_t buffer;
703     xmlstr_t elem, attr_name, attr_value;
704     xmlstr_t name, version, arch, key;
705     BOOL end = FALSE, error;
706
707     buffer.ptr = manifest;
708     buffer.end = manifest + len;
709     name.ptr = version.ptr = arch.ptr = key.ptr = NULL;
710     name.len = version.len = arch.len = key.len = 0;
711
712     while (next_xml_elem( &buffer, &elem ))
713     {
714         if (!xmlstr_cmp( &elem, "assemblyIdentity" )) continue;
715         while (next_xml_attr( &buffer, &attr_name, &attr_value, &error, &end ))
716         {
717             if (xmlstr_cmp(&attr_name, "name")) name = attr_value;
718             else if (xmlstr_cmp(&attr_name, "version")) version = attr_value;
719             else if (xmlstr_cmp(&attr_name, "processorArchitecture")) arch = attr_value;
720             else if (xmlstr_cmp(&attr_name, "publicKeyToken")) key = attr_value;
721         }
722         if (!error && name.ptr && version.ptr && arch.ptr && key.ptr)
723         {
724             if (!arch.len)  /* fixup the architecture */
725             {
726                 char *new_buffer = HeapAlloc( GetProcessHeap(), 0, len + sizeof(current_arch) );
727                 memcpy( new_buffer, manifest, arch.ptr - manifest );
728                 strcpy( new_buffer + (arch.ptr - manifest), current_arch );
729                 memcpy( new_buffer + strlen(new_buffer), arch.ptr, len - (arch.ptr - manifest) );
730                 arch.ptr = current_arch;
731                 arch.len = strlen( current_arch );
732                 if (create_winsxs_dll( dll_name, &arch, &name, &key, &version, dll_data, dll_size ))
733                     create_manifest( &arch, &name, &key, &version, new_buffer, len + arch.len );
734                 HeapFree( GetProcessHeap(), 0, new_buffer );
735             }
736             else
737             {
738                 if (create_winsxs_dll( dll_name, &arch, &name, &key, &version, dll_data, dll_size ))
739                     create_manifest( &arch, &name, &key, &version, manifest, len );
740             }
741         }
742     }
743 }
744
745 static BOOL CALLBACK register_resource( HMODULE module, LPCWSTR type, LPWSTR name, LONG_PTR arg )
746 {
747     HRESULT *hr = (HRESULT *)arg;
748     WCHAR *buffer;
749     HRSRC rsrc = FindResourceW( module, name, type );
750     char *str = LoadResource( module, rsrc );
751     DWORD lenW, lenA = SizeofResource( module, rsrc );
752
753     if (!str) return FALSE;
754     lenW = MultiByteToWideChar( CP_UTF8, 0, str, lenA, NULL, 0 ) + 1;
755     if (!(buffer = HeapAlloc( GetProcessHeap(), 0, lenW * sizeof(WCHAR) ))) return FALSE;
756     MultiByteToWideChar( CP_UTF8, 0, str, lenA, buffer, lenW );
757     buffer[lenW - 1] = 0;
758     *hr = IRegistrar_StringRegister( registrar, buffer );
759     HeapFree( GetProcessHeap(), 0, buffer );
760     return TRUE;
761 }
762
763 static void register_fake_dll( const WCHAR *name, const void *data, size_t size )
764 {
765     static const WCHAR atlW[] = {'a','t','l','.','d','l','l',0};
766     static const WCHAR moduleW[] = {'M','O','D','U','L','E',0};
767     static const WCHAR regtypeW[] = {'W','I','N','E','_','R','E','G','I','S','T','R','Y',0};
768     static const WCHAR manifestW[] = {'W','I','N','E','_','M','A','N','I','F','E','S','T',0};
769     const IMAGE_RESOURCE_DIRECTORY *resdir;
770     LDR_RESOURCE_INFO info;
771     HRESULT hr = S_OK;
772     HMODULE module = (HMODULE)((ULONG_PTR)data | 1);
773     HRSRC rsrc;
774
775     if ((rsrc = FindResourceW( module, manifestW, MAKEINTRESOURCEW(RT_MANIFEST) )))
776     {
777         char *manifest = LoadResource( module, rsrc );
778         register_manifest( name, manifest, SizeofResource( module, rsrc ), data, size );
779     }
780
781     info.Type = (ULONG_PTR)regtypeW;
782     if (LdrFindResourceDirectory_U( module, &info, 1, &resdir )) return;
783
784     if (!registrar)
785     {
786         /* create the object by hand since we can't guarantee that atl and ole32 are registered */
787         IClassFactory *cf;
788         HRESULT (WINAPI *pDllGetClassObject)( REFCLSID clsid, REFIID iid, LPVOID *ppv );
789         HMODULE atl = LoadLibraryW( atlW );
790
791         if ((pDllGetClassObject = (void *)GetProcAddress( atl, "DllGetClassObject" )))
792         {
793             hr = pDllGetClassObject( &CLSID_Registrar, &IID_IClassFactory, (void **)&cf );
794             if (SUCCEEDED( hr ))
795             {
796                 hr = IClassFactory_CreateInstance( cf, NULL, &IID_IRegistrar, (void **)&registrar );
797                 IClassFactory_Release( cf );
798             }
799         }
800         if (!registrar)
801         {
802             ERR( "failed to create IRegistrar: %x\n", hr );
803             return;
804         }
805     }
806
807     TRACE( "registering %s\n", debugstr_w(name) );
808     IRegistrar_ClearReplacements( registrar );
809     IRegistrar_AddReplacement( registrar, moduleW, name );
810     EnumResourceNamesW( module, regtypeW, register_resource, (LONG_PTR)&hr );
811     if (FAILED(hr)) ERR( "failed to register %s: %x\n", debugstr_w(name), hr );
812 }
813
814 /* copy a fake dll file to the dest directory */
815 static void install_fake_dll( WCHAR *dest, char *file, const char *ext )
816 {
817     int ret;
818     SIZE_T size;
819     void *data;
820     DWORD written;
821     WCHAR *destname = dest + strlenW(dest);
822     char *name = strrchr( file, '/' ) + 1;
823     char *end = name + strlen(name);
824
825     if (ext) strcpy( end, ext );
826     if (!(ret = read_file( file, &data, &size ))) return;
827
828     if (end > name + 2 && !strncmp( end - 2, "16", 2 )) end -= 2;  /* remove "16" suffix */
829     dll_name_AtoW( destname, name, end - name );
830     if (!add_handled_dll( destname )) ret = -1;
831
832     if (ret != -1)
833     {
834         HANDLE h = create_dest_file( dest );
835
836         if (h && h != INVALID_HANDLE_VALUE)
837         {
838             TRACE( "%s -> %s\n", debugstr_a(file), debugstr_w(dest) );
839
840             ret = (WriteFile( h, data, size, &written, NULL ) && written == size);
841             if (!ret) ERR( "failed to write to %s (error=%u)\n", debugstr_w(dest), GetLastError() );
842             CloseHandle( h );
843             if (ret) register_fake_dll( dest, data, size );
844             else DeleteFileW( dest );
845         }
846     }
847     *destname = 0;  /* restore it for next file */
848 }
849
850 /* find and install all fake dlls in a given lib directory */
851 static void install_lib_dir( WCHAR *dest, char *file, const char *default_ext )
852 {
853     DIR *dir;
854     struct dirent *de;
855     char *name;
856
857     if (!(dir = opendir( file ))) return;
858     name = file + strlen(file);
859     *name++ = '/';
860     while ((de = readdir( dir )))
861     {
862         if (strlen( de->d_name ) > max_dll_name_len) continue;
863         if (!strcmp( de->d_name, "." )) continue;
864         if (!strcmp( de->d_name, ".." )) continue;
865         strcpy( name, de->d_name );
866         if (default_ext)  /* inside build dir */
867         {
868             strcat( name, "/" );
869             strcat( name, de->d_name );
870             if (!strchr( de->d_name, '.' )) strcat( name, default_ext );
871             install_fake_dll( dest, file, ".fake" );
872         }
873         else install_fake_dll( dest, file, NULL );
874     }
875     closedir( dir );
876 }
877
878 /* create fake dlls in dirname for all the files we can find */
879 static BOOL create_wildcard_dlls( const WCHAR *dirname )
880 {
881     const char *build_dir = wine_get_build_dir();
882     const char *path;
883     unsigned int i, maxlen = 0;
884     char *file;
885     WCHAR *dest;
886
887     if (build_dir) maxlen = strlen(build_dir) + sizeof("/programs/");
888     for (i = 0; (path = wine_dll_enum_load_path(i)); i++) maxlen = max( maxlen, strlen(path) );
889     maxlen += 2 * max_dll_name_len + 2 + sizeof(".dll.fake");
890     if (!(file = HeapAlloc( GetProcessHeap(), 0, maxlen ))) return FALSE;
891
892     if (!(dest = HeapAlloc( GetProcessHeap(), 0, (strlenW(dirname) + max_dll_name_len) * sizeof(WCHAR) )))
893     {
894         HeapFree( GetProcessHeap(), 0, file );
895         return FALSE;
896     }
897     strcpyW( dest, dirname );
898     dest[strlenW(dest) - 1] = 0;  /* remove wildcard */
899
900     if (build_dir)
901     {
902         strcpy( file, build_dir );
903         strcat( file, "/dlls" );
904         install_lib_dir( dest, file, ".dll" );
905         strcpy( file, build_dir );
906         strcat( file, "/programs" );
907         install_lib_dir( dest, file, ".exe" );
908     }
909     for (i = 0; (path = wine_dll_enum_load_path( i )); i++)
910     {
911         strcpy( file, path );
912         strcat( file, "/fakedlls" );
913         install_lib_dir( dest, file, NULL );
914     }
915     HeapFree( GetProcessHeap(), 0, file );
916     HeapFree( GetProcessHeap(), 0, dest );
917     return TRUE;
918 }
919
920 /***********************************************************************
921  *            create_fake_dll
922  */
923 BOOL create_fake_dll( const WCHAR *name, const WCHAR *source )
924 {
925     HANDLE h;
926     BOOL ret;
927     SIZE_T size;
928     const WCHAR *filename;
929     void *buffer;
930
931     if (!(filename = strrchrW( name, '\\' ))) filename = name;
932     else filename++;
933
934     /* check for empty name which means to only create the directory */
935     if (!filename[0])
936     {
937         create_directories( name );
938         return TRUE;
939     }
940     if (filename[0] == '*' && !filename[1]) return create_wildcard_dlls( name );
941
942     add_handled_dll( filename );
943
944     if (!(h = create_dest_file( name ))) return TRUE;  /* not a fake dll */
945     if (h == INVALID_HANDLE_VALUE) return FALSE;
946
947     if (source[0] == '-' && !source[1])
948     {
949         /* '-' source means delete the file */
950         TRACE( "deleting %s\n", debugstr_w(name) );
951         ret = FALSE;
952     }
953     else if ((buffer = load_fake_dll( source, &size )))
954     {
955         DWORD written;
956
957         ret = (WriteFile( h, buffer, size, &written, NULL ) && written == size);
958         if (ret) register_fake_dll( name, buffer, size );
959         else ERR( "failed to write to %s (error=%u)\n", debugstr_w(name), GetLastError() );
960     }
961     else
962     {
963         WARN( "fake dll %s not found for %s\n", debugstr_w(source), debugstr_w(name) );
964         ret = build_fake_dll( h );
965     }
966
967     CloseHandle( h );
968     if (!ret) DeleteFileW( name );
969     return ret;
970 }
971
972
973 /***********************************************************************
974  *            cleanup_fake_dlls
975  */
976 void cleanup_fake_dlls(void)
977 {
978     if (file_buffer) VirtualFree( file_buffer, 0, MEM_RELEASE );
979     file_buffer = NULL;
980     HeapFree( GetProcessHeap(), 0, handled_dlls );
981     handled_dlls = NULL;
982     handled_count = handled_total = 0;
983     if (registrar) IRegistrar_Release( registrar );
984     registrar = NULL;
985 }