Add some Str* prototypes to shlwapi.h.
[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 "neexe.h"
22 #include "heap.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 (!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         /* FIXME: make UNIX filename from DOS fn? */
148
149         /* ... and open it */
150         dlhandle = ELFDLL_dlopen(t,RTLD_NOW);
151         if (!dlhandle) {
152                 HeapFree( GetProcessHeap(), 0, t );
153                 SetLastError( ERROR_FILE_NOT_FOUND );
154                 return NULL;
155         }
156
157         hmod = ELF_CreateDummyModule( t, modname );
158
159         SNOOP_RegisterDLL(hmod,libname,STUBSIZE/sizeof(ELF_STDCALL_STUB));
160
161         wm = PE_CreateModule( hmod, libname, 0, -1, FALSE );
162         wm->find_export = ELF_FindExportedFunction;
163         wm->dlhandle = dlhandle;
164         return wm;
165 }
166
167 static FARPROC ELF_FindExportedFunction( WINE_MODREF *wm, LPCSTR funcName, BOOL snoop )
168 {
169         LPVOID                  fun;
170         int                     i,nrofargs = 0;
171         ELF_STDCALL_STUB        *stub, *first_stub;
172
173         if (!HIWORD(funcName)) {
174                 ERR("Can't import from UNIX dynamic libs by ordinal, sorry.\n");
175                 return (FARPROC)0;
176         }
177         fun = dlsym(wm->dlhandle,funcName);
178         /* we sometimes have an excess '_' at the beginning of the name */
179         if (!fun && (funcName[0]=='_')) {
180                 funcName++ ;
181                 fun = dlsym(wm->dlhandle,funcName);
182         }
183         if (!fun) {
184                 /* Function@nrofargs usually marks a stdcall function 
185                  * with nrofargs bytes that are popped at the end
186                  */
187                 if (strchr(funcName,'@')) {
188                         LPSTR   t,fn = HEAP_strdupA( GetProcessHeap(), 0, funcName );
189
190                         t = strchr(fn,'@');
191                         *t = '\0';
192                         nrofargs = 0;
193                         sscanf(t+1,"%d",&nrofargs);
194                         fun = dlsym(wm->dlhandle,fn);
195                         HeapFree( GetProcessHeap(), 0, fn );
196                 }
197         }
198         /* We sometimes have Win32 dlls implemented using stdcall but UNIX 
199          * dlls using cdecl. If we find out the number of args the function
200          * uses, we remove them from the stack using two small stubs.
201          */
202         stub = first_stub = (ELF_STDCALL_STUB *)((char *)wm->module + STUBOFFSET);
203         for (i=0;i<STUBSIZE/sizeof(ELF_STDCALL_STUB);i++) {
204                 if (!stub->origfun)
205                         break;
206                 if (stub->origfun == (DWORD)fun)
207                         break;
208                 stub++;
209         }
210         if (i==STUBSIZE/sizeof(ELF_STDCALL_STUB)) {
211                 ERR("please report, that there are not enough slots for stdcall stubs in the ELF loader.\n");
212                 assert(i<STUBSIZE/sizeof(ELF_STDCALL_STUB));
213         }
214         if (!stub->origfun)
215                 stub->origfun=(DWORD)fun; /* just a marker */
216
217         if (fun && nrofargs) { /* we don't need it for 0 args */
218                 /* Selfmodifying entry/return stub for stdcall -> cdecl 
219                  * conversion.
220                  *  - Pop returnaddress directly into our return code
221                  *              popl <into code below>
222                  *  - Replace it by pointer to start of our returncode
223                  *              push $newret
224                  *  - And call the original function
225                  *              jmp $orgfun
226                  *  - Remove the arguments no longer needed
227                  * newret:      add esp, <nrofargs>
228                  *  - Push the original returnvalue on the stack
229                  *              pushl <poppedvalue>
230                  *  - And return to it.
231                  *              ret
232                  */
233
234                 /* FIXME: The function stub is not reentrant. */
235
236                 ((LPBYTE)&(stub->popl))[0]        = 0x8f;
237                 ((LPBYTE)&(stub->popl))[1]        = 0x05;
238                 stub->addr_popped = (DWORD)&(stub->oldret);
239                 stub->pushl1      = 0x68;
240                 stub->newret      = (DWORD)&(stub->addesp);
241                 stub->pushl2      = 0x68;
242                 stub->origfun     = (DWORD)fun;
243                 stub->ret1        = 0xc3;
244                 ((LPBYTE)&(stub->addesp))[0]=0x83;
245                 ((LPBYTE)&(stub->addesp))[1]=0xc4;
246                 stub->nrofargs    = nrofargs;
247                 stub->pushl3      = 0x68;
248                         /* filled out by entrycode */
249                 stub->oldret      = 0xdeadbeef;
250                 stub->ret2        = 0xc3;
251                 fun=(FARPROC)stub;
252         }
253         if (!fun) {
254                 FIXME("function %s not found: %s\n",funcName,dlerror());
255                 return fun;
256         }
257         fun = SNOOP_GetProcAddress(wm->module,funcName,stub-first_stub,fun);
258         return (FARPROC)fun;
259 }
260
261 #else  /* HAVE_DL_API */
262
263 WINE_MODREF *ELF_LoadLibraryExA( LPCSTR libname, DWORD flags)
264 {
265         return NULL;
266 }
267
268 #endif  /* HAVE_DL_API */