2 * Creation of Wine fake dlls for apps that access the dll file directly.
4 * Copyright 2006 Alexandre Julliard
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.
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.
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
22 #include "wine/port.h"
29 #ifdef HAVE_SYS_STAT_H
30 # include <sys/stat.h>
36 #define NONAMELESSSTRUCT
37 #define NONAMELESSUNION
39 #define WIN32_NO_STATUS
45 #include "wine/unicode.h"
46 #include "wine/library.h"
47 #include "wine/debug.h"
49 WINE_DEFAULT_DEBUG_CHANNEL(setupapi);
51 static const char fakedll_signature[] = "Wine placeholder DLL";
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;
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;
71 #define ALIGN(size,align) (((size) + (align) - 1) & ~((align) - 1))
73 /* contents of the dll sections */
75 static const BYTE dll_code_section[] = { 0x31, 0xc0, /* xor %eax,%eax */
76 0xc2, 0x0c, 0x00 }; /* ret $12 */
78 static const BYTE exe_code_section[] = { 0xb8, 0x01, 0x00, 0x00, 0x00, /* movl $1,%eax */
79 0xc2, 0x04, 0x00 }; /* ret $4 */
81 static const IMAGE_BASE_RELOCATION reloc_section; /* empty relocs */
84 /* wrapper for WriteFile */
85 static inline BOOL xwrite( struct dll_info *info, const void *data, DWORD size, DWORD offset )
89 return (SetFilePointer( info->handle, offset, NULL, FILE_BEGIN ) != INVALID_SET_FILE_POINTER &&
90 WriteFile( info->handle, data, size, &res, NULL ) &&
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 )
97 IMAGE_SECTION_HEADER *sec = (IMAGE_SECTION_HEADER *)(info->nt + 1);
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++;
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 )
114 info->nt->OptionalHeader.DataDirectory[idx].VirtualAddress = rva;
115 info->nt->OptionalHeader.DataDirectory[idx].Size = size;
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 )
123 for (i = 0; i < len; i++)
126 if (nameW[i] > 127) return NULL;
127 if (c >= 'A' && c <= 'Z') c += 'a' - 'A';
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 )
139 for (i = 0; i < len; i++) nameW[i] = nameA[i];
144 /* add a dll to the list of dll that have been taken care of */
145 static BOOL add_handled_dll( const WCHAR *name )
147 unsigned int len = strlenW( name );
148 int i, min, max, pos, res;
151 if (!(nameA = HeapAlloc( GetProcessHeap(), 0, len + 1 ))) return FALSE;
152 if (!dll_name_WtoA( nameA, name, len )) goto failed;
155 max = handled_count - 1;
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;
165 if (handled_count >= handled_total)
168 unsigned int new_count = max( 64, handled_total * 2 );
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;
178 for (i = handled_count; i > min; i--) handled_dlls[i] = handled_dlls[i - 1];
179 handled_dlls[i] = nameA;
184 HeapFree( GetProcessHeap(), 0, nameA );
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 )
192 static char static_file_buffer[4096];
194 void *buffer = static_file_buffer;
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 );
202 if ((fd = open( name, O_RDONLY | O_BINARY )) == -1) return 0;
203 if (fstat( fd, &st ) == -1) goto done;
205 if (st.st_size > sizeof(static_file_buffer))
207 if (!file_buffer || st.st_size > file_buffer_size)
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;
213 buffer = file_buffer;
216 /* check for valid fake dll file */
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;
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)
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)
230 /* wrong 32/64 type, pretend it doesn't exist */
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)
246 /* build a complete fake dll from scratch */
247 static BOOL build_fake_dll( HANDLE file )
249 IMAGE_DOS_HEADER *dos;
250 IMAGE_NT_HEADERS *nt;
251 struct dll_info info;
254 DWORD lfanew = (sizeof(*dos) + sizeof(fakedll_signature) + 15) & ~15;
255 DWORD size, header_size = lfanew + sizeof(*nt);
258 buffer = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, header_size + 8 * sizeof(IMAGE_SECTION_HEADER) );
260 dos = (IMAGE_DOS_HEADER *)buffer;
261 dos->e_magic = IMAGE_DOS_SIGNATURE;
262 dos->e_cblp = sizeof(*dos);
264 dos->e_cparhdr = lfanew / 16;
266 dos->e_maxalloc = 0xffff;
269 dos->e_lfarlc = lfanew;
270 dos->e_lfanew = lfanew;
271 memcpy( dos + 1, fakedll_signature, sizeof(fakedll_signature) );
273 nt = info.nt = (IMAGE_NT_HEADERS *)(buffer + lfanew);
274 /* some fields are copied from the source dll */
276 nt->FileHeader.Machine = IMAGE_FILE_MACHINE_AMD64;
278 nt->FileHeader.Machine = IMAGE_FILE_MACHINE_I386;
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;
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 );
311 nt->OptionalHeader.AddressOfEntryPoint = info.mem_pos;
312 nt->OptionalHeader.BaseOfCode = info.mem_pos;
314 if (nt->FileHeader.Characteristics & IMAGE_FILE_DLL)
316 size = sizeof(dll_code_section);
317 if (!xwrite( &info, dll_code_section, size, info.file_pos )) goto done;
321 size = sizeof(exe_code_section);
322 if (!xwrite( &info, exe_code_section, size, info.file_pos )) goto done;
324 nt->OptionalHeader.SizeOfCode = size;
325 add_section( &info, ".text", size, IMAGE_SCN_CNT_CODE | IMAGE_SCN_MEM_EXECUTE | IMAGE_SCN_MEM_READ );
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 );
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 );
337 HeapFree( GetProcessHeap(), 0, buffer );
341 /* check if an existing file is a fake dll so that we can overwrite it */
342 static BOOL is_fake_dll( HANDLE h )
344 IMAGE_DOS_HEADER *dos;
346 BYTE buffer[sizeof(*dos) + sizeof(fakedll_signature)];
348 if (!ReadFile( h, buffer, sizeof(buffer), &size, NULL ) || size != sizeof(buffer))
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) );
356 /* create directories leading to a given file */
357 static void create_directories( const WCHAR *name )
361 /* create the directory/directories */
362 path = HeapAlloc(GetProcessHeap(), 0, (strlenW(name) + 1)*sizeof(WCHAR));
365 p = strchrW(path, '\\');
369 if (!CreateDirectoryW(path, NULL))
370 TRACE("Couldn't create directory %s - error: %d\n", wine_dbgstr_w(path), GetLastError());
372 p = strchrW(p+1, '\\');
374 HeapFree(GetProcessHeap(), 0, path);
377 static inline char *prepend( char *buffer, const char *str, size_t len )
379 return memcpy( buffer - len, str, len );
382 /* try to load a pre-compiled fake dll */
383 static void *load_fake_dll( const WCHAR *name, size_t *size )
385 const char *build_dir = wine_get_build_dir();
389 unsigned int i, pos, len, namelen, maxlen = 0;
393 if ((p = strrchrW( name, '\\' ))) name = p + 1;
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;
400 if (!(file = HeapAlloc( GetProcessHeap(), 0, maxlen ))) return NULL;
402 len = strlenW( name );
403 pos = maxlen - len - sizeof(".fake");
404 if (!dll_name_WtoA( file + pos, name, len )) goto done;
409 strcpy( file + pos + len + 1, ".fake" );
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;
420 /* now as a program */
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;
430 file[pos + len + 1] = 0;
431 for (i = 0; (path = wine_dll_enum_load_path( i )); i++)
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;
439 HeapFree( GetProcessHeap(), 0, file );
440 if (res == 1) return data;
444 /* create the fake dll destination file */
445 static HANDLE create_dest_file( const WCHAR *name )
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)
451 if (!is_fake_dll( h ))
453 TRACE( "%s is not a fake dll, not overwriting it\n", debugstr_w(name) );
457 /* truncate the file */
458 SetFilePointer( h, 0, NULL, FILE_BEGIN );
463 if (GetLastError() == ERROR_PATH_NOT_FOUND) create_directories( name );
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() );
472 /* copy a fake dll file to the dest directory */
473 static void install_fake_dll( WCHAR *dest, char *file, const char *ext )
479 WCHAR *destname = dest + strlenW(dest);
480 char *name = strrchr( file, '/' ) + 1;
481 char *end = name + strlen(name);
483 if (ext) strcpy( end, ext );
484 if (!(ret = read_file( file, &data, &size ))) return;
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;
492 HANDLE h = create_dest_file( dest );
494 if (h && h != INVALID_HANDLE_VALUE)
496 TRACE( "%s -> %s\n", debugstr_a(file), debugstr_w(dest) );
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() );
501 if (!ret) DeleteFileW( dest );
504 *destname = 0; /* restore it for next file */
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 )
514 if (!(dir = opendir( file ))) return;
515 name = file + strlen(file);
517 while ((de = readdir( dir )))
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 */
526 strcat( name, de->d_name );
527 if (!strchr( de->d_name, '.' )) strcat( name, default_ext );
528 install_fake_dll( dest, file, ".fake" );
530 else install_fake_dll( dest, file, NULL );
535 /* create fake dlls in dirname for all the files we can find */
536 static BOOL create_wildcard_dlls( const WCHAR *dirname )
538 const char *build_dir = wine_get_build_dir();
540 unsigned int i, maxlen = 0;
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;
549 if (!(dest = HeapAlloc( GetProcessHeap(), 0, (strlenW(dirname) + max_dll_name_len) * sizeof(WCHAR) )))
551 HeapFree( GetProcessHeap(), 0, file );
554 strcpyW( dest, dirname );
555 dest[strlenW(dest) - 1] = 0; /* remove wildcard */
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" );
566 for (i = 0; (path = wine_dll_enum_load_path( i )); i++)
568 strcpy( file, path );
569 strcat( file, "/fakedlls" );
570 install_lib_dir( dest, file, NULL );
572 HeapFree( GetProcessHeap(), 0, file );
573 HeapFree( GetProcessHeap(), 0, dest );
577 /***********************************************************************
580 BOOL create_fake_dll( const WCHAR *name, const WCHAR *source )
585 const WCHAR *filename;
588 if (!(filename = strrchrW( name, '\\' ))) filename = name;
591 /* check for empty name which means to only create the directory */
594 create_directories( name );
597 if (filename[0] == '*' && !filename[1]) return create_wildcard_dlls( name );
599 add_handled_dll( filename );
601 if (!(h = create_dest_file( name ))) return TRUE; /* not a fake dll */
602 if (h == INVALID_HANDLE_VALUE) return FALSE;
604 if (source[0] == '-' && !source[1])
606 /* '-' source means delete the file */
607 TRACE( "deleting %s\n", debugstr_w(name) );
610 else if ((buffer = load_fake_dll( source, &size )))
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() );
619 WARN( "fake dll %s not found for %s\n", debugstr_w(source), debugstr_w(name) );
620 ret = build_fake_dll( h );
624 if (!ret) DeleteFileW( name );
629 /***********************************************************************
632 void cleanup_fake_dlls(void)
634 HeapFree( GetProcessHeap(), 0, file_buffer );
636 HeapFree( GetProcessHeap(), 0, handled_dlls );
638 handled_count = handled_total = 0;