8a8bc3eba7a389eecb9f0986c4a06fa2d678221e
[tpg/acess2.git] / KernelLand / Kernel / binary.c
1 /*
2  * Acess2
3  * Common Binary Loader
4  */
5 #define DEBUG   0
6 #include <acess.h>
7 #include <binary.h>
8 #include <mm_virt.h>
9 #include <hal_proc.h>
10 #include <vfs_threads.h>
11
12 // === CONSTANTS ===
13 #define BIN_LOWEST      MM_USER_MIN             // 1MiB
14 #define BIN_GRANUALITY  0x10000         // 64KiB
15 #define BIN_HIGHEST     (USER_LIB_MAX-BIN_GRANUALITY)           // Just below the kernel
16 #define KLIB_LOWEST     MM_MODULE_MIN
17 #define KLIB_GRANUALITY 0x10000         // 32KiB
18 #define KLIB_HIGHEST    (MM_MODULE_MAX-KLIB_GRANUALITY)
19
20 // === TYPES ===
21 typedef struct sKernelBin {
22         struct sKernelBin       *Next;
23         void    *Base;
24         tBinary *Info;
25 } tKernelBin;
26
27 // === IMPORTS ===
28 extern char     *Threads_GetName(int ID);
29 extern tKernelSymbol    gKernelSymbols[];
30 extern tKernelSymbol    gKernelSymbolsEnd[];
31 extern tBinaryType      gELF_Info;
32
33 // === PROTOTYPES ===
34  int    Binary_int_CacheArgs(const char **Path, const char ***ArgV, const char ***EnvP, void *DestBuffer);
35 tVAddr  Binary_Load(const char *Path, tVAddr *EntryPoint);
36 tBinary *Binary_GetInfo(tMount MountID, tInode InodeID);
37 tVAddr  Binary_MapIn(tBinary *Binary, const char *Path, tVAddr LoadMin, tVAddr LoadMax);
38 tVAddr  Binary_IsMapped(tBinary *Binary);
39 tBinary *Binary_DoLoad(tMount MountID, tInode Inode, const char *Path);
40 void    Binary_Dereference(tBinary *Info);
41 #if 0
42 Uint    Binary_Relocate(void *Base);
43 #endif
44 Uint    Binary_GetSymbolEx(const char *Name, Uint *Value);
45 #if 0
46 Uint    Binary_FindSymbol(void *Base, const char *Name, Uint *Val);
47 #endif
48  int    Binary_int_CheckMemFree( tVAddr _start, size_t _len );
49
50 // === GLOBALS ===
51 tShortSpinlock  glBinListLock;
52 tBinary *glLoadedBinaries = NULL;
53 char    **gsaRegInterps = NULL;
54  int    giRegInterps = 0;
55 tShortSpinlock  glKBinListLock;
56 tKernelBin      *glLoadedKernelLibs;
57 tBinaryType     *gRegBinTypes = &gELF_Info;
58  
59 // === FUNCTIONS ===
60 /**
61  * \brief Registers a binary type
62  */
63 int Binary_RegisterType(tBinaryType *Type)
64 {
65         Type->Next = gRegBinTypes;
66         gRegBinTypes = Type;
67         return 1;
68 }
69
70 /**
71  * \fn int Proc_Spawn(const char *Path)
72  */
73 int Proc_Spawn(const char *Path)
74 {
75         char    stackPath[strlen(Path)+1];
76         ENTER("sPath", Path);
77         
78         strcpy(stackPath, Path);
79         
80         LOG("stackPath = '%s'", stackPath);
81         
82         if(Proc_Clone(CLONE_VM|CLONE_NOUSER) == 0)
83         {
84                 // CHILD
85                 const char      *args[2] = {stackPath, NULL};
86                 LOG("stackPath = '%s'", stackPath);
87                 Proc_Execve(stackPath, args, &args[1], 0);
88                 for(;;);
89         }
90         LEAVE('i', 0);
91         return 0;
92 }
93
94 /**
95  * \todo Document
96  */
97 int Binary_int_CacheArgs(const char **Path, const char ***ArgV, const char ***EnvP, void *DestBuffer)
98 {
99          int    size, argc=0, envc=0;
100          int    i;
101         char    *strbuf;
102         const char      **arrays;
103         
104         // Calculate size
105         size = 0;
106         if( ArgV && *ArgV )
107         {
108                 const char      **argv = *ArgV;
109                 for( argc = 0; argv[argc]; argc ++ )
110                         size += strlen( argv[argc] ) + 1;
111         }
112         if( EnvP && *EnvP )
113         {
114                 const char      **envp = *EnvP;
115                 for( envc = 0; envp[envc]; envc ++ )
116                         size += strlen( envp[envc] ) + 1;
117         }
118         size = (size + sizeof(void*)-1) & ~(sizeof(void*)-1);   // Word align
119         size += (argc+1+envc+1)*sizeof(void*);  // Arrays
120         if( Path )
121         {
122                 size += strlen( *Path ) + 1;
123         }
124
125         if( DestBuffer )        
126         {
127                 arrays = DestBuffer;
128                 strbuf = (void*)&arrays[argc+1+envc+1];
129         
130                 // Fill ArgV
131                 if( ArgV && *ArgV )
132                 {
133                         const char      **argv = *ArgV;
134                         for( i = 0; argv[i]; i ++ )
135                         {
136                                 arrays[i] = strbuf;
137                                 strcpy(strbuf, argv[i]);
138                                 strbuf += strlen( argv[i] ) + 1;
139                         }
140                         *ArgV = arrays;
141                         arrays += i;
142                 }
143                 *arrays++ = NULL;
144                 // Fill EnvP
145                 if( EnvP && *EnvP )
146                 {
147                         const char      **envp = *EnvP;
148                         for( i = 0; envp[i]; i ++ )
149                         {
150                                 arrays[i] = strbuf;
151                                 strcpy(strbuf, envp[i]);
152                                 strbuf += strlen( envp[i] ) + 1;
153                         }
154                         *EnvP = arrays;
155                         arrays += i;
156                 }
157                 *arrays++ = NULL;
158                 // Fill path
159                 if( Path )
160                 {
161                         strcpy(strbuf, *Path);
162                         *Path = strbuf;
163                 }
164         }
165         
166         return size;
167 }
168
169 /**
170  * \brief Create a new process with the specified set of file descriptors
171  */
172 int Proc_SysSpawn(const char *Binary, const char **ArgV, const char **EnvP, int nFD, int *FDs)
173 {
174         void    *handles;
175         void    *cachebuf;
176          int    size;
177         tPID    ret;
178         
179         // --- Save File, ArgV and EnvP
180         size = Binary_int_CacheArgs( &Binary, &ArgV, &EnvP, NULL );
181         cachebuf = malloc( size );
182         Binary_int_CacheArgs( &Binary, &ArgV, &EnvP, cachebuf );
183
184         // Cache the VFS handles        
185         handles = VFS_SaveHandles(nFD, FDs);
186
187         // Create new process   
188         ret = Proc_Clone(CLONE_VM|CLONE_NOUSER);
189         if( ret == 0 )
190         {
191                 VFS_RestoreHandles(nFD, handles);
192                 VFS_FreeSavedHandles(nFD, handles);
193                 // Frees cachebuf
194                 Proc_Execve(Binary, ArgV, EnvP, size);
195                 for(;;);
196         }
197         if( ret < 0 )
198         {
199                 VFS_FreeSavedHandles(nFD, handles);
200         }
201         
202         return ret;
203 }
204
205 /**
206  * \brief Replace the current user image with another
207  * \param File  File to load as the next image
208  * \param ArgV  Arguments to pass to user
209  * \param EnvP  User's environment
210  * \note Called Proc_ for historical reasons
211  */
212 int Proc_Execve(const char *File, const char **ArgV, const char **EnvP, int DataSize)
213 {
214         void    *cachebuf;
215         tVAddr  entry;
216         Uint    base;   // Uint because Proc_StartUser wants it
217          int    argc;
218         
219         ENTER("sFile pArgV pEnvP", File, ArgV, EnvP);
220         
221         // --- Save File, ArgV and EnvP
222         if( DataSize == 0 )
223         {
224                 DataSize = Binary_int_CacheArgs( &File, &ArgV, &EnvP, NULL );
225                 cachebuf = malloc( DataSize );
226                 Binary_int_CacheArgs( &File, &ArgV, &EnvP, cachebuf );
227         }
228
229         // --- Get argc 
230         for( argc = 0; ArgV && ArgV[argc]; argc ++ );
231         
232         // --- Set Process Name
233         Threads_SetName(File);
234         
235         // --- Clear User Address space
236         // NOTE: This is a little roundabout, maybe telling ClearUser to not touch the
237         //       PPD area would be a better idea.
238         {
239                  int    nfd = *Threads_GetMaxFD();
240                 void    *handles;
241                 handles = VFS_SaveHandles(nfd, NULL);
242                 VFS_CloseAllUserHandles();
243                 MM_ClearUser();
244                 VFS_RestoreHandles(nfd, handles);
245                 VFS_FreeSavedHandles(nfd, handles);
246         }
247         
248         // --- Load new binary
249         base = Binary_Load(File, &entry);
250         if(base == 0)
251         {
252                 Log_Warning("Binary", "Proc_Execve - Unable to load '%s'", File);
253                 LEAVE('-');
254                 Threads_Exit(0, -10);
255                 for(;;);
256         }
257         
258         LOG("entry = 0x%x, base = 0x%x", entry, base);
259         LEAVE('-');
260         // --- And... Jump to it
261         Proc_StartUser(entry, base, argc, ArgV, DataSize);
262         for(;;);        // Tell GCC that we never return
263 }
264
265 /**
266  * \brief Load a binary into the current address space
267  * \param Path  Path to binary to load
268  * \param EntryPoint    Pointer for exectuable entry point
269  * \return Virtual address where the binary has been loaded
270  */
271 tVAddr Binary_Load(const char *Path, tVAddr *EntryPoint)
272 {
273         tMount  mount_id;
274         tInode  inode;
275         tBinary *pBinary;
276         tVAddr  base = -1;
277
278         ENTER("sPath pEntryPoint", Path, EntryPoint);
279         
280         // Sanity Check Argument
281         if(Path == NULL) {
282                 LEAVE('x', 0);
283                 return 0;
284         }
285
286         // Check if this path has been loaded before.
287         #if 0
288         // TODO: Implement a list of string/tBinary pairs for loaded bins
289         #endif
290
291         // Get Inode
292         {
293                 int fd;
294                 tFInfo  info;
295                 fd = VFS_Open(Path, VFS_OPENFLAG_READ|VFS_OPENFLAG_EXEC);
296                 if( fd == -1 ) {
297                         LOG("%s does not exist", Path);
298                         LEAVE_RET('x', 0);
299                 }
300                 VFS_FInfo(fd, &info, 0);
301                 VFS_Close(fd);
302                 mount_id = info.mount;
303                 inode = info.inode;
304                 LOG("mount_id = %i, inode = %i", mount_id, inode);
305         }
306
307         // TODO: Also get modifcation time?
308
309         // Check if the binary has already been loaded
310         if( !(pBinary = Binary_GetInfo(mount_id, inode)) )
311                 pBinary = Binary_DoLoad(mount_id, inode, Path); // Else load it
312         
313         // Error Check
314         if(pBinary == NULL) {
315                 LEAVE('x', 0);
316                 return 0;
317         }
318         
319         // Map into process space
320         base = Binary_MapIn(pBinary, Path, BIN_LOWEST, BIN_HIGHEST);
321         
322         // Check for errors
323         if(base == 0) {
324                 LEAVE('x', 0);
325                 return 0;
326         }
327         
328         // Interpret
329         if(pBinary->Interpreter) {
330                 tVAddr  start;
331                 if( Binary_Load(pBinary->Interpreter, &start) == 0 ) {
332                         LEAVE('x', 0);
333                         return 0;
334                 }
335                 *EntryPoint = start;
336         }
337         else
338                 *EntryPoint = pBinary->Entry - pBinary->Base + base;
339         
340         // Return
341         LOG("*EntryPoint = 0x%x", *EntryPoint);
342         LEAVE('x', base);
343         return base;    // Pass the base as an argument to the user if there is an interpreter
344 }
345
346 /**
347  * \brief Finds a matching binary entry
348  * \param MountID       Mountpoint ID of binary file
349  * \param InodeID       Inode ID of the file
350  * \return Pointer to the binary definition (if already loaded)
351  */
352 tBinary *Binary_GetInfo(tMount MountID, tInode InodeID)
353 {
354         tBinary *pBinary;
355         for(pBinary = glLoadedBinaries; pBinary; pBinary = pBinary->Next)
356         {
357                 if(pBinary->MountID == MountID && pBinary->Inode == InodeID)
358                         return pBinary;
359         }
360         return NULL;
361 }
362
363 /**
364  * \brief Maps an already-loaded binary into an address space.
365  * \param Binary        Pointer to globally stored binary definition
366  * \param Path  Path to the binary's file (for debug)
367  * \param LoadMin       Lowest location to map to
368  * \param LoadMax       Highest location to map to
369  * \return Base load address
370  */
371 tVAddr Binary_MapIn(tBinary *Binary, const char *Path, tVAddr LoadMin, tVAddr LoadMax)
372 {
373         tVAddr  base;
374          int    i, fd;
375
376         ENTER("pBinary sPath pLoadMin pLoadMax", Binary, Path, LoadMin, LoadMax);
377
378         // Reference Executable (Makes sure that it isn't unloaded)
379         Binary->ReferenceCount ++;
380         
381         // Get Binary Base
382         base = Binary->Base;
383         
384         // Check if base is free
385         if(base != 0)
386         {
387                 LOG("Checking base %p", base);
388                 for( i = 0; i < Binary->NumSections; i ++ )
389                 {
390                         if( Binary_int_CheckMemFree( Binary->LoadSections[i].Virtual, Binary->LoadSections[i].MemSize ) )
391                         {
392                                 base = 0;
393                                 LOG("Address 0x%x is taken\n", Binary->LoadSections[i].Virtual);
394                                 break;
395                         }
396                 }
397         }
398         
399         // Check if the executable has no base or it is not free
400         if(base == 0)
401         {
402                 // If so, give it a base
403                 base = LoadMax;
404                 while(base >= LoadMin)
405                 {
406                         for( i = 0; i < Binary->NumSections; i ++ )
407                         {
408                                 tVAddr  addr = Binary->LoadSections[i].Virtual - Binary->Base + base;
409                                 size_t  size = Binary->LoadSections[i].MemSize;
410                                 if( addr + size > LoadMax )
411                                         break;
412                                 if( Binary_int_CheckMemFree( addr, size ) )
413                                         break;
414                         }
415                         // If space was found, break
416                         if(i == Binary->NumSections)            break;
417                         // Else decrement pointer and try again
418                         base -= BIN_GRANUALITY;
419                 }
420                 LOG("Allocated base %p", base);
421         }
422         
423         // Error Check
424         if(base < LoadMin) {
425                 Log_Warning("Binary", "Executable '%s' cannot be loaded, no space", Path);
426                 LEAVE('i', 0);
427                 return 0;
428         }
429         
430         // Map Executable In
431         if( Binary->MountID )
432                 fd = VFS_OpenInode(Binary->MountID, Binary->Inode, VFS_OPENFLAG_READ);
433         else
434                 fd = VFS_Open(Path, VFS_OPENFLAG_READ);
435         for( i = 0; i < Binary->NumSections; i ++ )
436         {
437                 tBinarySection  *sect = &Binary->LoadSections[i];
438                 Uint    protflags, mapflags;
439                 tVAddr  addr = sect->Virtual - Binary->Base + base;
440                 LOG("%i - %p, 0x%x bytes from offset 0x%llx (%x)", i, addr, sect->FileSize, sect->Offset, sect->Flags);
441
442                 protflags = MMAP_PROT_READ;
443                 mapflags = MMAP_MAP_FIXED;
444
445                 if( sect->Flags & BIN_SECTFLAG_EXEC )
446                         protflags |= MMAP_PROT_EXEC;
447                 // Read only pages are COW
448                 if( sect->Flags & BIN_SECTFLAG_RO  ) {
449                         VFS_MMap( (void*)addr, sect->FileSize, protflags, MMAP_MAP_SHARED|mapflags, fd, sect->Offset );
450                 }
451                 else {
452                         protflags |= MMAP_PROT_WRITE;
453                         VFS_MMap( (void*)addr, sect->FileSize, protflags, MMAP_MAP_PRIVATE|mapflags, fd, sect->Offset );
454                 }
455                 
456                 // Apply anonymous memory for BSS
457                 if( sect->FileSize < sect->MemSize ) {
458                         mapflags |= MMAP_MAP_ANONYMOUS;
459                         VFS_MMap(
460                                 (void*)(addr + sect->FileSize), sect->MemSize - sect->FileSize,
461                                 protflags, MMAP_MAP_PRIVATE|mapflags,
462                                 0, 0
463                                 );
464                 }
465         }
466         
467         Log_Debug("Binary", "PID %i - Mapped '%s' to %p", Threads_GetPID(), Path, base);
468         VFS_Close(fd);
469         
470         LEAVE('p', base);
471         return base;
472 }
473
474 #if 0
475 /**
476  * \fn Uint Binary_IsMapped(tBinary *binary)
477  * \brief Check if a binary is already mapped into the address space
478  * \param binary        Binary information to check
479  * \return Current Base or 0
480  */
481 Uint Binary_IsMapped(tBinary *binary)
482 {
483         Uint    iBase;
484         
485         // Check prefered base
486         iBase = binary->Base;
487         if(MM_GetPage( iBase ) == (binary->Pages[0].Physical & ~0xFFF))
488                 return iBase;
489         
490         for(iBase = BIN_HIGHEST;
491                 iBase >= BIN_LOWEST;
492                 iBase -= BIN_GRANUALITY)
493         {
494                 if(MM_GetPage( iBase ) == (binary->Pages[0].Physical & ~0xFFF))
495                         return iBase;
496         }
497         
498         return 0;
499 }
500 #endif
501
502 /**
503  * \fn tBinary *Binary_DoLoad(char *truePath)
504  * \brief Loads a binary file into memory
505  * \param truePath      Absolute filename of binary
506  */
507 tBinary *Binary_DoLoad(tMount MountID, tInode Inode, const char *Path)
508 {
509         tBinary *pBinary;
510          int    fp;
511         Uint32  ident;
512         tBinaryType     *bt = gRegBinTypes;
513         
514         ENTER("iMountID XInode sPath", MountID, Inode, Path);
515         
516         // Open File
517         if( MountID )
518         {
519                 fp = VFS_OpenInode(MountID, Inode, VFS_OPENFLAG_READ);
520         }
521         else
522         {
523                 fp = VFS_Open(Path, VFS_OPENFLAG_READ);
524         }
525         if(fp == -1) {
526                 LOG("Unable to load file, access denied");
527                 LEAVE('n');
528                 return NULL;
529         }
530
531         LOG("fp = 0x%x", fp);
532         
533         // Read File Type
534         VFS_Read(fp, 4, &ident);
535         VFS_Seek(fp, 0, SEEK_SET);
536
537         LOG("ident = 0x%x", ident);
538
539         // Determine the type   
540         for(; bt; bt = bt->Next)
541         {
542                 if( (ident & bt->Mask) != (Uint32)bt->Ident )
543                         continue;
544                 LOG("bt = %p (%s)", bt, bt->Name);
545                 pBinary = bt->Load(fp);
546                 break;
547         }
548
549         // Close File
550         VFS_Close(fp);
551         
552         // Catch errors
553         if(!bt) {
554                 Log_Warning("Binary", "'%s' is an unknown file type. (%02x %02x %02x %02x)",
555                         Path, ident&0xFF, (ident>>8)&0xFF, (ident>>16)&0xFF, (ident>>24)&0xFF);
556                 LEAVE('n');
557                 return NULL;
558         }
559         
560         LOG("pBinary = %p", pBinary);
561         
562         // Error Check
563         if(pBinary == NULL) {
564                 LEAVE('n');
565                 return NULL;
566         }
567         
568         // Initialise Structure
569         pBinary->ReferenceCount = 0;
570         pBinary->MountID = MountID;
571         pBinary->Inode = Inode;
572         
573         // Debug Information
574         LOG("Interpreter: '%s'", pBinary->Interpreter);
575         LOG("Base: 0x%x, Entry: 0x%x", pBinary->Base, pBinary->Entry);
576         LOG("NumSections: %i", pBinary->NumSections);
577         
578         // Add to the list
579         SHORTLOCK(&glBinListLock);
580         pBinary->Next = glLoadedBinaries;
581         glLoadedBinaries = pBinary;
582         SHORTREL(&glBinListLock);
583
584         // TODO: Register the path with the binary      
585
586         // Return
587         LEAVE('p', pBinary);
588         return pBinary;
589 }
590
591 /**
592  * \fn void Binary_Unload(void *Base)
593  * \brief Unload / Unmap a binary
594  * \param Base  Loaded Base
595  * \note Currently used only for kernel libaries
596  */
597 void Binary_Unload(void *Base)
598 {
599         tKernelBin      *pKBin;
600         tKernelBin      *prev = NULL;
601          int    i;
602         
603         if((Uint)Base < 0xC0000000)
604         {
605                 // TODO: User Binaries
606                 Log_Warning("BIN", "Unloading user binaries is currently unimplemented");
607                 return;
608         }
609         
610         // Kernel Libraries
611         for(pKBin = glLoadedKernelLibs;
612                 pKBin;
613                 prev = pKBin, pKBin = pKBin->Next)
614         {
615                 // Check the base
616                 if(pKBin->Base != Base) continue;
617                 // Deallocate Memory
618                 for(i = 0; i < pKBin->Info->NumSections; i++)
619                 {
620                         // TODO: VFS_MUnmap();
621                 }
622                 // Dereference Binary
623                 Binary_Dereference( pKBin->Info );
624                 // Remove from list
625                 if(prev)        prev->Next = pKBin->Next;
626                 else            glLoadedKernelLibs = pKBin->Next;
627                 // Free Kernel Lib
628                 free(pKBin);
629                 return;
630         }
631 }
632
633 /**
634  * \fn void Binary_Dereference(tBinary *Info)
635  * \brief Dereferences and if nessasary, deletes a binary
636  * \param Info  Binary information structure
637  */
638 void Binary_Dereference(tBinary *Info)
639 {
640         // Decrement reference count
641         Info->ReferenceCount --;
642         
643         // Check if it is still in use
644         if(Info->ReferenceCount)        return;
645         
646         /// \todo Implement binary freeing
647 }
648
649 /**
650  * \fn char *Binary_RegInterp(char *Path)
651  * \brief Registers an Interpreter
652  * \param Path  Path to interpreter provided by executable
653  */
654 char *Binary_RegInterp(char *Path)
655 {
656          int    i;
657         // NULL Check Argument
658         if(Path == NULL)        return NULL;
659         // NULL Check the array
660         if(gsaRegInterps == NULL)
661         {
662                 giRegInterps = 1;
663                 gsaRegInterps = malloc( sizeof(char*) );
664                 gsaRegInterps[0] = malloc( strlen(Path) );
665                 strcpy(gsaRegInterps[0], Path);
666                 return gsaRegInterps[0];
667         }
668         
669         // Scan Array
670         for( i = 0; i < giRegInterps; i++ )
671         {
672                 if(strcmp(gsaRegInterps[i], Path) == 0)
673                         return gsaRegInterps[i];
674         }
675         
676         // Interpreter is not in list
677         giRegInterps ++;
678         gsaRegInterps = malloc( sizeof(char*)*giRegInterps );
679         gsaRegInterps[i] = malloc( strlen(Path) );
680         strcpy(gsaRegInterps[i], Path);
681         return gsaRegInterps[i];
682 }
683
684 // ============
685 // Kernel Binary Handling
686 // ============
687 /**
688  * \fn void *Binary_LoadKernel(const char *File)
689  * \brief Load a binary into kernel space
690  * \note This function shares much with #Binary_Load, but does it's own mapping
691  * \param File  File to load into the kernel
692  */
693 void *Binary_LoadKernel(const char *File)
694 {
695         tBinary *pBinary;
696         tKernelBin      *pKBinary;
697         tVAddr  base = -1;
698         tMount  mount_id;
699         tInode  inode;
700
701         ENTER("sFile", File);
702         
703         // Sanity Check Argument
704         if(File == NULL) {
705                 LEAVE('n');
706                 return 0;
707         }
708
709         {
710                 int fd = VFS_Open(File, VFS_OPENFLAG_READ);
711                 tFInfo  info;
712                 if(fd == -1) {
713                         LOG("Opening failed");
714                         LEAVE('n');
715                         return NULL;
716                 }
717                 VFS_FInfo(fd, &info, 0);
718                 mount_id = info.mount;
719                 inode = info.inode;
720                 VFS_Close(fd);
721                 LOG("Mount %i, Inode %lli", mount_id, inode);
722         }
723         
724         // Check if the binary has already been loaded
725         if( (pBinary = Binary_GetInfo(mount_id, inode)) )
726         {
727                 for(pKBinary = glLoadedKernelLibs;
728                         pKBinary;
729                         pKBinary = pKBinary->Next )
730                 {
731                         if(pKBinary->Info == pBinary) {
732                                 LOG("Already loaded");
733                                 LEAVE('p', pKBinary->Base);
734                                 return pKBinary->Base;
735                         }
736                 }
737         }
738         else
739                 pBinary = Binary_DoLoad(mount_id, inode, File); // Else load it
740         
741         // Error Check
742         if(pBinary == NULL) {
743                 LEAVE('n');
744                 return NULL;
745         }
746         
747         LOG("Loaded as %p", pBinary);
748         // --------------
749         // Now pBinary is valid (either freshly loaded or only user mapped)
750         // So, map it into kernel space
751         // --------------
752         
753         // Reference Executable (Makes sure that it isn't unloaded)
754         pBinary->ReferenceCount ++;
755
756         base = Binary_MapIn(pBinary, File, KLIB_LOWEST, KLIB_HIGHEST);
757         if( base == 0 ) {
758                 LEAVE('n');
759                 return 0;
760         }
761
762         // Add to list
763         // TODO: Could this cause race conditions if a binary isn't fully loaded when used
764         pKBinary = malloc(sizeof(*pKBinary));
765         pKBinary->Base = (void*)base;
766         pKBinary->Info = pBinary;
767         SHORTLOCK( &glKBinListLock );
768         pKBinary->Next = glLoadedKernelLibs;
769         glLoadedKernelLibs = pKBinary;
770         SHORTREL( &glKBinListLock );
771
772         LEAVE('p', base);
773         return (void*)base;
774 }
775
776 /**
777  * \fn Uint Binary_Relocate(void *Base)
778  * \brief Relocates a loaded binary (used by kernel libraries)
779  * \param Base  Loaded base address of binary
780  * \return Boolean Success
781  */
782 Uint Binary_Relocate(void *Base)
783 {
784         Uint32  ident = *(Uint32*) Base;
785         tBinaryType     *bt = gRegBinTypes;
786         
787         for( ; bt; bt = bt->Next)
788         {
789                 if( (ident & bt->Mask) == (Uint)bt->Ident )
790                         return bt->Relocate( (void*)Base);
791         }
792         
793         Log_Warning("BIN", "%p is an unknown file type. (%02x %02x %02x %02x)",
794                 Base, ident&0xFF, (ident>>8)&0xFF, (ident>>16)&0xFF, (ident>>24)&0xFF);
795         return 0;
796 }
797
798 /**
799  * \fn int Binary_GetSymbol(char *Name, Uint *Val)
800  * \brief Get a symbol value
801  * \return Value of symbol or -1 on error
802  * 
803  * Gets the value of a symbol from either the currently loaded
804  * libraries or the kernel's exports.
805  */
806 int Binary_GetSymbol(const char *Name, Uint *Val)
807 {
808         if( Binary_GetSymbolEx(Name, Val) )     return 1;
809         return 0;
810 }
811
812 /**
813  * \fn Uint Binary_GetSymbolEx(char *Name, Uint *Value)
814  * \brief Get a symbol value
815  * 
816  * Gets the value of a symbol from either the currently loaded
817  * libraries or the kernel's exports.
818  */
819 Uint Binary_GetSymbolEx(const char *Name, Uint *Value)
820 {
821          int    i;
822         tKernelBin      *pKBin;
823          int    numKSyms = ((Uint)&gKernelSymbolsEnd-(Uint)&gKernelSymbols)/sizeof(tKernelSymbol);
824         
825         // Scan Kernel
826         for( i = 0; i < numKSyms; i++ )
827         {
828                 if(strcmp(Name, gKernelSymbols[i].Name) == 0) {
829                         *Value = gKernelSymbols[i].Value;
830                         return 1;
831                 }
832         }
833         
834         // Scan Loaded Libraries
835         for(pKBin = glLoadedKernelLibs;
836                 pKBin;
837                 pKBin = pKBin->Next )
838         {
839                 if( Binary_FindSymbol(pKBin->Base, Name, Value) ) {
840                         return 1;
841                 }
842         }
843         
844         Log_Warning("BIN", "Unable to find symbol '%s'", Name);
845         return 0;
846 }
847
848 /**
849  * \fn Uint Binary_FindSymbol(void *Base, char *Name, Uint *Val)
850  * \brief Get a symbol from the specified library
851  * \param Base  Base address
852  * \param Name  Name of symbol to find
853  * \param Val   Pointer to place final value
854  */
855 Uint Binary_FindSymbol(void *Base, const char *Name, Uint *Val)
856 {
857         Uint32  ident = *(Uint32*) Base;
858         tBinaryType     *bt = gRegBinTypes;
859         
860         for(; bt; bt = bt->Next)
861         {
862                 if( (ident & bt->Mask) == (Uint)bt->Ident )
863                         return bt->GetSymbol(Base, Name, Val);
864         }
865         
866         Log_Warning("BIN", "Binary_FindSymbol - %p is an unknown file type. (%02x %02x %02x %02x)",
867                 Base, ident&0xFF, ident>>8, ident>>16, ident>>24);
868         return 0;
869 }
870
871 /**
872  * \brief Check if a range of memory is fully free
873  * \return Inverse boolean free (0 if all pages are unmapped)
874  */
875 int Binary_int_CheckMemFree( tVAddr _start, size_t _len )
876 {
877         ENTER("p_start x_len", _start, _len);
878
879         _len += _start & (PAGE_SIZE-1);
880         _len = (_len + PAGE_SIZE - 1) & ~(PAGE_SIZE-1);
881         _start &= ~(PAGE_SIZE-1);
882         LOG("_start = %p, _len = 0x%x", _start, _len);
883         for( ; _len > PAGE_SIZE; _len -= PAGE_SIZE, _start += PAGE_SIZE ) {
884                 if( MM_GetPhysAddr(_start) != 0 ) {
885                         LEAVE('i', 1);
886                         return 1;
887                 }
888         }
889         if( _len == PAGE_SIZE && MM_GetPhysAddr(_start) != 0 ) {
890                 LEAVE('i', 1);
891                 return 1;
892         }
893         LEAVE('i', 0);
894         return 0;
895 }
896
897
898 // === EXPORTS ===
899 EXPORT(Binary_FindSymbol);
900 EXPORT(Binary_Unload);

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