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 int Proc_int_Execve(const char *File, const char **ArgV, const char **EnvP, int DataSize, bool bClearUser);
36 tVAddr Binary_Load(const char *Path, tVAddr *EntryPoint);
37 tBinary *Binary_GetInfo(tMount MountID, tInode InodeID);
38 tVAddr Binary_MapIn(tBinary *Binary, const char *Path, tVAddr LoadMin, tVAddr LoadMax);
39 tVAddr Binary_IsMapped(tBinary *Binary);
40 tBinary *Binary_DoLoad(tMount MountID, tInode Inode, const char *Path);
41 void Binary_Dereference(tBinary *Info);
43 Uint Binary_Relocate(void *Base);
45 Uint Binary_GetSymbolEx(const char *Name, Uint *Value);
47 Uint Binary_FindSymbol(void *Base, const char *Name, Uint *Val);
49 int Binary_int_CheckMemFree( tVAddr _start, size_t _len );
52 tShortSpinlock glBinListLock;
53 tBinary *glLoadedBinaries = NULL;
54 char **gsaRegInterps = NULL;
56 tShortSpinlock glKBinListLock;
57 tKernelBin *glLoadedKernelLibs;
58 tBinaryType *gRegBinTypes = &gELF_Info;
62 * \brief Registers a binary type
64 int Binary_RegisterType(tBinaryType *Type)
66 Type->Next = gRegBinTypes;
72 * \fn int Proc_Spawn(const char *Path)
74 int Proc_Spawn(const char *Path)
76 char stackPath[strlen(Path)+1];
79 strcpy(stackPath, Path);
81 LOG("stackPath = '%s'", stackPath);
83 if(Proc_Clone(CLONE_VM|CLONE_NOUSER) == 0)
86 const char *args[2] = {stackPath, NULL};
87 LOG("stackPath = '%s'", stackPath);
88 Proc_Execve(stackPath, args, &args[1], 0);
98 int Binary_int_CacheArgs(const char **Path, const char ***ArgV, const char ***EnvP, void *DestBuffer)
100 int size, argc=0, envc=0;
109 const char **argv = *ArgV;
110 for( argc = 0; argv[argc]; argc ++ )
111 size += strlen( argv[argc] ) + 1;
115 const char **envp = *EnvP;
116 for( envc = 0; envp[envc]; envc ++ )
117 size += strlen( envp[envc] ) + 1;
119 size = (size + sizeof(void*)-1) & ~(sizeof(void*)-1); // Word align
120 size += (argc+1+envc+1)*sizeof(void*); // Arrays
123 size += strlen( *Path ) + 1;
129 strbuf = (void*)&arrays[argc+1+envc+1];
134 const char **argv = *ArgV;
135 for( i = 0; argv[i]; i ++ )
138 strcpy(strbuf, argv[i]);
139 strbuf += strlen( argv[i] ) + 1;
148 const char **envp = *EnvP;
149 for( i = 0; envp[i]; i ++ )
152 strcpy(strbuf, envp[i]);
153 strbuf += strlen( envp[i] ) + 1;
162 strcpy(strbuf, *Path);
171 * \brief Create a new process with the specified set of file descriptors
173 int Proc_SysSpawn(const char *Binary, const char **ArgV, const char **EnvP, int nFD, int *FDs)
180 // --- Save File, ArgV and EnvP
181 size = Binary_int_CacheArgs( &Binary, &ArgV, &EnvP, NULL );
182 cachebuf = malloc( size );
183 Binary_int_CacheArgs( &Binary, &ArgV, &EnvP, cachebuf );
185 // Cache the VFS handles
186 handles = VFS_SaveHandles(nFD, FDs);
188 // Create new process
189 ret = Proc_Clone(CLONE_VM|CLONE_NOUSER);
192 VFS_RestoreHandles(nFD, handles);
193 VFS_FreeSavedHandles(nFD, handles);
195 Proc_int_Execve(Binary, ArgV, EnvP, size, 0);
200 VFS_FreeSavedHandles(nFD, handles);
208 * \brief Replace the current user image with another
209 * \param File File to load as the next image
210 * \param ArgV Arguments to pass to user
211 * \param EnvP User's environment
212 * \note Called Proc_ for historical reasons
214 int Proc_Execve(const char *File, const char **ArgV, const char **EnvP, int DataSize)
216 return Proc_int_Execve(File, ArgV, EnvP, DataSize, 1);
219 int Proc_int_Execve(const char *File, const char **ArgV, const char **EnvP, int DataSize, bool bClearUser)
223 Uint base; // Uint because Proc_StartUser wants it
226 ENTER("sFile pArgV pEnvP", File, ArgV, EnvP);
228 // --- Save File, ArgV and EnvP
231 DataSize = Binary_int_CacheArgs( &File, &ArgV, &EnvP, NULL );
232 cachebuf = malloc( DataSize );
233 Binary_int_CacheArgs( &File, &ArgV, &EnvP, cachebuf );
237 for( argc = 0; ArgV && ArgV[argc]; argc ++ );
239 // --- Set Process Name
240 Threads_SetName(File);
242 // --- Clear User Address space
243 // NOTE: This is a little roundabout, maybe telling ClearUser to not touch the
244 // PPD area would be a better idea.
247 int nfd = *Threads_GetMaxFD();
249 handles = VFS_SaveHandles(nfd, NULL);
250 VFS_CloseAllUserHandles();
252 VFS_RestoreHandles(nfd, handles);
253 VFS_FreeSavedHandles(nfd, handles);
256 // --- Load new binary
257 base = Binary_Load(File, &entry);
260 Log_Warning("Binary", "Proc_Execve - Unable to load '%s' [errno=%i]", File, errno);
262 Threads_Exit(0, -10);
266 LOG("entry = 0x%x, base = 0x%x", entry, base);
268 // --- And... Jump to it
269 Proc_StartUser(entry, base, argc, ArgV, DataSize);
270 for(;;); // Tell GCC that we never return
274 * \brief Load a binary into the current address space
275 * \param Path Path to binary to load
276 * \param EntryPoint Pointer for exectuable entry point
277 * \return Virtual address where the binary has been loaded
279 tVAddr Binary_Load(const char *Path, tVAddr *EntryPoint)
286 ENTER("sPath pEntryPoint", Path, EntryPoint);
288 // Sanity Check Argument
294 // Check if this path has been loaded before.
296 // TODO: Implement a list of string/tBinary pairs for loaded bins
303 fd = VFS_Open(Path, VFS_OPENFLAG_READ|VFS_OPENFLAG_EXEC);
305 LOG("%s does not exist", Path);
308 VFS_FInfo(fd, &info, 0);
310 mount_id = info.mount;
312 LOG("mount_id = %i, inode = %i", mount_id, inode);
315 // TODO: Also get modifcation time?
317 // Check if the binary has already been loaded
318 if( !(pBinary = Binary_GetInfo(mount_id, inode)) )
319 pBinary = Binary_DoLoad(mount_id, inode, Path); // Else load it
322 if(pBinary == NULL) {
327 // Map into process space
328 base = Binary_MapIn(pBinary, Path, BIN_LOWEST, BIN_HIGHEST);
337 if(pBinary->Interpreter) {
339 if( Binary_Load(pBinary->Interpreter, &start) == 0 ) {
346 *EntryPoint = pBinary->Entry - pBinary->Base + base;
349 LOG("*EntryPoint = 0x%x", *EntryPoint);
351 return base; // Pass the base as an argument to the user if there is an interpreter
355 * \brief Finds a matching binary entry
356 * \param MountID Mountpoint ID of binary file
357 * \param InodeID Inode ID of the file
358 * \return Pointer to the binary definition (if already loaded)
360 tBinary *Binary_GetInfo(tMount MountID, tInode InodeID)
363 for(pBinary = glLoadedBinaries; pBinary; pBinary = pBinary->Next)
365 if(pBinary->MountID == MountID && pBinary->Inode == InodeID)
372 * \brief Maps an already-loaded binary into an address space.
373 * \param Binary Pointer to globally stored binary definition
374 * \param Path Path to the binary's file (for debug)
375 * \param LoadMin Lowest location to map to
376 * \param LoadMax Highest location to map to
377 * \return Base load address
379 tVAddr Binary_MapIn(tBinary *Binary, const char *Path, tVAddr LoadMin, tVAddr LoadMax)
384 ENTER("pBinary sPath pLoadMin pLoadMax", Binary, Path, LoadMin, LoadMax);
386 // Reference Executable (Makes sure that it isn't unloaded)
387 Binary->ReferenceCount ++;
392 // Check if base is free
395 LOG("Checking base %p", base);
396 for( i = 0; i < Binary->NumSections; i ++ )
398 if( Binary_int_CheckMemFree( Binary->LoadSections[i].Virtual, Binary->LoadSections[i].MemSize ) )
401 LOG("Address 0x%x is taken\n", Binary->LoadSections[i].Virtual);
407 // Check if the executable has no base or it is not free
410 // If so, give it a base
412 while(base >= LoadMin)
414 for( i = 0; i < Binary->NumSections; i ++ )
416 tVAddr addr = Binary->LoadSections[i].Virtual - Binary->Base + base;
417 size_t size = Binary->LoadSections[i].MemSize;
418 if( addr + size > LoadMax )
420 if( Binary_int_CheckMemFree( addr, size ) )
423 // If space was found, break
424 if(i == Binary->NumSections) break;
425 // Else decrement pointer and try again
426 base -= BIN_GRANUALITY;
428 LOG("Allocated base %p", base);
433 Log_Warning("Binary", "Executable '%s' cannot be loaded, no space", Path);
439 if( Binary->MountID )
440 fd = VFS_OpenInode(Binary->MountID, Binary->Inode, VFS_OPENFLAG_READ);
442 fd = VFS_Open(Path, VFS_OPENFLAG_READ);
443 for( i = 0; i < Binary->NumSections; i ++ )
445 tBinarySection *sect = &Binary->LoadSections[i];
446 Uint protflags, mapflags;
447 tVAddr addr = sect->Virtual - Binary->Base + base;
448 LOG("%i - %p, 0x%x bytes from offset 0x%llx (%x)", i, addr, sect->FileSize, sect->Offset, sect->Flags);
450 protflags = MMAP_PROT_READ;
451 mapflags = MMAP_MAP_FIXED;
453 if( sect->Flags & BIN_SECTFLAG_EXEC )
454 protflags |= MMAP_PROT_EXEC;
455 // Read only pages are COW
456 if( sect->Flags & BIN_SECTFLAG_RO ) {
457 VFS_MMap( (void*)addr, sect->FileSize, protflags, MMAP_MAP_SHARED|mapflags, fd, sect->Offset );
460 protflags |= MMAP_PROT_WRITE;
461 VFS_MMap( (void*)addr, sect->FileSize, protflags, MMAP_MAP_PRIVATE|mapflags, fd, sect->Offset );
464 // Apply anonymous memory for BSS
465 if( sect->FileSize < sect->MemSize ) {
466 mapflags |= MMAP_MAP_ANONYMOUS;
468 (void*)(addr + sect->FileSize), sect->MemSize - sect->FileSize,
469 protflags, MMAP_MAP_PRIVATE|mapflags,
475 Log_Debug("Binary", "PID %i - Mapped '%s' to %p", Threads_GetPID(), Path, base);
484 * \fn Uint Binary_IsMapped(tBinary *binary)
485 * \brief Check if a binary is already mapped into the address space
486 * \param binary Binary information to check
487 * \return Current Base or 0
489 Uint Binary_IsMapped(tBinary *binary)
493 // Check prefered base
494 iBase = binary->Base;
495 if(MM_GetPage( iBase ) == (binary->Pages[0].Physical & ~0xFFF))
498 for(iBase = BIN_HIGHEST;
500 iBase -= BIN_GRANUALITY)
502 if(MM_GetPage( iBase ) == (binary->Pages[0].Physical & ~0xFFF))
511 * \fn tBinary *Binary_DoLoad(char *truePath)
512 * \brief Loads a binary file into memory
513 * \param truePath Absolute filename of binary
515 tBinary *Binary_DoLoad(tMount MountID, tInode Inode, const char *Path)
520 tBinaryType *bt = gRegBinTypes;
522 ENTER("iMountID XInode sPath", MountID, Inode, Path);
527 fp = VFS_OpenInode(MountID, Inode, VFS_OPENFLAG_READ);
531 fp = VFS_Open(Path, VFS_OPENFLAG_READ);
534 LOG("Unable to load file, access denied");
539 LOG("fp = 0x%x", fp);
542 VFS_Read(fp, 4, &ident);
543 VFS_Seek(fp, 0, SEEK_SET);
545 LOG("ident = 0x%x", ident);
547 // Determine the type
548 for(; bt; bt = bt->Next)
550 if( (ident & bt->Mask) != (Uint32)bt->Ident )
552 LOG("bt = %p (%s)", bt, bt->Name);
553 pBinary = bt->Load(fp);
562 Log_Warning("Binary", "'%s' is an unknown file type. (%02x %02x %02x %02x)",
563 Path, ident&0xFF, (ident>>8)&0xFF, (ident>>16)&0xFF, (ident>>24)&0xFF);
568 LOG("pBinary = %p", pBinary);
571 if(pBinary == NULL) {
576 // Initialise Structure
577 pBinary->ReferenceCount = 0;
578 pBinary->MountID = MountID;
579 pBinary->Inode = Inode;
582 LOG("Interpreter: '%s'", pBinary->Interpreter);
583 LOG("Base: 0x%x, Entry: 0x%x", pBinary->Base, pBinary->Entry);
584 LOG("NumSections: %i", pBinary->NumSections);
587 SHORTLOCK(&glBinListLock);
588 pBinary->Next = glLoadedBinaries;
589 glLoadedBinaries = pBinary;
590 SHORTREL(&glBinListLock);
592 // TODO: Register the path with the binary
600 * \fn void Binary_Unload(void *Base)
601 * \brief Unload / Unmap a binary
602 * \param Base Loaded Base
603 * \note Currently used only for kernel libaries
605 void Binary_Unload(void *Base)
608 tKernelBin *prev = NULL;
611 if((Uint)Base < 0xC0000000)
613 // TODO: User Binaries
614 Log_Warning("BIN", "Unloading user binaries is currently unimplemented");
619 for(pKBin = glLoadedKernelLibs;
621 prev = pKBin, pKBin = pKBin->Next)
624 if(pKBin->Base != Base) continue;
626 for(i = 0; i < pKBin->Info->NumSections; i++)
628 // TODO: VFS_MUnmap();
630 // Dereference Binary
631 Binary_Dereference( pKBin->Info );
633 if(prev) prev->Next = pKBin->Next;
634 else glLoadedKernelLibs = pKBin->Next;
642 * \fn void Binary_Dereference(tBinary *Info)
643 * \brief Dereferences and if nessasary, deletes a binary
644 * \param Info Binary information structure
646 void Binary_Dereference(tBinary *Info)
648 // Decrement reference count
649 Info->ReferenceCount --;
651 // Check if it is still in use
652 if(Info->ReferenceCount) return;
654 /// \todo Implement binary freeing
658 * \fn char *Binary_RegInterp(char *Path)
659 * \brief Registers an Interpreter
660 * \param Path Path to interpreter provided by executable
662 char *Binary_RegInterp(char *Path)
665 // NULL Check Argument
666 if(Path == NULL) return NULL;
667 // NULL Check the array
668 if(gsaRegInterps == NULL)
671 gsaRegInterps = malloc( sizeof(char*) );
672 gsaRegInterps[0] = malloc( strlen(Path) );
673 strcpy(gsaRegInterps[0], Path);
674 return gsaRegInterps[0];
678 for( i = 0; i < giRegInterps; i++ )
680 if(strcmp(gsaRegInterps[i], Path) == 0)
681 return gsaRegInterps[i];
684 // Interpreter is not in list
686 gsaRegInterps = malloc( sizeof(char*)*giRegInterps );
687 gsaRegInterps[i] = malloc( strlen(Path) );
688 strcpy(gsaRegInterps[i], Path);
689 return gsaRegInterps[i];
693 // Kernel Binary Handling
696 * \fn void *Binary_LoadKernel(const char *File)
697 * \brief Load a binary into kernel space
698 * \note This function shares much with #Binary_Load, but does it's own mapping
699 * \param File File to load into the kernel
701 void *Binary_LoadKernel(const char *File)
704 tKernelBin *pKBinary;
709 ENTER("sFile", File);
711 // Sanity Check Argument
718 int fd = VFS_Open(File, VFS_OPENFLAG_READ);
721 LOG("Opening failed");
725 VFS_FInfo(fd, &info, 0);
726 mount_id = info.mount;
729 LOG("Mount %i, Inode %lli", mount_id, inode);
732 // Check if the binary has already been loaded
733 if( (pBinary = Binary_GetInfo(mount_id, inode)) )
735 for(pKBinary = glLoadedKernelLibs;
737 pKBinary = pKBinary->Next )
739 if(pKBinary->Info == pBinary) {
740 LOG("Already loaded");
741 LEAVE('p', pKBinary->Base);
742 return pKBinary->Base;
747 pBinary = Binary_DoLoad(mount_id, inode, File); // Else load it
750 if(pBinary == NULL) {
755 LOG("Loaded as %p", pBinary);
757 // Now pBinary is valid (either freshly loaded or only user mapped)
758 // So, map it into kernel space
761 // Reference Executable (Makes sure that it isn't unloaded)
762 pBinary->ReferenceCount ++;
764 base = Binary_MapIn(pBinary, File, KLIB_LOWEST, KLIB_HIGHEST);
771 // TODO: Could this cause race conditions if a binary isn't fully loaded when used
772 pKBinary = malloc(sizeof(*pKBinary));
773 pKBinary->Base = (void*)base;
774 pKBinary->Info = pBinary;
775 SHORTLOCK( &glKBinListLock );
776 pKBinary->Next = glLoadedKernelLibs;
777 glLoadedKernelLibs = pKBinary;
778 SHORTREL( &glKBinListLock );
785 * \fn Uint Binary_Relocate(void *Base)
786 * \brief Relocates a loaded binary (used by kernel libraries)
787 * \param Base Loaded base address of binary
788 * \return Boolean Success
790 Uint Binary_Relocate(void *Base)
792 Uint32 ident = *(Uint32*) Base;
793 tBinaryType *bt = gRegBinTypes;
795 for( ; bt; bt = bt->Next)
797 if( (ident & bt->Mask) == (Uint)bt->Ident )
798 return bt->Relocate( (void*)Base);
801 Log_Warning("BIN", "%p is an unknown file type. (%02x %02x %02x %02x)",
802 Base, ident&0xFF, (ident>>8)&0xFF, (ident>>16)&0xFF, (ident>>24)&0xFF);
807 * \fn int Binary_GetSymbol(char *Name, Uint *Val)
808 * \brief Get a symbol value
809 * \return Value of symbol or -1 on error
811 * Gets the value of a symbol from either the currently loaded
812 * libraries or the kernel's exports.
814 int Binary_GetSymbol(const char *Name, Uint *Val)
816 if( Binary_GetSymbolEx(Name, Val) ) return 1;
821 * \fn Uint Binary_GetSymbolEx(char *Name, Uint *Value)
822 * \brief Get a symbol value
824 * Gets the value of a symbol from either the currently loaded
825 * libraries or the kernel's exports.
827 Uint Binary_GetSymbolEx(const char *Name, Uint *Value)
831 int numKSyms = ((Uint)&gKernelSymbolsEnd-(Uint)&gKernelSymbols)/sizeof(tKernelSymbol);
833 LOG("numKSyms = %i", numKSyms);
836 for( i = 0; i < numKSyms; i++ )
838 LOG("KSym %s = %p", gKernelSymbols[i].Name, gKernelSymbols[i].Value);
839 if(strcmp(Name, gKernelSymbols[i].Name) == 0) {
840 *Value = gKernelSymbols[i].Value;
845 // Scan Loaded Libraries
846 for(pKBin = glLoadedKernelLibs;
848 pKBin = pKBin->Next )
850 if( Binary_FindSymbol(pKBin->Base, Name, Value) ) {
855 Log_Warning("BIN", "Unable to find symbol '%s'", Name);
860 * \fn Uint Binary_FindSymbol(void *Base, char *Name, Uint *Val)
861 * \brief Get a symbol from the specified library
862 * \param Base Base address
863 * \param Name Name of symbol to find
864 * \param Val Pointer to place final value
866 Uint Binary_FindSymbol(void *Base, const char *Name, Uint *Val)
868 Uint32 ident = *(Uint32*) Base;
869 tBinaryType *bt = gRegBinTypes;
871 for(; bt; bt = bt->Next)
873 if( (ident & bt->Mask) == (Uint)bt->Ident )
874 return bt->GetSymbol(Base, Name, Val);
877 Log_Warning("BIN", "Binary_FindSymbol - %p is an unknown file type. (%02x %02x %02x %02x)",
878 Base, ident&0xFF, ident>>8, ident>>16, ident>>24);
883 * \brief Check if a range of memory is fully free
884 * \return Inverse boolean free (0 if all pages are unmapped)
886 int Binary_int_CheckMemFree( tVAddr _start, size_t _len )
888 ENTER("p_start x_len", _start, _len);
890 _len += _start & (PAGE_SIZE-1);
891 _len = (_len + PAGE_SIZE - 1) & ~(PAGE_SIZE-1);
892 _start &= ~(PAGE_SIZE-1);
893 LOG("_start = %p, _len = 0x%x", _start, _len);
894 for( ; _len > PAGE_SIZE; _len -= PAGE_SIZE, _start += PAGE_SIZE ) {
895 if( MM_GetPhysAddr( (void*)_start ) != 0 ) {
900 if( _len == PAGE_SIZE && MM_GetPhysAddr( (void*)_start ) != 0 ) {
910 EXPORT(Binary_FindSymbol);
911 EXPORT(Binary_Unload);