comctl32: A couple fixes for tab icon offsets.
[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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19  */
20
21 #include <stdarg.h>
22
23 #define NONAMELESSSTRUCT
24 #define NONAMELESSUNION
25 #include "ntstatus.h"
26 #define WIN32_NO_STATUS
27 #include "windef.h"
28 #include "winbase.h"
29 #include "winuser.h"
30 #include "winver.h"
31 #include "winnt.h"
32 #include "winternl.h"
33 #include "wine/unicode.h"
34 #include "wine/debug.h"
35
36 WINE_DEFAULT_DEBUG_CHANNEL(setupapi);
37
38 static const char fakedll_signature[] = "Wine placeholder DLL";
39
40 static const unsigned int file_alignment = 512;
41 static const unsigned int section_alignment = 4096;
42
43 struct dll_info
44 {
45     HANDLE            handle;
46     IMAGE_NT_HEADERS *nt;
47     DWORD             file_pos;
48     DWORD             mem_pos;
49 };
50
51 #define ALIGN(size,align) (((size) + (align) - 1) & ~((align) - 1))
52
53 /* contents of the dll sections */
54
55 static const BYTE dll_code_section[] = { 0x31, 0xc0,          /* xor %eax,%eax */
56                                          0xc2, 0x0c, 0x00 };  /* ret $12 */
57
58 static const BYTE exe_code_section[] = { 0xb8, 0x01, 0x00, 0x00, 0x00,  /* movl $1,%eax */
59                                          0xc2, 0x04, 0x00 };            /* ret $4 */
60
61 static const IMAGE_BASE_RELOCATION reloc_section;  /* empty relocs */
62
63
64 /* wrapper for WriteFile */
65 static inline BOOL xwrite( struct dll_info *info, const void *data, DWORD size, DWORD offset )
66 {
67     DWORD res;
68
69     return (SetFilePointer( info->handle, offset, NULL, FILE_BEGIN ) != INVALID_SET_FILE_POINTER &&
70             WriteFile( info->handle, data, size, &res, NULL ) &&
71             res == size);
72 }
73
74 /* add a new section to the dll NT header */
75 static void add_section( struct dll_info *info, const char *name, DWORD size, DWORD flags )
76 {
77     IMAGE_SECTION_HEADER *sec = (IMAGE_SECTION_HEADER *)(info->nt + 1);
78
79     sec += info->nt->FileHeader.NumberOfSections;
80     memcpy( (char *)sec->Name, name, min( strlen(name), sizeof(sec->Name)) );
81     sec->Misc.VirtualSize = ALIGN( size, section_alignment );
82     sec->VirtualAddress   = info->mem_pos;
83     sec->SizeOfRawData    = size;
84     sec->PointerToRawData = info->file_pos;
85     sec->Characteristics  = flags;
86     info->file_pos += ALIGN( size, file_alignment );
87     info->mem_pos  += ALIGN( size, section_alignment );
88     info->nt->FileHeader.NumberOfSections++;
89 }
90
91 /* add a data directory to the dll NT header */
92 static inline void add_directory( struct dll_info *info, unsigned int idx, DWORD rva, DWORD size )
93 {
94     info->nt->OptionalHeader.DataDirectory[idx].VirtualAddress = rva;
95     info->nt->OptionalHeader.DataDirectory[idx].Size = size;
96 }
97
98 /* add version resources to the dll by copying them from the source module */
99 static BOOL add_version_resource( HMODULE module, struct dll_info *dll_info )
100 {
101     int i;
102     BOOL ret = FALSE;
103     DWORD size, pos;
104     BYTE *buffer;
105     LDR_RESOURCE_INFO info;
106     IMAGE_RESOURCE_DIRECTORY *dir;
107     IMAGE_RESOURCE_DIRECTORY_ENTRY *entry;
108     IMAGE_RESOURCE_DATA_ENTRY *data;
109     const IMAGE_RESOURCE_DIRECTORY *basedir, *resdir;
110     const IMAGE_RESOURCE_DIRECTORY_ENTRY *src_entry;
111     const IMAGE_RESOURCE_DATA_ENTRY *src_data;
112
113     if (!module) return TRUE;
114     if (LdrFindResourceDirectory_U( module, NULL, 0, &basedir ) != STATUS_SUCCESS) return TRUE;
115     info.Type = VS_FILE_INFO;
116     info.Name = VS_VERSION_INFO;
117     if (LdrFindResourceDirectory_U( module, &info, 2, &resdir ) != STATUS_SUCCESS) return TRUE;
118
119     size = 3 * sizeof(IMAGE_RESOURCE_DIRECTORY);
120     size += (resdir->NumberOfIdEntries + 2) * sizeof(IMAGE_RESOURCE_DIRECTORY_ENTRY);
121     size += resdir->NumberOfIdEntries * sizeof(IMAGE_RESOURCE_DATA_ENTRY);
122
123     buffer = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, size );
124
125     /* types directory */
126     dir = (IMAGE_RESOURCE_DIRECTORY *)buffer;
127     dir->NumberOfIdEntries = 1;
128     entry = (IMAGE_RESOURCE_DIRECTORY_ENTRY *)(dir + 1);
129     entry->u1.s2.Id = info.Type;
130     entry->u2.s3.DataIsDirectory = 1;
131     entry->u2.s3.OffsetToDirectory = (BYTE *)(entry + 1) - buffer;
132
133     /* names directory */
134     dir = (IMAGE_RESOURCE_DIRECTORY *)(entry + 1);
135     dir->NumberOfIdEntries = 1;
136     entry = (IMAGE_RESOURCE_DIRECTORY_ENTRY *)(dir + 1);
137     entry->u1.s2.Id = info.Name;
138     entry->u2.s3.DataIsDirectory = 1;
139     entry->u2.s3.OffsetToDirectory = (BYTE *)(entry + 1) - buffer;
140
141     /* languages directory */
142     dir = (IMAGE_RESOURCE_DIRECTORY *)(entry + 1);
143     *dir = *resdir;
144     entry = (IMAGE_RESOURCE_DIRECTORY_ENTRY *)(dir + 1);
145     src_entry = (const IMAGE_RESOURCE_DIRECTORY_ENTRY *)(resdir + 1);
146     memcpy( entry, src_entry, resdir->NumberOfIdEntries * sizeof(*entry) );
147
148     /* data entries */
149     data = (IMAGE_RESOURCE_DATA_ENTRY *)(entry + resdir->NumberOfIdEntries);
150     pos = size;
151     for (i = 0; i < resdir->NumberOfIdEntries; i++)
152     {
153         void *ptr;
154         ULONG data_size;
155         src_data = (const IMAGE_RESOURCE_DATA_ENTRY *)((const char *)basedir + src_entry[i].u2.OffsetToData);
156         if (LdrAccessResource( module, src_data, &ptr, &data_size )) goto done;
157
158         entry[i].u2.OffsetToData = (BYTE *)&data[i] - buffer;
159         data[i] = *src_data;
160         data[i].OffsetToData = dll_info->mem_pos + pos;
161         if (!xwrite( dll_info, ptr, data_size, dll_info->file_pos + pos )) goto done;
162         pos += (data_size + 3) & ~3;
163     }
164     if (!xwrite( dll_info, buffer, size, dll_info->file_pos )) goto done;
165
166     add_directory( dll_info, IMAGE_DIRECTORY_ENTRY_RESOURCE, dll_info->mem_pos, pos );
167     add_section( dll_info, ".rsrc", pos, IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_READ );
168     ret = TRUE;
169 done:
170     HeapFree( GetProcessHeap(), 0, buffer );
171     return ret;
172 }
173
174 void dummy(void)
175 {
176     __asm__ __volatile__("movl $1,%eax; ret $4");
177 }
178
179 /* build a complete fake dll, optionally using module as a source */
180 static BOOL build_fake_dll( HANDLE file, HMODULE module )
181 {
182     IMAGE_DOS_HEADER *dos;
183     IMAGE_NT_HEADERS *nt;
184     const IMAGE_NT_HEADERS *src_nt = NULL;
185     struct dll_info info;
186     BYTE *buffer;
187     BOOL ret = FALSE;
188     DWORD lfanew = (sizeof(*dos) + sizeof(fakedll_signature) + 15) & ~15;
189     DWORD size, header_size = lfanew + sizeof(*nt);
190
191     info.handle = file;
192     buffer = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, header_size + 8 * sizeof(IMAGE_SECTION_HEADER) );
193
194     dos = (IMAGE_DOS_HEADER *)buffer;
195     dos->e_magic    = IMAGE_DOS_SIGNATURE;
196     dos->e_cblp     = sizeof(*dos);
197     dos->e_cp       = 1;
198     dos->e_cparhdr  = lfanew / 16;
199     dos->e_minalloc = 0;
200     dos->e_maxalloc = 0xffff;
201     dos->e_ss       = 0x0000;
202     dos->e_sp       = 0x00b8;
203     dos->e_lfarlc   = lfanew;
204     dos->e_lfanew   = lfanew;
205     memcpy( dos + 1, fakedll_signature, sizeof(fakedll_signature) );
206
207     nt = info.nt = (IMAGE_NT_HEADERS *)(buffer + lfanew);
208     src_nt = RtlImageNtHeader( module );
209     /* some fields are copied from the source dll */
210 #define SET(field,def) nt->field = src_nt ? src_nt->field : def
211     SET( FileHeader.Machine, IMAGE_FILE_MACHINE_I386 );
212     SET( FileHeader.TimeDateStamp, 0 );
213     SET( FileHeader.Characteristics, IMAGE_FILE_DLL );
214     SET( OptionalHeader.MajorLinkerVersion, 1 );
215     SET( OptionalHeader.MinorLinkerVersion, 0 );
216     SET( OptionalHeader.MajorOperatingSystemVersion, 1 );
217     SET( OptionalHeader.MinorOperatingSystemVersion, 0 );
218     SET( OptionalHeader.MajorImageVersion, 1 );
219     SET( OptionalHeader.MinorImageVersion, 0 );
220     SET( OptionalHeader.MajorSubsystemVersion, 4 );
221     SET( OptionalHeader.MinorSubsystemVersion, 0 );
222     SET( OptionalHeader.Win32VersionValue, 0 );
223     SET( OptionalHeader.Subsystem, IMAGE_SUBSYSTEM_WINDOWS_GUI );
224     SET( OptionalHeader.DllCharacteristics, 0 );
225     SET( OptionalHeader.SizeOfStackReserve, 0 );
226     SET( OptionalHeader.SizeOfStackCommit, 0 );
227     SET( OptionalHeader.SizeOfHeapReserve, 0 );
228     SET( OptionalHeader.SizeOfHeapCommit, 0 );
229 #undef SET
230     /* other fields have fixed values */
231     nt->Signature                              = IMAGE_NT_SIGNATURE;
232     nt->FileHeader.NumberOfSections            = 0;
233     nt->FileHeader.SizeOfOptionalHeader        = IMAGE_SIZEOF_NT_OPTIONAL_HEADER;
234     nt->OptionalHeader.Magic                   = IMAGE_NT_OPTIONAL_HDR_MAGIC;
235     nt->OptionalHeader.ImageBase               = 0x10000000;
236     nt->OptionalHeader.SectionAlignment        = section_alignment;
237     nt->OptionalHeader.FileAlignment           = file_alignment;
238     nt->OptionalHeader.NumberOfRvaAndSizes     = IMAGE_NUMBEROF_DIRECTORY_ENTRIES;
239
240     header_size = (BYTE *)(nt + 1) - buffer;
241     info.mem_pos  = ALIGN( header_size, section_alignment );
242     info.file_pos = ALIGN( header_size, file_alignment );
243
244     nt->OptionalHeader.AddressOfEntryPoint = info.mem_pos;
245     nt->OptionalHeader.BaseOfCode          = info.mem_pos;
246
247     if (nt->FileHeader.Characteristics & IMAGE_FILE_DLL)
248     {
249         size = sizeof(dll_code_section);
250         if (!xwrite( &info, dll_code_section, size, info.file_pos )) goto done;
251     }
252     else
253     {
254         size = sizeof(exe_code_section);
255         if (!xwrite( &info, exe_code_section, size, info.file_pos )) goto done;
256     }
257     nt->OptionalHeader.SizeOfCode = size;
258     add_section( &info, ".text", size, IMAGE_SCN_CNT_CODE | IMAGE_SCN_MEM_EXECUTE | IMAGE_SCN_MEM_READ );
259
260     if (!xwrite( &info, &reloc_section, sizeof(reloc_section), info.file_pos )) goto done;
261     add_directory( &info, IMAGE_DIRECTORY_ENTRY_BASERELOC, info.mem_pos, sizeof(reloc_section) );
262     add_section( &info, ".reloc", sizeof(reloc_section),
263                  IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_DISCARDABLE | IMAGE_SCN_MEM_READ );
264
265     if (!add_version_resource( module, &info )) goto done;
266
267     header_size += nt->FileHeader.NumberOfSections * sizeof(IMAGE_SECTION_HEADER);
268     nt->OptionalHeader.SizeOfHeaders = ALIGN( header_size, file_alignment );
269     nt->OptionalHeader.SizeOfImage   = ALIGN( info.mem_pos, section_alignment );
270     ret = xwrite( &info, buffer, header_size, 0 );
271 done:
272     HeapFree( GetProcessHeap(), 0, buffer );
273     return ret;
274 }
275
276 /* check if an existing file is a fake dll so that we can overwrite it */
277 static BOOL is_fake_dll( HANDLE h )
278 {
279     IMAGE_DOS_HEADER *dos;
280     DWORD size;
281     BYTE buffer[sizeof(*dos) + sizeof(fakedll_signature)];
282
283     if (!ReadFile( h, buffer, sizeof(buffer), &size, NULL ) || size != sizeof(buffer))
284         return FALSE;
285     dos = (IMAGE_DOS_HEADER *)buffer;
286     if (dos->e_magic != IMAGE_DOS_SIGNATURE) return FALSE;
287     if (dos->e_lfanew < size) return FALSE;
288     return !memcmp( dos + 1, fakedll_signature, sizeof(fakedll_signature) );
289 }
290
291 /***********************************************************************
292  *            create_fake_dll
293  */
294 BOOL create_fake_dll( const WCHAR *name, const WCHAR *source )
295 {
296     HANDLE h;
297     HMODULE module;
298     BOOL ret;
299
300     /* first check for an existing file */
301     h = CreateFileW( name, GENERIC_READ|GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL );
302     if (h != INVALID_HANDLE_VALUE)
303     {
304         if (!is_fake_dll( h ))
305         {
306             TRACE( "%s is not a fake dll, not overwriting it\n", debugstr_w(name) );
307             CloseHandle( h );
308             return TRUE;
309         }
310         /* truncate the file */
311         SetFilePointer( h, 0, NULL, FILE_BEGIN );
312         SetEndOfFile( h );
313     }
314     else
315     {
316         h = CreateFileW( name, GENERIC_WRITE, 0, NULL, CREATE_NEW, 0, NULL );
317         if (h == INVALID_HANDLE_VALUE)
318         {
319             WARN( "failed to create %s\n", debugstr_w(name) );
320             return FALSE;
321         }
322     }
323
324     module = LoadLibraryW( source );
325
326     ret = build_fake_dll( h, module );
327
328     CloseHandle( h );
329     if (module) FreeLibrary( module );
330     if (!ret) DeleteFileW( name );
331     return ret;
332 }