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