10 #include <vfs_threads.h>
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)
21 typedef struct sKernelBin {
22 struct sKernelBin *Next;
28 extern char *Threads_GetName(int ID);
29 extern tKernelSymbol gKernelSymbols[];
30 extern tKernelSymbol gKernelSymbolsEnd[];
31 extern tBinaryType gELF_Info;
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);
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|CLONE_NOUSER) == 0)
85 const char *args[2] = {stackPath, NULL};
86 LOG("stackPath = '%s'", stackPath);
87 Proc_Execve(stackPath, args, &args[1], 0);
97 int Binary_int_CacheArgs(const char **Path, const char ***ArgV, const char ***EnvP, void *DestBuffer)
99 int size, argc=0, envc=0;
108 const char **argv = *ArgV;
109 for( argc = 0; argv[argc]; argc ++ )
110 size += strlen( argv[argc] ) + 1;
114 const char **envp = *EnvP;
115 for( envc = 0; envp[envc]; envc ++ )
116 size += strlen( envp[envc] ) + 1;
118 size = (size + sizeof(void*)-1) & ~(sizeof(void*)-1); // Word align
119 size += (argc+1+envc+1)*sizeof(void*); // Arrays
122 size += strlen( *Path ) + 1;
128 strbuf = (void*)&arrays[argc+1+envc+1];
133 const char **argv = *ArgV;
134 for( i = 0; argv[i]; i ++ )
137 strcpy(strbuf, argv[i]);
138 strbuf += strlen( argv[i] ) + 1;
147 const char **envp = *EnvP;
148 for( i = 0; envp[i]; i ++ )
151 strcpy(strbuf, envp[i]);
152 strbuf += strlen( envp[i] ) + 1;
161 strcpy(strbuf, *Path);
170 * \brief Create a new process with the specified set of file descriptors
172 int Proc_SysSpawn(const char *Binary, const char **ArgV, const char **EnvP, int nFD, int *FDs)
179 // --- Save File, ArgV and EnvP
180 size = Binary_int_CacheArgs( &Binary, &ArgV, &EnvP, NULL );
181 cachebuf = malloc( size );
182 Binary_int_CacheArgs( &Binary, &ArgV, &EnvP, cachebuf );
184 // Cache the VFS handles
185 handles = VFS_SaveHandles(nFD, FDs);
187 // Create new process
188 ret = Proc_Clone(CLONE_VM|CLONE_NOUSER);
191 VFS_RestoreHandles(nFD, handles);
192 VFS_FreeSavedHandles(nFD, handles);
194 Proc_Execve(Binary, ArgV, EnvP, size);
199 VFS_FreeSavedHandles(nFD, handles);
206 * \brief Replace the current user image with another
207 * \param File File to load as the next image
208 * \param ArgV Arguments to pass to user
209 * \param EnvP User's environment
210 * \note Called Proc_ for historical reasons
212 int Proc_Execve(const char *File, const char **ArgV, const char **EnvP, int DataSize)
216 Uint base; // Uint because Proc_StartUser wants it
219 ENTER("sFile pArgV pEnvP", File, ArgV, EnvP);
221 // --- Save File, ArgV and EnvP
224 DataSize = Binary_int_CacheArgs( &File, &ArgV, &EnvP, NULL );
225 cachebuf = malloc( DataSize );
226 Binary_int_CacheArgs( &File, &ArgV, &EnvP, cachebuf );
230 for( argc = 0; ArgV && ArgV[argc]; argc ++ );
232 // --- Set Process Name
233 Threads_SetName(File);
235 // --- Clear User Address space
236 // NOTE: This is a little roundabout, maybe telling ClearUser to not touch the
237 // PPD area would be a better idea.
239 int nfd = *Threads_GetMaxFD();
241 handles = VFS_SaveHandles(nfd, NULL);
242 VFS_CloseAllUserHandles();
244 VFS_RestoreHandles(nfd, handles);
245 VFS_FreeSavedHandles(nfd, handles);
248 // --- Load new binary
249 base = Binary_Load(File, &entry);
252 Log_Warning("Binary", "Proc_Execve - Unable to load '%s'", File);
254 Threads_Exit(0, -10);
258 LOG("entry = 0x%x, base = 0x%x", entry, base);
260 // --- And... Jump to it
261 Proc_StartUser(entry, base, argc, ArgV, DataSize);
262 for(;;); // Tell GCC that we never return
266 * \brief Load a binary into the current address space
267 * \param Path Path to binary to load
268 * \param EntryPoint Pointer for exectuable entry point
269 * \return Virtual address where the binary has been loaded
271 tVAddr Binary_Load(const char *Path, tVAddr *EntryPoint)
278 ENTER("sPath pEntryPoint", Path, EntryPoint);
280 // Sanity Check Argument
286 // Check if this path has been loaded before.
288 // TODO: Implement a list of string/tBinary pairs for loaded bins
295 fd = VFS_Open(Path, VFS_OPENFLAG_READ|VFS_OPENFLAG_EXEC);
297 LOG("%s does not exist", Path);
300 VFS_FInfo(fd, &info, 0);
302 mount_id = info.mount;
304 LOG("mount_id = %i, inode = %i", mount_id, inode);
307 // TODO: Also get modifcation time?
309 // Check if the binary has already been loaded
310 if( !(pBinary = Binary_GetInfo(mount_id, inode)) )
311 pBinary = Binary_DoLoad(mount_id, inode, Path); // Else load it
314 if(pBinary == NULL) {
319 // Map into process space
320 base = Binary_MapIn(pBinary, Path, BIN_LOWEST, BIN_HIGHEST);
329 if(pBinary->Interpreter) {
331 if( Binary_Load(pBinary->Interpreter, &start) == 0 ) {
338 *EntryPoint = pBinary->Entry - pBinary->Base + base;
341 LOG("*EntryPoint = 0x%x", *EntryPoint);
343 return base; // Pass the base as an argument to the user if there is an interpreter
347 * \brief Finds a matching binary entry
348 * \param MountID Mountpoint ID of binary file
349 * \param InodeID Inode ID of the file
350 * \return Pointer to the binary definition (if already loaded)
352 tBinary *Binary_GetInfo(tMount MountID, tInode InodeID)
355 for(pBinary = glLoadedBinaries; pBinary; pBinary = pBinary->Next)
357 if(pBinary->MountID == MountID && pBinary->Inode == InodeID)
364 * \brief Maps an already-loaded binary into an address space.
365 * \param Binary Pointer to globally stored binary definition
366 * \param Path Path to the binary's file (for debug)
367 * \param LoadMin Lowest location to map to
368 * \param LoadMax Highest location to map to
369 * \return Base load address
371 tVAddr Binary_MapIn(tBinary *Binary, const char *Path, tVAddr LoadMin, tVAddr LoadMax)
376 ENTER("pBinary sPath pLoadMin pLoadMax", Binary, Path, LoadMin, LoadMax);
378 // Reference Executable (Makes sure that it isn't unloaded)
379 Binary->ReferenceCount ++;
384 // Check if base is free
387 LOG("Checking base %p", base);
388 for( i = 0; i < Binary->NumSections; i ++ )
390 if( Binary_int_CheckMemFree( Binary->LoadSections[i].Virtual, Binary->LoadSections[i].MemSize ) )
393 LOG("Address 0x%x is taken\n", Binary->LoadSections[i].Virtual);
399 // Check if the executable has no base or it is not free
402 // If so, give it a base
404 while(base >= LoadMin)
406 for( i = 0; i < Binary->NumSections; i ++ )
408 tVAddr addr = Binary->LoadSections[i].Virtual - Binary->Base + base;
409 if( Binary_int_CheckMemFree( addr, Binary->LoadSections[i].MemSize ) )
412 // If space was found, break
413 if(i == Binary->NumSections) break;
414 // Else decrement pointer and try again
415 base -= BIN_GRANUALITY;
417 LOG("Allocated base %p", base);
422 Log_Warning("Binary", "Executable '%s' cannot be loaded, no space", Path);
428 fd = VFS_OpenInode(Binary->MountID, Binary->Inode, VFS_OPENFLAG_READ);
429 for( i = 0; i < Binary->NumSections; i ++ )
431 tBinarySection *sect = &Binary->LoadSections[i];
432 Uint protflags, mapflags;
433 tVAddr addr = sect->Virtual - Binary->Base + base;
434 LOG("%i - %p to offset 0x%llx (%x)", i, addr, sect->Offset, sect->Flags);
436 protflags = MMAP_PROT_READ;
437 mapflags = MMAP_MAP_FIXED;
439 if( sect->Flags & BIN_SECTFLAG_EXEC )
440 protflags |= MMAP_PROT_EXEC;
441 // Read only pages are COW
442 if( sect->Flags & BIN_SECTFLAG_RO ) {
443 VFS_MMap( (void*)addr, sect->FileSize, protflags, MMAP_MAP_SHARED|mapflags, fd, sect->Offset );
446 protflags |= MMAP_PROT_WRITE;
447 VFS_MMap( (void*)addr, sect->FileSize, protflags, MMAP_MAP_PRIVATE|mapflags, fd, sect->Offset );
450 // Apply anonymous memory for BSS
451 if( sect->FileSize < sect->MemSize ) {
452 mapflags |= MMAP_MAP_ANONYMOUS;
454 (void*)(addr + sect->FileSize), sect->MemSize - sect->FileSize,
455 protflags, MMAP_MAP_PRIVATE|mapflags,
461 Log_Debug("Binary", "PID %i - Mapped '%s' to %p", Threads_GetPID(), Path, base);
470 * \fn Uint Binary_IsMapped(tBinary *binary)
471 * \brief Check if a binary is already mapped into the address space
472 * \param binary Binary information to check
473 * \return Current Base or 0
475 Uint Binary_IsMapped(tBinary *binary)
479 // Check prefered base
480 iBase = binary->Base;
481 if(MM_GetPage( iBase ) == (binary->Pages[0].Physical & ~0xFFF))
484 for(iBase = BIN_HIGHEST;
486 iBase -= BIN_GRANUALITY)
488 if(MM_GetPage( iBase ) == (binary->Pages[0].Physical & ~0xFFF))
497 * \fn tBinary *Binary_DoLoad(char *truePath)
498 * \brief Loads a binary file into memory
499 * \param truePath Absolute filename of binary
501 tBinary *Binary_DoLoad(tMount MountID, tInode Inode, const char *Path)
506 tBinaryType *bt = gRegBinTypes;
508 ENTER("iMountID XInode sPath", MountID, Inode, Path);
511 fp = VFS_OpenInode(MountID, Inode, VFS_OPENFLAG_READ);
513 LOG("Unable to load file, access denied");
518 LOG("fp = 0x%x", fp);
521 VFS_Read(fp, 4, &ident);
522 VFS_Seek(fp, 0, SEEK_SET);
524 LOG("ident = 0x%x", ident);
526 // Determine the type
527 for(; bt; bt = bt->Next)
529 if( (ident & bt->Mask) != (Uint32)bt->Ident )
531 LOG("bt = %p (%s)", bt, bt->Name);
532 pBinary = bt->Load(fp);
541 Log_Warning("Binary", "'%s' is an unknown file type. (%02x %02x %02x %02x)",
542 Path, ident&0xFF, (ident>>8)&0xFF, (ident>>16)&0xFF, (ident>>24)&0xFF);
547 LOG("pBinary = %p", pBinary);
550 if(pBinary == NULL) {
555 // Initialise Structure
556 pBinary->ReferenceCount = 0;
557 pBinary->MountID = MountID;
558 pBinary->Inode = Inode;
561 LOG("Interpreter: '%s'", pBinary->Interpreter);
562 LOG("Base: 0x%x, Entry: 0x%x", pBinary->Base, pBinary->Entry);
563 LOG("NumSections: %i", pBinary->NumSections);
566 SHORTLOCK(&glBinListLock);
567 pBinary->Next = glLoadedBinaries;
568 glLoadedBinaries = pBinary;
569 SHORTREL(&glBinListLock);
571 // TODO: Register the path with the binary
579 * \fn void Binary_Unload(void *Base)
580 * \brief Unload / Unmap a binary
581 * \param Base Loaded Base
582 * \note Currently used only for kernel libaries
584 void Binary_Unload(void *Base)
587 tKernelBin *prev = NULL;
590 if((Uint)Base < 0xC0000000)
592 // TODO: User Binaries
593 Log_Warning("BIN", "Unloading user binaries is currently unimplemented");
598 for(pKBin = glLoadedKernelLibs;
600 prev = pKBin, pKBin = pKBin->Next)
603 if(pKBin->Base != Base) continue;
605 for(i = 0; i < pKBin->Info->NumSections; i++)
607 // TODO: VFS_MUnmap();
609 // Dereference Binary
610 Binary_Dereference( pKBin->Info );
612 if(prev) prev->Next = pKBin->Next;
613 else glLoadedKernelLibs = pKBin->Next;
621 * \fn void Binary_Dereference(tBinary *Info)
622 * \brief Dereferences and if nessasary, deletes a binary
623 * \param Info Binary information structure
625 void Binary_Dereference(tBinary *Info)
627 // Decrement reference count
628 Info->ReferenceCount --;
630 // Check if it is still in use
631 if(Info->ReferenceCount) return;
633 /// \todo Implement binary freeing
637 * \fn char *Binary_RegInterp(char *Path)
638 * \brief Registers an Interpreter
639 * \param Path Path to interpreter provided by executable
641 char *Binary_RegInterp(char *Path)
644 // NULL Check Argument
645 if(Path == NULL) return NULL;
646 // NULL Check the array
647 if(gsaRegInterps == NULL)
650 gsaRegInterps = malloc( sizeof(char*) );
651 gsaRegInterps[0] = malloc( strlen(Path) );
652 strcpy(gsaRegInterps[0], Path);
653 return gsaRegInterps[0];
657 for( i = 0; i < giRegInterps; i++ )
659 if(strcmp(gsaRegInterps[i], Path) == 0)
660 return gsaRegInterps[i];
663 // Interpreter is not in list
665 gsaRegInterps = malloc( sizeof(char*)*giRegInterps );
666 gsaRegInterps[i] = malloc( strlen(Path) );
667 strcpy(gsaRegInterps[i], Path);
668 return gsaRegInterps[i];
672 // Kernel Binary Handling
675 * \fn void *Binary_LoadKernel(const char *File)
676 * \brief Load a binary into kernel space
677 * \note This function shares much with #Binary_Load, but does it's own mapping
678 * \param File File to load into the kernel
680 void *Binary_LoadKernel(const char *File)
683 tKernelBin *pKBinary;
688 ENTER("sFile", File);
690 // Sanity Check Argument
697 int fd = VFS_Open(File, VFS_OPENFLAG_READ);
703 VFS_FInfo(fd, &info, 0);
704 mount_id = info.mount;
709 // Check if the binary has already been loaded
710 if( (pBinary = Binary_GetInfo(mount_id, inode)) )
712 for(pKBinary = glLoadedKernelLibs;
714 pKBinary = pKBinary->Next )
716 if(pKBinary->Info == pBinary) {
717 LEAVE('p', pKBinary->Base);
718 return pKBinary->Base;
723 pBinary = Binary_DoLoad(mount_id, inode, File); // Else load it
726 if(pBinary == NULL) {
732 // Now pBinary is valid (either freshly loaded or only user mapped)
733 // So, map it into kernel space
736 // Reference Executable (Makes sure that it isn't unloaded)
737 pBinary->ReferenceCount ++;
739 Binary_MapIn(pBinary, File, KLIB_LOWEST, KLIB_HIGHEST);
742 if( !Binary_Relocate( (void*)base ) )
744 Log_Warning("Binary", "Relocation of '%s' failed, unloading", File);
745 Binary_Unload( (void*)base );
746 Binary_Dereference( pBinary );
751 // Add to list (relocator must look at itself manually, not via Binary_GetSymbol)
752 pKBinary = malloc(sizeof(*pKBinary));
753 pKBinary->Base = (void*)base;
754 pKBinary->Info = pBinary;
755 SHORTLOCK( &glKBinListLock );
756 pKBinary->Next = glLoadedKernelLibs;
757 glLoadedKernelLibs = pKBinary;
758 SHORTREL( &glKBinListLock );
765 * \fn Uint Binary_Relocate(void *Base)
766 * \brief Relocates a loaded binary (used by kernel libraries)
767 * \param Base Loaded base address of binary
768 * \return Boolean Success
770 Uint Binary_Relocate(void *Base)
772 Uint32 ident = *(Uint32*) Base;
773 tBinaryType *bt = gRegBinTypes;
775 for(; bt; bt = bt->Next)
777 if( (ident & bt->Mask) == (Uint)bt->Ident )
778 return bt->Relocate( (void*)Base);
781 Log_Warning("BIN", "%p is an unknown file type. (%02x %02x %02x %02x)",
782 Base, ident&0xFF, (ident>>8)&0xFF, (ident>>16)&0xFF, (ident>>24)&0xFF);
787 * \fn int Binary_GetSymbol(char *Name, Uint *Val)
788 * \brief Get a symbol value
789 * \return Value of symbol or -1 on error
791 * Gets the value of a symbol from either the currently loaded
792 * libraries or the kernel's exports.
794 int Binary_GetSymbol(const char *Name, Uint *Val)
796 if( Binary_GetSymbolEx(Name, Val) ) return 1;
801 * \fn Uint Binary_GetSymbolEx(char *Name, Uint *Value)
802 * \brief Get a symbol value
804 * Gets the value of a symbol from either the currently loaded
805 * libraries or the kernel's exports.
807 Uint Binary_GetSymbolEx(const char *Name, Uint *Value)
811 int numKSyms = ((Uint)&gKernelSymbolsEnd-(Uint)&gKernelSymbols)/sizeof(tKernelSymbol);
814 for( i = 0; i < numKSyms; i++ )
816 if(strcmp(Name, gKernelSymbols[i].Name) == 0) {
817 *Value = gKernelSymbols[i].Value;
822 // Scan Loaded Libraries
823 for(pKBin = glLoadedKernelLibs;
825 pKBin = pKBin->Next )
827 if( Binary_FindSymbol(pKBin->Base, Name, Value) ) {
832 Log_Warning("BIN", "Unable to find symbol '%s'", Name);
837 * \fn Uint Binary_FindSymbol(void *Base, char *Name, Uint *Val)
838 * \brief Get a symbol from the specified library
839 * \param Base Base address
840 * \param Name Name of symbol to find
841 * \param Val Pointer to place final value
843 Uint Binary_FindSymbol(void *Base, const char *Name, Uint *Val)
845 Uint32 ident = *(Uint32*) Base;
846 tBinaryType *bt = gRegBinTypes;
848 for(; bt; bt = bt->Next)
850 if( (ident & bt->Mask) == (Uint)bt->Ident )
851 return bt->GetSymbol(Base, Name, Val);
854 Log_Warning("BIN", "Binary_FindSymbol - %p is an unknown file type. (%02x %02x %02x %02x)",
855 Base, ident&0xFF, ident>>8, ident>>16, ident>>24);
860 * \brief Check if a range of memory is fully free
861 * \return Inverse boolean free (0 if all pages are unmapped)
863 int Binary_int_CheckMemFree( tVAddr _start, size_t _len )
865 _len += _start & (PAGE_SIZE-1);
866 _len = (_len + PAGE_SIZE - 1) & ~(PAGE_SIZE-1);
867 _start &= ~(PAGE_SIZE-1);
868 for( ; _len > PAGE_SIZE; _len -= PAGE_SIZE, _start += PAGE_SIZE ) {
869 if( MM_GetPhysAddr(_start) != 0 )
872 if( _len == PAGE_SIZE && MM_GetPhysAddr(_start) != 0 )
879 EXPORT(Binary_FindSymbol);
880 EXPORT(Binary_Unload);