setupapi: Validate the cabinet filename parameter in SetupIterateCabinetA.
[wine] / dlls / setupapi / fakedll.c
1 /*
2  * Creation of Wine fake dlls for apps that access the dll file directly.
3  *
4  * Copyright 2006 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 NONAMELESSSTRUCT
37 #define NONAMELESSUNION
38 #include "ntstatus.h"
39 #define WIN32_NO_STATUS
40 #include "windef.h"
41 #include "winbase.h"
42 #include "winuser.h"
43 #include "winnt.h"
44 #include "winternl.h"
45 #include "wine/unicode.h"
46 #include "wine/library.h"
47 #include "wine/debug.h"
48
49 WINE_DEFAULT_DEBUG_CHANNEL(setupapi);
50
51 static const char fakedll_signature[] = "Wine placeholder DLL";
52
53 static const unsigned int file_alignment = 512;
54 static const unsigned int section_alignment = 4096;
55 static const unsigned int max_dll_name_len = 64;
56
57 static void *file_buffer;
58 static size_t file_buffer_size;
59 static unsigned int handled_count;
60 static unsigned int handled_total;
61 static char **handled_dlls;
62
63 struct dll_info
64 {
65     HANDLE            handle;
66     IMAGE_NT_HEADERS *nt;
67     DWORD             file_pos;
68     DWORD             mem_pos;
69 };
70
71 #define ALIGN(size,align) (((size) + (align) - 1) & ~((align) - 1))
72
73 /* contents of the dll sections */
74
75 static const BYTE dll_code_section[] = { 0x31, 0xc0,          /* xor %eax,%eax */
76                                          0xc2, 0x0c, 0x00 };  /* ret $12 */
77
78 static const BYTE exe_code_section[] = { 0xb8, 0x01, 0x00, 0x00, 0x00,  /* movl $1,%eax */
79                                          0xc2, 0x04, 0x00 };            /* ret $4 */
80
81 static const IMAGE_BASE_RELOCATION reloc_section;  /* empty relocs */
82
83
84 /* wrapper for WriteFile */
85 static inline BOOL xwrite( struct dll_info *info, const void *data, DWORD size, DWORD offset )
86 {
87     DWORD res;
88
89     return (SetFilePointer( info->handle, offset, NULL, FILE_BEGIN ) != INVALID_SET_FILE_POINTER &&
90             WriteFile( info->handle, data, size, &res, NULL ) &&
91             res == size);
92 }
93
94 /* add a new section to the dll NT header */
95 static void add_section( struct dll_info *info, const char *name, DWORD size, DWORD flags )
96 {
97     IMAGE_SECTION_HEADER *sec = (IMAGE_SECTION_HEADER *)(info->nt + 1);
98
99     sec += info->nt->FileHeader.NumberOfSections;
100     memcpy( sec->Name, name, min( strlen(name), sizeof(sec->Name)) );
101     sec->Misc.VirtualSize = ALIGN( size, section_alignment );
102     sec->VirtualAddress   = info->mem_pos;
103     sec->SizeOfRawData    = size;
104     sec->PointerToRawData = info->file_pos;
105     sec->Characteristics  = flags;
106     info->file_pos += ALIGN( size, file_alignment );
107     info->mem_pos  += ALIGN( size, section_alignment );
108     info->nt->FileHeader.NumberOfSections++;
109 }
110
111 /* add a data directory to the dll NT header */
112 static inline void add_directory( struct dll_info *info, unsigned int idx, DWORD rva, DWORD size )
113 {
114     info->nt->OptionalHeader.DataDirectory[idx].VirtualAddress = rva;
115     info->nt->OptionalHeader.DataDirectory[idx].Size = size;
116 }
117
118 /* convert a dll name W->A without depending on the current codepage */
119 static char *dll_name_WtoA( char *nameA, const WCHAR *nameW, unsigned int len )
120 {
121     unsigned int i;
122
123     for (i = 0; i < len; i++)
124     {
125         char c = nameW[i];
126         if (nameW[i] > 127) return NULL;
127         if (c >= 'A' && c <= 'Z') c += 'a' - 'A';
128         nameA[i] = c;
129     }
130     nameA[i] = 0;
131     return nameA;
132 }
133
134 /* convert a dll name A->W without depending on the current codepage */
135 static WCHAR *dll_name_AtoW( WCHAR *nameW, const char *nameA, unsigned int len )
136 {
137     unsigned int i;
138
139     for (i = 0; i < len; i++) nameW[i] = nameA[i];
140     nameW[i] = 0;
141     return nameW;
142 }
143
144 /* add a dll to the list of dll that have been taken care of */
145 static BOOL add_handled_dll( const WCHAR *name )
146 {
147     unsigned int len = strlenW( name );
148     int i, min, max, pos, res;
149     char *nameA;
150
151     if (!(nameA = HeapAlloc( GetProcessHeap(), 0, len + 1 ))) return FALSE;
152     if (!dll_name_WtoA( nameA, name, len )) goto failed;
153
154     min = 0;
155     max = handled_count - 1;
156     while (min <= max)
157     {
158         pos = (min + max) / 2;
159         res = strcmp( handled_dlls[pos], nameA );
160         if (!res) goto failed;  /* already in the list */
161         if (res < 0) min = pos + 1;
162         else max = pos - 1;
163     }
164
165     if (handled_count >= handled_total)
166     {
167         char **new_dlls;
168         unsigned int new_count = max( 64, handled_total * 2 );
169
170         if (handled_dlls) new_dlls = HeapReAlloc( GetProcessHeap(), 0, handled_dlls,
171                                                   new_count * sizeof(*handled_dlls) );
172         else new_dlls = HeapAlloc( GetProcessHeap(), 0, new_count * sizeof(*handled_dlls) );
173         if (!new_dlls) goto failed;
174         handled_dlls = new_dlls;
175         handled_total = new_count;
176     }
177
178     for (i = handled_count; i > min; i--) handled_dlls[i] = handled_dlls[i - 1];
179     handled_dlls[i] = nameA;
180     handled_count++;
181     return TRUE;
182
183 failed:
184     HeapFree( GetProcessHeap(), 0, nameA );
185     return FALSE;
186 }
187
188 /* read in the contents of a file into the global file buffer */
189 /* return 1 on success, 0 on nonexistent file, -1 on other error */
190 static int read_file( const char *name, void **data, size_t *size )
191 {
192     static char static_file_buffer[4096];
193     struct stat st;
194     void *buffer = static_file_buffer;
195     int fd, ret = -1;
196     size_t header_size;
197     IMAGE_DOS_HEADER *dos;
198     IMAGE_NT_HEADERS *nt;
199     const size_t min_size = sizeof(*dos) + sizeof(fakedll_signature) +
200         FIELD_OFFSET( IMAGE_NT_HEADERS, OptionalHeader.MajorLinkerVersion );
201
202     if ((fd = open( name, O_RDONLY | O_BINARY )) == -1) return 0;
203     if (fstat( fd, &st ) == -1) goto done;
204     *size = st.st_size;
205     if (st.st_size > sizeof(static_file_buffer))
206     {
207         if (!file_buffer || st.st_size > file_buffer_size)
208         {
209             HeapFree( GetProcessHeap(), 0, file_buffer );
210             if (!(file_buffer = HeapAlloc( GetProcessHeap(), 0, st.st_size ))) goto done;
211             file_buffer_size = st.st_size;
212         }
213         buffer = file_buffer;
214     }
215
216     /* check for valid fake dll file */
217
218     if (st.st_size < min_size) goto done;
219     header_size = min( st.st_size, 4096 );
220     if (pread( fd, buffer, header_size, 0 ) != header_size) goto done;
221     dos = buffer;
222     if (dos->e_magic != IMAGE_DOS_SIGNATURE) goto done;
223     if (dos->e_lfanew < sizeof(fakedll_signature)) goto done;
224     if (memcmp( dos + 1, fakedll_signature, sizeof(fakedll_signature) )) goto done;
225     if (dos->e_lfanew + FIELD_OFFSET(IMAGE_NT_HEADERS,OptionalHeader.MajorLinkerVersion) > header_size)
226         goto done;
227     nt = (IMAGE_NT_HEADERS *)((char *)buffer + dos->e_lfanew);
228     if (nt->Signature == IMAGE_NT_SIGNATURE && nt->OptionalHeader.Magic != IMAGE_NT_OPTIONAL_HDR_MAGIC)
229     {
230         /* wrong 32/64 type, pretend it doesn't exist */
231         ret = 0;
232         goto done;
233     }
234     if (st.st_size == header_size ||
235         pread( fd, (char *)buffer + header_size,
236                st.st_size - header_size, header_size ) == st.st_size - header_size)
237     {
238         *data = buffer;
239         ret = 1;
240     }
241 done:
242     close( fd );
243     return ret;
244 }
245
246 /* build a complete fake dll from scratch */
247 static BOOL build_fake_dll( HANDLE file )
248 {
249     IMAGE_DOS_HEADER *dos;
250     IMAGE_NT_HEADERS *nt;
251     struct dll_info info;
252     BYTE *buffer;
253     BOOL ret = FALSE;
254     DWORD lfanew = (sizeof(*dos) + sizeof(fakedll_signature) + 15) & ~15;
255     DWORD size, header_size = lfanew + sizeof(*nt);
256
257     info.handle = file;
258     buffer = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, header_size + 8 * sizeof(IMAGE_SECTION_HEADER) );
259
260     dos = (IMAGE_DOS_HEADER *)buffer;
261     dos->e_magic    = IMAGE_DOS_SIGNATURE;
262     dos->e_cblp     = sizeof(*dos);
263     dos->e_cp       = 1;
264     dos->e_cparhdr  = lfanew / 16;
265     dos->e_minalloc = 0;
266     dos->e_maxalloc = 0xffff;
267     dos->e_ss       = 0x0000;
268     dos->e_sp       = 0x00b8;
269     dos->e_lfarlc   = lfanew;
270     dos->e_lfanew   = lfanew;
271     memcpy( dos + 1, fakedll_signature, sizeof(fakedll_signature) );
272
273     nt = info.nt = (IMAGE_NT_HEADERS *)(buffer + lfanew);
274     /* some fields are copied from the source dll */
275 #ifdef _WIN64
276     nt->FileHeader.Machine = IMAGE_FILE_MACHINE_AMD64;
277 #else
278     nt->FileHeader.Machine = IMAGE_FILE_MACHINE_I386;
279 #endif
280     nt->FileHeader.TimeDateStamp = 0;
281     nt->FileHeader.Characteristics = IMAGE_FILE_DLL;
282     nt->OptionalHeader.MajorLinkerVersion = 1;
283     nt->OptionalHeader.MinorLinkerVersion = 0;
284     nt->OptionalHeader.MajorOperatingSystemVersion = 1;
285     nt->OptionalHeader.MinorOperatingSystemVersion = 0;
286     nt->OptionalHeader.MajorImageVersion = 1;
287     nt->OptionalHeader.MinorImageVersion = 0;
288     nt->OptionalHeader.MajorSubsystemVersion = 4;
289     nt->OptionalHeader.MinorSubsystemVersion = 0;
290     nt->OptionalHeader.Win32VersionValue = 0;
291     nt->OptionalHeader.Subsystem = IMAGE_SUBSYSTEM_WINDOWS_GUI;
292     nt->OptionalHeader.DllCharacteristics = 0;
293     nt->OptionalHeader.SizeOfStackReserve = 0;
294     nt->OptionalHeader.SizeOfStackCommit = 0;
295     nt->OptionalHeader.SizeOfHeapReserve = 0;
296     nt->OptionalHeader.SizeOfHeapCommit = 0;
297     /* other fields have fixed values */
298     nt->Signature                              = IMAGE_NT_SIGNATURE;
299     nt->FileHeader.NumberOfSections            = 0;
300     nt->FileHeader.SizeOfOptionalHeader        = IMAGE_SIZEOF_NT_OPTIONAL_HEADER;
301     nt->OptionalHeader.Magic                   = IMAGE_NT_OPTIONAL_HDR_MAGIC;
302     nt->OptionalHeader.ImageBase               = 0x10000000;
303     nt->OptionalHeader.SectionAlignment        = section_alignment;
304     nt->OptionalHeader.FileAlignment           = file_alignment;
305     nt->OptionalHeader.NumberOfRvaAndSizes     = IMAGE_NUMBEROF_DIRECTORY_ENTRIES;
306
307     header_size = (BYTE *)(nt + 1) - buffer;
308     info.mem_pos  = ALIGN( header_size, section_alignment );
309     info.file_pos = ALIGN( header_size, file_alignment );
310
311     nt->OptionalHeader.AddressOfEntryPoint = info.mem_pos;
312     nt->OptionalHeader.BaseOfCode          = info.mem_pos;
313
314     if (nt->FileHeader.Characteristics & IMAGE_FILE_DLL)
315     {
316         size = sizeof(dll_code_section);
317         if (!xwrite( &info, dll_code_section, size, info.file_pos )) goto done;
318     }
319     else
320     {
321         size = sizeof(exe_code_section);
322         if (!xwrite( &info, exe_code_section, size, info.file_pos )) goto done;
323     }
324     nt->OptionalHeader.SizeOfCode = size;
325     add_section( &info, ".text", size, IMAGE_SCN_CNT_CODE | IMAGE_SCN_MEM_EXECUTE | IMAGE_SCN_MEM_READ );
326
327     if (!xwrite( &info, &reloc_section, sizeof(reloc_section), info.file_pos )) goto done;
328     add_directory( &info, IMAGE_DIRECTORY_ENTRY_BASERELOC, info.mem_pos, sizeof(reloc_section) );
329     add_section( &info, ".reloc", sizeof(reloc_section),
330                  IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_DISCARDABLE | IMAGE_SCN_MEM_READ );
331
332     header_size += nt->FileHeader.NumberOfSections * sizeof(IMAGE_SECTION_HEADER);
333     nt->OptionalHeader.SizeOfHeaders = ALIGN( header_size, file_alignment );
334     nt->OptionalHeader.SizeOfImage   = ALIGN( info.mem_pos, section_alignment );
335     ret = xwrite( &info, buffer, header_size, 0 );
336 done:
337     HeapFree( GetProcessHeap(), 0, buffer );
338     return ret;
339 }
340
341 /* check if an existing file is a fake dll so that we can overwrite it */
342 static BOOL is_fake_dll( HANDLE h )
343 {
344     IMAGE_DOS_HEADER *dos;
345     DWORD size;
346     BYTE buffer[sizeof(*dos) + sizeof(fakedll_signature)];
347
348     if (!ReadFile( h, buffer, sizeof(buffer), &size, NULL ) || size != sizeof(buffer))
349         return FALSE;
350     dos = (IMAGE_DOS_HEADER *)buffer;
351     if (dos->e_magic != IMAGE_DOS_SIGNATURE) return FALSE;
352     if (dos->e_lfanew < size) return FALSE;
353     return !memcmp( dos + 1, fakedll_signature, sizeof(fakedll_signature) );
354 }
355
356 /* create directories leading to a given file */
357 static void create_directories( const WCHAR *name )
358 {
359     WCHAR *path, *p;
360
361     /* create the directory/directories */
362     path = HeapAlloc(GetProcessHeap(), 0, (strlenW(name) + 1)*sizeof(WCHAR));
363     strcpyW(path, name);
364
365     p = strchrW(path, '\\');
366     while (p != NULL)
367     {
368         *p = 0;
369         if (!CreateDirectoryW(path, NULL))
370             TRACE("Couldn't create directory %s - error: %d\n", wine_dbgstr_w(path), GetLastError());
371         *p = '\\';
372         p = strchrW(p+1, '\\');
373     }
374     HeapFree(GetProcessHeap(), 0, path);
375 }
376
377 static inline char *prepend( char *buffer, const char *str, size_t len )
378 {
379     return memcpy( buffer - len, str, len );
380 }
381
382 /* try to load a pre-compiled fake dll */
383 static void *load_fake_dll( const WCHAR *name, size_t *size )
384 {
385     const char *build_dir = wine_get_build_dir();
386     const char *path;
387     char *file, *ptr;
388     void *data = NULL;
389     unsigned int i, pos, len, namelen, maxlen = 0;
390     WCHAR *p;
391     int res = 0;
392
393     if ((p = strrchrW( name, '\\' ))) name = p + 1;
394
395     i = 0;
396     if (build_dir) maxlen = strlen(build_dir) + sizeof("/programs/") + strlenW(name);
397     while ((path = wine_dll_enum_load_path( i++ ))) maxlen = max( maxlen, strlen(path) );
398     maxlen += sizeof("/fakedlls") + strlenW(name) + 2;
399
400     if (!(file = HeapAlloc( GetProcessHeap(), 0, maxlen ))) return NULL;
401
402     len = strlenW( name );
403     pos = maxlen - len - sizeof(".fake");
404     if (!dll_name_WtoA( file + pos, name, len )) goto done;
405     file[--pos] = '/';
406
407     if (build_dir)
408     {
409         strcpy( file + pos + len + 1, ".fake" );
410
411         /* try as a dll */
412         ptr = file + pos;
413         namelen = len + 1;
414         if (namelen > 4 && !memcmp( ptr + namelen - 4, ".dll", 4 )) namelen -= 4;
415         ptr = prepend( ptr, ptr, namelen );
416         ptr = prepend( ptr, "/dlls", sizeof("/dlls") - 1 );
417         ptr = prepend( ptr, build_dir, strlen(build_dir) );
418         if ((res = read_file( ptr, &data, size ))) goto done;
419
420         /* now as a program */
421         ptr = file + pos;
422         namelen = len + 1;
423         if (namelen > 4 && !memcmp( ptr + namelen - 4, ".exe", 4 )) namelen -= 4;
424         ptr = prepend( ptr, ptr, namelen );
425         ptr = prepend( ptr, "/programs", sizeof("/programs") - 1 );
426         ptr = prepend( ptr, build_dir, strlen(build_dir) );
427         if ((res = read_file( ptr, &data, size ))) goto done;
428     }
429
430     file[pos + len + 1] = 0;
431     for (i = 0; (path = wine_dll_enum_load_path( i )); i++)
432     {
433         ptr = prepend( file + pos, "/fakedlls", sizeof("/fakedlls") - 1 );
434         ptr = prepend( ptr, path, strlen(path) );
435         if ((res = read_file( ptr, &data, size ))) break;
436     }
437
438 done:
439     HeapFree( GetProcessHeap(), 0, file );
440     if (res == 1) return data;
441     return NULL;
442 }
443
444 /* create the fake dll destination file */
445 static HANDLE create_dest_file( const WCHAR *name )
446 {
447     /* first check for an existing file */
448     HANDLE h = CreateFileW( name, GENERIC_READ|GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL );
449     if (h != INVALID_HANDLE_VALUE)
450     {
451         if (!is_fake_dll( h ))
452         {
453             TRACE( "%s is not a fake dll, not overwriting it\n", debugstr_w(name) );
454             CloseHandle( h );
455             return 0;
456         }
457         /* truncate the file */
458         SetFilePointer( h, 0, NULL, FILE_BEGIN );
459         SetEndOfFile( h );
460     }
461     else
462     {
463         if (GetLastError() == ERROR_PATH_NOT_FOUND) create_directories( name );
464
465         h = CreateFileW( name, GENERIC_WRITE, 0, NULL, CREATE_NEW, 0, NULL );
466         if (h == INVALID_HANDLE_VALUE)
467             ERR( "failed to create %s (error=%u)\n", debugstr_w(name), GetLastError() );
468     }
469     return h;
470 }
471
472 /* copy a fake dll file to the dest directory */
473 static void install_fake_dll( WCHAR *dest, char *file, const char *ext )
474 {
475     int ret;
476     size_t size;
477     void *data;
478     DWORD written;
479     WCHAR *destname = dest + strlenW(dest);
480     char *name = strrchr( file, '/' ) + 1;
481     char *end = name + strlen(name);
482
483     if (ext) strcpy( end, ext );
484     if (!(ret = read_file( file, &data, &size ))) return;
485
486     if (end > name + 2 && !strncmp( end - 2, "16", 2 )) end -= 2;  /* remove "16" suffix */
487     dll_name_AtoW( destname, name, end - name );
488     if (!add_handled_dll( destname )) ret = -1;
489
490     if (ret != -1)
491     {
492         HANDLE h = create_dest_file( dest );
493
494         if (h && h != INVALID_HANDLE_VALUE)
495         {
496             TRACE( "%s -> %s\n", debugstr_a(file), debugstr_w(dest) );
497
498             ret = (WriteFile( h, data, size, &written, NULL ) && written == size);
499             if (!ret) ERR( "failed to write to %s (error=%u)\n", debugstr_w(dest), GetLastError() );
500             CloseHandle( h );
501             if (!ret) DeleteFileW( dest );
502         }
503     }
504     *destname = 0;  /* restore it for next file */
505 }
506
507 /* find and install all fake dlls in a given lib directory */
508 static void install_lib_dir( WCHAR *dest, char *file, const char *default_ext )
509 {
510     DIR *dir;
511     struct dirent *de;
512     char *name;
513
514     if (!(dir = opendir( file ))) return;
515     name = file + strlen(file);
516     *name++ = '/';
517     while ((de = readdir( dir )))
518     {
519         if (strlen( de->d_name ) > max_dll_name_len) continue;
520         if (!strcmp( de->d_name, "." )) continue;
521         if (!strcmp( de->d_name, ".." )) continue;
522         strcpy( name, de->d_name );
523         if (default_ext)  /* inside build dir */
524         {
525             strcat( name, "/" );
526             strcat( name, de->d_name );
527             if (!strchr( de->d_name, '.' )) strcat( name, default_ext );
528             install_fake_dll( dest, file, ".fake" );
529         }
530         else install_fake_dll( dest, file, NULL );
531     }
532     closedir( dir );
533 }
534
535 /* create fake dlls in dirname for all the files we can find */
536 static BOOL create_wildcard_dlls( const WCHAR *dirname )
537 {
538     const char *build_dir = wine_get_build_dir();
539     const char *path;
540     unsigned int i, maxlen = 0;
541     char *file;
542     WCHAR *dest;
543
544     if (build_dir) maxlen = strlen(build_dir) + sizeof("/programs/");
545     for (i = 0; (path = wine_dll_enum_load_path(i)); i++) maxlen = max( maxlen, strlen(path) );
546     maxlen += 2 * max_dll_name_len + 2 + sizeof(".dll.fake");
547     if (!(file = HeapAlloc( GetProcessHeap(), 0, maxlen ))) return FALSE;
548
549     if (!(dest = HeapAlloc( GetProcessHeap(), 0, (strlenW(dirname) + max_dll_name_len) * sizeof(WCHAR) )))
550     {
551         HeapFree( GetProcessHeap(), 0, file );
552         return FALSE;
553     }
554     strcpyW( dest, dirname );
555     dest[strlenW(dest) - 1] = 0;  /* remove wildcard */
556
557     if (build_dir)
558     {
559         strcpy( file, build_dir );
560         strcat( file, "/dlls" );
561         install_lib_dir( dest, file, ".dll" );
562         strcpy( file, build_dir );
563         strcat( file, "/programs" );
564         install_lib_dir( dest, file, ".exe" );
565     }
566     for (i = 0; (path = wine_dll_enum_load_path( i )); i++)
567     {
568         strcpy( file, path );
569         strcat( file, "/fakedlls" );
570         install_lib_dir( dest, file, NULL );
571     }
572     HeapFree( GetProcessHeap(), 0, file );
573     HeapFree( GetProcessHeap(), 0, dest );
574     return TRUE;
575 }
576
577 /***********************************************************************
578  *            create_fake_dll
579  */
580 BOOL create_fake_dll( const WCHAR *name, const WCHAR *source )
581 {
582     HANDLE h;
583     BOOL ret;
584     size_t size;
585     const WCHAR *filename;
586     void *buffer;
587
588     if (!(filename = strrchrW( name, '\\' ))) filename = name;
589     else filename++;
590
591     /* check for empty name which means to only create the directory */
592     if (!filename[0])
593     {
594         create_directories( name );
595         return TRUE;
596     }
597     if (filename[0] == '*' && !filename[1]) return create_wildcard_dlls( name );
598
599     add_handled_dll( filename );
600
601     if (!(h = create_dest_file( name ))) return TRUE;  /* not a fake dll */
602     if (h == INVALID_HANDLE_VALUE) return FALSE;
603
604     if (source[0] == '-' && !source[1])
605     {
606         /* '-' source means delete the file */
607         TRACE( "deleting %s\n", debugstr_w(name) );
608         ret = FALSE;
609     }
610     else if ((buffer = load_fake_dll( source, &size )))
611     {
612         DWORD written;
613
614         ret = (WriteFile( h, buffer, size, &written, NULL ) && written == size);
615         if (!ret) ERR( "failed to write to %s (error=%u)\n", debugstr_w(name), GetLastError() );
616     }
617     else
618     {
619         WARN( "fake dll %s not found for %s\n", debugstr_w(source), debugstr_w(name) );
620         ret = build_fake_dll( h );
621     }
622
623     CloseHandle( h );
624     if (!ret) DeleteFileW( name );
625     return ret;
626 }
627
628
629 /***********************************************************************
630  *            cleanup_fake_dlls
631  */
632 void cleanup_fake_dlls(void)
633 {
634     HeapFree( GetProcessHeap(), 0, file_buffer );
635     file_buffer = NULL;
636     HeapFree( GetProcessHeap(), 0, handled_dlls );
637     handled_dlls = NULL;
638     handled_count = handled_total = 0;
639 }