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

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