12 #define BIN_LOWEST MM_USER_MIN // 1MiB
13 #define BIN_GRANUALITY 0x10000 // 64KiB
14 #define BIN_HIGHEST (USER_LIB_MAX-BIN_GRANUALITY) // Just below the kernel
15 #define KLIB_LOWEST MM_MODULE_MIN
16 #define KLIB_GRANUALITY 0x10000 // 32KiB
17 #define KLIB_HIGHEST (MM_MODULE_MAX-KLIB_GRANUALITY)
20 typedef struct sKernelBin {
21 struct sKernelBin *Next;
27 extern char *Threads_GetName(int ID);
28 extern tKernelSymbol gKernelSymbols[];
29 extern tKernelSymbol gKernelSymbolsEnd[];
30 extern tBinaryType gELF_Info;
31 extern void MM_DumpTables(tVAddr, tVAddr);
34 int Proc_Execve(const char *File, const char **ArgV, const char **EnvP);
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);
42 Uint Binary_Relocate(void *Base);
44 Uint Binary_GetSymbolEx(const char *Name, Uint *Value);
46 Uint Binary_FindSymbol(void *Base, const char *Name, Uint *Val);
48 int Binary_int_CheckMemFree( tVAddr _start, size_t _len );
51 tShortSpinlock glBinListLock;
52 tBinary *glLoadedBinaries = NULL;
53 char **gsaRegInterps = NULL;
55 tShortSpinlock glKBinListLock;
56 tKernelBin *glLoadedKernelLibs;
57 tBinaryType *gRegBinTypes = &gELF_Info;
61 * \brief Registers a binary type
63 int Binary_RegisterType(tBinaryType *Type)
65 Type->Next = gRegBinTypes;
71 * \fn int Proc_Spawn(const char *Path)
73 int Proc_Spawn(const char *Path)
75 char stackPath[strlen(Path)+1];
78 strcpy(stackPath, Path);
80 LOG("stackPath = '%s'", stackPath);
82 if(Proc_Clone(CLONE_VM) == 0)
85 const char *args[2] = {stackPath, NULL};
86 LOG("stackPath = '%s'", stackPath);
87 Proc_Execve(stackPath, args, &args[1]);
95 * \fn int Proc_Execve(char *File, char **ArgV, char **EnvP)
96 * \brief Replace the current user image with another
97 * \param File File to load as the next image
98 * \param ArgV Arguments to pass to user
99 * \param EnvP User's environment
100 * \note Called Proc_ for historical reasons
102 int Proc_Execve(const char *File, const char **ArgV, const char **EnvP)
106 char **argenvBuf, *strBuf;
107 char **argvSaved, **envpSaved;
110 Uint bases[2] = {0}; // Uint because Proc_StartUser wants it
112 ENTER("sFile pArgV pEnvP", File, ArgV, EnvP);
114 // --- Save File, ArgV and EnvP (also get argc)
116 // Count Arguments, Environment Variables and total string sizes
118 for( argc = 0; ArgV && ArgV[argc]; argc++ )
119 argenvBytes += strlen(ArgV[argc])+1;
120 for( envc = 0; EnvP && EnvP[envc]; envc++ )
121 argenvBytes += strlen(EnvP[envc])+1;
122 argenvBytes = (argenvBytes + sizeof(void*)-1) & ~(sizeof(void*)-1);
123 argenvBytes += (argc+1)*sizeof(void*) + (envc+1)*sizeof(void*);
126 argenvBuf = malloc(argenvBytes);
127 if(argenvBuf == NULL) {
128 Log_Error("Binary", "Proc_Execve - What the hell? The kernel is out of heap space");
132 strBuf = (char*)argenvBuf + (argc+1)*sizeof(void*) + (envc+1)*sizeof(void*);
135 argvSaved = argenvBuf;
136 for( i = 0; i < argc; i++ )
138 argvSaved[i] = strBuf;
139 strcpy(argvSaved[i], ArgV[i]);
140 strBuf += strlen(ArgV[i])+1;
143 envpSaved = &argvSaved[i+1];
144 for( i = 0; i < envc; i++ )
146 envpSaved[i] = strBuf;
147 strcpy(envpSaved[i], EnvP[i]);
148 strBuf += strlen(EnvP[i])+1;
152 savedFile = malloc(strlen(File)+1);
153 strcpy(savedFile, File);
155 // --- Set Process Name
156 Threads_SetName(File);
158 // --- Clear User Address space
161 // --- Load new binary
162 bases[0] = Binary_Load(savedFile, &entry);
166 Log_Warning("Binary", "Proc_Execve - Unable to load '%s'", Threads_GetName(-1));
168 Threads_Exit(0, -10);
172 LOG("entry = 0x%x, bases[0] = 0x%x", entry, bases[0]);
174 MM_DumpTables(0, KERNEL_BASE);
177 // --- And... Jump to it
178 Proc_StartUser(entry, bases, argc, argvSaved, envpSaved, argenvBytes);
179 for(;;); // Tell GCC that we never return
183 * \fn tVAddr Binary_Load(char *Path, tVAddr *EntryPoint)
184 * \brief Load a binary into the current address space
185 * \param Path Path to binary to load
186 * \param EntryPoint Pointer for exectuable entry point
188 tVAddr Binary_Load(const char *Path, tVAddr *EntryPoint)
195 ENTER("sPath pEntryPoint", Path, EntryPoint);
197 // Sanity Check Argument
203 // Check if this path has been loaded before.
205 // TODO: Implement a list of string/tBinary pairs for loaded bins
212 fd = VFS_Open(Path, VFS_OPENFLAG_READ|VFS_OPENFLAG_EXEC);
214 LOG("%s does not exist", Path);
217 VFS_FInfo(fd, &info, 0);
219 mount_id = info.mount;
223 // TODO: Also get modifcation time?
225 // Check if the binary has already been loaded
226 if( !(pBinary = Binary_GetInfo(mount_id, inode)) )
227 pBinary = Binary_DoLoad(mount_id, inode, Path); // Else load it
230 if(pBinary == NULL) {
235 // Map into process space
236 base = Binary_MapIn(pBinary, Path, BIN_LOWEST, BIN_HIGHEST);
245 if(pBinary->Interpreter) {
247 if( Binary_Load(pBinary->Interpreter, &start) == 0 ) {
254 *EntryPoint = pBinary->Entry - pBinary->Base + base;
257 LOG("*EntryPoint = 0x%x", *EntryPoint);
259 return base; // Pass the base as an argument to the user if there is an interpreter
263 * \brief Finds a matching binary entry
264 * \param TruePath File Identifier (True path name)
266 tBinary *Binary_GetInfo(tMount MountID, tInode InodeID)
269 pBinary = glLoadedBinaries;
272 if(pBinary->MountID == MountID && pBinary->Inode == InodeID)
274 pBinary = pBinary->Next;
280 \fn Uint Binary_MapIn(tBinary *binary)
281 \brief Maps an already-loaded binary into an address space.
282 \param binary Pointer to globally stored data.
284 tVAddr Binary_MapIn(tBinary *Binary, const char *Path, tVAddr LoadMin, tVAddr LoadMax)
289 ENTER("pBinary sPath pLoadMin pLoadMax", Binary, Path, LoadMin, LoadMax);
291 // Reference Executable (Makes sure that it isn't unloaded)
292 Binary->ReferenceCount ++;
297 // Check if base is free
300 LOG("Checking base %p", base);
301 for(i=0;i<Binary->NumSections;i++)
303 if( Binary_int_CheckMemFree( Binary->LoadSections[i].Virtual, Binary->LoadSections[i].MemSize ) )
306 LOG("Address 0x%x is taken\n", Binary->LoadSections[i].Virtual);
312 // Check if the executable has no base or it is not free
315 // If so, give it a base
317 while(base >= LoadMin)
319 for( i = 0; i < Binary->NumSections; i ++ )
321 tVAddr addr = Binary->LoadSections[i].Virtual - Binary->Base + base;
322 if( Binary_int_CheckMemFree( addr, Binary->LoadSections[i].MemSize ) )
325 // If space was found, break
326 if(i == Binary->NumSections) break;
327 // Else decrement pointer and try again
328 base -= BIN_GRANUALITY;
330 LOG("Allocated base %p", base);
335 Log_Warning("Binary", "Executable '%s' cannot be loaded, no space", Path);
341 fd = VFS_OpenInode(Binary->MountID, Binary->Inode, VFS_OPENFLAG_READ);
342 for( i = 0; i < Binary->NumSections; i ++ )
344 tBinarySection *sect = &Binary->LoadSections[i];
345 Uint protflags, mapflags;
346 tVAddr addr = sect->Virtual - Binary->Base + base;
347 LOG("%i - %p to 0x%llx (%x)", i, addr, sect->Offset, sect->Flags);
349 protflags = MMAP_PROT_READ;
350 mapflags = MMAP_MAP_FIXED;
352 if( sect->Flags & BIN_SECTFLAG_EXEC )
353 protflags |= MMAP_PROT_EXEC;
354 if( sect->Flags & BIN_SECTFLAG_RO ) {
355 VFS_MMap( (void*)addr, sect->FileSize, protflags, MMAP_MAP_SHARED|mapflags, fd, sect->Offset );
358 protflags |= MMAP_PROT_WRITE;
359 VFS_MMap( (void*)addr, sect->FileSize, protflags, MMAP_MAP_PRIVATE|mapflags, fd, sect->Offset );
361 if( sect->FileSize < sect->MemSize ) {
362 mapflags |= MMAP_MAP_ANONYMOUS;
364 (void*)(addr + sect->FileSize), sect->MemSize - sect->FileSize,
365 protflags, MMAP_MAP_PRIVATE|mapflags,
371 Log_Debug("Binary", "PID %i - Mapped '%s' to 0x%x", Threads_GetPID(), Path, base);
373 //LOG("*0x%x = 0x%x\n", binary->Pages[0].Virtual, *(Uint*)binary->Pages[0].Virtual);
381 * \fn Uint Binary_IsMapped(tBinary *binary)
382 * \brief Check if a binary is already mapped into the address space
383 * \param binary Binary information to check
384 * \return Current Base or 0
386 Uint Binary_IsMapped(tBinary *binary)
390 // Check prefered base
391 iBase = binary->Base;
392 if(MM_GetPage( iBase ) == (binary->Pages[0].Physical & ~0xFFF))
395 for(iBase = BIN_HIGHEST;
397 iBase -= BIN_GRANUALITY)
399 if(MM_GetPage( iBase ) == (binary->Pages[0].Physical & ~0xFFF))
408 * \fn tBinary *Binary_DoLoad(char *truePath)
409 * \brief Loads a binary file into memory
410 * \param truePath Absolute filename of binary
412 tBinary *Binary_DoLoad(tMount MountID, tInode Inode, const char *Path)
417 tBinaryType *bt = gRegBinTypes;
419 ENTER("iMountID XInode sPath", MountID, Inode, Path);
422 fp = VFS_OpenInode(MountID, Inode, VFS_OPENFLAG_READ);
424 LOG("Unable to load file, access denied");
430 VFS_Read(fp, 4, &ident);
431 VFS_Seek(fp, 0, SEEK_SET);
433 // Determine the type
434 for(; bt; bt = bt->Next)
436 if( (ident & bt->Mask) != (Uint)bt->Ident )
438 pBinary = bt->Load(fp);
447 Log_Warning("Binary", "'%s' is an unknown file type. (%02x %02x %02x %02x)",
448 Path, ident&0xFF, (ident>>8)&0xFF, (ident>>16)&0xFF, (ident>>24)&0xFF);
454 if(pBinary == NULL) {
459 // Initialise Structure
460 pBinary->ReferenceCount = 0;
461 pBinary->MountID = MountID;
462 pBinary->Inode = Inode;
465 LOG("Interpreter: '%s'", pBinary->Interpreter);
466 LOG("Base: 0x%x, Entry: 0x%x", pBinary->Base, pBinary->Entry);
467 LOG("NumSections: %i", pBinary->NumSections);
470 SHORTLOCK(&glBinListLock);
471 pBinary->Next = glLoadedBinaries;
472 glLoadedBinaries = pBinary;
473 SHORTREL(&glBinListLock);
475 // TODO: Register the path with the binary
483 * \fn void Binary_Unload(void *Base)
484 * \brief Unload / Unmap a binary
485 * \param Base Loaded Base
486 * \note Currently used only for kernel libaries
488 void Binary_Unload(void *Base)
491 tKernelBin *prev = NULL;
494 if((Uint)Base < 0xC0000000)
496 // TODO: User Binaries
497 Log_Warning("BIN", "Unloading user binaries is currently unimplemented");
502 for(pKBin = glLoadedKernelLibs;
504 prev = pKBin, pKBin = pKBin->Next)
507 if(pKBin->Base != Base) continue;
509 for(i = 0; i < pKBin->Info->NumSections; i++)
511 // TODO: VFS_MUnmap();
513 // Dereference Binary
514 Binary_Dereference( pKBin->Info );
516 if(prev) prev->Next = pKBin->Next;
517 else glLoadedKernelLibs = pKBin->Next;
525 * \fn void Binary_Dereference(tBinary *Info)
526 * \brief Dereferences and if nessasary, deletes a binary
527 * \param Info Binary information structure
529 void Binary_Dereference(tBinary *Info)
531 // Decrement reference count
532 Info->ReferenceCount --;
534 // Check if it is still in use
535 if(Info->ReferenceCount) return;
537 /// \todo Implement binary freeing
541 * \fn char *Binary_RegInterp(char *Path)
542 * \brief Registers an Interpreter
543 * \param Path Path to interpreter provided by executable
545 char *Binary_RegInterp(char *Path)
548 // NULL Check Argument
549 if(Path == NULL) return NULL;
550 // NULL Check the array
551 if(gsaRegInterps == NULL)
554 gsaRegInterps = malloc( sizeof(char*) );
555 gsaRegInterps[0] = malloc( strlen(Path) );
556 strcpy(gsaRegInterps[0], Path);
557 return gsaRegInterps[0];
561 for( i = 0; i < giRegInterps; i++ )
563 if(strcmp(gsaRegInterps[i], Path) == 0)
564 return gsaRegInterps[i];
567 // Interpreter is not in list
569 gsaRegInterps = malloc( sizeof(char*)*giRegInterps );
570 gsaRegInterps[i] = malloc( strlen(Path) );
571 strcpy(gsaRegInterps[i], Path);
572 return gsaRegInterps[i];
576 // Kernel Binary Handling
579 * \fn void *Binary_LoadKernel(const char *File)
580 * \brief Load a binary into kernel space
581 * \note This function shares much with #Binary_Load, but does it's own mapping
582 * \param File File to load into the kernel
584 void *Binary_LoadKernel(const char *File)
587 tKernelBin *pKBinary;
592 ENTER("sFile", File);
594 // Sanity Check Argument
601 int fd = VFS_Open(File, VFS_OPENFLAG_READ);
607 VFS_FInfo(fd, &info, 0);
608 mount_id = info.mount;
613 // Check if the binary has already been loaded
614 if( (pBinary = Binary_GetInfo(mount_id, inode)) )
616 for(pKBinary = glLoadedKernelLibs;
618 pKBinary = pKBinary->Next )
620 if(pKBinary->Info == pBinary) {
621 LEAVE('p', pKBinary->Base);
622 return pKBinary->Base;
627 pBinary = Binary_DoLoad(mount_id, inode, File); // Else load it
630 if(pBinary == NULL) {
636 // Now pBinary is valid (either freshly loaded or only user mapped)
637 // So, map it into kernel space
640 // Reference Executable (Makes sure that it isn't unloaded)
641 pBinary->ReferenceCount ++;
643 Binary_MapIn(pBinary, File, KLIB_LOWEST, KLIB_HIGHEST);
646 if( !Binary_Relocate( (void*)base ) )
648 Log_Warning("Binary", "Relocation of '%s' failed, unloading", File);
649 Binary_Unload( (void*)base );
650 Binary_Dereference( pBinary );
655 // Add to list (relocator must look at itself manually, not via Binary_GetSymbol)
656 pKBinary = malloc(sizeof(*pKBinary));
657 pKBinary->Base = (void*)base;
658 pKBinary->Info = pBinary;
659 SHORTLOCK( &glKBinListLock );
660 pKBinary->Next = glLoadedKernelLibs;
661 glLoadedKernelLibs = pKBinary;
662 SHORTREL( &glKBinListLock );
669 * \fn Uint Binary_Relocate(void *Base)
670 * \brief Relocates a loaded binary (used by kernel libraries)
671 * \param Base Loaded base address of binary
672 * \return Boolean Success
674 Uint Binary_Relocate(void *Base)
676 Uint32 ident = *(Uint32*) Base;
677 tBinaryType *bt = gRegBinTypes;
679 for(; bt; bt = bt->Next)
681 if( (ident & bt->Mask) == (Uint)bt->Ident )
682 return bt->Relocate( (void*)Base);
685 Log_Warning("BIN", "%p is an unknown file type. (%02x %02x %02x %02x)",
686 Base, ident&0xFF, (ident>>8)&0xFF, (ident>>16)&0xFF, (ident>>24)&0xFF);
691 * \fn int Binary_GetSymbol(char *Name, Uint *Val)
692 * \brief Get a symbol value
693 * \return Value of symbol or -1 on error
695 * Gets the value of a symbol from either the currently loaded
696 * libraries or the kernel's exports.
698 int Binary_GetSymbol(const char *Name, Uint *Val)
700 if( Binary_GetSymbolEx(Name, Val) ) return 1;
705 * \fn Uint Binary_GetSymbolEx(char *Name, Uint *Value)
706 * \brief Get a symbol value
708 * Gets the value of a symbol from either the currently loaded
709 * libraries or the kernel's exports.
711 Uint Binary_GetSymbolEx(const char *Name, Uint *Value)
715 int numKSyms = ((Uint)&gKernelSymbolsEnd-(Uint)&gKernelSymbols)/sizeof(tKernelSymbol);
718 for( i = 0; i < numKSyms; i++ )
720 if(strcmp(Name, gKernelSymbols[i].Name) == 0) {
721 *Value = gKernelSymbols[i].Value;
726 // Scan Loaded Libraries
727 for(pKBin = glLoadedKernelLibs;
729 pKBin = pKBin->Next )
731 if( Binary_FindSymbol(pKBin->Base, Name, Value) ) {
736 Log_Warning("BIN", "Unable to find symbol '%s'", Name);
741 * \fn Uint Binary_FindSymbol(void *Base, char *Name, Uint *Val)
742 * \brief Get a symbol from the specified library
743 * \param Base Base address
744 * \param Name Name of symbol to find
745 * \param Val Pointer to place final value
747 Uint Binary_FindSymbol(void *Base, const char *Name, Uint *Val)
749 Uint32 ident = *(Uint32*) Base;
750 tBinaryType *bt = gRegBinTypes;
752 for(; bt; bt = bt->Next)
754 if( (ident & bt->Mask) == (Uint)bt->Ident )
755 return bt->GetSymbol(Base, Name, Val);
758 Log_Warning("BIN", "Binary_FindSymbol - %p is an unknown file type. (%02x %02x %02x %02x)",
759 Base, ident&0xFF, ident>>8, ident>>16, ident>>24);
764 * \brief Check if a range of memory is fully free
765 * \return Inverse boolean free (0 if all pages are unmapped)
767 int Binary_int_CheckMemFree( tVAddr _start, size_t _len )
769 _len += _start & (PAGE_SIZE-1);
770 _len = (_len + PAGE_SIZE - 1) & ~(PAGE_SIZE-1);
771 _start &= ~(PAGE_SIZE-1);
772 for( ; _len > PAGE_SIZE; _len -= PAGE_SIZE, _start += PAGE_SIZE ) {
773 if( MM_GetPhysAddr(_start) != 0 )
776 if( _len == PAGE_SIZE && MM_GetPhysAddr(_start) != 0 )
783 EXPORT(Binary_FindSymbol);
784 EXPORT(Binary_Unload);