Added a first-cut version of MapVirtualKeyExW() that has the same
[wine] / loader / elf.c
1 /* 
2  *      UNIX dynamic loader
3  * 
4  * Currently only supports stuff using the dl* API.
5  *
6  * Copyright 1998 Marcus Meissner
7  *
8  * FIXME:       Small reentrancy problem.
9  * IDEA(s):     could be used to split up shell32,comctl32... 
10  */
11
12 #include "config.h"
13
14 #include <assert.h>
15 #include <stdio.h>
16 #include <string.h>
17 #include <sys/types.h>
18
19 #include "snoop.h"
20 #include "process.h"
21 #include "heap.h"
22 #include "file.h"
23 #include "module.h"
24 #include "debugtools.h"
25 #include "winerror.h"
26 #include "elfdll.h"
27
28 DEFAULT_DEBUG_CHANNEL(win32);
29
30 #ifdef HAVE_DL_API
31
32 typedef struct {
33         WORD    popl    WINE_PACKED;    /* 0x8f 0x05 */
34         DWORD   addr_popped WINE_PACKED;/* ...  */
35         BYTE    pushl1  WINE_PACKED;    /* 0x68 */
36         DWORD   newret WINE_PACKED;     /* ...  */
37         BYTE    pushl2  WINE_PACKED;    /* 0x68 */
38         DWORD   origfun WINE_PACKED;    /* original function */
39         BYTE    ret1    WINE_PACKED;    /* 0xc3 */
40         WORD    addesp  WINE_PACKED;    /* 0x83 0xc4 */
41         BYTE    nrofargs WINE_PACKED;   /* nr of arguments to add esp, */
42         BYTE    pushl3  WINE_PACKED;    /* 0x68 */
43         DWORD   oldret  WINE_PACKED;    /* Filled out from popl above  */
44         BYTE    ret2    WINE_PACKED;    /* 0xc3 */
45 } ELF_STDCALL_STUB;
46
47 #define UNIX_DLL_ENDING         "so"
48
49 #define STUBSIZE                4095
50 #define STUBOFFSET  (sizeof(IMAGE_DOS_HEADER) + \
51                      sizeof(IMAGE_NT_HEADERS) + \
52                      sizeof(IMAGE_SECTION_HEADER))
53
54 #include <dlfcn.h>
55
56 static FARPROC ELF_FindExportedFunction( WINE_MODREF *wm, LPCSTR funcName, BOOL snoop );
57
58 static HMODULE ELF_CreateDummyModule( LPCSTR libname, LPCSTR modname )
59 {
60         PIMAGE_DOS_HEADER       dh;
61         PIMAGE_NT_HEADERS       nth;
62         PIMAGE_SECTION_HEADER   sh;
63         HMODULE hmod;
64
65         hmod = (HMODULE)HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, 
66                                      sizeof(IMAGE_DOS_HEADER) + 
67                                      sizeof(IMAGE_NT_HEADERS) +
68                                      sizeof(IMAGE_SECTION_HEADER) + STUBSIZE );
69         dh = (PIMAGE_DOS_HEADER)hmod;
70         dh->e_magic = IMAGE_DOS_SIGNATURE;
71         dh->e_lfanew = sizeof(IMAGE_DOS_HEADER);
72         nth = PE_HEADER(hmod);
73         nth->Signature = IMAGE_NT_SIGNATURE; 
74         nth->FileHeader.Machine = IMAGE_FILE_MACHINE_I386;
75         nth->FileHeader.NumberOfSections = 1;
76         nth->FileHeader.SizeOfOptionalHeader = sizeof(IMAGE_OPTIONAL_HEADER);
77         nth->FileHeader.Characteristics = 
78                 IMAGE_FILE_RELOCS_STRIPPED|IMAGE_FILE_LINE_NUMS_STRIPPED|
79                 IMAGE_FILE_LOCAL_SYMS_STRIPPED|IMAGE_FILE_32BIT_MACHINE|
80                 IMAGE_FILE_DLL|IMAGE_FILE_DEBUG_STRIPPED;
81         nth->OptionalHeader.Magic = IMAGE_NT_OPTIONAL_HDR_MAGIC;
82         nth->OptionalHeader.SizeOfCode = 0;
83         nth->OptionalHeader.SizeOfInitializedData = 0;
84         nth->OptionalHeader.SizeOfUninitializedData = 0;
85         nth->OptionalHeader.AddressOfEntryPoint = 0;
86         nth->OptionalHeader.BaseOfCode          = 0;
87         nth->OptionalHeader.MajorOperatingSystemVersion = 4;
88         nth->OptionalHeader.MajorImageVersion   = 4;
89         nth->OptionalHeader.SizeOfImage         = 0;
90         nth->OptionalHeader.SizeOfHeaders       = 0;
91         nth->OptionalHeader.Subsystem           = IMAGE_SUBSYSTEM_NATIVE;
92         nth->OptionalHeader.DllCharacteristics  = 0;
93         nth->OptionalHeader.NumberOfRvaAndSizes = 0;
94
95         /* allocate one code section that crosses the whole process range
96          * (we could find out from internal tables ... hmm )
97          */
98         sh=(PIMAGE_SECTION_HEADER)(nth+1);
99         strcpy(sh->Name,".text");
100         sh->Misc.VirtualSize    = STUBSIZE;
101         sh->VirtualAddress      = STUBOFFSET; /* so snoop can use it ... */
102         sh->SizeOfRawData       = STUBSIZE;
103         sh->PointerToRawData    = 0;
104         sh->Characteristics     = IMAGE_SCN_CNT_CODE|IMAGE_SCN_CNT_INITIALIZED_DATA|IMAGE_SCN_MEM_EXECUTE|IMAGE_SCN_MEM_READ;
105         return hmod;
106 }
107
108 WINE_MODREF *ELF_LoadLibraryExA( LPCSTR libname, DWORD flags)
109 {
110         WINE_MODREF     *wm;
111         HMODULE         hmod;
112         char            *modname,*s,*t,*x;
113         LPVOID          *dlhandle;
114
115         t = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY,
116                        strlen(libname) + strlen("lib.so") + 1 );
117         *t = '\0';
118         /* copy path to tempvar ... */
119         s=strrchr(libname,'/');
120         if (!s)
121                 s=strrchr(libname,'\\');
122         if (s) {
123                 s++; /* skip / or \ */
124                 /* copy everything up to s-1 */
125                 memcpy(t,libname,s-libname);
126                 t[s-libname]= '\0';
127         } else
128                 s = (LPSTR)libname;
129         modname = s;
130         /* append "lib" foo ".so" */
131         strcat(t,"lib");
132         x = t+strlen(t);
133         strcat(t,s);
134         s = strchr(x,'.');
135         if (s) {
136             while (s) {
137                 if (!FILE_strcasecmp(s,".dll")) {
138                     strcpy(s+1,UNIX_DLL_ENDING);
139                     break;
140                 }
141                 s=strchr(s+1,'.');
142             }
143         } else {
144                 strcat(x,"."UNIX_DLL_ENDING);
145         }
146
147         /* grab just the last piece of the path/filename
148            which should be the name of the library we are
149            looking to load. increment by 1 to skip the DOS slash */
150         s = strrchr(t,'\\');
151         s++;
152
153        /* ... and open the library pointed by s, while t points
154          points to the ENTIRE DOS filename of the library
155          t is returned by HeapAlloc() above and so is also used
156          with HeapFree() below */
157         dlhandle = ELFDLL_dlopen(s,RTLD_NOW);
158         if (!dlhandle) {
159                 HeapFree( GetProcessHeap(), 0, t );
160                 SetLastError( ERROR_FILE_NOT_FOUND );
161                 return NULL;
162         }
163
164         hmod = ELF_CreateDummyModule( t, modname );
165
166         SNOOP_RegisterDLL(hmod,libname,STUBSIZE/sizeof(ELF_STDCALL_STUB));
167
168         wm = PE_CreateModule( hmod, libname, 0, -1, FALSE );
169         wm->find_export = ELF_FindExportedFunction;
170         wm->dlhandle = dlhandle;
171         return wm;
172 }
173
174 static FARPROC ELF_FindExportedFunction( WINE_MODREF *wm, LPCSTR funcName, BOOL snoop )
175 {
176         LPVOID                  fun;
177         int                     i,nrofargs = 0;
178         ELF_STDCALL_STUB        *stub, *first_stub;
179
180         if (!HIWORD(funcName)) {
181                 ERR("Can't import from UNIX dynamic libs by ordinal, sorry.\n");
182                 return (FARPROC)0;
183         }
184         fun = dlsym(wm->dlhandle,funcName);
185         /* we sometimes have an excess '_' at the beginning of the name */
186         if (!fun && (funcName[0]=='_')) {
187                 funcName++ ;
188                 fun = dlsym(wm->dlhandle,funcName);
189         }
190         if (!fun) {
191                 /* Function@nrofargs usually marks a stdcall function 
192                  * with nrofargs bytes that are popped at the end
193                  */
194                 if (strchr(funcName,'@')) {
195                         LPSTR   t,fn = HEAP_strdupA( GetProcessHeap(), 0, funcName );
196
197                         t = strchr(fn,'@');
198                         *t = '\0';
199                         nrofargs = 0;
200                         sscanf(t+1,"%d",&nrofargs);
201                         fun = dlsym(wm->dlhandle,fn);
202                         HeapFree( GetProcessHeap(), 0, fn );
203                 }
204         }
205         /* We sometimes have Win32 dlls implemented using stdcall but UNIX 
206          * dlls using cdecl. If we find out the number of args the function
207          * uses, we remove them from the stack using two small stubs.
208          */
209         stub = first_stub = (ELF_STDCALL_STUB *)((char *)wm->module + STUBOFFSET);
210         for (i=0;i<STUBSIZE/sizeof(ELF_STDCALL_STUB);i++) {
211                 if (!stub->origfun)
212                         break;
213                 if (stub->origfun == (DWORD)fun)
214                         break;
215                 stub++;
216         }
217         if (i==STUBSIZE/sizeof(ELF_STDCALL_STUB)) {
218                 ERR("please report, that there are not enough slots for stdcall stubs in the ELF loader.\n");
219                 assert(i<STUBSIZE/sizeof(ELF_STDCALL_STUB));
220         }
221         if (!stub->origfun)
222                 stub->origfun=(DWORD)fun; /* just a marker */
223
224         if (fun && nrofargs) { /* we don't need it for 0 args */
225                 /* Selfmodifying entry/return stub for stdcall -> cdecl 
226                  * conversion.
227                  *  - Pop returnaddress directly into our return code
228                  *              popl <into code below>
229                  *  - Replace it by pointer to start of our returncode
230                  *              push $newret
231                  *  - And call the original function
232                  *              jmp $orgfun
233                  *  - Remove the arguments no longer needed
234                  * newret:      add esp, <nrofargs>
235                  *  - Push the original returnvalue on the stack
236                  *              pushl <poppedvalue>
237                  *  - And return to it.
238                  *              ret
239                  */
240
241                 /* FIXME: The function stub is not reentrant. */
242
243                 ((LPBYTE)&(stub->popl))[0]        = 0x8f;
244                 ((LPBYTE)&(stub->popl))[1]        = 0x05;
245                 stub->addr_popped = (DWORD)&(stub->oldret);
246                 stub->pushl1      = 0x68;
247                 stub->newret      = (DWORD)&(stub->addesp);
248                 stub->pushl2      = 0x68;
249                 stub->origfun     = (DWORD)fun;
250                 stub->ret1        = 0xc3;
251                 ((LPBYTE)&(stub->addesp))[0]=0x83;
252                 ((LPBYTE)&(stub->addesp))[1]=0xc4;
253                 stub->nrofargs    = nrofargs;
254                 stub->pushl3      = 0x68;
255                         /* filled out by entrycode */
256                 stub->oldret      = 0xdeadbeef;
257                 stub->ret2        = 0xc3;
258                 fun=(FARPROC)stub;
259         }
260         if (!fun) {
261                 FIXME("function %s not found: %s\n",funcName,dlerror());
262                 return fun;
263         }
264         fun = SNOOP_GetProcAddress(wm->module,funcName,stub-first_stub,fun);
265         return (FARPROC)fun;
266 }
267
268 #else  /* HAVE_DL_API */
269
270 WINE_MODREF *ELF_LoadLibraryExA( LPCSTR libname, DWORD flags)
271 {
272         return NULL;
273 }
274
275 #endif  /* HAVE_DL_API */