atexit doesn't take a _onexit_t parameter.
[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 #include "wine/port.h" 
14
15 #include <assert.h>
16 #include <stdio.h>
17 #include <string.h>
18 #include <sys/types.h>
19
20 #include "snoop.h"
21 #include "file.h"
22 #include "module.h"
23 #include "debugtools.h"
24 #include "winerror.h"
25
26 DEFAULT_DEBUG_CHANNEL(win32);
27
28 typedef struct {
29         WORD    popl    WINE_PACKED;    /* 0x8f 0x05 */
30         DWORD   addr_popped WINE_PACKED;/* ...  */
31         BYTE    pushl1  WINE_PACKED;    /* 0x68 */
32         DWORD   newret WINE_PACKED;     /* ...  */
33         BYTE    pushl2  WINE_PACKED;    /* 0x68 */
34         DWORD   origfun WINE_PACKED;    /* original function */
35         BYTE    ret1    WINE_PACKED;    /* 0xc3 */
36         WORD    addesp  WINE_PACKED;    /* 0x83 0xc4 */
37         BYTE    nrofargs WINE_PACKED;   /* nr of arguments to add esp, */
38         BYTE    pushl3  WINE_PACKED;    /* 0x68 */
39         DWORD   oldret  WINE_PACKED;    /* Filled out from popl above  */
40         BYTE    ret2    WINE_PACKED;    /* 0xc3 */
41 } ELF_STDCALL_STUB;
42
43 #define UNIX_DLL_ENDING         "so"
44
45 #define STUBSIZE                4095
46 #define STUBOFFSET  (sizeof(IMAGE_DOS_HEADER) + \
47                      sizeof(IMAGE_NT_HEADERS) + \
48                      sizeof(IMAGE_SECTION_HEADER))
49
50 static FARPROC ELF_FindExportedFunction( WINE_MODREF *wm, LPCSTR funcName, BOOL snoop );
51
52 static HMODULE ELF_CreateDummyModule( LPCSTR libname, LPCSTR modname )
53 {
54         PIMAGE_DOS_HEADER       dh;
55         PIMAGE_NT_HEADERS       nth;
56         PIMAGE_SECTION_HEADER   sh;
57         HMODULE hmod;
58
59         hmod = (HMODULE)HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, 
60                                      sizeof(IMAGE_DOS_HEADER) + 
61                                      sizeof(IMAGE_NT_HEADERS) +
62                                      sizeof(IMAGE_SECTION_HEADER) + STUBSIZE );
63         dh = (PIMAGE_DOS_HEADER)hmod;
64         dh->e_magic = IMAGE_DOS_SIGNATURE;
65         dh->e_lfanew = sizeof(IMAGE_DOS_HEADER);
66         nth = PE_HEADER(hmod);
67         nth->Signature = IMAGE_NT_SIGNATURE; 
68         nth->FileHeader.Machine = IMAGE_FILE_MACHINE_I386;
69         nth->FileHeader.NumberOfSections = 1;
70         nth->FileHeader.SizeOfOptionalHeader = sizeof(IMAGE_OPTIONAL_HEADER);
71         nth->FileHeader.Characteristics = 
72                 IMAGE_FILE_RELOCS_STRIPPED|IMAGE_FILE_LINE_NUMS_STRIPPED|
73                 IMAGE_FILE_LOCAL_SYMS_STRIPPED|IMAGE_FILE_32BIT_MACHINE|
74                 IMAGE_FILE_DLL|IMAGE_FILE_DEBUG_STRIPPED;
75         nth->OptionalHeader.Magic = IMAGE_NT_OPTIONAL_HDR_MAGIC;
76         nth->OptionalHeader.SizeOfCode = 0;
77         nth->OptionalHeader.SizeOfInitializedData = 0;
78         nth->OptionalHeader.SizeOfUninitializedData = 0;
79         nth->OptionalHeader.AddressOfEntryPoint = 0;
80         nth->OptionalHeader.BaseOfCode          = 0;
81         nth->OptionalHeader.MajorOperatingSystemVersion = 4;
82         nth->OptionalHeader.MajorImageVersion   = 4;
83         nth->OptionalHeader.SizeOfImage         = 0;
84         nth->OptionalHeader.SizeOfHeaders       = 0;
85         nth->OptionalHeader.Subsystem           = IMAGE_SUBSYSTEM_NATIVE;
86         nth->OptionalHeader.DllCharacteristics  = 0;
87         nth->OptionalHeader.NumberOfRvaAndSizes = 0;
88
89         /* allocate one code section that crosses the whole process range
90          * (we could find out from internal tables ... hmm )
91          */
92         sh=(PIMAGE_SECTION_HEADER)(nth+1);
93         strcpy(sh->Name,".text");
94         sh->Misc.VirtualSize    = STUBSIZE;
95         sh->VirtualAddress      = STUBOFFSET; /* so snoop can use it ... */
96         sh->SizeOfRawData       = STUBSIZE;
97         sh->PointerToRawData    = 0;
98         sh->Characteristics     = IMAGE_SCN_CNT_CODE|IMAGE_SCN_CNT_INITIALIZED_DATA|IMAGE_SCN_MEM_EXECUTE|IMAGE_SCN_MEM_READ;
99         return hmod;
100 }
101
102 WINE_MODREF *ELF_LoadLibraryExA( LPCSTR libname, DWORD flags)
103 {
104         WINE_MODREF     *wm;
105         HMODULE         hmod;
106         char            *modname,*s,*t,*x;
107         LPVOID          *dlhandle;
108         char            error[256];
109
110         t = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY,
111                        strlen(libname) + strlen("lib.so") + 1 );
112         *t = '\0';
113         /* copy path to tempvar ... */
114         s=strrchr(libname,'/');
115         if (!s)
116                 s=strrchr(libname,'\\');
117         if (s) {
118                 s++; /* skip / or \ */
119                 /* copy everything up to s-1 */
120                 memcpy(t,libname,s-libname);
121                 t[s-libname]= '\0';
122         } else
123                 s = (LPSTR)libname;
124         modname = s;
125         /* append "lib" foo ".so" */
126         strcat(t,"lib");
127         x = t+strlen(t);
128         strcat(t,s);
129         s = strchr(x,'.');
130         if (s) {
131             while (s) {
132                 if (!FILE_strcasecmp(s,".dll")) {
133                     strcpy(s+1,UNIX_DLL_ENDING);
134                     break;
135                 }
136                 s=strchr(s+1,'.');
137             }
138         } else {
139                 strcat(x,"."UNIX_DLL_ENDING);
140         }
141
142         /* grab just the last piece of the path/filename
143            which should be the name of the library we are
144            looking to load. increment by 1 to skip the DOS slash */
145         s = strrchr(t,'\\');
146         s++;
147
148        /* ... and open the library pointed by s, while t points
149          points to the ENTIRE DOS filename of the library
150          t is returned by HeapAlloc() above and so is also used
151          with HeapFree() below */
152         dlhandle = wine_dlopen(s,RTLD_NOW,error,sizeof(error));
153         if (!dlhandle) {
154                 WARN("failed to load %s: %s\n", s, error);
155                 HeapFree( GetProcessHeap(), 0, t );
156                 SetLastError( ERROR_FILE_NOT_FOUND );
157                 return NULL;
158         }
159
160         hmod = ELF_CreateDummyModule( t, modname );
161
162         SNOOP_RegisterDLL(hmod,libname,0,STUBSIZE/sizeof(ELF_STDCALL_STUB));
163
164         wm = PE_CreateModule( hmod, libname, 0, 0, FALSE );
165         wm->find_export = ELF_FindExportedFunction;
166         wm->dlhandle = dlhandle;
167         return wm;
168 }
169
170 static FARPROC ELF_FindExportedFunction( WINE_MODREF *wm, LPCSTR funcName, BOOL snoop )
171 {
172         LPVOID                  fun;
173         int                     i,nrofargs = 0;
174         ELF_STDCALL_STUB        *stub, *first_stub;
175         char                    error[256];
176
177         if (!HIWORD(funcName)) {
178                 ERR("Can't import from UNIX dynamic libs by ordinal, sorry.\n");
179                 return (FARPROC)0;
180         }
181         fun = wine_dlsym(wm->dlhandle,funcName,error,sizeof(error));
182         if (!fun)
183         {
184             /* we sometimes have an excess '_' at the beginning of the name */
185             if (funcName[0]=='_')
186             {
187                 funcName++ ;
188                 fun = wine_dlsym(wm->dlhandle,funcName,error,sizeof(error));
189             }
190         }
191         if (!fun) {
192                 /* Function@nrofargs usually marks a stdcall function 
193                  * with nrofargs bytes that are popped at the end
194                  */
195             LPCSTR t;
196             if ((t = strchr(funcName,'@')))
197             {
198                 LPSTR fn = HeapAlloc( GetProcessHeap(), 0, t - funcName + 1 );
199                 memcpy( fn, funcName, t - funcName );
200                 fn[t - funcName] = 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 }