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;
33 int Proc_Execve(const char *File, const char **ArgV, const char **EnvP);
34 tVAddr Binary_Load(const char *Path, tVAddr *EntryPoint);
35 tBinary *Binary_GetInfo(tMount MountID, tInode InodeID);
36 tVAddr Binary_MapIn(tBinary *Binary, const char *Path, tVAddr LoadMin, tVAddr LoadMax);
37 tVAddr Binary_IsMapped(tBinary *Binary);
38 tBinary *Binary_DoLoad(tMount MountID, tInode Inode, const char *Path);
39 void Binary_Dereference(tBinary *Info);
41 Uint Binary_Relocate(void *Base);
43 Uint Binary_GetSymbolEx(const char *Name, Uint *Value);
45 Uint Binary_FindSymbol(void *Base, const char *Name, Uint *Val);
47 int Binary_int_CheckMemFree( tVAddr _start, size_t _len );
50 tShortSpinlock glBinListLock;
51 tBinary *glLoadedBinaries = NULL;
52 char **gsaRegInterps = NULL;
54 tShortSpinlock glKBinListLock;
55 tKernelBin *glLoadedKernelLibs;
56 tBinaryType *gRegBinTypes = &gELF_Info;
60 * \brief Registers a binary type
62 int Binary_RegisterType(tBinaryType *Type)
64 Type->Next = gRegBinTypes;
70 * \fn int Proc_Spawn(const char *Path)
72 int Proc_Spawn(const char *Path)
74 char stackPath[strlen(Path)+1];
77 strcpy(stackPath, Path);
79 LOG("stackPath = '%s'", stackPath);
81 if(Proc_Clone(CLONE_VM) == 0)
84 const char *args[2] = {stackPath, NULL};
85 LOG("stackPath = '%s'", stackPath);
86 Proc_Execve(stackPath, args, &args[1]);
94 * \fn int Proc_Execve(char *File, char **ArgV, char **EnvP)
95 * \brief Replace the current user image with another
96 * \param File File to load as the next image
97 * \param ArgV Arguments to pass to user
98 * \param EnvP User's environment
99 * \note Called Proc_ for historical reasons
101 int Proc_Execve(const char *File, const char **ArgV, const char **EnvP)
105 char **argenvBuf, *strBuf;
106 char **argvSaved, **envpSaved;
109 Uint base; // Uint because Proc_StartUser wants it
111 ENTER("sFile pArgV pEnvP", File, ArgV, EnvP);
113 // --- Save File, ArgV and EnvP (also get argc)
115 // Count Arguments, Environment Variables and total string sizes
117 for( argc = 0; ArgV && ArgV[argc]; argc++ )
118 argenvBytes += strlen(ArgV[argc])+1;
119 for( envc = 0; EnvP && EnvP[envc]; envc++ )
120 argenvBytes += strlen(EnvP[envc])+1;
121 argenvBytes = (argenvBytes + sizeof(void*)-1) & ~(sizeof(void*)-1);
122 argenvBytes += (argc+1)*sizeof(void*) + (envc+1)*sizeof(void*);
125 argenvBuf = malloc(argenvBytes);
126 if(argenvBuf == NULL) {
127 Log_Error("Binary", "Proc_Execve - What the hell? The kernel is out of heap space");
131 strBuf = (char*)argenvBuf + (argc+1)*sizeof(void*) + (envc+1)*sizeof(void*);
134 argvSaved = argenvBuf;
135 for( i = 0; i < argc; i++ )
137 argvSaved[i] = strBuf;
138 strcpy(argvSaved[i], ArgV[i]);
139 strBuf += strlen(ArgV[i])+1;
142 envpSaved = &argvSaved[i+1];
143 for( i = 0; i < envc; i++ )
145 envpSaved[i] = strBuf;
146 strcpy(envpSaved[i], EnvP[i]);
147 strBuf += strlen(EnvP[i])+1;
151 savedFile = malloc(strlen(File)+1);
152 strcpy(savedFile, File);
154 // --- Set Process Name
155 Threads_SetName(File);
157 // --- Clear User Address space
160 // --- Load new binary
161 base = 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, base = 0x%x", entry, base);
174 // MM_DumpTables(0, KERNEL_BASE);
177 // --- And... Jump to it
178 Proc_StartUser(entry, base, argc, argvSaved, argenvBytes);
179 for(;;); // Tell GCC that we never return
183 * \brief Load a binary into the current address space
184 * \param Path Path to binary to load
185 * \param EntryPoint Pointer for exectuable entry point
186 * \return Virtual address where the binary has been loaded
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;
221 LOG("mount_id = %i, inode = %i", mount_id, inode);
224 // TODO: Also get modifcation time?
226 // Check if the binary has already been loaded
227 if( !(pBinary = Binary_GetInfo(mount_id, inode)) )
228 pBinary = Binary_DoLoad(mount_id, inode, Path); // Else load it
231 if(pBinary == NULL) {
236 // Map into process space
237 base = Binary_MapIn(pBinary, Path, BIN_LOWEST, BIN_HIGHEST);
246 if(pBinary->Interpreter) {
248 if( Binary_Load(pBinary->Interpreter, &start) == 0 ) {
255 *EntryPoint = pBinary->Entry - pBinary->Base + base;
258 LOG("*EntryPoint = 0x%x", *EntryPoint);
260 return base; // Pass the base as an argument to the user if there is an interpreter
264 * \brief Finds a matching binary entry
265 * \param MountID Mountpoint ID of binary file
266 * \param InodeID Inode ID of the file
267 * \return Pointer to the binary definition (if already loaded)
269 tBinary *Binary_GetInfo(tMount MountID, tInode InodeID)
272 for(pBinary = glLoadedBinaries; pBinary; pBinary = pBinary->Next)
274 if(pBinary->MountID == MountID && pBinary->Inode == InodeID)
281 * \brief Maps an already-loaded binary into an address space.
282 * \param Binary Pointer to globally stored binary definition
283 * \param Path Path to the binary's file (for debug)
284 * \param LoadMin Lowest location to map to
285 * \param LoadMax Highest location to map to
286 * \return Base load address
288 tVAddr Binary_MapIn(tBinary *Binary, const char *Path, tVAddr LoadMin, tVAddr LoadMax)
293 ENTER("pBinary sPath pLoadMin pLoadMax", Binary, Path, LoadMin, LoadMax);
295 // Reference Executable (Makes sure that it isn't unloaded)
296 Binary->ReferenceCount ++;
301 // Check if base is free
304 LOG("Checking base %p", base);
305 for( i = 0; i < Binary->NumSections; i ++ )
307 if( Binary_int_CheckMemFree( Binary->LoadSections[i].Virtual, Binary->LoadSections[i].MemSize ) )
310 LOG("Address 0x%x is taken\n", Binary->LoadSections[i].Virtual);
316 // Check if the executable has no base or it is not free
319 // If so, give it a base
321 while(base >= LoadMin)
323 for( i = 0; i < Binary->NumSections; i ++ )
325 tVAddr addr = Binary->LoadSections[i].Virtual - Binary->Base + base;
326 if( Binary_int_CheckMemFree( addr, Binary->LoadSections[i].MemSize ) )
329 // If space was found, break
330 if(i == Binary->NumSections) break;
331 // Else decrement pointer and try again
332 base -= BIN_GRANUALITY;
334 LOG("Allocated base %p", base);
339 Log_Warning("Binary", "Executable '%s' cannot be loaded, no space", Path);
345 fd = VFS_OpenInode(Binary->MountID, Binary->Inode, VFS_OPENFLAG_READ);
346 for( i = 0; i < Binary->NumSections; i ++ )
348 tBinarySection *sect = &Binary->LoadSections[i];
349 Uint protflags, mapflags;
350 tVAddr addr = sect->Virtual - Binary->Base + base;
351 LOG("%i - %p to offset 0x%llx (%x)", i, addr, sect->Offset, sect->Flags);
353 protflags = MMAP_PROT_READ;
354 mapflags = MMAP_MAP_FIXED;
356 if( sect->Flags & BIN_SECTFLAG_EXEC )
357 protflags |= MMAP_PROT_EXEC;
358 // Read only pages are COW
359 if( sect->Flags & BIN_SECTFLAG_RO ) {
360 VFS_MMap( (void*)addr, sect->FileSize, protflags, MMAP_MAP_SHARED|mapflags, fd, sect->Offset );
363 protflags |= MMAP_PROT_WRITE;
364 VFS_MMap( (void*)addr, sect->FileSize, protflags, MMAP_MAP_PRIVATE|mapflags, fd, sect->Offset );
367 // Apply anonymous memory for BSS
368 if( sect->FileSize < sect->MemSize ) {
369 mapflags |= MMAP_MAP_ANONYMOUS;
371 (void*)(addr + sect->FileSize), sect->MemSize - sect->FileSize,
372 protflags, MMAP_MAP_PRIVATE|mapflags,
378 Log_Debug("Binary", "PID %i - Mapped '%s' to 0x%x", Threads_GetPID(), Path, base);
387 * \fn Uint Binary_IsMapped(tBinary *binary)
388 * \brief Check if a binary is already mapped into the address space
389 * \param binary Binary information to check
390 * \return Current Base or 0
392 Uint Binary_IsMapped(tBinary *binary)
396 // Check prefered base
397 iBase = binary->Base;
398 if(MM_GetPage( iBase ) == (binary->Pages[0].Physical & ~0xFFF))
401 for(iBase = BIN_HIGHEST;
403 iBase -= BIN_GRANUALITY)
405 if(MM_GetPage( iBase ) == (binary->Pages[0].Physical & ~0xFFF))
414 * \fn tBinary *Binary_DoLoad(char *truePath)
415 * \brief Loads a binary file into memory
416 * \param truePath Absolute filename of binary
418 tBinary *Binary_DoLoad(tMount MountID, tInode Inode, const char *Path)
423 tBinaryType *bt = gRegBinTypes;
425 ENTER("iMountID XInode sPath", MountID, Inode, Path);
428 fp = VFS_OpenInode(MountID, Inode, VFS_OPENFLAG_READ);
430 LOG("Unable to load file, access denied");
435 LOG("fp = 0x%x", fp);
438 VFS_Read(fp, 4, &ident);
439 VFS_Seek(fp, 0, SEEK_SET);
441 LOG("ident = 0x%x", ident);
443 // Determine the type
444 for(; bt; bt = bt->Next)
446 if( (ident & bt->Mask) != (Uint32)bt->Ident )
448 LOG("bt = %p (%s)", bt, bt->Name);
449 pBinary = bt->Load(fp);
453 LOG("pBinary = %p", pBinary);
460 Log_Warning("Binary", "'%s' is an unknown file type. (%02x %02x %02x %02x)",
461 Path, ident&0xFF, (ident>>8)&0xFF, (ident>>16)&0xFF, (ident>>24)&0xFF);
467 if(pBinary == NULL) {
472 // Initialise Structure
473 pBinary->ReferenceCount = 0;
474 pBinary->MountID = MountID;
475 pBinary->Inode = Inode;
478 LOG("Interpreter: '%s'", pBinary->Interpreter);
479 LOG("Base: 0x%x, Entry: 0x%x", pBinary->Base, pBinary->Entry);
480 LOG("NumSections: %i", pBinary->NumSections);
483 SHORTLOCK(&glBinListLock);
484 pBinary->Next = glLoadedBinaries;
485 glLoadedBinaries = pBinary;
486 SHORTREL(&glBinListLock);
488 // TODO: Register the path with the binary
496 * \fn void Binary_Unload(void *Base)
497 * \brief Unload / Unmap a binary
498 * \param Base Loaded Base
499 * \note Currently used only for kernel libaries
501 void Binary_Unload(void *Base)
504 tKernelBin *prev = NULL;
507 if((Uint)Base < 0xC0000000)
509 // TODO: User Binaries
510 Log_Warning("BIN", "Unloading user binaries is currently unimplemented");
515 for(pKBin = glLoadedKernelLibs;
517 prev = pKBin, pKBin = pKBin->Next)
520 if(pKBin->Base != Base) continue;
522 for(i = 0; i < pKBin->Info->NumSections; i++)
524 // TODO: VFS_MUnmap();
526 // Dereference Binary
527 Binary_Dereference( pKBin->Info );
529 if(prev) prev->Next = pKBin->Next;
530 else glLoadedKernelLibs = pKBin->Next;
538 * \fn void Binary_Dereference(tBinary *Info)
539 * \brief Dereferences and if nessasary, deletes a binary
540 * \param Info Binary information structure
542 void Binary_Dereference(tBinary *Info)
544 // Decrement reference count
545 Info->ReferenceCount --;
547 // Check if it is still in use
548 if(Info->ReferenceCount) return;
550 /// \todo Implement binary freeing
554 * \fn char *Binary_RegInterp(char *Path)
555 * \brief Registers an Interpreter
556 * \param Path Path to interpreter provided by executable
558 char *Binary_RegInterp(char *Path)
561 // NULL Check Argument
562 if(Path == NULL) return NULL;
563 // NULL Check the array
564 if(gsaRegInterps == NULL)
567 gsaRegInterps = malloc( sizeof(char*) );
568 gsaRegInterps[0] = malloc( strlen(Path) );
569 strcpy(gsaRegInterps[0], Path);
570 return gsaRegInterps[0];
574 for( i = 0; i < giRegInterps; i++ )
576 if(strcmp(gsaRegInterps[i], Path) == 0)
577 return gsaRegInterps[i];
580 // Interpreter is not in list
582 gsaRegInterps = malloc( sizeof(char*)*giRegInterps );
583 gsaRegInterps[i] = malloc( strlen(Path) );
584 strcpy(gsaRegInterps[i], Path);
585 return gsaRegInterps[i];
589 // Kernel Binary Handling
592 * \fn void *Binary_LoadKernel(const char *File)
593 * \brief Load a binary into kernel space
594 * \note This function shares much with #Binary_Load, but does it's own mapping
595 * \param File File to load into the kernel
597 void *Binary_LoadKernel(const char *File)
600 tKernelBin *pKBinary;
605 ENTER("sFile", File);
607 // Sanity Check Argument
614 int fd = VFS_Open(File, VFS_OPENFLAG_READ);
620 VFS_FInfo(fd, &info, 0);
621 mount_id = info.mount;
626 // Check if the binary has already been loaded
627 if( (pBinary = Binary_GetInfo(mount_id, inode)) )
629 for(pKBinary = glLoadedKernelLibs;
631 pKBinary = pKBinary->Next )
633 if(pKBinary->Info == pBinary) {
634 LEAVE('p', pKBinary->Base);
635 return pKBinary->Base;
640 pBinary = Binary_DoLoad(mount_id, inode, File); // Else load it
643 if(pBinary == NULL) {
649 // Now pBinary is valid (either freshly loaded or only user mapped)
650 // So, map it into kernel space
653 // Reference Executable (Makes sure that it isn't unloaded)
654 pBinary->ReferenceCount ++;
656 Binary_MapIn(pBinary, File, KLIB_LOWEST, KLIB_HIGHEST);
659 if( !Binary_Relocate( (void*)base ) )
661 Log_Warning("Binary", "Relocation of '%s' failed, unloading", File);
662 Binary_Unload( (void*)base );
663 Binary_Dereference( pBinary );
668 // Add to list (relocator must look at itself manually, not via Binary_GetSymbol)
669 pKBinary = malloc(sizeof(*pKBinary));
670 pKBinary->Base = (void*)base;
671 pKBinary->Info = pBinary;
672 SHORTLOCK( &glKBinListLock );
673 pKBinary->Next = glLoadedKernelLibs;
674 glLoadedKernelLibs = pKBinary;
675 SHORTREL( &glKBinListLock );
682 * \fn Uint Binary_Relocate(void *Base)
683 * \brief Relocates a loaded binary (used by kernel libraries)
684 * \param Base Loaded base address of binary
685 * \return Boolean Success
687 Uint Binary_Relocate(void *Base)
689 Uint32 ident = *(Uint32*) Base;
690 tBinaryType *bt = gRegBinTypes;
692 for(; bt; bt = bt->Next)
694 if( (ident & bt->Mask) == (Uint)bt->Ident )
695 return bt->Relocate( (void*)Base);
698 Log_Warning("BIN", "%p is an unknown file type. (%02x %02x %02x %02x)",
699 Base, ident&0xFF, (ident>>8)&0xFF, (ident>>16)&0xFF, (ident>>24)&0xFF);
704 * \fn int Binary_GetSymbol(char *Name, Uint *Val)
705 * \brief Get a symbol value
706 * \return Value of symbol or -1 on error
708 * Gets the value of a symbol from either the currently loaded
709 * libraries or the kernel's exports.
711 int Binary_GetSymbol(const char *Name, Uint *Val)
713 if( Binary_GetSymbolEx(Name, Val) ) return 1;
718 * \fn Uint Binary_GetSymbolEx(char *Name, Uint *Value)
719 * \brief Get a symbol value
721 * Gets the value of a symbol from either the currently loaded
722 * libraries or the kernel's exports.
724 Uint Binary_GetSymbolEx(const char *Name, Uint *Value)
728 int numKSyms = ((Uint)&gKernelSymbolsEnd-(Uint)&gKernelSymbols)/sizeof(tKernelSymbol);
731 for( i = 0; i < numKSyms; i++ )
733 if(strcmp(Name, gKernelSymbols[i].Name) == 0) {
734 *Value = gKernelSymbols[i].Value;
739 // Scan Loaded Libraries
740 for(pKBin = glLoadedKernelLibs;
742 pKBin = pKBin->Next )
744 if( Binary_FindSymbol(pKBin->Base, Name, Value) ) {
749 Log_Warning("BIN", "Unable to find symbol '%s'", Name);
754 * \fn Uint Binary_FindSymbol(void *Base, char *Name, Uint *Val)
755 * \brief Get a symbol from the specified library
756 * \param Base Base address
757 * \param Name Name of symbol to find
758 * \param Val Pointer to place final value
760 Uint Binary_FindSymbol(void *Base, const char *Name, Uint *Val)
762 Uint32 ident = *(Uint32*) Base;
763 tBinaryType *bt = gRegBinTypes;
765 for(; bt; bt = bt->Next)
767 if( (ident & bt->Mask) == (Uint)bt->Ident )
768 return bt->GetSymbol(Base, Name, Val);
771 Log_Warning("BIN", "Binary_FindSymbol - %p is an unknown file type. (%02x %02x %02x %02x)",
772 Base, ident&0xFF, ident>>8, ident>>16, ident>>24);
777 * \brief Check if a range of memory is fully free
778 * \return Inverse boolean free (0 if all pages are unmapped)
780 int Binary_int_CheckMemFree( tVAddr _start, size_t _len )
782 _len += _start & (PAGE_SIZE-1);
783 _len = (_len + PAGE_SIZE - 1) & ~(PAGE_SIZE-1);
784 _start &= ~(PAGE_SIZE-1);
785 for( ; _len > PAGE_SIZE; _len -= PAGE_SIZE, _start += PAGE_SIZE ) {
786 if( MM_GetPhysAddr(_start) != 0 )
789 if( _len == PAGE_SIZE && MM_GetPhysAddr(_start) != 0 )
796 EXPORT(Binary_FindSymbol);
797 EXPORT(Binary_Unload);