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 size_t 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 size_t Binary_int_CacheArgs(const char **Path, const char ***ArgV, const char ***EnvP, void *DestBuffer)
110 const char **argv = *ArgV;
111 for( argc = 0; argv[argc]; argc ++ )
112 size += strlen( argv[argc] ) + 1;
116 const char **envp = *EnvP;
117 for( envc = 0; envp[envc]; envc ++ )
118 size += strlen( envp[envc] ) + 1;
120 size = (size + sizeof(void*)-1) & ~(sizeof(void*)-1); // Word align
121 size += (argc+1+envc+1)*sizeof(void*); // Arrays
124 size += strlen( *Path ) + 1;
130 strbuf = (void*)&arrays[argc+1+envc+1];
135 const char **argv = *ArgV;
136 for( i = 0; argv[i]; i ++ )
139 strcpy(strbuf, argv[i]);
140 strbuf += strlen( argv[i] ) + 1;
149 const char **envp = *EnvP;
150 for( i = 0; envp[i]; i ++ )
153 strcpy(strbuf, envp[i]);
154 strbuf += strlen( envp[i] ) + 1;
163 strcpy(strbuf, *Path);
172 * \brief Create a new process with the specified set of file descriptors
174 int Proc_SysSpawn(const char *Binary, const char **ArgV, const char **EnvP, int nFD, int *FDs)
177 // --- Save File, ArgV and EnvP
178 size_t size = Binary_int_CacheArgs( &Binary, &ArgV, &EnvP, NULL );
179 void *cachebuf = malloc( size );
180 Binary_int_CacheArgs( &Binary, &ArgV, &EnvP, cachebuf );
182 // Cache the VFS handles
183 void *handles = VFS_SaveHandles(nFD, FDs);
185 // Create new process
186 tPID ret = Proc_Clone(CLONE_VM|CLONE_NOUSER);
189 VFS_RestoreHandles(nFD, handles);
190 VFS_FreeSavedHandles(nFD, handles);
192 Proc_int_Execve(Binary, ArgV, EnvP, size, 0);
197 VFS_FreeSavedHandles(nFD, handles);
205 * \brief Replace the current user image with another
206 * \param File File to load as the next image
207 * \param ArgV Arguments to pass to user
208 * \param EnvP User's environment
209 * \note Called Proc_ for historical reasons
211 int Proc_Execve(const char *File, const char **ArgV, const char **EnvP, int DataSize)
213 return Proc_int_Execve(File, ArgV, EnvP, DataSize, 1);
216 int Proc_int_Execve(const char *File, const char **ArgV, const char **EnvP, int DataSize, bool bClearUser)
220 Uint base; // Uint because Proc_StartUser wants it
223 ENTER("sFile pArgV pEnvP", File, ArgV, EnvP);
225 // --- Save File, ArgV and EnvP
228 DataSize = Binary_int_CacheArgs( &File, &ArgV, &EnvP, NULL );
229 cachebuf = malloc( DataSize );
230 Binary_int_CacheArgs( &File, &ArgV, &EnvP, cachebuf );
234 for( argc = 0; ArgV && ArgV[argc]; argc ++ );
236 // --- Set Process Name
237 Threads_SetName(File);
239 // --- Clear User Address space
240 // NOTE: This is a little roundabout, maybe telling ClearUser to not touch the
241 // PPD area would be a better idea.
244 int nfd = *Threads_GetMaxFD();
246 handles = VFS_SaveHandles(nfd, NULL);
247 VFS_CloseAllUserHandles();
249 VFS_RestoreHandles(nfd, handles);
250 VFS_FreeSavedHandles(nfd, handles);
253 // --- Load new binary
254 base = Binary_Load(File, &entry);
257 Log_Warning("Binary", "Proc_Execve - Unable to load '%s' [errno=%i]", File, errno);
259 Threads_Exit(0, -10);
263 LOG("entry = 0x%x, base = 0x%x", entry, base);
265 // --- And... Jump to it
266 Proc_StartUser(entry, base, argc, ArgV, DataSize);
267 for(;;); // Tell GCC that we never return
271 * \brief Load a binary into the current address space
272 * \param Path Path to binary to load
273 * \param EntryPoint Pointer for exectuable entry point
274 * \return Virtual address where the binary has been loaded
276 tVAddr Binary_Load(const char *Path, tVAddr *EntryPoint)
283 ENTER("sPath pEntryPoint", Path, EntryPoint);
285 // Sanity Check Argument
291 // Check if this path has been loaded before.
293 // TODO: Implement a list of string/tBinary pairs for loaded bins
300 fd = VFS_Open(Path, VFS_OPENFLAG_READ|VFS_OPENFLAG_EXEC);
302 LOG("%s does not exist", Path);
305 VFS_FInfo(fd, &info, 0);
307 mount_id = info.mount;
309 LOG("mount_id = %i, inode = %i", mount_id, inode);
312 // TODO: Also get modifcation time?
314 // Check if the binary has already been loaded
315 if( !(pBinary = Binary_GetInfo(mount_id, inode)) )
316 pBinary = Binary_DoLoad(mount_id, inode, Path); // Else load it
319 if(pBinary == NULL) {
324 // Map into process space
325 base = Binary_MapIn(pBinary, Path, BIN_LOWEST, BIN_HIGHEST);
334 if(pBinary->Interpreter) {
336 if( Binary_Load(pBinary->Interpreter, &start) == 0 ) {
343 *EntryPoint = pBinary->Entry - pBinary->Base + base;
346 LOG("*EntryPoint = 0x%x", *EntryPoint);
348 return base; // Pass the base as an argument to the user if there is an interpreter
352 * \brief Finds a matching binary entry
353 * \param MountID Mountpoint ID of binary file
354 * \param InodeID Inode ID of the file
355 * \return Pointer to the binary definition (if already loaded)
357 tBinary *Binary_GetInfo(tMount MountID, tInode InodeID)
360 for(pBinary = glLoadedBinaries; pBinary; pBinary = pBinary->Next)
362 if(pBinary->MountID == MountID && pBinary->Inode == InodeID)
369 * \brief Maps an already-loaded binary into an address space.
370 * \param Binary Pointer to globally stored binary definition
371 * \param Path Path to the binary's file (for debug)
372 * \param LoadMin Lowest location to map to
373 * \param LoadMax Highest location to map to
374 * \return Base load address
376 tVAddr Binary_MapIn(tBinary *Binary, const char *Path, tVAddr LoadMin, tVAddr LoadMax)
381 ENTER("pBinary sPath pLoadMin pLoadMax", Binary, Path, LoadMin, LoadMax);
383 // Reference Executable (Makes sure that it isn't unloaded)
384 Binary->ReferenceCount ++;
389 // Check if base is free
392 LOG("Checking base %p", base);
393 for( i = 0; i < Binary->NumSections; i ++ )
395 if( Binary_int_CheckMemFree( Binary->LoadSections[i].Virtual, Binary->LoadSections[i].MemSize ) )
398 LOG("Address 0x%x is taken\n", Binary->LoadSections[i].Virtual);
404 // Check if the executable has no base or it is not free
407 // If so, give it a base
409 while(base >= LoadMin)
411 for( i = 0; i < Binary->NumSections; i ++ )
413 tVAddr addr = Binary->LoadSections[i].Virtual - Binary->Base + base;
414 size_t size = Binary->LoadSections[i].MemSize;
415 if( addr + size > LoadMax )
417 if( Binary_int_CheckMemFree( addr, size ) )
420 // If space was found, break
421 if(i == Binary->NumSections) break;
422 // Else decrement pointer and try again
423 base -= BIN_GRANUALITY;
425 LOG("Allocated base %p", base);
430 Log_Warning("Binary", "Executable '%s' cannot be loaded, no space", Path);
436 if( Binary->MountID )
437 fd = VFS_OpenInode(Binary->MountID, Binary->Inode, VFS_OPENFLAG_READ);
439 fd = VFS_Open(Path, VFS_OPENFLAG_READ);
440 for( i = 0; i < Binary->NumSections; i ++ )
442 tBinarySection *sect = &Binary->LoadSections[i];
443 Uint protflags, mapflags;
444 tVAddr addr = sect->Virtual - Binary->Base + base;
445 LOG("%i - %p, 0x%x bytes from offset 0x%llx (%x)", i, addr, sect->FileSize, sect->Offset, sect->Flags);
447 protflags = MMAP_PROT_READ;
448 mapflags = MMAP_MAP_FIXED;
450 if( sect->Flags & BIN_SECTFLAG_EXEC )
451 protflags |= MMAP_PROT_EXEC;
452 // Read only pages are COW
453 if( sect->Flags & BIN_SECTFLAG_RO ) {
454 VFS_MMap( (void*)addr, sect->FileSize, protflags, MMAP_MAP_SHARED|mapflags, fd, sect->Offset );
457 protflags |= MMAP_PROT_WRITE;
458 VFS_MMap( (void*)addr, sect->FileSize, protflags, MMAP_MAP_PRIVATE|mapflags, fd, sect->Offset );
461 // Apply anonymous memory for BSS
462 if( sect->FileSize < sect->MemSize ) {
463 mapflags |= MMAP_MAP_ANONYMOUS;
465 (void*)(addr + sect->FileSize), sect->MemSize - sect->FileSize,
466 protflags, MMAP_MAP_PRIVATE|mapflags,
472 Log_Debug("Binary", "PID %i - Mapped '%s' to %p", Threads_GetPID(), Path, base);
481 * \fn Uint Binary_IsMapped(tBinary *binary)
482 * \brief Check if a binary is already mapped into the address space
483 * \param binary Binary information to check
484 * \return Current Base or 0
486 Uint Binary_IsMapped(tBinary *binary)
490 // Check prefered base
491 iBase = binary->Base;
492 if(MM_GetPage( iBase ) == (binary->Pages[0].Physical & ~0xFFF))
495 for(iBase = BIN_HIGHEST;
497 iBase -= BIN_GRANUALITY)
499 if(MM_GetPage( iBase ) == (binary->Pages[0].Physical & ~0xFFF))
508 * \fn tBinary *Binary_DoLoad(char *truePath)
509 * \brief Loads a binary file into memory
510 * \param truePath Absolute filename of binary
512 tBinary *Binary_DoLoad(tMount MountID, tInode Inode, const char *Path)
517 tBinaryType *bt = gRegBinTypes;
519 ENTER("iMountID XInode sPath", MountID, Inode, Path);
524 fp = VFS_OpenInode(MountID, Inode, VFS_OPENFLAG_READ);
528 fp = VFS_Open(Path, VFS_OPENFLAG_READ);
531 LOG("Unable to load file, access denied");
536 LOG("fp = 0x%x", fp);
539 VFS_Read(fp, 4, &ident);
540 VFS_Seek(fp, 0, SEEK_SET);
542 LOG("ident = 0x%x", ident);
544 // Determine the type
545 for(; bt; bt = bt->Next)
547 if( (ident & bt->Mask) != (Uint32)bt->Ident )
549 LOG("bt = %p (%s)", bt, bt->Name);
550 pBinary = bt->Load(fp);
559 Log_Warning("Binary", "'%s' is an unknown file type. (%02x %02x %02x %02x)",
560 Path, ident&0xFF, (ident>>8)&0xFF, (ident>>16)&0xFF, (ident>>24)&0xFF);
565 LOG("pBinary = %p", pBinary);
568 if(pBinary == NULL) {
573 // Initialise Structure
574 pBinary->ReferenceCount = 0;
575 pBinary->MountID = MountID;
576 pBinary->Inode = Inode;
579 LOG("Interpreter: '%s'", pBinary->Interpreter);
580 LOG("Base: 0x%x, Entry: 0x%x", pBinary->Base, pBinary->Entry);
581 LOG("NumSections: %i", pBinary->NumSections);
584 SHORTLOCK(&glBinListLock);
585 pBinary->Next = glLoadedBinaries;
586 glLoadedBinaries = pBinary;
587 SHORTREL(&glBinListLock);
589 // TODO: Register the path with the binary
597 * \fn void Binary_Unload(void *Base)
598 * \brief Unload / Unmap a binary
599 * \param Base Loaded Base
600 * \note Currently used only for kernel libaries
602 void Binary_Unload(void *Base)
605 tKernelBin *prev = NULL;
608 if((Uint)Base < 0xC0000000)
610 // TODO: User Binaries
611 Log_Warning("BIN", "Unloading user binaries is currently unimplemented");
616 for(pKBin = glLoadedKernelLibs;
618 prev = pKBin, pKBin = pKBin->Next)
621 if(pKBin->Base != Base) continue;
623 for(i = 0; i < pKBin->Info->NumSections; i++)
625 // TODO: VFS_MUnmap();
627 // Dereference Binary
628 Binary_Dereference( pKBin->Info );
630 if(prev) prev->Next = pKBin->Next;
631 else glLoadedKernelLibs = pKBin->Next;
639 * \fn void Binary_Dereference(tBinary *Info)
640 * \brief Dereferences and if nessasary, deletes a binary
641 * \param Info Binary information structure
643 void Binary_Dereference(tBinary *Info)
645 // Decrement reference count
646 Info->ReferenceCount --;
648 // Check if it is still in use
649 if(Info->ReferenceCount) return;
651 /// \todo Implement binary freeing
655 * \fn char *Binary_RegInterp(char *Path)
656 * \brief Registers an Interpreter
657 * \param Path Path to interpreter provided by executable
659 char *Binary_RegInterp(char *Path)
662 // NULL Check Argument
663 if(Path == NULL) return NULL;
664 // NULL Check the array
665 if(gsaRegInterps == NULL)
668 gsaRegInterps = malloc( sizeof(char*) );
669 gsaRegInterps[0] = malloc( strlen(Path) );
670 strcpy(gsaRegInterps[0], Path);
671 return gsaRegInterps[0];
675 for( i = 0; i < giRegInterps; i++ )
677 if(strcmp(gsaRegInterps[i], Path) == 0)
678 return gsaRegInterps[i];
681 // Interpreter is not in list
683 gsaRegInterps = malloc( sizeof(char*)*giRegInterps );
684 gsaRegInterps[i] = malloc( strlen(Path) );
685 strcpy(gsaRegInterps[i], Path);
686 return gsaRegInterps[i];
690 // Kernel Binary Handling
693 * \fn void *Binary_LoadKernel(const char *File)
694 * \brief Load a binary into kernel space
695 * \note This function shares much with #Binary_Load, but does it's own mapping
696 * \param File File to load into the kernel
698 void *Binary_LoadKernel(const char *File)
701 tKernelBin *pKBinary;
706 ENTER("sFile", File);
708 // Sanity Check Argument
715 int fd = VFS_Open(File, VFS_OPENFLAG_READ);
718 LOG("Opening failed");
722 VFS_FInfo(fd, &info, 0);
723 mount_id = info.mount;
726 LOG("Mount %i, Inode %lli", mount_id, inode);
729 // Check if the binary has already been loaded
730 if( (pBinary = Binary_GetInfo(mount_id, inode)) )
732 for(pKBinary = glLoadedKernelLibs;
734 pKBinary = pKBinary->Next )
736 if(pKBinary->Info == pBinary) {
737 LOG("Already loaded");
738 LEAVE('p', pKBinary->Base);
739 return pKBinary->Base;
744 pBinary = Binary_DoLoad(mount_id, inode, File); // Else load it
747 if(pBinary == NULL) {
752 LOG("Loaded as %p", pBinary);
754 // Now pBinary is valid (either freshly loaded or only user mapped)
755 // So, map it into kernel space
758 // Reference Executable (Makes sure that it isn't unloaded)
759 pBinary->ReferenceCount ++;
761 base = Binary_MapIn(pBinary, File, KLIB_LOWEST, KLIB_HIGHEST);
768 // TODO: Could this cause race conditions if a binary isn't fully loaded when used
769 pKBinary = malloc(sizeof(*pKBinary));
770 pKBinary->Base = (void*)base;
771 pKBinary->Info = pBinary;
772 SHORTLOCK( &glKBinListLock );
773 pKBinary->Next = glLoadedKernelLibs;
774 glLoadedKernelLibs = pKBinary;
775 SHORTREL( &glKBinListLock );
782 * \fn Uint Binary_Relocate(void *Base)
783 * \brief Relocates a loaded binary (used by kernel libraries)
784 * \param Base Loaded base address of binary
785 * \return Boolean Success
787 Uint Binary_Relocate(void *Base)
789 Uint32 ident = *(Uint32*) Base;
790 tBinaryType *bt = gRegBinTypes;
792 for( ; bt; bt = bt->Next)
794 if( (ident & bt->Mask) == (Uint)bt->Ident )
795 return bt->Relocate( (void*)Base);
798 Log_Warning("BIN", "%p is an unknown file type. (%02x %02x %02x %02x)",
799 Base, ident&0xFF, (ident>>8)&0xFF, (ident>>16)&0xFF, (ident>>24)&0xFF);
804 * \fn int Binary_GetSymbol(char *Name, Uint *Val)
805 * \brief Get a symbol value
806 * \return Value of symbol or -1 on error
808 * Gets the value of a symbol from either the currently loaded
809 * libraries or the kernel's exports.
811 int Binary_GetSymbol(const char *Name, Uint *Val)
813 if( Binary_GetSymbolEx(Name, Val) ) return 1;
818 * \fn Uint Binary_GetSymbolEx(char *Name, Uint *Value)
819 * \brief Get a symbol value
821 * Gets the value of a symbol from either the currently loaded
822 * libraries or the kernel's exports.
824 Uint Binary_GetSymbolEx(const char *Name, Uint *Value)
827 int numKSyms = ((Uint)&gKernelSymbolsEnd-(Uint)&gKernelSymbols)/sizeof(tKernelSymbol);
830 for( int i = 0; i < numKSyms; i++ )
832 if(strcmp(Name, gKernelSymbols[i].Name) == 0) {
833 LOG("KSym %s = %p", gKernelSymbols[i].Name, gKernelSymbols[i].Value);
834 *Value = gKernelSymbols[i].Value;
840 // Scan Loaded Libraries
841 for(pKBin = glLoadedKernelLibs;
843 pKBin = pKBin->Next )
845 if( Binary_FindSymbol(pKBin->Base, Name, Value) ) {
850 Log_Warning("BIN", "Unable to find symbol '%s'", Name);
855 * \fn Uint Binary_FindSymbol(void *Base, char *Name, Uint *Val)
856 * \brief Get a symbol from the specified library
857 * \param Base Base address
858 * \param Name Name of symbol to find
859 * \param Val Pointer to place final value
861 Uint Binary_FindSymbol(void *Base, const char *Name, Uint *Val)
863 Uint32 ident = *(Uint32*) Base;
864 tBinaryType *bt = gRegBinTypes;
866 for(; bt; bt = bt->Next)
868 if( (ident & bt->Mask) == (Uint)bt->Ident )
869 return bt->GetSymbol(Base, Name, Val);
872 Log_Warning("BIN", "Binary_FindSymbol - %p is an unknown file type. (%02x %02x %02x %02x)",
873 Base, ident&0xFF, ident>>8, ident>>16, ident>>24);
878 * \brief Check if a range of memory is fully free
879 * \return Inverse boolean free (0 if all pages are unmapped)
881 int Binary_int_CheckMemFree( tVAddr _start, size_t _len )
883 ENTER("p_start x_len", _start, _len);
885 _len += _start & (PAGE_SIZE-1);
886 _len = (_len + PAGE_SIZE - 1) & ~(PAGE_SIZE-1);
887 _start &= ~(PAGE_SIZE-1);
888 LOG("_start = %p, _len = 0x%x", _start, _len);
889 for( ; _len > PAGE_SIZE; _len -= PAGE_SIZE, _start += PAGE_SIZE ) {
890 if( MM_GetPhysAddr( (void*)_start ) != 0 ) {
895 if( _len == PAGE_SIZE && MM_GetPhysAddr( (void*)_start ) != 0 ) {
905 EXPORT(Binary_FindSymbol);
906 EXPORT(Binary_Unload);