Removed some unnecessary inclusions of wingdi.h and winuser.h
[wine] / relay32 / builtin32.c
1 /*
2  * Win32 builtin functions
3  *
4  * Copyright 1997 Alexandre Julliard
5  */
6
7 #include "config.h"
8
9 #include <assert.h>
10 #include <string.h>
11 #include <stdio.h>
12 #include <ctype.h>
13 #ifdef HAVE_DL_API
14 #include <dlfcn.h>
15 #endif
16 #include <sys/types.h>
17 #ifdef HAVE_SYS_MMAN_H
18 #include <sys/mman.h>
19 #endif
20
21 #include "windef.h"
22 #include "wine/winbase16.h"
23 #include "builtin32.h"
24 #include "elfdll.h"
25 #include "file.h"
26 #include "global.h"
27 #include "neexe.h"
28 #include "heap.h"
29 #include "main.h"
30 #include "snoop.h"
31 #include "winerror.h"
32 #include "server.h"
33 #include "debugtools.h"
34
35 DEFAULT_DEBUG_CHANNEL(module);
36 DECLARE_DEBUG_CHANNEL(relay);
37
38 typedef struct
39 {
40     BYTE                        *restab;
41     DWORD                       nresources;
42     DWORD                       restabsize;
43     IMAGE_RESOURCE_DATA_ENTRY   *entries;
44 } BUILTIN32_RESOURCE;
45
46 #define MAX_DLLS 60
47
48 static const BUILTIN32_DESCRIPTOR *builtin_dlls[MAX_DLLS];
49 static HMODULE dll_modules[MAX_DLLS];
50 static int nb_dlls;
51
52
53 /***********************************************************************
54  *           BUILTIN32_WarnSecondInstance
55  *
56  * Emit a warning when we are creating a second instance for a DLL
57  * that is known to not support this.
58  */
59 static void BUILTIN32_WarnSecondInstance( const char *name )
60 {
61     static const char * const warning_list[] =
62     { "comctl32.dll", "comdlg32.dll", "crtdll.dll",
63       "imagehlp.dll", "msacm32.dll", "shell32.dll", NULL };
64
65     const char * const *ptr = warning_list;
66
67     while (*ptr)
68     {
69         if (!strcasecmp( *ptr, name ))
70         {
71             ERR( "Attempt to instantiate built-in dll '%s' twice "
72                  "in the same address space. Expect trouble!\n", name );
73             return;
74         }
75         ptr++;
76     }
77 }
78
79 /***********************************************************************
80  *           BUILTIN32_dlopen
81  */
82 void *BUILTIN32_dlopen( const char *name )
83 {
84 #ifdef HAVE_DL_API
85     void *handle;
86     char buffer[128], *p;
87     if ((p = strrchr( name, '/' ))) name = p + 1;
88     if ((p = strrchr( name, '\\' ))) name = p + 1;
89     sprintf( buffer, "lib%s", name );
90     for (p = buffer; *p; p++) *p = tolower(*p);
91     if ((p = strrchr( buffer, '.' )) && (!strcmp( p, ".dll" ) || !strcmp( p, ".exe" ))) *p = 0;
92     strcat( buffer, ".so" );
93
94     if (!(handle = ELFDLL_dlopen( buffer, RTLD_NOW )))
95         WARN( "failed to load %s: %s\n", buffer, dlerror() );
96     return handle;
97 #else
98     return NULL;
99 #endif
100 }
101
102 /***********************************************************************
103  *           BUILTIN32_dlclose
104  */
105 int BUILTIN32_dlclose( void *handle )
106 {
107 #ifdef HAVE_DL_API
108     /* FIXME: should unregister descriptors first */
109     /* return dlclose( handle ); */
110 #endif
111     return 0;
112 }
113
114
115 /***********************************************************************
116  *           fixup_rva_ptrs
117  *
118  * Adjust an array of pointers to make them into RVAs.
119  */
120 static inline void fixup_rva_ptrs( void *array, void *base, int count )
121 {
122     void **ptr = (void **)array;
123     while (count--)
124     {
125         if (*ptr) *ptr = (void *)((char *)*ptr - (char *)base);
126         ptr++;
127     }
128 }
129
130
131 /***********************************************************************
132  *           BUILTIN32_DoLoadImage
133  *
134  * Load a built-in Win32 module. Helper function for BUILTIN32_LoadImage.
135  */
136 static HMODULE BUILTIN32_DoLoadImage( const BUILTIN32_DESCRIPTOR *descr )
137 {
138     IMAGE_DATA_DIRECTORY *dir;
139     IMAGE_DOS_HEADER *dos;
140     IMAGE_NT_HEADERS *nt;
141     IMAGE_SECTION_HEADER *sec;
142     IMAGE_IMPORT_DESCRIPTOR *imp;
143     IMAGE_EXPORT_DIRECTORY *exports = descr->exports;
144     INT i, size, nb_sections;
145     BYTE *addr, *code_start, *data_start;
146     int page_size = VIRTUAL_GetPageSize();
147
148     /* Allocate the module */
149
150     nb_sections = 2;  /* code + data */
151
152     size = (sizeof(IMAGE_DOS_HEADER)
153             + sizeof(IMAGE_NT_HEADERS)
154             + nb_sections * sizeof(IMAGE_SECTION_HEADER)
155             + (descr->nb_imports+1) * sizeof(IMAGE_IMPORT_DESCRIPTOR));
156
157     assert( size <= page_size );
158
159     if (descr->pe_header)
160     {
161         if ((addr = FILE_dommap( -1, descr->pe_header, 0, page_size, 0, 0,
162                                  PROT_READ|PROT_WRITE, MAP_FIXED )) != descr->pe_header)
163         {
164             ERR("failed to map over PE header for %s at %p\n", descr->filename, descr->pe_header );
165             return 0;
166         }
167     }
168     else
169     {
170         if (!(addr = VirtualAlloc( NULL, page_size, MEM_COMMIT, PAGE_READWRITE ))) return 0;
171     }
172
173     dos    = (IMAGE_DOS_HEADER *)addr;
174     nt     = (IMAGE_NT_HEADERS *)(dos + 1);
175     sec    = (IMAGE_SECTION_HEADER *)(nt + 1);
176     imp    = (IMAGE_IMPORT_DESCRIPTOR *)(sec + nb_sections);
177     code_start = addr + page_size;
178
179     /* HACK! */
180     data_start = code_start + page_size;
181
182     /* Build the DOS and NT headers */
183
184     dos->e_magic  = IMAGE_DOS_SIGNATURE;
185     dos->e_lfanew = sizeof(*dos);
186
187     nt->Signature                       = IMAGE_NT_SIGNATURE;
188     nt->FileHeader.Machine              = IMAGE_FILE_MACHINE_I386;
189     nt->FileHeader.NumberOfSections     = nb_sections;
190     nt->FileHeader.SizeOfOptionalHeader = sizeof(nt->OptionalHeader);
191     nt->FileHeader.Characteristics      = descr->characteristics;
192
193     nt->OptionalHeader.Magic = IMAGE_NT_OPTIONAL_HDR_MAGIC;
194     nt->OptionalHeader.SizeOfCode                  = data_start - code_start;
195     nt->OptionalHeader.SizeOfInitializedData       = 0;
196     nt->OptionalHeader.SizeOfUninitializedData     = 0;
197     nt->OptionalHeader.ImageBase                   = (DWORD)addr;
198     nt->OptionalHeader.SectionAlignment            = page_size;
199     nt->OptionalHeader.FileAlignment               = page_size;
200     nt->OptionalHeader.MajorOperatingSystemVersion = 1;
201     nt->OptionalHeader.MinorOperatingSystemVersion = 0;
202     nt->OptionalHeader.MajorSubsystemVersion       = 4;
203     nt->OptionalHeader.MinorSubsystemVersion       = 0;
204     nt->OptionalHeader.SizeOfImage                 = page_size;
205     nt->OptionalHeader.SizeOfHeaders               = page_size;
206     nt->OptionalHeader.NumberOfRvaAndSizes = IMAGE_NUMBEROF_DIRECTORY_ENTRIES;
207     if (descr->dllentrypoint) 
208         nt->OptionalHeader.AddressOfEntryPoint = (DWORD)descr->dllentrypoint - (DWORD)addr;
209     
210     /* Build the code section */
211
212     strcpy( sec->Name, ".text" );
213     sec->SizeOfRawData = data_start - code_start;
214     sec->Misc.VirtualSize = sec->SizeOfRawData;
215     sec->VirtualAddress   = code_start - addr;
216     sec->PointerToRawData = code_start - addr;
217     sec->Characteristics  = (IMAGE_SCN_CNT_CODE | IMAGE_SCN_MEM_EXECUTE | IMAGE_SCN_MEM_READ);
218     sec++;
219
220     /* Build the data section */
221
222     strcpy( sec->Name, ".data" );
223     sec->SizeOfRawData = 0;
224     sec->Misc.VirtualSize = sec->SizeOfRawData;
225     sec->VirtualAddress   = data_start - addr;
226     sec->PointerToRawData = data_start - addr;
227     sec->Characteristics  = (IMAGE_SCN_CNT_INITIALIZED_DATA |
228                              IMAGE_SCN_MEM_WRITE | IMAGE_SCN_MEM_READ);
229     sec++;
230
231     /* Build the import directory */
232
233     if (descr->nb_imports)
234     {
235         dir = &nt->OptionalHeader.DataDirectory[IMAGE_FILE_IMPORT_DIRECTORY];
236         dir->VirtualAddress = (BYTE *)imp - addr;
237         dir->Size = sizeof(*imp) * (descr->nb_imports + 1);
238
239         /* Build the imports */
240         for (i = 0; i < descr->nb_imports; i++)
241         {
242             imp[i].u.Characteristics = 0;
243             imp[i].ForwarderChain = -1;
244             imp[i].Name = (BYTE *)descr->imports[i] - addr;
245             /* hack: make first thunk point to some zero value */
246             imp[i].FirstThunk = (PIMAGE_THUNK_DATA)((BYTE *)&imp[i].u.Characteristics - addr);
247         }
248     }
249
250     /* Build the resource directory */
251
252     if (descr->rsrc)
253     {
254         BUILTIN32_RESOURCE *rsrc = descr->rsrc;
255         IMAGE_RESOURCE_DATA_ENTRY *rdep;
256         dir = &nt->OptionalHeader.DataDirectory[IMAGE_FILE_RESOURCE_DIRECTORY];
257         dir->VirtualAddress = (BYTE *)rsrc->restab - addr;
258         dir->Size = rsrc->restabsize;
259         rdep = rsrc->entries;
260         for (i = 0; i < rsrc->nresources; i++) rdep[i].OffsetToData += dir->VirtualAddress;
261     }
262
263     /* Build the export directory */
264
265     if (exports)
266     {
267         dir = &nt->OptionalHeader.DataDirectory[IMAGE_FILE_EXPORT_DIRECTORY];
268         dir->VirtualAddress = (BYTE *)exports - addr;
269         dir->Size = descr->exports_size;
270
271         fixup_rva_ptrs( (void *)exports->AddressOfFunctions, addr, exports->NumberOfFunctions );
272         fixup_rva_ptrs( (void *)exports->AddressOfNames, addr, exports->NumberOfNames );
273         fixup_rva_ptrs( &exports->Name, addr, 1 );
274         fixup_rva_ptrs( &exports->AddressOfFunctions, addr, 1 );
275         fixup_rva_ptrs( &exports->AddressOfNames, addr, 1 );
276         fixup_rva_ptrs( &exports->AddressOfNameOrdinals, addr, 1 );
277
278         /* Setup relay debugging entry points */
279         if (WARN_ON(relay) || TRACE_ON(relay)) RELAY_SetupDLL( addr );
280     }
281
282     return (HMODULE)addr;
283 }
284
285 /***********************************************************************
286  *           BUILTIN32_LoadLibraryExA
287  *
288  * Partly copied from the original PE_ version.
289  *
290  */
291 WINE_MODREF *BUILTIN32_LoadLibraryExA(LPCSTR path, DWORD flags)
292 {
293     struct load_dll_request *req = get_req_buffer();
294     HMODULE16      hModule16;
295     NE_MODULE     *pModule;
296     WINE_MODREF   *wm;
297     char           dllname[MAX_PATH], *p;
298     void *handle;
299     int i;
300
301     /* Fix the name in case we have a full path and extension */
302     if ((p = strrchr( path, '\\' ))) path = p + 1;
303     lstrcpynA( dllname, path, sizeof(dllname) );
304
305     p = strrchr( dllname, '.' );
306     if (!p) strcat( dllname, ".dll" );
307
308     /* Search built-in descriptor */
309     for (i = 0; i < nb_dlls; i++)
310         if (!strcasecmp( builtin_dlls[i]->filename, dllname )) goto found;
311
312     if ((handle = BUILTIN32_dlopen( dllname )))
313     {
314         for (i = 0; i < nb_dlls; i++)
315             if (!strcasecmp( builtin_dlls[i]->filename, dllname )) goto found;
316         ERR( "loaded .so but dll %s still not found\n", dllname );
317         BUILTIN32_dlclose( handle );
318     }
319
320     SetLastError( ERROR_FILE_NOT_FOUND );
321     return NULL;
322
323  found:
324     /* Load built-in module */
325     if (!dll_modules[i])
326     {
327         if (!(dll_modules[i] = BUILTIN32_DoLoadImage( builtin_dlls[i] ))) return NULL;
328     }
329     else BUILTIN32_WarnSecondInstance( builtin_dlls[i]->filename );
330
331     /* Create 16-bit dummy module */
332     if ((hModule16 = MODULE_CreateDummyModule( dllname, dll_modules[i] )) < 32)
333     {
334         SetLastError( (DWORD)hModule16 );
335         return NULL;    /* FIXME: Should unload the builtin module */
336     }
337     pModule = (NE_MODULE *)GlobalLock16( hModule16 );
338     pModule->flags = NE_FFLAGS_LIBMODULE | NE_FFLAGS_SINGLEDATA | NE_FFLAGS_WIN32 | NE_FFLAGS_BUILTIN;
339
340     /* Create 32-bit MODREF */
341     if ( !(wm = PE_CreateModule( pModule->module32, dllname, flags, TRUE )) )
342     {
343         ERR( "can't load %s\n", path );
344         FreeLibrary16( hModule16 );     /* FIXME: Should unload the builtin module */
345         SetLastError( ERROR_OUTOFMEMORY );
346         return NULL;
347     }
348
349     if (wm->binfmt.pe.pe_export)
350         SNOOP_RegisterDLL(wm->module,wm->modname,wm->binfmt.pe.pe_export->NumberOfFunctions);
351
352     req->handle     = -1;
353     req->base       = (void *)pModule->module32;
354     req->dbg_offset = 0;
355     req->dbg_size   = 0;
356     req->name       = &wm->modname;
357     server_call_noerr( REQ_LOAD_DLL );
358     return wm;
359 }
360
361 /***********************************************************************
362  *           BUILTIN32_LoadExeModule
363  */
364 HMODULE BUILTIN32_LoadExeModule(void)
365 {
366     int i, exe = -1;
367
368     /* Search built-in EXE descriptor */
369     for ( i = 0; i < nb_dlls; i++ )
370         if ( !(builtin_dlls[i]->characteristics & IMAGE_FILE_DLL) ) 
371         {
372             if ( exe != -1 )
373             {
374                 MESSAGE( "More than one built-in EXE module loaded!\n" );
375                 break;
376             }
377
378             exe = i;
379         }
380
381     if ( exe == -1 ) 
382     {
383         MESSAGE( "No built-in EXE module loaded!  Did you create a .spec file?\n" );
384         return 0;
385     }
386
387     /* Load built-in module */
388     if ( !dll_modules[exe] )
389         if ( !(dll_modules[exe] = BUILTIN32_DoLoadImage( builtin_dlls[exe] )) )
390             return 0;
391     return dll_modules[exe];
392 }
393
394
395 /***********************************************************************
396  *      BUILTIN32_UnloadLibrary
397  *
398  * Unload the built-in library and free the modref.
399  */
400 void BUILTIN32_UnloadLibrary(WINE_MODREF *wm)
401 {
402         /* FIXME: do something here */
403 }
404
405 /***********************************************************************
406  *           BUILTIN32_RegisterDLL
407  *
408  * Register a built-in DLL descriptor.
409  */
410 void BUILTIN32_RegisterDLL( const BUILTIN32_DESCRIPTOR *descr )
411 {
412     assert( nb_dlls < MAX_DLLS );
413     builtin_dlls[nb_dlls++] = descr;
414 }
415
416 /***********************************************************************
417  *           BUILTIN32_Unimplemented
418  *
419  * This function is called for unimplemented 32-bit entry points (declared
420  * as 'stub' in the spec file).
421  */
422 void BUILTIN32_Unimplemented( const char *dllname, const char *funcname )
423 {
424     __RESTORE_ES;  /* Just in case */
425
426     MESSAGE( "FATAL: No handler for Win32 routine %s.%s", dllname, funcname );
427 #ifdef __GNUC__
428     MESSAGE( " (called from %p)", __builtin_return_address(1) );
429 #endif
430     MESSAGE( "\n" );
431     ExitProcess(1);
432 }