Usermode/libc - Fix strchr and strrchr behavior
[tpg/acess2.git] / KernelLand / Kernel / modules.c
1 /*
2  * Acess2
3  * - Module Loader
4  */
5 #define DEBUG   0
6 #include <acess.h>
7 #include <modules.h>
8
9 #define USE_EDI 0
10 #define USE_UDI 0
11 #define MODULE_FLAG_LOADERROR   0x1
12
13 // === PROTOTYPES ===
14  int    Module_int_Initialise(tModule *Module, const char *ArgString);
15 size_t  Modules_int_PopulateBuiltins(tModule **Array);
16 void    Modules_int_GetBuiltinArray(void);
17 void    Modules_LoadBuiltins(void);
18 void    Modules_SetBuiltinParams(const char *Name, char *ArgString);
19  int    Modules_InitialiseBuiltin(const char *Name);
20 // int  Module_RegisterLoader(tModuleLoader *Loader);
21 // int  Module_LoadMem(void *Buffer, Uint Length, char *ArgString);
22 // int  Module_LoadFile(char *Path, char *ArgString);
23  int    Module_int_ResolveDeps(tModule *Info);
24  int    Module_IsLoaded(const char *Name);
25 // int  Module_EnsureLoaded(const char *Name);
26
27 // === EXPORTS ===
28 EXPORT(Module_RegisterLoader);
29
30 // === IMPORTS ===
31 #if USE_UDI
32 extern int      UDI_LoadDriver(void *Base);
33 #endif
34 extern void     StartupPrint(const char *Str);
35 extern tModule  gKernelModules;
36 extern tModule  gKernelModulesEnd;
37
38 // === GLOBALS ===
39  int    giNumBuiltinModules = 0;
40 tShortSpinlock  glModuleSpinlock;
41 tModule *gLoadedModules = NULL;
42 tModuleLoader   *gModule_Loaders = NULL;
43 tModule *gLoadingModules = NULL;
44 tModule **gapBuiltinModules = NULL;
45 char    **gasBuiltinModuleArgs;
46
47 // === CODE ===
48 /**
49  * \brief Initialises a module
50  * \param Module        Pointer to the module header
51  * \param ArgString     Comma separated list of module arguments
52  * \return Zero on success, eModuleErrors or -1 on error
53  * \retval -1   Returned if a dependency fails, or a circular dependency
54  *              exists.
55  * \retval 0    Returned on success
56  * \retval >0   Error code form the module's initialisation function
57  */
58 int Module_int_Initialise(tModule *Module, const char *ArgString)
59 {
60          int    i, j;
61          int    ret;
62         const char      **deps;
63         char    **args;
64         tModule *mod;
65         
66         ENTER("pModule", Module);
67         LOG("Module->Magic = 0x%x", Module->Magic);
68         if(Module->Magic != MODULE_MAGIC) {
69                 Log_Warning(
70                         "Module",
71                         "Module %p is no a valid Acess2 module (0x%08x != 0x%08x)",
72                         Module, Module->Magic, MODULE_MAGIC
73                         );
74                 LEAVE('i', MODULE_ERR_BADMODULE);
75                 return MODULE_ERR_BADMODULE;
76         }
77         LOG("Module->Name = %p \"%s\"", Module->Name, Module->Name);
78         
79         if(Module->Arch != MODULE_ARCH_ID) {
80                 Log_Warning(
81                         "Module",
82                         "Module %p (%s) is for another architecture (%i)",
83                         Module, Module->Name, Module->Arch
84                         );
85                 LEAVE('i', MODULE_ERR_BADMODULE);
86                 return MODULE_ERR_BADMODULE;
87         }
88
89         LOG("Module->Flags = %x", Module->Flags);       
90         if(Module->Flags & MODULE_FLAG_LOADERROR ) {
91                 Log_Warning("Module", "%s has already attempted to load and encountered errors", Module->Name);
92                 LEAVE('i', MODULE_ERR_MISC);
93                 return MODULE_ERR_MISC;
94         }
95         
96         deps = Module->Dependencies;
97         
98         // Check if the module has been loaded
99         for( mod = gLoadedModules; mod; mod = mod->Next )
100         {
101                 if(mod == Module)       LEAVE_RET('i', 0);
102         }
103         
104         // Add to the "loading" (prevents circular deps)
105         Module->Next = gLoadingModules;
106         gLoadingModules = Module;
107         
108         // Scan dependency list
109         for( j = 0; deps && deps[j]; j++ )
110         {
111                 // Check if the module is already loaded
112                 for( mod = gLoadedModules; mod; mod = mod->Next )
113                 {
114                         if(strcmp(deps[j], mod->Name) == 0)
115                                 break;
116                 }
117                 if( mod )       continue;       // Dependency is loaded, check the rest
118                 
119                 // Ok, check if it's loading
120                 for( mod = gLoadingModules->Next; mod; mod = mod->Next )
121                 {
122                         if(strcmp(deps[j], mod->Name) == 0)
123                                 break;
124                 }
125                 if( mod ) {
126                         Log_Warning("Module", "Circular dependency detected (%s and %s)",
127                                 mod->Name, Module->Name);
128                         LEAVE_RET('i', -1);
129                 }
130                 
131                 // So, if it's not loaded, we better load it then
132                 for( i = 0; i < giNumBuiltinModules; i ++ )
133                 {
134                         if( strcmp(deps[j], gapBuiltinModules[i]->Name) == 0 )
135                                 break;
136                 }
137                 if( i == giNumBuiltinModules ) {
138                         Log_Warning("Module", "Dependency '%s' for module '%s' failed",
139                                 deps[j], Module->Name);
140                         return -1;
141                 }
142                 
143                 // Dependency is not loaded, so load it
144                 ret = Module_int_Initialise(
145                         gapBuiltinModules[i],
146                         gasBuiltinModuleArgs ? gasBuiltinModuleArgs[i] : NULL
147                         );
148                 if( ret )
149                 {
150                         // The only "ok" error is NOTNEEDED
151                         if(ret != MODULE_ERR_NOTNEEDED)
152                                 LEAVE_RET('i', -1);
153                 }
154         }
155         
156         // All Dependencies OK? Initialise
157         StartupPrint(Module->Name);
158         Log_Log("Module", "Starting %p '%s' v%i.%i",
159                 Module, Module->Name,
160                 Module->Version >> 8, Module->Version & 0xFF
161                 );
162         
163         if( ArgString )
164                 args = str_split( ArgString, ',' );
165         else
166                 args = NULL;
167         
168         ret = Module->Init(args);
169         
170         if(args)        free(args);
171         
172         // Remove from loading list
173         gLoadingModules = gLoadingModules->Next;
174         
175         if( ret != MODULE_ERR_OK ) {
176                 switch(ret)
177                 {
178                 case MODULE_ERR_MISC:
179                         Log_Warning("Module", "Unable to load, reason: Miscelanious");
180                         break;
181                 case MODULE_ERR_NOTNEEDED:
182 //                      Log_Debug("Module", "Unable to load, reason: Module not needed");
183                         break;
184                 case MODULE_ERR_MALLOC:
185                         Log_Warning("Module", "Unable to load, reason: Error in malloc/realloc/calloc, probably not good");
186                         break;
187                 default:
188                         Log_Warning("Module", "Unable to load reason - Unknown code %i", ret);
189                         break;
190                 }
191                 Module->Flags |= MODULE_FLAG_LOADERROR;
192                 LEAVE_RET('i', ret);
193                 return ret;
194         }
195         LOG("ret = %i", ret);
196         
197         // Add to loaded list
198         SHORTLOCK( &glModuleSpinlock );
199         Module->Next = gLoadedModules;
200         gLoadedModules = Module;
201         SHORTREL( &glModuleSpinlock );
202         
203         LEAVE_RET('i', 0);
204 }
205
206 size_t Modules_int_PopulateBuiltins(tModule **Array)
207 {
208         size_t  count = 0;
209         for( tModule *module = &gKernelModules; module < (tModule*)&gKernelModulesEnd; )
210         {
211                 if(module->Magic == MODULE_MAGIC) {
212                         if( Array ) {
213                                 Array[count] = module;
214                         }
215                         count ++;
216                         module ++;
217                 }
218                 else {
219                         module = (void*)( (tVAddr)module + 4 );
220                 }
221         }
222         return count;
223 }
224
225 /**
226  * \brief Scans the builtin modules and creates an array of them
227  */
228 void Modules_int_GetBuiltinArray(void)
229 {
230         if( !gapBuiltinModules )
231         {
232                 // Count
233                 giNumBuiltinModules = Modules_int_PopulateBuiltins(NULL);
234                 
235                 // Create
236                 gasBuiltinModuleArgs = calloc( giNumBuiltinModules, sizeof(char*) );
237                 gapBuiltinModules = malloc( giNumBuiltinModules * sizeof(tModule*) );
238                 
239                 // Fill
240                 Modules_int_PopulateBuiltins(gapBuiltinModules);
241         }
242 }
243
244 /**
245  * \brief Initialises builtin modules
246  */
247 void Modules_LoadBuiltins(void)
248 {
249         Modules_int_GetBuiltinArray();
250         for( int i = 0; i < giNumBuiltinModules; i++ )
251         {
252                 Module_int_Initialise(
253                         gapBuiltinModules[i],
254                         (gasBuiltinModuleArgs ? gasBuiltinModuleArgs[i] : NULL)
255                         );
256         }
257         
258         if( gasBuiltinModuleArgs != NULL )
259                 free(gasBuiltinModuleArgs);
260 }
261
262 /**
263  * \brief Initialise a builtin module given it's name
264  * 
265  * E.g. Used by VTerm to load an alternate video driver at runtime
266  */
267 int Modules_InitialiseBuiltin(const char *Name)
268 {
269          int    i;
270         
271         // Check if it's loaded
272         if( Module_IsLoaded(Name) )
273                 return 0;
274         
275         if( !gapBuiltinModules )
276                 Modules_int_GetBuiltinArray();
277         
278         for( i = 0; i < giNumBuiltinModules; i++ )
279         {
280                 if( strcmp(gapBuiltinModules[i]->Name, Name) == 0 ) {
281                         return Module_int_Initialise(gapBuiltinModules[i],
282                                 (gasBuiltinModuleArgs ? gasBuiltinModuleArgs[i] : NULL)
283                                 );
284                 }
285         }
286         return -1;
287 }
288
289 /**
290  * \brief Sets the parameters for a builtin module
291  */
292 void Modules_SetBuiltinParams(const char *Name, char *ArgString)
293 {
294          int    i;
295         
296         if( gasBuiltinModuleArgs == NULL )
297         {
298                 Modules_int_GetBuiltinArray();
299         }
300         
301         // I hate expensive scans
302         for( i = 0; i < giNumBuiltinModules; i++ )
303         {
304                 if(strcmp( gapBuiltinModules[i]->Name, Name ) == 0) {
305                         gasBuiltinModuleArgs[i] = ArgString;
306                         return ;
307                 }
308         }
309         
310         Log_Warning("Modules", "Unknown builtin kernel module '%s'", Name);
311 }
312
313 /**
314  * \brief Registers a tModuleLoader with the kernel
315  * \param Loader        Pointer to loader structure (must be persistent)
316  */
317 int Module_RegisterLoader(tModuleLoader *Loader)
318 {
319         if(!Loader)     return 1;
320         
321         Loader->Next = gModule_Loaders;
322         gModule_Loaders = Loader;
323         
324         return 0;
325 }
326
327 /**
328  * \fn int Module_LoadMem(void *Buffer, Uint Length, char *ArgString)
329  * \brief Load a module from a memory location
330  */
331 int Module_LoadMem(void *Buffer, Uint Length, const char *ArgString)
332 {
333         char    path[VFS_MEMPATH_SIZE];
334         
335         VFS_GetMemPath(path, Buffer, Length);
336         
337         return Module_LoadFile( path, ArgString ) == EOK;
338 }
339
340 /**
341  * \fn int Module_LoadFile(const char *Path, const char *ArgString)
342  * \brief Load a module from a file
343  */
344 int Module_LoadFile(const char *Path, const char *ArgString)
345 {
346         void    *base;
347         tModule *info;
348         tModuleLoader   *loader = NULL;
349         
350         // Load Binary
351         base = Binary_LoadKernel(Path);
352         
353         // Error check
354         if(base == NULL) {
355                 Log_Warning("Module", "Module_LoadFile - Unable to load '%s'", Path);
356                 return ENOENT;
357         }
358
359         // TODO: I need a way of relocating the dependencies before everything else, so
360         // they can be resolved before any other link errors
361         if( !Binary_Relocate(base) ) {
362                 Log_Warning("Module", "Relocation of module %s failed", Path);
363                 Binary_Unload(base);
364                 return EINVAL;
365         }
366         
367         // Check for Acess Driver
368         if( Binary_FindSymbol(base, "DriverInfo", (Uint*)&info ) == 0 )
369         {
370                 for( loader = gModule_Loaders; loader; loader = loader->Next)
371                 {
372                         if( loader->Detector(base) )
373                                 break;
374                 }
375                 
376                 // Unknown module type?, return error
377                 if( !loader ) {
378                         Binary_Unload(base);
379                         Log_Warning("Module", "Module '%s' does not have a Module Info struct", Path);
380                         return EINVAL;
381                 }
382         }
383
384         if( loader )
385         {
386                 if( loader->Loader(base, ArgString) )
387                 {
388                         Binary_Unload(base);
389                         return EINVAL;
390                 }
391         }
392         else
393         {
394                 if( !Module_int_ResolveDeps(info) ) {
395                         Log_Warning("Module", "Dependencies not met for '%s'", Path);
396                         Binary_Unload(base);
397                         return EINVAL;
398                 }
399                 
400                 if( Module_int_Initialise(info, ArgString) )
401                 {
402                         Binary_Unload(base);
403                         return EINVAL;
404                 }
405         }
406         
407         return 0;
408 }
409
410 /**
411  * \fn int Module_int_ResolveDeps(tModule *Info)
412  * \brief Resolves the dependencies
413  * \todo Implement
414  * \note Currently does not resolve the dependencies, just checks them
415  */
416 int Module_int_ResolveDeps(tModule *Info)
417 {
418         const char      **names = Info->Dependencies;
419         
420         // Walk dependencies array
421         for( ; *names; names++ )
422         {
423                 // Check if the module is loaded
424                 if( !Module_IsLoaded(*names) ) {
425                         Log_Warning("Module", "Module `%s' requires `%s', which is not loaded\n", Info->Name, *names);
426                         return 0;
427                 }
428         }
429         return 1;
430 }
431
432 /**
433  * \fn int Module_IsLoaded(const char *Name)
434  * \brief Checks if a module is loaded
435  * \param Name  Name of module to find
436  */
437 int Module_IsLoaded(const char *Name)
438 {
439         tModule *mod = gLoadedModules;
440         
441         // Scan loaded list
442         for( ; mod; mod = mod->Next )
443         {
444                 // If found, return true
445                 if(strcmp(mod->Name, Name) == 0)
446                         return 1;
447         }
448         // not found - return false
449         return 0;
450 }
451
452 /**
453  * \brief Load a module if needed
454  */
455 int Module_EnsureLoaded(const char *Name)
456 {
457         if( Module_IsLoaded(Name) )
458                 return 0;
459
460         if( Modules_InitialiseBuiltin(Name) == 0 )
461                 return 0;
462
463         // TODO: Load from a file?
464
465         return -1;
466 }

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