dbb7c156f000d71d1983a0e8d6c9d54f2f833c43
[tpg/acess2.git] / Usermode / Libraries / ld-acess.so_src / loadlib.c
1 /*
2  AcessOS 1 - Dynamic Loader
3  By thePowersGang
4 */
5 #include "common.h"
6 #include <stdint.h>
7 #include <acess/sys.h>
8
9 #define DEBUG   0
10
11 #if DEBUG
12 # define DEBUGS(v...)   SysDebug(v)
13 #else
14 # define DEBUGS(v...)   
15 #endif
16
17 #define MAX_QUEUED_ENTRYPOINTS  8
18
19 // === IMPORTS ===
20 extern const struct {
21         void    *Value;
22         char    *Name;
23 }       caLocalExports[];
24 extern const int        ciNumLocalExports;
25 extern char     **gEnvP;
26 extern char     gLinkedBase[];
27
28 // === TYPES ===
29 typedef void    tLibEntry(void *, int, char *[], char**);
30
31 // === PROTOTYPES ===
32 void    *IsFileLoaded(const char *file);
33
34 // === GLOABLS ===
35 tLoadedLib      gLoadedLibraries[MAX_LOADED_LIBRARIES];
36 char    gsLoadedStrings[MAX_STRINGS_BYTES];
37 char    *gsNextAvailString = gsLoadedStrings;
38 struct sQueuedEntry {
39         void    *Base;
40         tLibEntry       *Entry;
41 }       gaQueuedEntrypoints[MAX_QUEUED_ENTRYPOINTS];
42  int    giNumQueuedEntrypoints;
43 //tLoadLib      *gpLoadedLibraries = NULL;
44
45 // === CODE ===
46 void ldacess_DumpLoadedLibraries(void)
47 {
48         for( int i = 0; i < MAX_LOADED_LIBRARIES; i ++ )
49         {
50                 if(gLoadedLibraries[i].Base == 0)       break;  // Last entry has Base set to NULL
51                 _SysDebug("%p: %s",
52                         gLoadedLibraries[i].Base,
53                         gLoadedLibraries[i].Name
54                         );
55         }
56 }
57
58 /**
59  * \brief Call queued up entry points (after relocations completed) 
60  */
61 void CallQueuedEntrypoints(char **EnvP)
62 {
63         while( giNumQueuedEntrypoints )
64         {
65                 giNumQueuedEntrypoints --;
66                 const struct sQueuedEntry       *qe = &gaQueuedEntrypoints[giNumQueuedEntrypoints];
67                 //_SysDebug("Calling EP for %p", qe->Base);
68                 qe->Entry(qe->Base, 0, NULL, EnvP);
69         }
70 }
71
72 const char *FindLibrary(char *DestBuf, const char *SoName, const char *ExtraSearchDir)
73 {       
74         // -- #1: Executable Specified
75         if(ExtraSearchDir)
76         {
77                 strcpy(DestBuf, ExtraSearchDir);
78                 strcat(DestBuf, "/");
79                 strcat(DestBuf, SoName);
80                 if(file_exists(DestBuf))        return DestBuf;
81         }
82         
83         // -- #2: System
84         strcpy(DestBuf, SYSTEM_LIB_DIR);
85         strcat(DestBuf, SoName);
86         if(file_exists(DestBuf))        return DestBuf;
87         
88         // -- #3: Current Directory
89         if(file_exists(SoName)) return SoName;
90         
91         return NULL;
92 }
93
94 /**
95  */
96 void *LoadLibrary(const char *SoName, const char *SearchDir, char **envp)
97 {
98         char    sTmpName[1024];
99         void    *base;
100         
101         DEBUGS("LoadLibrary: (SoName='%s', SearchDir='%s', envp=%p)", SoName, SearchDir, envp);
102         
103         // Create Temp Name
104         const char *filename = FindLibrary(sTmpName, SoName, SearchDir);
105         if(filename == NULL) {
106                 DEBUGS("LoadLibrary: RETURN 0");
107                 return 0;
108         }
109         DEBUGS(" LoadLibrary: filename='%s'", filename);
110         
111         if( (base = IsFileLoaded(filename)) )
112                 return base;
113
114         DEBUGS(" LoadLibrary: SysLoadBin()");   
115         // Load Library
116         tLibEntry       *fEntry;
117         base = _SysLoadBin(filename, (void**)&fEntry);
118         if(!base) {
119                 DEBUGS("LoadLibrary: RETURN 0");
120                 return 0;
121         }
122         
123         DEBUGS(" LoadLibrary: iArg=%p, fEntry=%p", base, fEntry);
124         
125         // Load Symbols
126         fEntry = DoRelocate( base, envp, filename );
127         if( !fEntry ) {
128                 return 0;
129         }
130         
131         // Call Entrypoint
132         // - TODO: Queue entrypoint calls
133         if( giNumQueuedEntrypoints >= MAX_QUEUED_ENTRYPOINTS ) {
134                 SysDebug("ERROR - Maximum number of queued entrypoints exceeded on %p '%s'",
135                         base, SoName);
136                 return 0;
137         }
138         gaQueuedEntrypoints[giNumQueuedEntrypoints].Base  = base;
139         gaQueuedEntrypoints[giNumQueuedEntrypoints].Entry = fEntry;
140         giNumQueuedEntrypoints ++;
141         
142         DEBUGS("LoadLibrary: RETURN success");
143         return base;
144 }
145
146 /**
147  * \fn Uint IsFileLoaded(char *file)
148  * \brief Determine if a file is already loaded
149  */
150 void *IsFileLoaded(const char *file)
151 {
152          int    i;
153         DEBUGS("IsFileLoaded: (file='%s')", file);
154
155         // Applications link against either libld-acess.so or ld-acess.so
156         if( strcmp(file, "/Acess/Libs/libld-acess.so") == 0
157          || strcmp(file, "/Acess/Libs/ld-acess.so") == 0 )
158         {
159                 DEBUGS("IsFileLoaded: Found local (%p)", &gLinkedBase);
160                 return &gLinkedBase;
161         }
162
163         for( i = 0; i < MAX_LOADED_LIBRARIES; i++ )
164         {
165                 if(gLoadedLibraries[i].Base == 0)       break;  // Last entry has Base set to NULL
166                 DEBUGS(" strcmp('%s', '%s')", gLoadedLibraries[i].Name, file);
167                 if(strcmp(gLoadedLibraries[i].Name, file) == 0) {
168                         DEBUGS("IsFileLoaded: Found %i (%p)", i, gLoadedLibraries[i].Base);
169                         return gLoadedLibraries[i].Base;
170                 }
171         }
172         DEBUGS("IsFileLoaded: Not Found");
173         return 0;
174 }
175
176 /**
177  * \fn void AddLoaded(char *File, Uint base)
178  * \brief Add a file to the loaded list
179  */
180 void AddLoaded(const char *File, void *base)
181 {
182          int    i, length;
183         char    *name = gsNextAvailString;
184         
185         DEBUGS("AddLoaded: (File='%s', base=%p)", File, base);
186         
187         // Find a free slot
188         for( i = 0; i < MAX_LOADED_LIBRARIES; i ++ )
189         {
190                 if(gLoadedLibraries[i].Base == 0)       break;
191         }
192         if(i == MAX_LOADED_LIBRARIES) {
193                 SysDebug("ERROR - ld-acess.so has run out of load slots!");
194                 return;
195         }
196         
197         // Check space in string buffer
198         length = strlen(File);
199         if(&name[length+1] >= &gsLoadedStrings[MAX_STRINGS_BYTES]) {
200                 SysDebug("ERROR - ld-acess.so has run out of string buffer memory!");
201                 return;
202         }
203         
204         // Set information
205         gLoadedLibraries[i].Base = base;
206         strcpy(name, File);
207         gLoadedLibraries[i].Name = name;
208         gsNextAvailString = &name[length+1];
209         DEBUGS("'%s' (%p) loaded as %i", name, base, i);
210         return;
211 }
212
213 /**
214  * \fn void Unload(Uint Base)
215  */
216 void Unload(void *Base)
217 {       
218          int    i, j;
219          int    id;
220         char    *str;
221         for( id = 0; id < MAX_LOADED_LIBRARIES; id++ )
222         {
223                 if(gLoadedLibraries[id].Base == Base)   break;
224         }
225         if(id == MAX_LOADED_LIBRARIES)  return;
226         
227         // Unload Binary
228         _SysUnloadBin( Base );
229         // Save String Pointer
230         str = gLoadedLibraries[id].Name;
231         
232         // Compact Loaded List
233         j = id;
234         for( i = j + 1; i < MAX_LOADED_LIBRARIES; i++, j++ )
235         {
236                 if(gLoadedLibraries[i].Base == 0)       break;
237                 // Compact String
238                 strcpy(str, gLoadedLibraries[i].Name);
239                 str += strlen(str)+1;
240                 // Compact Entry
241                 gLoadedLibraries[j].Base = gLoadedLibraries[i].Base;
242                 gLoadedLibraries[j].Name = str;
243         }
244         
245         // NULL Last Entry
246         gLoadedLibraries[j].Base = 0;
247         gLoadedLibraries[j].Name = NULL;
248         // Save next string
249         gsNextAvailString = str;
250 }
251
252 /**
253  \fn Uint GetSymbol(const char *name)
254  \brief Gets a symbol value from a loaded library
255 */
256 int GetSymbol(const char *name, void **Value, size_t *Size, void *IgnoreBase)
257 {
258         //SysDebug("GetSymbol: (%s)");
259         for( int i = 0; i < ciNumLocalExports; i ++ )
260         {
261                 if( strcmp(caLocalExports[i].Name, name) == 0 ) {
262                         *Value = caLocalExports[i].Value;
263                         if(Size)
264                                 *Size = 0;
265                         //SysDebug("GetSymbol: Local %p+0x%x", *Value, 0);
266                         return 1;
267                 }
268         }
269         
270         for(int i = 0; i < MAX_LOADED_LIBRARIES && gLoadedLibraries[i].Base != 0; i ++)
271         {
272                 // Allow ignoring the current module
273                 if( gLoadedLibraries[i].Base == IgnoreBase ) {
274                         //SysDebug("GetSymbol: Ignore %p", gLoadedLibraries[i].Base);
275                         continue ;
276                 }
277                 
278                 //SysDebug(" GetSymbol: Trying 0x%x, '%s'",
279                 //      gLoadedLibraries[i].Base, gLoadedLibraries[i].Name);
280                 if(GetSymbolFromBase(gLoadedLibraries[i].Base, name, Value, Size)) {
281                         //SysDebug("GetSymbol: Remote %p - %p", gLoadedLibraries[i].Base, *Value);
282                         return 1;
283                 }
284         }
285         //SysDebug("GetSymbol: None");
286         return 0;
287 }
288
289 /**
290  \fn int GetSymbolFromBase(Uint base, char *name, Uint *ret)
291  \breif Gets a symbol from a specified library
292 */
293 int GetSymbolFromBase(void *base, const char *name, void **ret, size_t *Size)
294 {
295         uint8_t *hdr = base;
296         if(hdr[0] == 0x7F && hdr[1] == 'E' && hdr[2] == 'L' && hdr[3] == 'F')
297                 return ElfGetSymbol(base, name, ret, Size);
298         if(hdr[0] == 'M' && hdr[1] == 'Z')
299                 return PE_GetSymbol(base, name, ret, Size);
300         SysDebug("Unknown type at %p (%02x %02x %02x %02x)", base,
301                 hdr[0], hdr[1], hdr[2], hdr[3]);
302         return 0;
303 }
304

UCC git Repository :: git.ucc.asn.au