mfplat: Read queue subscriber within the critical section.
[wine/zf.git] / dlls / setupapi / fakedll.c
blob852cef3d54f2fcd3cd9ca0a1c5b1d74ac088a6c3
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 static const char builtin_signature[] = "Wine builtin DLL";
44 static const char fakedll_signature[] = "Wine placeholder DLL";
46 static const unsigned int file_alignment = 512;
47 static const unsigned int section_alignment = 4096;
48 static const unsigned int max_dll_name_len = 64;
50 static void *file_buffer;
51 static SIZE_T file_buffer_size;
52 static unsigned int handled_count;
53 static unsigned int handled_total;
54 static WCHAR **handled_dlls;
55 static IRegistrar *registrar;
57 struct dll_info
59 HANDLE handle;
60 IMAGE_NT_HEADERS *nt;
61 DWORD file_pos;
62 DWORD mem_pos;
65 #define ALIGN(size,align) (((size) + (align) - 1) & ~((align) - 1))
67 /* contents of the dll sections */
69 static const BYTE dll_code_section[] = { 0x31, 0xc0, /* xor %eax,%eax */
70 0xc2, 0x0c, 0x00 }; /* ret $12 */
72 static const BYTE exe_code_section[] = { 0xb8, 0x01, 0x00, 0x00, 0x00, /* movl $1,%eax */
73 0xc2, 0x04, 0x00 }; /* ret $4 */
75 static const IMAGE_BASE_RELOCATION reloc_section; /* empty relocs */
78 /* wrapper for WriteFile */
79 static inline BOOL xwrite( struct dll_info *info, const void *data, DWORD size, DWORD offset )
81 DWORD res;
83 return (SetFilePointer( info->handle, offset, NULL, FILE_BEGIN ) != INVALID_SET_FILE_POINTER &&
84 WriteFile( info->handle, data, size, &res, NULL ) &&
85 res == size);
88 /* add a new section to the dll NT header */
89 static void add_section( struct dll_info *info, const char *name, DWORD size, DWORD flags )
91 IMAGE_SECTION_HEADER *sec = (IMAGE_SECTION_HEADER *)(info->nt + 1);
93 sec += info->nt->FileHeader.NumberOfSections;
94 memcpy( sec->Name, name, min( strlen(name), sizeof(sec->Name)) );
95 sec->Misc.VirtualSize = ALIGN( size, section_alignment );
96 sec->VirtualAddress = info->mem_pos;
97 sec->SizeOfRawData = size;
98 sec->PointerToRawData = info->file_pos;
99 sec->Characteristics = flags;
100 info->file_pos += ALIGN( size, file_alignment );
101 info->mem_pos += ALIGN( size, section_alignment );
102 info->nt->FileHeader.NumberOfSections++;
105 /* add a data directory to the dll NT header */
106 static inline void add_directory( struct dll_info *info, unsigned int idx, DWORD rva, DWORD size )
108 info->nt->OptionalHeader.DataDirectory[idx].VirtualAddress = rva;
109 info->nt->OptionalHeader.DataDirectory[idx].Size = size;
112 /* add a dll to the list of dll that have been taken care of */
113 static BOOL add_handled_dll( const WCHAR *name )
115 int i, min, max, pos, res;
117 min = 0;
118 max = handled_count - 1;
119 while (min <= max)
121 pos = (min + max) / 2;
122 res = wcscmp( handled_dlls[pos], name );
123 if (!res) return FALSE; /* already in the list */
124 if (res < 0) min = pos + 1;
125 else max = pos - 1;
128 if (handled_count >= handled_total)
130 WCHAR **new_dlls;
131 unsigned int new_count = max( 64, handled_total * 2 );
133 if (handled_dlls) new_dlls = HeapReAlloc( GetProcessHeap(), 0, handled_dlls,
134 new_count * sizeof(*handled_dlls) );
135 else new_dlls = HeapAlloc( GetProcessHeap(), 0, new_count * sizeof(*handled_dlls) );
136 if (!new_dlls) return FALSE;
137 handled_dlls = new_dlls;
138 handled_total = new_count;
141 for (i = handled_count; i > min; i--) handled_dlls[i] = handled_dlls[i - 1];
142 handled_dlls[i] = wcsdup( name );
143 handled_count++;
144 return TRUE;
147 static int is_valid_ptr( const void *data, SIZE_T size, const void *ptr, SIZE_T ptr_size )
149 if (ptr < data) return 0;
150 if ((char *)ptr - (char *)data >= size) return 0;
151 return (size - ((char *)ptr - (char *)data) >= ptr_size);
154 /* extract the 16-bit NE dll from a PE builtin */
155 static void extract_16bit_image( IMAGE_NT_HEADERS *nt, void **data, SIZE_T *size )
157 DWORD exp_size, *size_ptr;
158 IMAGE_DOS_HEADER *dos;
159 IMAGE_EXPORT_DIRECTORY *exports;
160 IMAGE_SECTION_HEADER *section = NULL;
161 WORD *ordinals;
162 DWORD *names, *functions;
163 int i;
165 exports = RtlImageDirectoryEntryToData( *data, FALSE, IMAGE_DIRECTORY_ENTRY_EXPORT, &exp_size );
166 if (!is_valid_ptr( *data, *size, exports, exp_size )) return;
167 ordinals = RtlImageRvaToVa( nt, *data, exports->AddressOfNameOrdinals, &section );
168 names = RtlImageRvaToVa( nt, *data, exports->AddressOfNames, &section );
169 functions = RtlImageRvaToVa( nt, *data, exports->AddressOfFunctions, &section );
170 if (!is_valid_ptr( *data, *size, ordinals, exports->NumberOfNames * sizeof(*ordinals) )) return;
171 if (!is_valid_ptr( *data, *size, names, exports->NumberOfNames * sizeof(*names) )) return;
173 for (i = 0; i < exports->NumberOfNames; i++)
175 char *ename = RtlImageRvaToVa( nt, *data, names[i], &section );
176 if (strcmp( ename, "__wine_spec_dos_header" )) continue;
177 if (ordinals[i] >= exports->NumberOfFunctions) return;
178 if (!is_valid_ptr( *data, *size, functions, sizeof(*functions) )) return;
179 if (!functions[ordinals[i]]) return;
180 dos = RtlImageRvaToVa( nt, *data, functions[ordinals[i]], NULL );
181 if (!is_valid_ptr( *data, *size, dos, sizeof(*dos) )) return;
182 if (dos->e_magic != IMAGE_DOS_SIGNATURE) return;
183 size_ptr = (DWORD *)dos->e_res2;
184 *size = min( *size_ptr, *size - ((const char *)dos - (const char *)*data) );
185 *size_ptr = 0;
186 *data = dos;
187 break;
191 /* read in the contents of a file into the global file buffer */
192 /* return 1 on success, 0 on nonexistent file, -1 on other error */
193 static int read_file( const WCHAR *name, void **data, SIZE_T *size, BOOL expect_builtin )
195 struct stat st;
196 int fd, ret = -1;
197 size_t header_size;
198 IMAGE_DOS_HEADER *dos;
199 IMAGE_NT_HEADERS *nt;
200 const char *signature = expect_builtin ? builtin_signature : fakedll_signature;
201 const size_t min_size = sizeof(*dos) + 32 +
202 FIELD_OFFSET( IMAGE_NT_HEADERS, OptionalHeader.MajorLinkerVersion );
204 if ((fd = _wopen( name, O_RDONLY | O_BINARY )) == -1) return 0;
205 if (fstat( fd, &st ) == -1) goto done;
206 *size = st.st_size;
207 if (!file_buffer || st.st_size > file_buffer_size)
209 VirtualFree( file_buffer, 0, MEM_RELEASE );
210 file_buffer = NULL;
211 file_buffer_size = st.st_size;
212 if (NtAllocateVirtualMemory( GetCurrentProcess(), &file_buffer, 0, &file_buffer_size,
213 MEM_COMMIT, PAGE_READWRITE )) goto done;
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 (read( fd, file_buffer, header_size ) != header_size) goto done;
221 dos = file_buffer;
222 if (dos->e_magic != IMAGE_DOS_SIGNATURE) goto done;
223 if (dos->e_lfanew < strlen(signature) + 1) goto done;
224 if (memcmp( dos + 1, signature, strlen(signature) + 1 )) 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 *)file_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 */
231 ret = 0;
232 goto done;
234 if (st.st_size == header_size ||
235 read( fd, (char *)file_buffer + header_size,
236 st.st_size - header_size ) == st.st_size - header_size)
238 *data = file_buffer;
239 if (lstrlenW(name) > 2 && !wcscmp( name + lstrlenW(name) - 2, L"16" ))
240 extract_16bit_image( nt, data, size );
241 ret = 1;
243 done:
244 close( fd );
245 return ret;
248 /* build a complete fake dll from scratch */
249 static BOOL build_fake_dll( HANDLE file, const WCHAR *name )
251 IMAGE_DOS_HEADER *dos;
252 IMAGE_NT_HEADERS *nt;
253 struct dll_info info;
254 const WCHAR *ext;
255 BYTE *buffer;
256 BOOL ret = FALSE;
257 DWORD lfanew = (sizeof(*dos) + sizeof(fakedll_signature) + 15) & ~15;
258 DWORD size, header_size = lfanew + sizeof(*nt);
260 info.handle = file;
261 buffer = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, header_size + 8 * sizeof(IMAGE_SECTION_HEADER) );
263 dos = (IMAGE_DOS_HEADER *)buffer;
264 dos->e_magic = IMAGE_DOS_SIGNATURE;
265 dos->e_cblp = sizeof(*dos);
266 dos->e_cp = 1;
267 dos->e_cparhdr = lfanew / 16;
268 dos->e_minalloc = 0;
269 dos->e_maxalloc = 0xffff;
270 dos->e_ss = 0x0000;
271 dos->e_sp = 0x00b8;
272 dos->e_lfarlc = lfanew;
273 dos->e_lfanew = lfanew;
274 memcpy( dos + 1, fakedll_signature, sizeof(fakedll_signature) );
276 nt = info.nt = (IMAGE_NT_HEADERS *)(buffer + lfanew);
277 /* some fields are copied from the source dll */
278 #if defined __x86_64__
279 nt->FileHeader.Machine = IMAGE_FILE_MACHINE_AMD64;
280 #elif defined __aarch64__
281 nt->FileHeader.Machine = IMAGE_FILE_MACHINE_ARM64;
282 #elif defined __arm__
283 nt->FileHeader.Machine = IMAGE_FILE_MACHINE_ARMNT;
284 #else
285 nt->FileHeader.Machine = IMAGE_FILE_MACHINE_I386;
286 #endif
287 nt->FileHeader.TimeDateStamp = 0;
288 nt->FileHeader.Characteristics = 0;
289 nt->OptionalHeader.MajorLinkerVersion = 1;
290 nt->OptionalHeader.MinorLinkerVersion = 0;
291 nt->OptionalHeader.MajorOperatingSystemVersion = 1;
292 nt->OptionalHeader.MinorOperatingSystemVersion = 0;
293 nt->OptionalHeader.MajorImageVersion = 1;
294 nt->OptionalHeader.MinorImageVersion = 0;
295 nt->OptionalHeader.MajorSubsystemVersion = 4;
296 nt->OptionalHeader.MinorSubsystemVersion = 0;
297 nt->OptionalHeader.Win32VersionValue = 0;
298 nt->OptionalHeader.Subsystem = IMAGE_SUBSYSTEM_WINDOWS_GUI;
299 nt->OptionalHeader.DllCharacteristics = 0;
300 nt->OptionalHeader.SizeOfStackReserve = 0;
301 nt->OptionalHeader.SizeOfStackCommit = 0;
302 nt->OptionalHeader.SizeOfHeapReserve = 0;
303 nt->OptionalHeader.SizeOfHeapCommit = 0;
304 /* other fields have fixed values */
305 nt->Signature = IMAGE_NT_SIGNATURE;
306 nt->FileHeader.NumberOfSections = 0;
307 nt->FileHeader.SizeOfOptionalHeader = IMAGE_SIZEOF_NT_OPTIONAL_HEADER;
308 nt->OptionalHeader.Magic = IMAGE_NT_OPTIONAL_HDR_MAGIC;
309 nt->OptionalHeader.ImageBase = 0x10000000;
310 nt->OptionalHeader.SectionAlignment = section_alignment;
311 nt->OptionalHeader.FileAlignment = file_alignment;
312 nt->OptionalHeader.NumberOfRvaAndSizes = IMAGE_NUMBEROF_DIRECTORY_ENTRIES;
314 header_size = (BYTE *)(nt + 1) - buffer;
315 info.mem_pos = ALIGN( header_size, section_alignment );
316 info.file_pos = ALIGN( header_size, file_alignment );
318 nt->OptionalHeader.AddressOfEntryPoint = info.mem_pos;
319 nt->OptionalHeader.BaseOfCode = info.mem_pos;
321 ext = wcsrchr( name, '.' );
322 if (!ext || wcsicmp( ext, L".exe" )) nt->FileHeader.Characteristics |= IMAGE_FILE_DLL;
324 if (nt->FileHeader.Characteristics & IMAGE_FILE_DLL)
326 size = sizeof(dll_code_section);
327 if (!xwrite( &info, dll_code_section, size, info.file_pos )) goto done;
329 else
331 size = sizeof(exe_code_section);
332 if (!xwrite( &info, exe_code_section, size, info.file_pos )) goto done;
334 nt->OptionalHeader.SizeOfCode = size;
335 add_section( &info, ".text", size, IMAGE_SCN_CNT_CODE | IMAGE_SCN_MEM_EXECUTE | IMAGE_SCN_MEM_READ );
337 if (!xwrite( &info, &reloc_section, sizeof(reloc_section), info.file_pos )) goto done;
338 add_directory( &info, IMAGE_DIRECTORY_ENTRY_BASERELOC, info.mem_pos, sizeof(reloc_section) );
339 add_section( &info, ".reloc", sizeof(reloc_section),
340 IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_DISCARDABLE | IMAGE_SCN_MEM_READ );
342 header_size += nt->FileHeader.NumberOfSections * sizeof(IMAGE_SECTION_HEADER);
343 nt->OptionalHeader.SizeOfHeaders = ALIGN( header_size, file_alignment );
344 nt->OptionalHeader.SizeOfImage = ALIGN( info.mem_pos, section_alignment );
345 ret = xwrite( &info, buffer, header_size, 0 );
346 done:
347 HeapFree( GetProcessHeap(), 0, buffer );
348 return ret;
351 /* check if an existing file is a fake dll so that we can overwrite it */
352 static BOOL is_fake_dll( HANDLE h )
354 IMAGE_DOS_HEADER *dos;
355 DWORD size;
356 BYTE buffer[sizeof(*dos) + 32];
358 if (!ReadFile( h, buffer, sizeof(buffer), &size, NULL ) || size != sizeof(buffer))
359 return FALSE;
360 dos = (IMAGE_DOS_HEADER *)buffer;
361 if (dos->e_magic != IMAGE_DOS_SIGNATURE) return FALSE;
362 if (dos->e_lfanew < size) return FALSE;
363 return (!memcmp( dos + 1, builtin_signature, sizeof(builtin_signature) ) ||
364 !memcmp( dos + 1, fakedll_signature, sizeof(fakedll_signature) ));
367 /* create directories leading to a given file */
368 static void create_directories( const WCHAR *name )
370 WCHAR *path, *p;
372 /* create the directory/directories */
373 path = HeapAlloc(GetProcessHeap(), 0, (lstrlenW(name) + 1)*sizeof(WCHAR));
374 lstrcpyW(path, name);
376 p = wcschr(path, '\\');
377 while (p != NULL)
379 *p = 0;
380 if (!CreateDirectoryW(path, NULL))
381 TRACE("Couldn't create directory %s - error: %d\n", wine_dbgstr_w(path), GetLastError());
382 *p = '\\';
383 p = wcschr(p+1, '\\');
385 HeapFree(GetProcessHeap(), 0, path);
388 static inline WCHAR *prepend( WCHAR *buffer, const WCHAR *str, size_t len )
390 return memcpy( buffer - len, str, len * sizeof(WCHAR) );
393 static const WCHAR *enum_load_path( unsigned int idx )
395 WCHAR buffer[32];
396 swprintf( buffer, ARRAY_SIZE(buffer), L"WINEDLLDIR%u", idx );
397 return _wgetenv( buffer );
400 /* try to load a pre-compiled fake dll */
401 static void *load_fake_dll( const WCHAR *name, SIZE_T *size )
403 const WCHAR *build_dir = _wgetenv( L"WINEBUILDDIR" );
404 const WCHAR *path;
405 WCHAR *file, *ptr;
406 void *data = NULL;
407 unsigned int i, pos, len, namelen, maxlen = 0;
408 WCHAR *p;
409 int res = 0;
411 if ((p = wcsrchr( name, '\\' ))) name = p + 1;
413 i = 0;
414 len = lstrlenW( name );
415 if (build_dir) maxlen = lstrlenW(build_dir) + ARRAY_SIZE(L"\\programs") + len + 1;
416 while ((path = enum_load_path( i++ ))) maxlen = max( maxlen, lstrlenW(path) );
417 maxlen += ARRAY_SIZE(L"\\fakedlls") + len + ARRAY_SIZE(L".fake");
419 if (!(file = HeapAlloc( GetProcessHeap(), 0, maxlen * sizeof(WCHAR) ))) return NULL;
421 pos = maxlen - len - ARRAY_SIZE(L".fake");
422 lstrcpyW( file + pos, name );
423 file[--pos] = '\\';
425 if (build_dir)
427 /* try as a dll */
428 ptr = file + pos;
429 namelen = len + 1;
430 file[pos + len + 1] = 0;
431 if (namelen > 4 && !wcsncmp( ptr + namelen - 4, L".dll", 4 )) namelen -= 4;
432 ptr = prepend( ptr, ptr, namelen );
433 ptr = prepend( ptr, L"\\dlls", 5 );
434 ptr = prepend( ptr, build_dir, lstrlenW(build_dir) );
435 if ((res = read_file( ptr, &data, size, TRUE ))) goto done;
436 lstrcpyW( file + pos + len + 1, L".fake" );
437 if ((res = read_file( ptr, &data, size, FALSE ))) goto done;
439 /* now as a program */
440 ptr = file + pos;
441 namelen = len + 1;
442 file[pos + len + 1] = 0;
443 if (namelen > 4 && !wcsncmp( ptr + namelen - 4, L".exe", 4 )) namelen -= 4;
444 ptr = prepend( ptr, ptr, namelen );
445 ptr = prepend( ptr, L"\\programs", 9 );
446 ptr = prepend( ptr, build_dir, lstrlenW(build_dir) );
447 if ((res = read_file( ptr, &data, size, TRUE ))) goto done;
448 lstrcpyW( file + pos + len + 1, L".fake" );
449 if ((res = read_file( ptr, &data, size, FALSE ))) goto done;
452 file[pos + len + 1] = 0;
453 for (i = 0; (path = enum_load_path( i )); i++)
455 ptr = prepend( file + pos, path, lstrlenW(path) );
456 if ((res = read_file( ptr, &data, size, TRUE ))) break;
457 ptr = prepend( file + pos, L"\\fakedlls", 9 );
458 ptr = prepend( ptr, path, lstrlenW(path) );
459 if ((res = read_file( ptr, &data, size, FALSE ))) break;
462 done:
463 HeapFree( GetProcessHeap(), 0, file );
464 if (res == 1) return data;
465 return NULL;
468 /* create the fake dll destination file */
469 static HANDLE create_dest_file( const WCHAR *name, BOOL delete )
471 /* first check for an existing file */
472 HANDLE h = CreateFileW( name, GENERIC_READ|GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL );
473 if (h != INVALID_HANDLE_VALUE)
475 if (!is_fake_dll( h ))
477 TRACE( "%s is not a fake dll, not overwriting it\n", debugstr_w(name) );
478 CloseHandle( h );
479 return 0;
481 if (delete)
483 CloseHandle( h );
484 DeleteFileW( name );
485 return INVALID_HANDLE_VALUE;
487 /* truncate the file */
488 SetFilePointer( h, 0, NULL, FILE_BEGIN );
489 SetEndOfFile( h );
491 else if (!delete)
493 if (GetLastError() == ERROR_PATH_NOT_FOUND) create_directories( name );
495 h = CreateFileW( name, GENERIC_WRITE, 0, NULL, CREATE_NEW, 0, NULL );
496 if (h == INVALID_HANDLE_VALUE)
497 ERR( "failed to create %s (error=%u)\n", debugstr_w(name), GetLastError() );
499 return h;
502 /* XML parsing code copied from ntdll */
504 typedef struct
506 const char *ptr;
507 unsigned int len;
508 } xmlstr_t;
510 typedef struct
512 const char *ptr;
513 const char *end;
514 } xmlbuf_t;
516 static inline BOOL xmlstr_cmp(const xmlstr_t* xmlstr, const char *str)
518 return !strncmp(xmlstr->ptr, str, xmlstr->len) && !str[xmlstr->len];
521 static inline BOOL isxmlspace( char ch )
523 return (ch == ' ' || ch == '\r' || ch == '\n' || ch == '\t');
526 static BOOL next_xml_elem( xmlbuf_t *xmlbuf, xmlstr_t *elem )
528 const char *ptr;
530 for (;;)
532 ptr = memchr(xmlbuf->ptr, '<', xmlbuf->end - xmlbuf->ptr);
533 if (!ptr)
535 xmlbuf->ptr = xmlbuf->end;
536 return FALSE;
538 ptr++;
539 if (ptr + 3 < xmlbuf->end && ptr[0] == '!' && ptr[1] == '-' && ptr[2] == '-') /* skip comment */
541 for (ptr += 3; ptr + 3 <= xmlbuf->end; ptr++)
542 if (ptr[0] == '-' && ptr[1] == '-' && ptr[2] == '>') break;
544 if (ptr + 3 > xmlbuf->end)
546 xmlbuf->ptr = xmlbuf->end;
547 return FALSE;
549 xmlbuf->ptr = ptr + 3;
551 else break;
554 xmlbuf->ptr = ptr;
555 while (ptr < xmlbuf->end && !isxmlspace(*ptr) && *ptr != '>' && (*ptr != '/' || ptr == xmlbuf->ptr))
556 ptr++;
558 elem->ptr = xmlbuf->ptr;
559 elem->len = ptr - xmlbuf->ptr;
560 xmlbuf->ptr = ptr;
561 return xmlbuf->ptr != xmlbuf->end;
564 static BOOL next_xml_attr(xmlbuf_t* xmlbuf, xmlstr_t* name, xmlstr_t* value, BOOL* error)
566 const char *ptr;
568 *error = TRUE;
570 while (xmlbuf->ptr < xmlbuf->end && isxmlspace(*xmlbuf->ptr))
571 xmlbuf->ptr++;
573 if (xmlbuf->ptr == xmlbuf->end) return FALSE;
575 if (*xmlbuf->ptr == '/')
577 xmlbuf->ptr++;
578 if (xmlbuf->ptr == xmlbuf->end || *xmlbuf->ptr != '>')
579 return FALSE;
581 xmlbuf->ptr++;
582 *error = FALSE;
583 return FALSE;
586 if (*xmlbuf->ptr == '>')
588 xmlbuf->ptr++;
589 *error = FALSE;
590 return FALSE;
593 ptr = xmlbuf->ptr;
594 while (ptr < xmlbuf->end && *ptr != '=' && *ptr != '>' && !isxmlspace(*ptr)) ptr++;
596 if (ptr == xmlbuf->end || *ptr != '=') return FALSE;
598 name->ptr = xmlbuf->ptr;
599 name->len = ptr-xmlbuf->ptr;
600 xmlbuf->ptr = ptr;
602 ptr++;
603 if (ptr == xmlbuf->end || (*ptr != '"' && *ptr != '\'')) return FALSE;
605 value->ptr = ++ptr;
606 if (ptr == xmlbuf->end) return FALSE;
608 ptr = memchr(ptr, ptr[-1], xmlbuf->end - ptr);
609 if (!ptr)
611 xmlbuf->ptr = xmlbuf->end;
612 return FALSE;
615 value->len = ptr - value->ptr;
616 xmlbuf->ptr = ptr + 1;
618 if (xmlbuf->ptr == xmlbuf->end) return FALSE;
620 *error = FALSE;
621 return TRUE;
624 static void append_manifest_filename( const xmlstr_t *arch, const xmlstr_t *name, const xmlstr_t *key,
625 const xmlstr_t *version, const xmlstr_t *lang, WCHAR *buffer, DWORD size )
627 DWORD pos = lstrlenW( buffer );
629 pos += MultiByteToWideChar( CP_UTF8, 0, arch->ptr, arch->len, buffer + pos, size - pos );
630 buffer[pos++] = '_';
631 pos += MultiByteToWideChar( CP_UTF8, 0, name->ptr, name->len, buffer + pos, size - pos );
632 buffer[pos++] = '_';
633 pos += MultiByteToWideChar( CP_UTF8, 0, key->ptr, key->len, buffer + pos, size - pos );
634 buffer[pos++] = '_';
635 pos += MultiByteToWideChar( CP_UTF8, 0, version->ptr, version->len, buffer + pos, size - pos );
636 buffer[pos++] = '_';
637 pos += MultiByteToWideChar( CP_UTF8, 0, lang->ptr, lang->len, buffer + pos, size - pos );
638 lstrcpyW( buffer + pos, L"_deadbeef" );
639 wcslwr( buffer );
642 static WCHAR* create_winsxs_dll_path( const xmlstr_t *arch, const xmlstr_t *name,
643 const xmlstr_t *key, const xmlstr_t *version,
644 const xmlstr_t *lang )
646 WCHAR *path;
647 DWORD path_len;
649 path_len = GetWindowsDirectoryW( NULL, 0 ) + ARRAY_SIZE( L"\\winsxs\\" )
650 + arch->len + name->len + key->len + version->len + 19;
652 path = HeapAlloc( GetProcessHeap(), 0, path_len * sizeof(WCHAR) );
653 GetWindowsDirectoryW( path, path_len );
654 lstrcatW( path, L"\\winsxs\\" );
655 append_manifest_filename( arch, name, key, version, lang, path, path_len );
656 lstrcatW( path, L"\\" );
657 return path;
660 static BOOL create_manifest( const xmlstr_t *arch, const xmlstr_t *name, const xmlstr_t *key,
661 const xmlstr_t *version, const xmlstr_t *lang, const void *data, DWORD len )
663 WCHAR *path;
664 DWORD written, path_len;
665 HANDLE handle;
666 BOOL ret = FALSE;
668 path_len = GetWindowsDirectoryW( NULL, 0 ) + ARRAY_SIZE( L"\\winsxs\\manifests\\" )
669 + arch->len + name->len + key->len + version->len + 18 + ARRAY_SIZE( L".manifest" );
671 path = HeapAlloc( GetProcessHeap(), 0, path_len * sizeof(WCHAR) );
672 GetWindowsDirectoryW( path, path_len );
673 lstrcatW( path, L"\\winsxs\\manifests\\" );
674 append_manifest_filename( arch, name, key, version, lang, path, path_len );
675 lstrcatW( path, L".manifest" );
676 handle = CreateFileW( path, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, NULL );
677 if (handle == INVALID_HANDLE_VALUE && GetLastError() == ERROR_PATH_NOT_FOUND)
679 create_directories( path );
680 handle = CreateFileW( path, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, NULL );
683 if (handle != INVALID_HANDLE_VALUE)
685 TRACE( "creating %s\n", debugstr_w(path) );
686 ret = (WriteFile( handle, data, len, &written, NULL ) && written == len);
687 if (!ret) ERR( "failed to write to %s (error=%u)\n", debugstr_w(path), GetLastError() );
688 CloseHandle( handle );
689 if (!ret) DeleteFileW( path );
691 HeapFree( GetProcessHeap(), 0, path );
692 return ret;
695 struct delay_copy
697 struct list entry;
698 WCHAR *src;
699 WCHAR *dest;
700 WCHAR data[1];
703 struct dll_data
705 struct list *delay_copy;
706 const WCHAR *src_dir;
707 DWORD src_len;
710 static BOOL CALLBACK register_manifest( HMODULE module, const WCHAR *type, WCHAR *res_name, LONG_PTR arg )
712 #ifdef __i386__
713 static const char current_arch[] = "x86";
714 #elif defined __x86_64__
715 static const char current_arch[] = "amd64";
716 #elif defined __arm__
717 static const char current_arch[] = "arm";
718 #elif defined __aarch64__
719 static const char current_arch[] = "arm64";
720 #else
721 static const char current_arch[] = "none";
722 #endif
723 const struct dll_data *dll_data = (const struct dll_data*)arg;
724 WCHAR *dest = NULL;
725 DWORD dest_len = 0;
726 xmlbuf_t buffer;
727 xmlstr_t elem, attr_name, attr_value;
728 xmlstr_t name, version, arch, key, lang;
729 BOOL error;
730 const char *manifest;
731 SIZE_T len;
732 HRSRC rsrc;
734 if (IS_INTRESOURCE( res_name ) || wcsncmp( res_name, L"WINE_MANIFEST", 13 )) return TRUE;
736 rsrc = FindResourceW( module, res_name, type );
737 manifest = LoadResource( module, rsrc );
738 len = SizeofResource( module, rsrc );
740 buffer.ptr = manifest;
741 buffer.end = manifest + len;
742 name.ptr = version.ptr = arch.ptr = key.ptr = lang.ptr = NULL;
743 name.len = version.len = arch.len = key.len = lang.len = 0;
745 while (next_xml_elem( &buffer, &elem ))
747 if (xmlstr_cmp( &elem, "file" ))
749 while (next_xml_attr( &buffer, &attr_name, &attr_value, &error ))
751 if (xmlstr_cmp(&attr_name, "name"))
753 name = attr_value;
754 break;
758 if (!error && dest && name.ptr)
760 struct delay_copy *add = HeapAlloc( GetProcessHeap(), 0,
761 sizeof(*add) + (dll_data->src_len + name.len +
762 dest_len + name.len + 1) * sizeof(WCHAR) );
763 add->src = add->data;
764 memcpy( add->src, dll_data->src_dir, dll_data->src_len * sizeof(WCHAR) );
765 MultiByteToWideChar( CP_UTF8, 0, name.ptr, name.len,
766 add->src + dll_data->src_len, name.len );
767 add->src[dll_data->src_len + name.len] = 0;
768 add->dest = add->data + dll_data->src_len + name.len + 1;
769 memcpy( add->dest, dest, dest_len * sizeof(WCHAR) );
770 memcpy( add->dest + dest_len, add->src + dll_data->src_len,
771 (name.len + 1) * sizeof(WCHAR) );
772 TRACE("schedule copy %s -> %s\n", wine_dbgstr_w(add->src), wine_dbgstr_w(add->dest));
773 list_add_tail( dll_data->delay_copy, &add->entry );
775 continue;
778 if (!xmlstr_cmp( &elem, "assemblyIdentity" )) continue;
779 HeapFree( GetProcessHeap(), 0, dest );
780 dest = NULL;
781 while (next_xml_attr( &buffer, &attr_name, &attr_value, &error ))
783 if (xmlstr_cmp(&attr_name, "name")) name = attr_value;
784 else if (xmlstr_cmp(&attr_name, "version")) version = attr_value;
785 else if (xmlstr_cmp(&attr_name, "processorArchitecture")) arch = attr_value;
786 else if (xmlstr_cmp(&attr_name, "publicKeyToken")) key = attr_value;
787 else if (xmlstr_cmp(&attr_name, "language")) lang = attr_value;
789 if (!error && name.ptr && version.ptr && arch.ptr && key.ptr)
791 if (!lang.ptr)
793 lang.ptr = "none";
794 lang.len = strlen( lang.ptr );
796 if (!arch.len) /* fixup the architecture */
798 char *new_buffer = HeapAlloc( GetProcessHeap(), 0, len + sizeof(current_arch) );
799 memcpy( new_buffer, manifest, arch.ptr - manifest );
800 strcpy( new_buffer + (arch.ptr - manifest), current_arch );
801 memcpy( new_buffer + strlen(new_buffer), arch.ptr, len - (arch.ptr - manifest) );
802 arch.ptr = current_arch;
803 arch.len = strlen( current_arch );
804 dest = create_winsxs_dll_path( &arch, &name, &key, &version, &lang );
805 create_manifest( &arch, &name, &key, &version, &lang, new_buffer, len + arch.len );
806 HeapFree( GetProcessHeap(), 0, new_buffer );
808 else
810 dest = create_winsxs_dll_path( &arch, &name, &key, &version, &lang );
811 create_manifest( &arch, &name, &key, &version, &lang, manifest, len );
813 dest_len = wcslen( dest );
816 HeapFree( GetProcessHeap(), 0, dest );
818 return TRUE;
821 static BOOL CALLBACK register_resource( HMODULE module, LPCWSTR type, LPWSTR name, LONG_PTR arg )
823 HRESULT *hr = (HRESULT *)arg;
824 WCHAR *buffer;
825 HRSRC rsrc = FindResourceW( module, name, type );
826 char *str = LoadResource( module, rsrc );
827 DWORD lenW, lenA = SizeofResource( module, rsrc );
829 if (!str) return FALSE;
830 lenW = MultiByteToWideChar( CP_UTF8, 0, str, lenA, NULL, 0 ) + 1;
831 if (!(buffer = HeapAlloc( GetProcessHeap(), 0, lenW * sizeof(WCHAR) ))) return FALSE;
832 MultiByteToWideChar( CP_UTF8, 0, str, lenA, buffer, lenW );
833 buffer[lenW - 1] = 0;
834 *hr = IRegistrar_StringRegister( registrar, buffer );
835 HeapFree( GetProcessHeap(), 0, buffer );
836 return TRUE;
839 static void register_fake_dll( const WCHAR *name, const void *data, size_t size, struct list *delay_copy )
841 const IMAGE_RESOURCE_DIRECTORY *resdir;
842 LDR_RESOURCE_INFO info;
843 HRESULT hr = S_OK;
844 HMODULE module = (HMODULE)((ULONG_PTR)data | 1);
845 struct dll_data dll_data = { delay_copy, name, 0 };
846 WCHAR buffer[MAX_PATH];
847 const WCHAR *p;
849 if (!(p = wcsrchr( name, '\\' ))) p = name;
850 else p++;
851 dll_data.src_len = p - name;
852 EnumResourceNamesW( module, (WCHAR*)RT_MANIFEST, register_manifest, (LONG_PTR)&dll_data );
854 info.Type = (ULONG_PTR)L"WINE_REGISTRY";
855 if (LdrFindResourceDirectory_U( module, &info, 1, &resdir )) return;
857 if (!registrar)
859 HRESULT (WINAPI *pAtlCreateRegistrar)(IRegistrar**);
860 HMODULE atl = LoadLibraryW( L"atl100.dll" );
862 if ((pAtlCreateRegistrar = (void *)GetProcAddress( atl, "AtlCreateRegistrar" )))
863 hr = pAtlCreateRegistrar( &registrar );
864 else
865 hr = E_NOINTERFACE;
867 if (!registrar)
869 ERR( "failed to create IRegistrar: %x\n", hr );
870 return;
874 TRACE( "registering %s\n", debugstr_w(name) );
875 IRegistrar_ClearReplacements( registrar );
876 IRegistrar_AddReplacement( registrar, L"MODULE", name );
877 GetEnvironmentVariableW( L"SystemRoot", buffer, ARRAY_SIZE(buffer) );
878 IRegistrar_AddReplacement( registrar, L"SystemRoot", buffer );
879 EnumResourceNamesW( module, L"WINE_REGISTRY", register_resource, (LONG_PTR)&hr );
880 if (FAILED(hr)) ERR( "failed to register %s: %x\n", debugstr_w(name), hr );
883 /* copy a fake dll file to the dest directory */
884 static int install_fake_dll( WCHAR *dest, WCHAR *file, const WCHAR *ext, BOOL delete, BOOL expect_builtin, struct list *delay_copy )
886 int ret;
887 SIZE_T size;
888 void *data;
889 DWORD written;
890 WCHAR *destname = dest + lstrlenW(dest);
891 WCHAR *name = wcsrchr( file, '\\' ) + 1;
892 WCHAR *end = name + lstrlenW(name);
893 SIZE_T len = end - name;
895 if (ext) lstrcpyW( end, ext );
896 if (!(ret = read_file( file, &data, &size, expect_builtin )))
898 *end = 0;
899 return 0;
902 if (end > name + 2 && !wcsncmp( end - 2, L"16", 2 )) len -= 2; /* remove "16" suffix */
903 memcpy( destname, name, len * sizeof(WCHAR) );
904 destname[len] = 0;
905 if (!add_handled_dll( destname )) ret = -1;
907 if (ret != -1)
909 HANDLE h = create_dest_file( dest, delete );
911 if (h && h != INVALID_HANDLE_VALUE)
913 TRACE( "%s -> %s\n", debugstr_w(file), debugstr_w(dest) );
915 ret = (WriteFile( h, data, size, &written, NULL ) && written == size);
916 if (!ret) ERR( "failed to write to %s (error=%u)\n", debugstr_w(dest), GetLastError() );
917 CloseHandle( h );
918 if (ret) register_fake_dll( dest, data, size, delay_copy );
919 else DeleteFileW( dest );
922 *destname = 0; /* restore it for next file */
923 *end = 0;
924 return ret;
927 static void delay_copy_files( struct list *delay_copy )
929 struct delay_copy *copy, *next;
930 DWORD written;
931 SIZE_T size;
932 void *data;
933 HANDLE h;
934 int ret;
936 LIST_FOR_EACH_ENTRY_SAFE( copy, next, delay_copy, struct delay_copy, entry )
938 list_remove( &copy->entry );
939 ret = read_file( copy->src, &data, &size, TRUE );
940 if (ret == -1) ret = read_file( copy->src, &data, &size, FALSE );
941 if (ret != 1)
943 HeapFree( GetProcessHeap(), 0, copy );
944 continue;
947 h = create_dest_file( copy->dest, FALSE );
948 if (h && h != INVALID_HANDLE_VALUE)
950 ret = (WriteFile( h, data, size, &written, NULL ) && written == size);
951 if (!ret) ERR( "failed to write to %s (error=%u)\n", debugstr_w(copy->dest), GetLastError() );
952 CloseHandle( h );
953 if (!ret) DeleteFileW( copy->dest );
955 HeapFree( GetProcessHeap(), 0, copy );
959 /* find and install all fake dlls in a given lib directory */
960 static void install_lib_dir( WCHAR *dest, WCHAR *file, const WCHAR *wildcard,
961 const WCHAR *default_ext, BOOL delete, BOOL expect_builtin )
963 WCHAR *name;
964 intptr_t handle;
965 struct _wfinddata_t data;
966 struct list delay_copy = LIST_INIT( delay_copy );
968 file[1] = '\\'; /* change \??\ to \\?\ */
969 name = file + lstrlenW(file);
970 *name++ = '\\';
971 lstrcpyW( name, wildcard );
973 if ((handle = _wfindfirst( file, &data )) == -1) return;
976 if (lstrlenW( data.name ) > max_dll_name_len) continue;
977 if (!wcscmp( data.name, L"." )) continue;
978 if (!wcscmp( data.name, L".." )) continue;
979 lstrcpyW( name, data.name );
980 if (default_ext) /* inside build dir */
982 lstrcatW( name, L"\\" );
983 lstrcatW( name, data.name );
984 if (wcschr( data.name, '.' )) /* module possibly already has an extension */
986 if (install_fake_dll( dest, file, NULL, delete, expect_builtin, &delay_copy )) continue;
987 if (install_fake_dll( dest, file, L".fake", delete, FALSE, &delay_copy )) continue;
989 lstrcatW( name, default_ext );
990 if (install_fake_dll( dest, file, NULL, delete, expect_builtin, &delay_copy )) continue;
991 if (install_fake_dll( dest, file, L".fake", delete, FALSE, &delay_copy )) continue;
993 else install_fake_dll( dest, file, NULL, delete, expect_builtin, &delay_copy );
995 while (!_wfindnext( handle, &data ));
996 _findclose( handle );
998 delay_copy_files( &delay_copy );
1001 /* create fake dlls in dirname for all the files we can find */
1002 static BOOL create_wildcard_dlls( const WCHAR *dirname, const WCHAR *wildcard, BOOL delete )
1004 const WCHAR *build_dir = _wgetenv( L"WINEBUILDDIR" );
1005 const WCHAR *path;
1006 unsigned int i, maxlen = 0;
1007 WCHAR *file, *dest, *p;
1009 if (build_dir) maxlen = lstrlenW(build_dir) + ARRAY_SIZE(L"\\programs") + 1;
1010 for (i = 0; (path = enum_load_path(i)); i++) maxlen = max( maxlen, lstrlenW(path) );
1011 maxlen += 2 * max_dll_name_len + 2 + 10; /* ".dll.fake" */
1012 if (!(file = HeapAlloc( GetProcessHeap(), 0, maxlen * sizeof(WCHAR) ))) return FALSE;
1014 if (!(dest = HeapAlloc( GetProcessHeap(), 0, (lstrlenW(dirname) + max_dll_name_len) * sizeof(WCHAR) )))
1016 HeapFree( GetProcessHeap(), 0, file );
1017 return FALSE;
1019 lstrcpyW( dest, dirname );
1020 if ((p = wcsrchr( dest, '\\' ))) p[1] = 0; /* remove wildcard */
1022 if (build_dir)
1024 lstrcpyW( file, build_dir );
1025 lstrcatW( file, L"\\dlls" );
1026 install_lib_dir( dest, file, wildcard, L".dll", delete, TRUE );
1027 lstrcpyW( file, build_dir );
1028 lstrcatW( file, L"\\programs" );
1029 install_lib_dir( dest, file, wildcard, L".exe", delete, TRUE );
1031 for (i = 0; (path = enum_load_path( i )); i++)
1033 lstrcpyW( file, path );
1034 install_lib_dir( dest, file, wildcard, NULL, delete, TRUE );
1035 lstrcpyW( file, path );
1036 lstrcatW( file, L"\\fakedlls" );
1037 install_lib_dir( dest, file, wildcard, NULL, delete, FALSE );
1039 HeapFree( GetProcessHeap(), 0, file );
1040 HeapFree( GetProcessHeap(), 0, dest );
1041 return TRUE;
1044 /***********************************************************************
1045 * create_fake_dll
1047 BOOL create_fake_dll( const WCHAR *name, const WCHAR *source )
1049 struct list delay_copy = LIST_INIT( delay_copy );
1050 HANDLE h;
1051 BOOL ret;
1052 SIZE_T size;
1053 const WCHAR *filename;
1054 void *buffer;
1055 BOOL delete = !wcscmp( source, L"-" ); /* '-' source means delete the file */
1057 if (!(filename = wcsrchr( name, '\\' ))) filename = name;
1058 else filename++;
1060 /* check for empty name which means to only create the directory */
1061 if (!filename[0])
1063 create_directories( name );
1064 return TRUE;
1066 if (wcspbrk( filename, L"*?" )) return create_wildcard_dlls( name, filename, delete );
1068 add_handled_dll( filename );
1070 if (!(h = create_dest_file( name, delete ))) return TRUE; /* not a fake dll */
1071 if (h == INVALID_HANDLE_VALUE) return FALSE;
1073 if ((buffer = load_fake_dll( source, &size )))
1075 DWORD written;
1077 ret = (WriteFile( h, buffer, size, &written, NULL ) && written == size);
1078 if (ret) register_fake_dll( name, buffer, size, &delay_copy );
1079 else ERR( "failed to write to %s (error=%u)\n", debugstr_w(name), GetLastError() );
1081 else
1083 WARN( "fake dll %s not found for %s\n", debugstr_w(source), debugstr_w(name) );
1084 ret = build_fake_dll( h, name );
1087 CloseHandle( h );
1088 if (!ret) DeleteFileW( name );
1090 delay_copy_files( &delay_copy );
1091 return ret;
1095 /***********************************************************************
1096 * cleanup_fake_dlls
1098 void cleanup_fake_dlls(void)
1100 if (file_buffer) VirtualFree( file_buffer, 0, MEM_RELEASE );
1101 file_buffer = NULL;
1102 HeapFree( GetProcessHeap(), 0, handled_dlls );
1103 handled_dlls = NULL;
1104 handled_count = handled_total = 0;
1105 if (registrar) IRegistrar_Release( registrar );
1106 registrar = NULL;