msado15: Semi-stub _Recordset get/put Filter.
[wine.git] / dlls / setupapi / fakedll.c
blob7f4d7367285ce68fde529035cf4189ba86a2ba74
1 /*
2 * Creation of Wine fake dlls for apps that access the dll file directly.
4 * Copyright 2006, 2011 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
21 #include <stdarg.h>
22 #include <fcntl.h>
23 #include <sys/stat.h>
24 #include <unistd.h>
26 #define COBJMACROS
27 #define ATL_INITGUID
29 #include "ntstatus.h"
30 #define WIN32_NO_STATUS
31 #include "windef.h"
32 #include "winbase.h"
33 #include "winuser.h"
34 #include "winnt.h"
35 #include "winternl.h"
36 #include "wine/debug.h"
37 #include "wine/list.h"
38 #include "ole2.h"
39 #include "atliface.h"
41 WINE_DEFAULT_DEBUG_CHANNEL(setupapi);
43 #ifdef __i386__
44 static const WCHAR pe_dir[] = L"\\i386-windows";
45 static const char current_arch[] = "x86";
46 #elif defined __x86_64__
47 static const WCHAR pe_dir[] = L"\\x86_64-windows";
48 static const char current_arch[] = "amd64";
49 #elif defined __arm__
50 static const WCHAR pe_dir[] = L"\\arm-windows";
51 static const char current_arch[] = "arm";
52 #elif defined __aarch64__
53 static const WCHAR pe_dir[] = L"\\aarch64-windows";
54 static const char current_arch[] = "arm64";
55 #else
56 static const WCHAR pe_dir[] = L"";
57 static const char current_arch[] = "none";
58 #endif
60 static const char builtin_signature[] = "Wine builtin DLL";
61 static const char fakedll_signature[] = "Wine placeholder DLL";
63 static const unsigned int file_alignment = 512;
64 static const unsigned int section_alignment = 4096;
65 static const unsigned int max_dll_name_len = 64;
67 static void *file_buffer;
68 static SIZE_T file_buffer_size;
69 static unsigned int handled_count;
70 static unsigned int handled_total;
71 static WCHAR **handled_dlls;
72 static IRegistrar *registrar;
74 struct dll_info
76 HANDLE handle;
77 IMAGE_NT_HEADERS *nt;
78 DWORD file_pos;
79 DWORD mem_pos;
82 #define ALIGN(size,align) (((size) + (align) - 1) & ~((align) - 1))
84 /* contents of the dll sections */
86 static const BYTE dll_code_section[] = { 0x31, 0xc0, /* xor %eax,%eax */
87 0xc2, 0x0c, 0x00 }; /* ret $12 */
89 static const BYTE exe_code_section[] = { 0xb8, 0x01, 0x00, 0x00, 0x00, /* movl $1,%eax */
90 0xc2, 0x04, 0x00 }; /* ret $4 */
92 static const IMAGE_BASE_RELOCATION reloc_section; /* empty relocs */
95 /* wrapper for WriteFile */
96 static inline BOOL xwrite( struct dll_info *info, const void *data, DWORD size, DWORD offset )
98 DWORD res;
100 return (SetFilePointer( info->handle, offset, NULL, FILE_BEGIN ) != INVALID_SET_FILE_POINTER &&
101 WriteFile( info->handle, data, size, &res, NULL ) &&
102 res == size);
105 /* add a new section to the dll NT header */
106 static void add_section( struct dll_info *info, const char *name, DWORD size, DWORD flags )
108 IMAGE_SECTION_HEADER *sec = (IMAGE_SECTION_HEADER *)(info->nt + 1);
110 sec += info->nt->FileHeader.NumberOfSections;
111 memcpy( sec->Name, name, min( strlen(name), sizeof(sec->Name)) );
112 sec->Misc.VirtualSize = ALIGN( size, section_alignment );
113 sec->VirtualAddress = info->mem_pos;
114 sec->SizeOfRawData = size;
115 sec->PointerToRawData = info->file_pos;
116 sec->Characteristics = flags;
117 info->file_pos += ALIGN( size, file_alignment );
118 info->mem_pos += ALIGN( size, section_alignment );
119 info->nt->FileHeader.NumberOfSections++;
122 /* add a data directory to the dll NT header */
123 static inline void add_directory( struct dll_info *info, unsigned int idx, DWORD rva, DWORD size )
125 info->nt->OptionalHeader.DataDirectory[idx].VirtualAddress = rva;
126 info->nt->OptionalHeader.DataDirectory[idx].Size = size;
129 /* add a dll to the list of dll that have been taken care of */
130 static BOOL add_handled_dll( const WCHAR *name )
132 int i, min, max, pos, res;
134 min = 0;
135 max = handled_count - 1;
136 while (min <= max)
138 pos = (min + max) / 2;
139 res = wcscmp( handled_dlls[pos], name );
140 if (!res) return FALSE; /* already in the list */
141 if (res < 0) min = pos + 1;
142 else max = pos - 1;
145 if (handled_count >= handled_total)
147 WCHAR **new_dlls;
148 unsigned int new_count = max( 64, handled_total * 2 );
150 if (handled_dlls) new_dlls = HeapReAlloc( GetProcessHeap(), 0, handled_dlls,
151 new_count * sizeof(*handled_dlls) );
152 else new_dlls = HeapAlloc( GetProcessHeap(), 0, new_count * sizeof(*handled_dlls) );
153 if (!new_dlls) return FALSE;
154 handled_dlls = new_dlls;
155 handled_total = new_count;
158 for (i = handled_count; i > min; i--) handled_dlls[i] = handled_dlls[i - 1];
159 handled_dlls[i] = wcsdup( name );
160 handled_count++;
161 return TRUE;
164 static int is_valid_ptr( const void *data, SIZE_T size, const void *ptr, SIZE_T ptr_size )
166 if (ptr < data) return 0;
167 if ((char *)ptr - (char *)data >= size) return 0;
168 return (size - ((char *)ptr - (char *)data) >= ptr_size);
171 /* extract the 16-bit NE dll from a PE builtin */
172 static void extract_16bit_image( IMAGE_NT_HEADERS *nt, void **data, SIZE_T *size )
174 DWORD exp_size, *size_ptr;
175 IMAGE_DOS_HEADER *dos;
176 IMAGE_EXPORT_DIRECTORY *exports;
177 IMAGE_SECTION_HEADER *section = NULL;
178 WORD *ordinals;
179 DWORD *names, *functions;
180 int i;
182 exports = RtlImageDirectoryEntryToData( *data, FALSE, IMAGE_DIRECTORY_ENTRY_EXPORT, &exp_size );
183 if (!is_valid_ptr( *data, *size, exports, exp_size )) return;
184 ordinals = RtlImageRvaToVa( nt, *data, exports->AddressOfNameOrdinals, &section );
185 names = RtlImageRvaToVa( nt, *data, exports->AddressOfNames, &section );
186 functions = RtlImageRvaToVa( nt, *data, exports->AddressOfFunctions, &section );
187 if (!is_valid_ptr( *data, *size, ordinals, exports->NumberOfNames * sizeof(*ordinals) )) return;
188 if (!is_valid_ptr( *data, *size, names, exports->NumberOfNames * sizeof(*names) )) return;
190 for (i = 0; i < exports->NumberOfNames; i++)
192 char *ename = RtlImageRvaToVa( nt, *data, names[i], &section );
193 if (strcmp( ename, "__wine_spec_dos_header" )) continue;
194 if (ordinals[i] >= exports->NumberOfFunctions) return;
195 if (!is_valid_ptr( *data, *size, functions, sizeof(*functions) )) return;
196 if (!functions[ordinals[i]]) return;
197 dos = RtlImageRvaToVa( nt, *data, functions[ordinals[i]], NULL );
198 if (!is_valid_ptr( *data, *size, dos, sizeof(*dos) )) return;
199 if (dos->e_magic != IMAGE_DOS_SIGNATURE) return;
200 size_ptr = (DWORD *)dos->e_res2;
201 *size = min( *size_ptr, *size - ((const char *)dos - (const char *)*data) );
202 *size_ptr = 0;
203 *data = dos;
204 break;
208 /* read in the contents of a file into the global file buffer */
209 /* return 1 on success, 0 on nonexistent file, -1 on other error */
210 static int read_file( const WCHAR *name, void **data, SIZE_T *size )
212 struct stat st;
213 int fd, ret = -1;
214 size_t header_size;
215 IMAGE_DOS_HEADER *dos;
216 IMAGE_NT_HEADERS *nt;
217 const size_t min_size = sizeof(*dos) + 32 +
218 FIELD_OFFSET( IMAGE_NT_HEADERS, OptionalHeader.MajorLinkerVersion );
220 if ((fd = _wopen( name, O_RDONLY | O_BINARY )) == -1) return 0;
221 if (fstat( fd, &st ) == -1) goto done;
222 *size = st.st_size;
223 if (!file_buffer || st.st_size > file_buffer_size)
225 VirtualFree( file_buffer, 0, MEM_RELEASE );
226 file_buffer = NULL;
227 file_buffer_size = st.st_size;
228 if (NtAllocateVirtualMemory( GetCurrentProcess(), &file_buffer, 0, &file_buffer_size,
229 MEM_COMMIT, PAGE_READWRITE )) goto done;
232 /* check for valid fake dll file */
234 if (st.st_size < min_size) goto done;
235 header_size = min( st.st_size, 4096 );
236 if (read( fd, file_buffer, header_size ) != header_size) goto done;
237 dos = file_buffer;
238 if (dos->e_magic != IMAGE_DOS_SIGNATURE) goto done;
239 if (dos->e_lfanew < sizeof(*dos) + 32) goto done;
240 if (memcmp( dos + 1, builtin_signature, strlen(builtin_signature) + 1 ) &&
241 memcmp( dos + 1, fakedll_signature, strlen(fakedll_signature) + 1 )) goto done;
242 if (dos->e_lfanew + FIELD_OFFSET(IMAGE_NT_HEADERS,OptionalHeader.MajorLinkerVersion) > header_size)
243 goto done;
244 nt = (IMAGE_NT_HEADERS *)((char *)file_buffer + dos->e_lfanew);
245 if (nt->Signature == IMAGE_NT_SIGNATURE && nt->OptionalHeader.Magic != IMAGE_NT_OPTIONAL_HDR_MAGIC)
247 /* wrong 32/64 type, pretend it doesn't exist */
248 ret = 0;
249 goto done;
251 if (st.st_size == header_size ||
252 read( fd, (char *)file_buffer + header_size,
253 st.st_size - header_size ) == st.st_size - header_size)
255 *data = file_buffer;
256 if (lstrlenW(name) > 2 && !wcscmp( name + lstrlenW(name) - 2, L"16" ))
257 extract_16bit_image( nt, data, size );
258 ret = 1;
260 done:
261 close( fd );
262 return ret;
265 /* build a complete fake dll from scratch */
266 static BOOL build_fake_dll( HANDLE file, const WCHAR *name )
268 IMAGE_DOS_HEADER *dos;
269 IMAGE_NT_HEADERS *nt;
270 struct dll_info info;
271 const WCHAR *ext;
272 BYTE *buffer;
273 BOOL ret = FALSE;
274 DWORD lfanew = (sizeof(*dos) + sizeof(fakedll_signature) + 15) & ~15;
275 DWORD size, header_size = lfanew + sizeof(*nt);
277 info.handle = file;
278 buffer = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, header_size + 8 * sizeof(IMAGE_SECTION_HEADER) );
280 dos = (IMAGE_DOS_HEADER *)buffer;
281 dos->e_magic = IMAGE_DOS_SIGNATURE;
282 dos->e_cblp = sizeof(*dos);
283 dos->e_cp = 1;
284 dos->e_cparhdr = lfanew / 16;
285 dos->e_minalloc = 0;
286 dos->e_maxalloc = 0xffff;
287 dos->e_ss = 0x0000;
288 dos->e_sp = 0x00b8;
289 dos->e_lfarlc = lfanew;
290 dos->e_lfanew = lfanew;
291 memcpy( dos + 1, fakedll_signature, sizeof(fakedll_signature) );
293 nt = info.nt = (IMAGE_NT_HEADERS *)(buffer + lfanew);
294 /* some fields are copied from the source dll */
295 #if defined __x86_64__
296 nt->FileHeader.Machine = IMAGE_FILE_MACHINE_AMD64;
297 #elif defined __aarch64__
298 nt->FileHeader.Machine = IMAGE_FILE_MACHINE_ARM64;
299 #elif defined __arm__
300 nt->FileHeader.Machine = IMAGE_FILE_MACHINE_ARMNT;
301 #else
302 nt->FileHeader.Machine = IMAGE_FILE_MACHINE_I386;
303 #endif
304 nt->FileHeader.TimeDateStamp = 0;
305 nt->FileHeader.Characteristics = 0;
306 nt->OptionalHeader.MajorLinkerVersion = 1;
307 nt->OptionalHeader.MinorLinkerVersion = 0;
308 nt->OptionalHeader.MajorOperatingSystemVersion = 1;
309 nt->OptionalHeader.MinorOperatingSystemVersion = 0;
310 nt->OptionalHeader.MajorImageVersion = 1;
311 nt->OptionalHeader.MinorImageVersion = 0;
312 nt->OptionalHeader.MajorSubsystemVersion = 4;
313 nt->OptionalHeader.MinorSubsystemVersion = 0;
314 nt->OptionalHeader.Win32VersionValue = 0;
315 nt->OptionalHeader.Subsystem = IMAGE_SUBSYSTEM_WINDOWS_GUI;
316 nt->OptionalHeader.DllCharacteristics = 0;
317 nt->OptionalHeader.SizeOfStackReserve = 0;
318 nt->OptionalHeader.SizeOfStackCommit = 0;
319 nt->OptionalHeader.SizeOfHeapReserve = 0;
320 nt->OptionalHeader.SizeOfHeapCommit = 0;
321 /* other fields have fixed values */
322 nt->Signature = IMAGE_NT_SIGNATURE;
323 nt->FileHeader.NumberOfSections = 0;
324 nt->FileHeader.SizeOfOptionalHeader = IMAGE_SIZEOF_NT_OPTIONAL_HEADER;
325 nt->OptionalHeader.Magic = IMAGE_NT_OPTIONAL_HDR_MAGIC;
326 nt->OptionalHeader.ImageBase = 0x10000000;
327 nt->OptionalHeader.SectionAlignment = section_alignment;
328 nt->OptionalHeader.FileAlignment = file_alignment;
329 nt->OptionalHeader.NumberOfRvaAndSizes = IMAGE_NUMBEROF_DIRECTORY_ENTRIES;
331 header_size = (BYTE *)(nt + 1) - buffer;
332 info.mem_pos = ALIGN( header_size, section_alignment );
333 info.file_pos = ALIGN( header_size, file_alignment );
335 nt->OptionalHeader.AddressOfEntryPoint = info.mem_pos;
336 nt->OptionalHeader.BaseOfCode = info.mem_pos;
338 ext = wcsrchr( name, '.' );
339 if (!ext || wcsicmp( ext, L".exe" )) nt->FileHeader.Characteristics |= IMAGE_FILE_DLL;
341 if (nt->FileHeader.Characteristics & IMAGE_FILE_DLL)
343 size = sizeof(dll_code_section);
344 if (!xwrite( &info, dll_code_section, size, info.file_pos )) goto done;
346 else
348 size = sizeof(exe_code_section);
349 if (!xwrite( &info, exe_code_section, size, info.file_pos )) goto done;
351 nt->OptionalHeader.SizeOfCode = size;
352 add_section( &info, ".text", size, IMAGE_SCN_CNT_CODE | IMAGE_SCN_MEM_EXECUTE | IMAGE_SCN_MEM_READ );
354 if (!xwrite( &info, &reloc_section, sizeof(reloc_section), info.file_pos )) goto done;
355 add_directory( &info, IMAGE_DIRECTORY_ENTRY_BASERELOC, info.mem_pos, sizeof(reloc_section) );
356 add_section( &info, ".reloc", sizeof(reloc_section),
357 IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_DISCARDABLE | IMAGE_SCN_MEM_READ );
359 header_size += nt->FileHeader.NumberOfSections * sizeof(IMAGE_SECTION_HEADER);
360 nt->OptionalHeader.SizeOfHeaders = ALIGN( header_size, file_alignment );
361 nt->OptionalHeader.SizeOfImage = ALIGN( info.mem_pos, section_alignment );
362 ret = xwrite( &info, buffer, header_size, 0 );
363 done:
364 HeapFree( GetProcessHeap(), 0, buffer );
365 return ret;
368 /* check if an existing file is a fake dll so that we can overwrite it */
369 static BOOL is_fake_dll( HANDLE h )
371 IMAGE_DOS_HEADER *dos;
372 DWORD size;
373 BYTE buffer[sizeof(*dos) + 32];
375 if (!ReadFile( h, buffer, sizeof(buffer), &size, NULL ) || size != sizeof(buffer))
376 return FALSE;
377 dos = (IMAGE_DOS_HEADER *)buffer;
378 if (dos->e_magic != IMAGE_DOS_SIGNATURE) return FALSE;
379 if (dos->e_lfanew < size) return FALSE;
380 return (!memcmp( dos + 1, builtin_signature, sizeof(builtin_signature) ) ||
381 !memcmp( dos + 1, fakedll_signature, sizeof(fakedll_signature) ));
384 /* create directories leading to a given file */
385 static void create_directories( const WCHAR *name )
387 WCHAR *path, *p;
389 /* create the directory/directories */
390 path = HeapAlloc(GetProcessHeap(), 0, (lstrlenW(name) + 1)*sizeof(WCHAR));
391 lstrcpyW(path, name);
393 p = wcschr(path, '\\');
394 while (p != NULL)
396 *p = 0;
397 if (!CreateDirectoryW(path, NULL))
398 TRACE("Couldn't create directory %s - error: %ld\n", wine_dbgstr_w(path), GetLastError());
399 *p = '\\';
400 p = wcschr(p+1, '\\');
402 HeapFree(GetProcessHeap(), 0, path);
405 static inline WCHAR *prepend( WCHAR *buffer, const WCHAR *str, size_t len )
407 return memcpy( buffer - len, str, len * sizeof(WCHAR) );
410 static inline WCHAR *prepend_build_dir_path( WCHAR *ptr, const WCHAR *ext, const WCHAR *arch_dir,
411 const WCHAR *top_dir, const WCHAR *build_dir )
413 WCHAR *name = ptr;
414 unsigned int namelen = wcslen(name), extlen = wcslen(ext);
416 if (namelen > extlen && !wcscmp( name + namelen - extlen, ext )) namelen -= extlen;
417 ptr = prepend( ptr, arch_dir, wcslen(arch_dir) );
418 ptr = prepend( ptr, name, namelen );
419 ptr = prepend( ptr, top_dir, wcslen(top_dir) );
420 ptr = prepend( ptr, build_dir, wcslen(build_dir) );
421 return ptr;
425 static const WCHAR *enum_load_path( unsigned int idx )
427 WCHAR buffer[32];
428 swprintf( buffer, ARRAY_SIZE(buffer), L"WINEDLLDIR%u", idx );
429 return _wgetenv( buffer );
432 /* try to load a pre-compiled fake dll */
433 static void *load_fake_dll( const WCHAR *name, SIZE_T *size )
435 const WCHAR *build_dir = _wgetenv( L"WINEBUILDDIR" );
436 const WCHAR *path;
437 WCHAR *file, *ptr;
438 void *data = NULL;
439 unsigned int i, pos, len, maxlen = 0;
440 WCHAR *p;
441 int res = 0;
443 if ((p = wcsrchr( name, '\\' ))) name = p + 1;
445 i = 0;
446 len = lstrlenW( name );
447 if (build_dir) maxlen = lstrlenW(build_dir) + ARRAY_SIZE(L"\\programs") + len + 1;
448 while ((path = enum_load_path( i++ ))) maxlen = max( maxlen, lstrlenW(path) );
449 maxlen += ARRAY_SIZE(pe_dir) + len + 1;
451 if (!(file = HeapAlloc( GetProcessHeap(), 0, maxlen * sizeof(WCHAR) ))) return NULL;
453 pos = maxlen - len - 1;
454 lstrcpyW( file + pos, name );
455 file[--pos] = '\\';
457 if (build_dir)
459 /* try as a dll */
460 file[pos + len + 1] = 0;
461 ptr = prepend_build_dir_path( file + pos, L".dll", pe_dir, L"\\dlls", build_dir );
462 if ((res = read_file( ptr, &data, size ))) goto done;
464 /* now as a program */
465 file[pos + len + 1] = 0;
466 ptr = prepend_build_dir_path( file + pos, L".exe", pe_dir, L"\\programs", build_dir );
467 if ((res = read_file( ptr, &data, size ))) goto done;
470 file[pos + len + 1] = 0;
471 for (i = 0; (path = enum_load_path( i )); i++)
473 ptr = prepend( file + pos, pe_dir, lstrlenW(pe_dir) );
474 ptr = prepend( ptr, path, lstrlenW(path) );
475 if ((res = read_file( ptr, &data, size ))) break;
476 ptr = prepend( file + pos, path, lstrlenW(path) );
477 if ((res = read_file( ptr, &data, size ))) break;
480 done:
481 HeapFree( GetProcessHeap(), 0, file );
482 if (res == 1) return data;
483 return NULL;
486 /* create the fake dll destination file */
487 static HANDLE create_dest_file( const WCHAR *name, BOOL delete )
489 /* first check for an existing file */
490 HANDLE h = CreateFileW( name, GENERIC_READ|GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL );
491 if (h != INVALID_HANDLE_VALUE)
493 if (!is_fake_dll( h ))
495 TRACE( "%s is not a fake dll, not overwriting it\n", debugstr_w(name) );
496 CloseHandle( h );
497 return 0;
499 if (delete)
501 CloseHandle( h );
502 DeleteFileW( name );
503 return INVALID_HANDLE_VALUE;
505 /* truncate the file */
506 SetFilePointer( h, 0, NULL, FILE_BEGIN );
507 SetEndOfFile( h );
509 else if (!delete)
511 if (GetLastError() == ERROR_PATH_NOT_FOUND) create_directories( name );
513 h = CreateFileW( name, GENERIC_WRITE, 0, NULL, CREATE_NEW, 0, NULL );
514 if (h == INVALID_HANDLE_VALUE)
515 ERR( "failed to create %s (error=%lu)\n", debugstr_w(name), GetLastError() );
517 return h;
520 /* XML parsing code copied from ntdll */
522 typedef struct
524 const char *ptr;
525 unsigned int len;
526 } xmlstr_t;
528 typedef struct
530 const char *ptr;
531 const char *end;
532 } xmlbuf_t;
534 static inline BOOL xmlstr_cmp(const xmlstr_t* xmlstr, const char *str)
536 return !strncmp(xmlstr->ptr, str, xmlstr->len) && !str[xmlstr->len];
539 static inline BOOL isxmlspace( char ch )
541 return (ch == ' ' || ch == '\r' || ch == '\n' || ch == '\t');
544 static BOOL next_xml_elem( xmlbuf_t *xmlbuf, xmlstr_t *elem )
546 const char *ptr;
548 for (;;)
550 ptr = memchr(xmlbuf->ptr, '<', xmlbuf->end - xmlbuf->ptr);
551 if (!ptr)
553 xmlbuf->ptr = xmlbuf->end;
554 return FALSE;
556 ptr++;
557 if (ptr + 3 < xmlbuf->end && ptr[0] == '!' && ptr[1] == '-' && ptr[2] == '-') /* skip comment */
559 for (ptr += 3; ptr + 3 <= xmlbuf->end; ptr++)
560 if (ptr[0] == '-' && ptr[1] == '-' && ptr[2] == '>') break;
562 if (ptr + 3 > xmlbuf->end)
564 xmlbuf->ptr = xmlbuf->end;
565 return FALSE;
567 xmlbuf->ptr = ptr + 3;
569 else break;
572 xmlbuf->ptr = ptr;
573 while (ptr < xmlbuf->end && !isxmlspace(*ptr) && *ptr != '>' && (*ptr != '/' || ptr == xmlbuf->ptr))
574 ptr++;
576 elem->ptr = xmlbuf->ptr;
577 elem->len = ptr - xmlbuf->ptr;
578 xmlbuf->ptr = ptr;
579 return xmlbuf->ptr != xmlbuf->end;
582 static BOOL next_xml_attr(xmlbuf_t* xmlbuf, xmlstr_t* name, xmlstr_t* value, BOOL* error)
584 const char *ptr;
586 *error = TRUE;
588 while (xmlbuf->ptr < xmlbuf->end && isxmlspace(*xmlbuf->ptr))
589 xmlbuf->ptr++;
591 if (xmlbuf->ptr == xmlbuf->end) return FALSE;
593 if (*xmlbuf->ptr == '/')
595 xmlbuf->ptr++;
596 if (xmlbuf->ptr == xmlbuf->end || *xmlbuf->ptr != '>')
597 return FALSE;
599 xmlbuf->ptr++;
600 *error = FALSE;
601 return FALSE;
604 if (*xmlbuf->ptr == '>')
606 xmlbuf->ptr++;
607 *error = FALSE;
608 return FALSE;
611 ptr = xmlbuf->ptr;
612 while (ptr < xmlbuf->end && *ptr != '=' && *ptr != '>' && !isxmlspace(*ptr)) ptr++;
614 if (ptr == xmlbuf->end || *ptr != '=') return FALSE;
616 name->ptr = xmlbuf->ptr;
617 name->len = ptr-xmlbuf->ptr;
618 xmlbuf->ptr = ptr;
620 ptr++;
621 if (ptr == xmlbuf->end || (*ptr != '"' && *ptr != '\'')) return FALSE;
623 value->ptr = ++ptr;
624 if (ptr == xmlbuf->end) return FALSE;
626 ptr = memchr(ptr, ptr[-1], xmlbuf->end - ptr);
627 if (!ptr)
629 xmlbuf->ptr = xmlbuf->end;
630 return FALSE;
633 value->len = ptr - value->ptr;
634 xmlbuf->ptr = ptr + 1;
636 if (xmlbuf->ptr == xmlbuf->end) return FALSE;
638 *error = FALSE;
639 return TRUE;
642 static void append_manifest_filename( const xmlstr_t *arch, const xmlstr_t *name, const xmlstr_t *key,
643 const xmlstr_t *version, const xmlstr_t *lang, WCHAR *buffer, DWORD size )
645 DWORD pos = lstrlenW( buffer );
647 pos += MultiByteToWideChar( CP_UTF8, 0, arch->ptr, arch->len, buffer + pos, size - pos );
648 buffer[pos++] = '_';
649 pos += MultiByteToWideChar( CP_UTF8, 0, name->ptr, name->len, buffer + pos, size - pos );
650 buffer[pos++] = '_';
651 pos += MultiByteToWideChar( CP_UTF8, 0, key->ptr, key->len, buffer + pos, size - pos );
652 buffer[pos++] = '_';
653 pos += MultiByteToWideChar( CP_UTF8, 0, version->ptr, version->len, buffer + pos, size - pos );
654 buffer[pos++] = '_';
655 pos += MultiByteToWideChar( CP_UTF8, 0, lang->ptr, lang->len, buffer + pos, size - pos );
656 lstrcpyW( buffer + pos, L"_deadbeef" );
657 wcslwr( buffer );
660 static WCHAR* create_winsxs_dll_path( const xmlstr_t *arch, const xmlstr_t *name,
661 const xmlstr_t *key, const xmlstr_t *version,
662 const xmlstr_t *lang )
664 WCHAR *path;
665 DWORD path_len;
667 path_len = GetWindowsDirectoryW( NULL, 0 ) + ARRAY_SIZE( L"\\winsxs\\" )
668 + arch->len + name->len + key->len + version->len + 19;
670 path = HeapAlloc( GetProcessHeap(), 0, path_len * sizeof(WCHAR) );
671 GetWindowsDirectoryW( path, path_len );
672 lstrcatW( path, L"\\winsxs\\" );
673 append_manifest_filename( arch, name, key, version, lang, path, path_len );
674 lstrcatW( path, L"\\" );
675 return path;
678 static BOOL create_manifest( const xmlstr_t *arch, const xmlstr_t *name, const xmlstr_t *key,
679 const xmlstr_t *version, const xmlstr_t *lang, const void *data, DWORD len )
681 WCHAR *path;
682 DWORD written, path_len;
683 HANDLE handle;
684 BOOL ret = FALSE;
686 path_len = GetWindowsDirectoryW( NULL, 0 ) + ARRAY_SIZE( L"\\winsxs\\manifests\\" )
687 + arch->len + name->len + key->len + version->len + 18 + ARRAY_SIZE( L".manifest" );
689 path = HeapAlloc( GetProcessHeap(), 0, path_len * sizeof(WCHAR) );
690 GetWindowsDirectoryW( path, path_len );
691 lstrcatW( path, L"\\winsxs\\manifests\\" );
692 append_manifest_filename( arch, name, key, version, lang, path, path_len );
693 lstrcatW( path, L".manifest" );
694 handle = CreateFileW( path, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, NULL );
695 if (handle == INVALID_HANDLE_VALUE && GetLastError() == ERROR_PATH_NOT_FOUND)
697 create_directories( path );
698 handle = CreateFileW( path, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, NULL );
701 if (handle != INVALID_HANDLE_VALUE)
703 TRACE( "creating %s\n", debugstr_w(path) );
704 ret = (WriteFile( handle, data, len, &written, NULL ) && written == len);
705 if (!ret) ERR( "failed to write to %s (error=%lu)\n", debugstr_w(path), GetLastError() );
706 CloseHandle( handle );
707 if (!ret) DeleteFileW( path );
709 HeapFree( GetProcessHeap(), 0, path );
710 return ret;
713 struct delay_copy
715 struct list entry;
716 WCHAR *src;
717 WCHAR *dest;
718 WCHAR data[1];
721 struct dll_data
723 struct list *delay_copy;
724 const WCHAR *src_dir;
725 DWORD src_len;
728 static BOOL CALLBACK register_manifest( HMODULE module, const WCHAR *type, WCHAR *res_name, LONG_PTR arg )
730 const struct dll_data *dll_data = (const struct dll_data*)arg;
731 WCHAR *dest = NULL;
732 DWORD dest_len = 0;
733 xmlbuf_t buffer;
734 xmlstr_t elem, attr_name, attr_value;
735 xmlstr_t name, version, arch, key, lang;
736 BOOL error;
737 const char *manifest;
738 SIZE_T len;
739 HRSRC rsrc;
741 if (IS_INTRESOURCE( res_name ) || wcsncmp( res_name, L"WINE_MANIFEST", 13 )) return TRUE;
743 rsrc = FindResourceW( module, res_name, type );
744 manifest = LoadResource( module, rsrc );
745 len = SizeofResource( module, rsrc );
747 buffer.ptr = manifest;
748 buffer.end = manifest + len;
749 name.ptr = version.ptr = arch.ptr = key.ptr = lang.ptr = NULL;
750 name.len = version.len = arch.len = key.len = lang.len = 0;
752 while (next_xml_elem( &buffer, &elem ))
754 if (xmlstr_cmp( &elem, "file" ))
756 while (next_xml_attr( &buffer, &attr_name, &attr_value, &error ))
758 if (xmlstr_cmp(&attr_name, "name"))
760 name = attr_value;
761 break;
765 if (!error && dest && name.ptr)
767 struct delay_copy *add = HeapAlloc( GetProcessHeap(), 0,
768 sizeof(*add) + (dll_data->src_len + name.len +
769 dest_len + name.len + 1) * sizeof(WCHAR) );
770 add->src = add->data;
771 memcpy( add->src, dll_data->src_dir, dll_data->src_len * sizeof(WCHAR) );
772 MultiByteToWideChar( CP_UTF8, 0, name.ptr, name.len,
773 add->src + dll_data->src_len, name.len );
774 add->src[dll_data->src_len + name.len] = 0;
775 add->dest = add->data + dll_data->src_len + name.len + 1;
776 memcpy( add->dest, dest, dest_len * sizeof(WCHAR) );
777 memcpy( add->dest + dest_len, add->src + dll_data->src_len,
778 (name.len + 1) * sizeof(WCHAR) );
779 TRACE("schedule copy %s -> %s\n", wine_dbgstr_w(add->src), wine_dbgstr_w(add->dest));
780 list_add_tail( dll_data->delay_copy, &add->entry );
782 continue;
785 if (!xmlstr_cmp( &elem, "assemblyIdentity" )) continue;
786 HeapFree( GetProcessHeap(), 0, dest );
787 dest = NULL;
788 while (next_xml_attr( &buffer, &attr_name, &attr_value, &error ))
790 if (xmlstr_cmp(&attr_name, "name")) name = attr_value;
791 else if (xmlstr_cmp(&attr_name, "version")) version = attr_value;
792 else if (xmlstr_cmp(&attr_name, "processorArchitecture")) arch = attr_value;
793 else if (xmlstr_cmp(&attr_name, "publicKeyToken")) key = attr_value;
794 else if (xmlstr_cmp(&attr_name, "language")) lang = attr_value;
796 if (!error && name.ptr && version.ptr && arch.ptr && key.ptr)
798 if (!lang.ptr)
800 lang.ptr = "none";
801 lang.len = strlen( lang.ptr );
803 if (!arch.len) /* fixup the architecture */
805 char *new_buffer = HeapAlloc( GetProcessHeap(), 0, len + sizeof(current_arch) );
806 memcpy( new_buffer, manifest, arch.ptr - manifest );
807 strcpy( new_buffer + (arch.ptr - manifest), current_arch );
808 memcpy( new_buffer + strlen(new_buffer), arch.ptr, len - (arch.ptr - manifest) );
809 arch.ptr = current_arch;
810 arch.len = strlen( current_arch );
811 dest = create_winsxs_dll_path( &arch, &name, &key, &version, &lang );
812 create_manifest( &arch, &name, &key, &version, &lang, new_buffer, len + arch.len );
813 HeapFree( GetProcessHeap(), 0, new_buffer );
815 else
817 dest = create_winsxs_dll_path( &arch, &name, &key, &version, &lang );
818 create_manifest( &arch, &name, &key, &version, &lang, manifest, len );
820 dest_len = wcslen( dest );
823 HeapFree( GetProcessHeap(), 0, dest );
825 return TRUE;
828 static BOOL CALLBACK register_resource( HMODULE module, LPCWSTR type, LPWSTR name, LONG_PTR arg )
830 HRESULT *hr = (HRESULT *)arg;
831 WCHAR *buffer;
832 HRSRC rsrc = FindResourceW( module, name, type );
833 char *str = LoadResource( module, rsrc );
834 DWORD lenW, lenA = SizeofResource( module, rsrc );
836 if (!str) return FALSE;
837 lenW = MultiByteToWideChar( CP_UTF8, 0, str, lenA, NULL, 0 ) + 1;
838 if (!(buffer = HeapAlloc( GetProcessHeap(), 0, lenW * sizeof(WCHAR) ))) return FALSE;
839 MultiByteToWideChar( CP_UTF8, 0, str, lenA, buffer, lenW );
840 buffer[lenW - 1] = 0;
841 *hr = IRegistrar_StringRegister( registrar, buffer );
842 HeapFree( GetProcessHeap(), 0, buffer );
843 return TRUE;
846 static void register_fake_dll( const WCHAR *name, const void *data, size_t size, struct list *delay_copy )
848 const IMAGE_RESOURCE_DIRECTORY *resdir;
849 LDR_RESOURCE_INFO info;
850 HRESULT hr = S_OK;
851 HMODULE module = (HMODULE)((ULONG_PTR)data | 1);
852 struct dll_data dll_data = { delay_copy, name, 0 };
853 WCHAR buffer[MAX_PATH];
854 const WCHAR *p;
856 if (!(p = wcsrchr( name, '\\' ))) p = name;
857 else p++;
858 dll_data.src_len = p - name;
859 EnumResourceNamesW( module, (WCHAR*)RT_MANIFEST, register_manifest, (LONG_PTR)&dll_data );
861 info.Type = (ULONG_PTR)L"WINE_REGISTRY";
862 if (LdrFindResourceDirectory_U( module, &info, 1, &resdir )) return;
864 if (!registrar)
866 HRESULT (WINAPI *pAtlCreateRegistrar)(IRegistrar**);
867 HMODULE atl = LoadLibraryW( L"atl100.dll" );
869 if ((pAtlCreateRegistrar = (void *)GetProcAddress( atl, "AtlCreateRegistrar" )))
870 hr = pAtlCreateRegistrar( &registrar );
871 else
872 hr = E_NOINTERFACE;
874 if (!registrar)
876 ERR( "failed to create IRegistrar: %lx\n", hr );
877 return;
881 TRACE( "registering %s\n", debugstr_w(name) );
882 IRegistrar_ClearReplacements( registrar );
883 IRegistrar_AddReplacement( registrar, L"MODULE", name );
884 GetEnvironmentVariableW( L"SystemRoot", buffer, ARRAY_SIZE(buffer) );
885 IRegistrar_AddReplacement( registrar, L"SystemRoot", buffer );
886 EnumResourceNamesW( module, L"WINE_REGISTRY", register_resource, (LONG_PTR)&hr );
887 if (FAILED(hr)) ERR( "failed to register %s: %lx\n", debugstr_w(name), hr );
890 /* copy a fake dll file to the dest directory */
891 static int install_fake_dll( WCHAR *dest, WCHAR *file, BOOL delete, struct list *delay_copy )
893 int ret;
894 SIZE_T size;
895 void *data;
896 DWORD written;
897 WCHAR *destname = dest + lstrlenW(dest);
898 WCHAR *name = wcsrchr( file, '\\' ) + 1;
899 WCHAR *end = name + lstrlenW(name);
900 SIZE_T len = end - name;
902 if (!(ret = read_file( file, &data, &size )))
904 *end = 0;
905 return 0;
908 if (end > name + 2 && !wcsncmp( end - 2, L"16", 2 )) len -= 2; /* remove "16" suffix */
909 memcpy( destname, name, len * sizeof(WCHAR) );
910 destname[len] = 0;
911 if (!add_handled_dll( destname )) ret = -1;
913 if (ret != -1)
915 HANDLE h = create_dest_file( dest, delete );
917 if (h && h != INVALID_HANDLE_VALUE)
919 TRACE( "%s -> %s\n", debugstr_w(file), debugstr_w(dest) );
921 ret = (WriteFile( h, data, size, &written, NULL ) && written == size);
922 if (!ret) ERR( "failed to write to %s (error=%lu)\n", debugstr_w(dest), GetLastError() );
923 CloseHandle( h );
924 if (ret) register_fake_dll( dest, data, size, delay_copy );
925 else DeleteFileW( dest );
928 *destname = 0; /* restore it for next file */
929 *end = 0;
930 return ret;
933 static void delay_copy_files( struct list *delay_copy )
935 struct delay_copy *copy, *next;
936 DWORD written;
937 SIZE_T size;
938 void *data;
939 HANDLE h;
940 int ret;
942 LIST_FOR_EACH_ENTRY_SAFE( copy, next, delay_copy, struct delay_copy, entry )
944 list_remove( &copy->entry );
945 ret = read_file( copy->src, &data, &size );
946 if (ret != 1)
948 HeapFree( GetProcessHeap(), 0, copy );
949 continue;
952 h = create_dest_file( copy->dest, FALSE );
953 if (h && h != INVALID_HANDLE_VALUE)
955 ret = (WriteFile( h, data, size, &written, NULL ) && written == size);
956 if (!ret) ERR( "failed to write to %s (error=%lu)\n", debugstr_w(copy->dest), GetLastError() );
957 CloseHandle( h );
958 if (!ret) DeleteFileW( copy->dest );
960 HeapFree( GetProcessHeap(), 0, copy );
964 /* find and install all fake dlls in a given lib directory */
965 static void install_lib_dir( WCHAR *dest, WCHAR *file, const WCHAR *wildcard,
966 const WCHAR *default_ext, BOOL delete )
968 WCHAR *name;
969 intptr_t handle;
970 struct _wfinddata_t data;
971 struct list delay_copy = LIST_INIT( delay_copy );
973 file[1] = '\\'; /* change \??\ to \\?\ */
974 name = file + lstrlenW(file);
975 *name++ = '\\';
976 lstrcpyW( name, wildcard );
978 if ((handle = _wfindfirst( file, &data )) == -1) return;
981 if (lstrlenW( data.name ) > max_dll_name_len) continue;
982 if (!wcscmp( data.name, L"." )) continue;
983 if (!wcscmp( data.name, L".." )) continue;
984 lstrcpyW( name, data.name );
985 if (default_ext) /* inside build dir */
987 lstrcatW( name, pe_dir );
988 lstrcatW( name, L"\\" );
989 lstrcatW( name, data.name );
990 if (wcschr( data.name, '.' ) && install_fake_dll( dest, file, delete, &delay_copy ))
991 continue;
992 if (wcschr( wildcard, '.' )) /* don't append default if wildcard has an explicit extension */
993 continue;
994 lstrcatW( name, default_ext );
996 install_fake_dll( dest, file, delete, &delay_copy );
998 while (!_wfindnext( handle, &data ));
999 _findclose( handle );
1001 delay_copy_files( &delay_copy );
1004 /* create fake dlls in dirname for all the files we can find */
1005 static BOOL create_wildcard_dlls( const WCHAR *dirname, const WCHAR *wildcard, BOOL delete )
1007 const WCHAR *build_dir = _wgetenv( L"WINEBUILDDIR" );
1008 const WCHAR *path;
1009 unsigned int i, maxlen = 0;
1010 WCHAR *file, *dest, *p;
1012 if (build_dir) maxlen = lstrlenW(build_dir) + ARRAY_SIZE(L"\\programs") + 1;
1013 for (i = 0; (path = enum_load_path(i)); i++) maxlen = max( maxlen, lstrlenW(path) );
1014 maxlen += 2 * max_dll_name_len + 2 + ARRAY_SIZE(pe_dir) + 10; /* ".dll" */
1015 if (!(file = HeapAlloc( GetProcessHeap(), 0, maxlen * sizeof(WCHAR) ))) return FALSE;
1017 if (!(dest = HeapAlloc( GetProcessHeap(), 0, (lstrlenW(dirname) + max_dll_name_len) * sizeof(WCHAR) )))
1019 HeapFree( GetProcessHeap(), 0, file );
1020 return FALSE;
1022 lstrcpyW( dest, dirname );
1023 if ((p = wcsrchr( dest, '\\' ))) p[1] = 0; /* remove wildcard */
1025 if (build_dir)
1027 lstrcpyW( file, build_dir );
1028 lstrcatW( file, L"\\dlls" );
1029 install_lib_dir( dest, file, wildcard, L".dll", delete );
1030 lstrcpyW( file, build_dir );
1031 lstrcatW( file, L"\\programs" );
1032 install_lib_dir( dest, file, wildcard, L".exe", delete );
1034 for (i = 0; (path = enum_load_path( i )); i++)
1036 swprintf( file, maxlen, L"%s%s", path, pe_dir );
1037 install_lib_dir( dest, file, wildcard, NULL, delete );
1038 lstrcpyW( file, path );
1039 install_lib_dir( dest, file, wildcard, NULL, delete );
1041 HeapFree( GetProcessHeap(), 0, file );
1042 HeapFree( GetProcessHeap(), 0, dest );
1043 return TRUE;
1046 /***********************************************************************
1047 * create_fake_dll
1049 BOOL create_fake_dll( const WCHAR *name, const WCHAR *source )
1051 struct list delay_copy = LIST_INIT( delay_copy );
1052 HANDLE h;
1053 BOOL ret;
1054 SIZE_T size;
1055 const WCHAR *filename;
1056 void *buffer;
1057 BOOL delete = !wcscmp( source, L"-" ); /* '-' source means delete the file */
1059 if (!(filename = wcsrchr( name, '\\' ))) filename = name;
1060 else filename++;
1062 /* check for empty name which means to only create the directory */
1063 if (!filename[0])
1065 create_directories( name );
1066 return TRUE;
1068 if (wcspbrk( filename, L"*?" )) return create_wildcard_dlls( name, filename, delete );
1070 add_handled_dll( filename );
1072 if (!(h = create_dest_file( name, delete ))) return TRUE; /* not a fake dll */
1073 if (h == INVALID_HANDLE_VALUE) return FALSE;
1075 if ((buffer = load_fake_dll( source, &size )))
1077 DWORD written;
1079 ret = (WriteFile( h, buffer, size, &written, NULL ) && written == size);
1080 if (ret) register_fake_dll( name, buffer, size, &delay_copy );
1081 else ERR( "failed to write to %s (error=%lu)\n", debugstr_w(name), GetLastError() );
1083 else
1085 WARN( "fake dll %s not found for %s\n", debugstr_w(source), debugstr_w(name) );
1086 ret = build_fake_dll( h, name );
1089 CloseHandle( h );
1090 if (!ret) DeleteFileW( name );
1092 delay_copy_files( &delay_copy );
1093 return ret;
1097 /***********************************************************************
1098 * cleanup_fake_dlls
1100 void cleanup_fake_dlls(void)
1102 if (file_buffer) VirtualFree( file_buffer, 0, MEM_RELEASE );
1103 file_buffer = NULL;
1104 HeapFree( GetProcessHeap(), 0, handled_dlls );
1105 handled_dlls = NULL;
1106 handled_count = handled_total = 0;
1107 if (registrar) IRegistrar_Release( registrar );
1108 registrar = NULL;