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

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