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 bases[2] = {0}; // 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 bases[0] = Binary_Load(savedFile, &entry);
165 Log_Warning("Binary", "Proc_Execve - Unable to load '%s'", Threads_GetName(-1));
167 Threads_Exit(0, -10);
171 LOG("entry = 0x%x, bases[0] = 0x%x", entry, bases[0]);
173 // MM_DumpTables(0, KERNEL_BASE);
176 // --- And... Jump to it
177 Proc_StartUser(entry, bases, argc, argvSaved, envpSaved, argenvBytes);
178 for(;;); // Tell GCC that we never return
182 * \fn tVAddr Binary_Load(char *Path, tVAddr *EntryPoint)
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
187 tVAddr Binary_Load(const char *Path, tVAddr *EntryPoint)
194 ENTER("sPath pEntryPoint", Path, EntryPoint);
196 // Sanity Check Argument
202 // Check if this path has been loaded before.
204 // TODO: Implement a list of string/tBinary pairs for loaded bins
211 fd = VFS_Open(Path, VFS_OPENFLAG_READ|VFS_OPENFLAG_EXEC);
213 LOG("%s does not exist", Path);
216 VFS_FInfo(fd, &info, 0);
218 mount_id = info.mount;
222 // TODO: Also get modifcation time?
224 // Check if the binary has already been loaded
225 if( !(pBinary = Binary_GetInfo(mount_id, inode)) )
226 pBinary = Binary_DoLoad(mount_id, inode, Path); // Else load it
229 if(pBinary == NULL) {
234 // Map into process space
235 base = Binary_MapIn(pBinary, Path, BIN_LOWEST, BIN_HIGHEST);
244 if(pBinary->Interpreter) {
246 if( Binary_Load(pBinary->Interpreter, &start) == 0 ) {
253 *EntryPoint = pBinary->Entry - pBinary->Base + base;
256 LOG("*EntryPoint = 0x%x", *EntryPoint);
258 return base; // Pass the base as an argument to the user if there is an interpreter
262 * \brief Finds a matching binary entry
263 * \param TruePath File Identifier (True path name)
265 tBinary *Binary_GetInfo(tMount MountID, tInode InodeID)
268 pBinary = glLoadedBinaries;
271 if(pBinary->MountID == MountID && pBinary->Inode == InodeID)
273 pBinary = pBinary->Next;
279 \fn Uint Binary_MapIn(tBinary *binary)
280 \brief Maps an already-loaded binary into an address space.
281 \param binary Pointer to globally stored data.
283 tVAddr Binary_MapIn(tBinary *Binary, const char *Path, tVAddr LoadMin, tVAddr LoadMax)
288 ENTER("pBinary sPath pLoadMin pLoadMax", Binary, Path, LoadMin, LoadMax);
290 // Reference Executable (Makes sure that it isn't unloaded)
291 Binary->ReferenceCount ++;
296 // Check if base is free
299 LOG("Checking base %p", base);
300 for(i=0;i<Binary->NumSections;i++)
302 if( Binary_int_CheckMemFree( Binary->LoadSections[i].Virtual, Binary->LoadSections[i].MemSize ) )
305 LOG("Address 0x%x is taken\n", Binary->LoadSections[i].Virtual);
311 // Check if the executable has no base or it is not free
314 // If so, give it a base
316 while(base >= LoadMin)
318 for( i = 0; i < Binary->NumSections; i ++ )
320 tVAddr addr = Binary->LoadSections[i].Virtual - Binary->Base + base;
321 if( Binary_int_CheckMemFree( addr, Binary->LoadSections[i].MemSize ) )
324 // If space was found, break
325 if(i == Binary->NumSections) break;
326 // Else decrement pointer and try again
327 base -= BIN_GRANUALITY;
329 LOG("Allocated base %p", base);
334 Log_Warning("Binary", "Executable '%s' cannot be loaded, no space", Path);
340 fd = VFS_OpenInode(Binary->MountID, Binary->Inode, VFS_OPENFLAG_READ);
341 for( i = 0; i < Binary->NumSections; i ++ )
343 tBinarySection *sect = &Binary->LoadSections[i];
344 Uint protflags, mapflags;
345 tVAddr addr = sect->Virtual - Binary->Base + base;
346 LOG("%i - %p to 0x%llx (%x)", i, addr, sect->Offset, sect->Flags);
348 protflags = MMAP_PROT_READ;
349 mapflags = MMAP_MAP_FIXED;
351 if( sect->Flags & BIN_SECTFLAG_EXEC )
352 protflags |= MMAP_PROT_EXEC;
353 if( sect->Flags & BIN_SECTFLAG_RO ) {
354 VFS_MMap( (void*)addr, sect->FileSize, protflags, MMAP_MAP_SHARED|mapflags, fd, sect->Offset );
357 protflags |= MMAP_PROT_WRITE;
358 VFS_MMap( (void*)addr, sect->FileSize, protflags, MMAP_MAP_PRIVATE|mapflags, fd, sect->Offset );
360 if( sect->FileSize < sect->MemSize ) {
361 mapflags |= MMAP_MAP_ANONYMOUS;
363 (void*)(addr + sect->FileSize), sect->MemSize - sect->FileSize,
364 protflags, MMAP_MAP_PRIVATE|mapflags,
367 // memset((void*)(addr + sect->FileSize), 0, sect->MemSize - sect->FileSize);
371 Log_Debug("Binary", "PID %i - Mapped '%s' to 0x%x", Threads_GetPID(), Path, base);
374 //LOG("*0x%x = 0x%x\n", binary->Pages[0].Virtual, *(Uint*)binary->Pages[0].Virtual);
382 * \fn Uint Binary_IsMapped(tBinary *binary)
383 * \brief Check if a binary is already mapped into the address space
384 * \param binary Binary information to check
385 * \return Current Base or 0
387 Uint Binary_IsMapped(tBinary *binary)
391 // Check prefered base
392 iBase = binary->Base;
393 if(MM_GetPage( iBase ) == (binary->Pages[0].Physical & ~0xFFF))
396 for(iBase = BIN_HIGHEST;
398 iBase -= BIN_GRANUALITY)
400 if(MM_GetPage( iBase ) == (binary->Pages[0].Physical & ~0xFFF))
409 * \fn tBinary *Binary_DoLoad(char *truePath)
410 * \brief Loads a binary file into memory
411 * \param truePath Absolute filename of binary
413 tBinary *Binary_DoLoad(tMount MountID, tInode Inode, const char *Path)
418 tBinaryType *bt = gRegBinTypes;
420 ENTER("iMountID XInode sPath", MountID, Inode, Path);
423 fp = VFS_OpenInode(MountID, Inode, VFS_OPENFLAG_READ);
425 LOG("Unable to load file, access denied");
431 VFS_Read(fp, 4, &ident);
432 VFS_Seek(fp, 0, SEEK_SET);
434 // Determine the type
435 for(; bt; bt = bt->Next)
437 if( (ident & bt->Mask) != (Uint)bt->Ident )
439 pBinary = bt->Load(fp);
448 Log_Warning("Binary", "'%s' is an unknown file type. (%02x %02x %02x %02x)",
449 Path, ident&0xFF, (ident>>8)&0xFF, (ident>>16)&0xFF, (ident>>24)&0xFF);
455 if(pBinary == NULL) {
460 // Initialise Structure
461 pBinary->ReferenceCount = 0;
462 pBinary->MountID = MountID;
463 pBinary->Inode = Inode;
466 LOG("Interpreter: '%s'", pBinary->Interpreter);
467 LOG("Base: 0x%x, Entry: 0x%x", pBinary->Base, pBinary->Entry);
468 LOG("NumSections: %i", pBinary->NumSections);
471 SHORTLOCK(&glBinListLock);
472 pBinary->Next = glLoadedBinaries;
473 glLoadedBinaries = pBinary;
474 SHORTREL(&glBinListLock);
476 // TODO: Register the path with the binary
484 * \fn void Binary_Unload(void *Base)
485 * \brief Unload / Unmap a binary
486 * \param Base Loaded Base
487 * \note Currently used only for kernel libaries
489 void Binary_Unload(void *Base)
492 tKernelBin *prev = NULL;
495 if((Uint)Base < 0xC0000000)
497 // TODO: User Binaries
498 Log_Warning("BIN", "Unloading user binaries is currently unimplemented");
503 for(pKBin = glLoadedKernelLibs;
505 prev = pKBin, pKBin = pKBin->Next)
508 if(pKBin->Base != Base) continue;
510 for(i = 0; i < pKBin->Info->NumSections; i++)
512 // TODO: VFS_MUnmap();
514 // Dereference Binary
515 Binary_Dereference( pKBin->Info );
517 if(prev) prev->Next = pKBin->Next;
518 else glLoadedKernelLibs = pKBin->Next;
526 * \fn void Binary_Dereference(tBinary *Info)
527 * \brief Dereferences and if nessasary, deletes a binary
528 * \param Info Binary information structure
530 void Binary_Dereference(tBinary *Info)
532 // Decrement reference count
533 Info->ReferenceCount --;
535 // Check if it is still in use
536 if(Info->ReferenceCount) return;
538 /// \todo Implement binary freeing
542 * \fn char *Binary_RegInterp(char *Path)
543 * \brief Registers an Interpreter
544 * \param Path Path to interpreter provided by executable
546 char *Binary_RegInterp(char *Path)
549 // NULL Check Argument
550 if(Path == NULL) return NULL;
551 // NULL Check the array
552 if(gsaRegInterps == NULL)
555 gsaRegInterps = malloc( sizeof(char*) );
556 gsaRegInterps[0] = malloc( strlen(Path) );
557 strcpy(gsaRegInterps[0], Path);
558 return gsaRegInterps[0];
562 for( i = 0; i < giRegInterps; i++ )
564 if(strcmp(gsaRegInterps[i], Path) == 0)
565 return gsaRegInterps[i];
568 // Interpreter is not in list
570 gsaRegInterps = malloc( sizeof(char*)*giRegInterps );
571 gsaRegInterps[i] = malloc( strlen(Path) );
572 strcpy(gsaRegInterps[i], Path);
573 return gsaRegInterps[i];
577 // Kernel Binary Handling
580 * \fn void *Binary_LoadKernel(const char *File)
581 * \brief Load a binary into kernel space
582 * \note This function shares much with #Binary_Load, but does it's own mapping
583 * \param File File to load into the kernel
585 void *Binary_LoadKernel(const char *File)
588 tKernelBin *pKBinary;
593 ENTER("sFile", File);
595 // Sanity Check Argument
602 int fd = VFS_Open(File, VFS_OPENFLAG_READ);
608 VFS_FInfo(fd, &info, 0);
609 mount_id = info.mount;
614 // Check if the binary has already been loaded
615 if( (pBinary = Binary_GetInfo(mount_id, inode)) )
617 for(pKBinary = glLoadedKernelLibs;
619 pKBinary = pKBinary->Next )
621 if(pKBinary->Info == pBinary) {
622 LEAVE('p', pKBinary->Base);
623 return pKBinary->Base;
628 pBinary = Binary_DoLoad(mount_id, inode, File); // Else load it
631 if(pBinary == NULL) {
637 // Now pBinary is valid (either freshly loaded or only user mapped)
638 // So, map it into kernel space
641 // Reference Executable (Makes sure that it isn't unloaded)
642 pBinary->ReferenceCount ++;
644 Binary_MapIn(pBinary, File, KLIB_LOWEST, KLIB_HIGHEST);
647 if( !Binary_Relocate( (void*)base ) )
649 Log_Warning("Binary", "Relocation of '%s' failed, unloading", File);
650 Binary_Unload( (void*)base );
651 Binary_Dereference( pBinary );
656 // Add to list (relocator must look at itself manually, not via Binary_GetSymbol)
657 pKBinary = malloc(sizeof(*pKBinary));
658 pKBinary->Base = (void*)base;
659 pKBinary->Info = pBinary;
660 SHORTLOCK( &glKBinListLock );
661 pKBinary->Next = glLoadedKernelLibs;
662 glLoadedKernelLibs = pKBinary;
663 SHORTREL( &glKBinListLock );
670 * \fn Uint Binary_Relocate(void *Base)
671 * \brief Relocates a loaded binary (used by kernel libraries)
672 * \param Base Loaded base address of binary
673 * \return Boolean Success
675 Uint Binary_Relocate(void *Base)
677 Uint32 ident = *(Uint32*) Base;
678 tBinaryType *bt = gRegBinTypes;
680 for(; bt; bt = bt->Next)
682 if( (ident & bt->Mask) == (Uint)bt->Ident )
683 return bt->Relocate( (void*)Base);
686 Log_Warning("BIN", "%p is an unknown file type. (%02x %02x %02x %02x)",
687 Base, ident&0xFF, (ident>>8)&0xFF, (ident>>16)&0xFF, (ident>>24)&0xFF);
692 * \fn int Binary_GetSymbol(char *Name, Uint *Val)
693 * \brief Get a symbol value
694 * \return Value of symbol or -1 on error
696 * Gets the value of a symbol from either the currently loaded
697 * libraries or the kernel's exports.
699 int Binary_GetSymbol(const char *Name, Uint *Val)
701 if( Binary_GetSymbolEx(Name, Val) ) return 1;
706 * \fn Uint Binary_GetSymbolEx(char *Name, Uint *Value)
707 * \brief Get a symbol value
709 * Gets the value of a symbol from either the currently loaded
710 * libraries or the kernel's exports.
712 Uint Binary_GetSymbolEx(const char *Name, Uint *Value)
716 int numKSyms = ((Uint)&gKernelSymbolsEnd-(Uint)&gKernelSymbols)/sizeof(tKernelSymbol);
719 for( i = 0; i < numKSyms; i++ )
721 if(strcmp(Name, gKernelSymbols[i].Name) == 0) {
722 *Value = gKernelSymbols[i].Value;
727 // Scan Loaded Libraries
728 for(pKBin = glLoadedKernelLibs;
730 pKBin = pKBin->Next )
732 if( Binary_FindSymbol(pKBin->Base, Name, Value) ) {
737 Log_Warning("BIN", "Unable to find symbol '%s'", Name);
742 * \fn Uint Binary_FindSymbol(void *Base, char *Name, Uint *Val)
743 * \brief Get a symbol from the specified library
744 * \param Base Base address
745 * \param Name Name of symbol to find
746 * \param Val Pointer to place final value
748 Uint Binary_FindSymbol(void *Base, const char *Name, Uint *Val)
750 Uint32 ident = *(Uint32*) Base;
751 tBinaryType *bt = gRegBinTypes;
753 for(; bt; bt = bt->Next)
755 if( (ident & bt->Mask) == (Uint)bt->Ident )
756 return bt->GetSymbol(Base, Name, Val);
759 Log_Warning("BIN", "Binary_FindSymbol - %p is an unknown file type. (%02x %02x %02x %02x)",
760 Base, ident&0xFF, ident>>8, ident>>16, ident>>24);
765 * \brief Check if a range of memory is fully free
766 * \return Inverse boolean free (0 if all pages are unmapped)
768 int Binary_int_CheckMemFree( tVAddr _start, size_t _len )
770 _len += _start & (PAGE_SIZE-1);
771 _len = (_len + PAGE_SIZE - 1) & ~(PAGE_SIZE-1);
772 _start &= ~(PAGE_SIZE-1);
773 for( ; _len > PAGE_SIZE; _len -= PAGE_SIZE, _start += PAGE_SIZE ) {
774 if( MM_GetPhysAddr(_start) != 0 )
777 if( _len == PAGE_SIZE && MM_GetPhysAddr(_start) != 0 )
784 EXPORT(Binary_FindSymbol);
785 EXPORT(Binary_Unload);