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 ) {
337 Log_Error("Binary", "Can't load interpeter '%s' for '%s'",
338 pBinary->Interpreter, Path);
345 *EntryPoint = pBinary->Entry - pBinary->Base + base;
348 LOG("*EntryPoint = 0x%x", *EntryPoint);
350 return base; // Pass the base as an argument to the user if there is an interpreter
354 * \brief Finds a matching binary entry
355 * \param MountID Mountpoint ID of binary file
356 * \param InodeID Inode ID of the file
357 * \return Pointer to the binary definition (if already loaded)
359 tBinary *Binary_GetInfo(tMount MountID, tInode InodeID)
362 for(pBinary = glLoadedBinaries; pBinary; pBinary = pBinary->Next)
364 if(pBinary->MountID == MountID && pBinary->Inode == InodeID)
371 * \brief Maps an already-loaded binary into an address space.
372 * \param Binary Pointer to globally stored binary definition
373 * \param Path Path to the binary's file (for debug)
374 * \param LoadMin Lowest location to map to
375 * \param LoadMax Highest location to map to
376 * \return Base load address
378 tVAddr Binary_MapIn(tBinary *Binary, const char *Path, tVAddr LoadMin, tVAddr LoadMax)
383 ENTER("pBinary sPath pLoadMin pLoadMax", Binary, Path, LoadMin, LoadMax);
385 // Reference Executable (Makes sure that it isn't unloaded)
386 Binary->ReferenceCount ++;
391 // Check if base is free
394 LOG("Checking base %p", base);
395 for( i = 0; i < Binary->NumSections; i ++ )
397 if( Binary_int_CheckMemFree( Binary->LoadSections[i].Virtual, Binary->LoadSections[i].MemSize ) )
400 LOG("Address 0x%x is taken\n", Binary->LoadSections[i].Virtual);
406 // Check if the executable has no base or it is not free
409 // If so, give it a base
411 while(base >= LoadMin)
413 for( i = 0; i < Binary->NumSections; i ++ )
415 tVAddr addr = Binary->LoadSections[i].Virtual - Binary->Base + base;
416 size_t size = Binary->LoadSections[i].MemSize;
417 if( addr + size > LoadMax )
419 if( Binary_int_CheckMemFree( addr, size ) )
422 // If space was found, break
423 if(i == Binary->NumSections) break;
424 // Else decrement pointer and try again
425 base -= BIN_GRANUALITY;
427 LOG("Allocated base %p", base);
432 Log_Warning("Binary", "Executable '%s' cannot be loaded, no space", Path);
438 if( Binary->MountID )
439 fd = VFS_OpenInode(Binary->MountID, Binary->Inode, VFS_OPENFLAG_READ);
441 fd = VFS_Open(Path, VFS_OPENFLAG_READ);
442 for( i = 0; i < Binary->NumSections; i ++ )
444 tBinarySection *sect = &Binary->LoadSections[i];
445 Uint protflags, mapflags;
446 tVAddr addr = sect->Virtual - Binary->Base + base;
447 LOG("%i - %p, 0x%x bytes from offset 0x%llx (%x)", i, addr, sect->FileSize, sect->Offset, sect->Flags);
449 protflags = MMAP_PROT_READ;
450 mapflags = MMAP_MAP_FIXED;
452 if( sect->Flags & BIN_SECTFLAG_EXEC )
453 protflags |= MMAP_PROT_EXEC;
454 // Read only pages are COW
455 if( sect->Flags & BIN_SECTFLAG_RO ) {
456 VFS_MMap( (void*)addr, sect->FileSize, protflags, MMAP_MAP_SHARED|mapflags, fd, sect->Offset );
459 protflags |= MMAP_PROT_WRITE;
460 VFS_MMap( (void*)addr, sect->FileSize, protflags, MMAP_MAP_PRIVATE|mapflags, fd, sect->Offset );
463 // Apply anonymous memory for BSS
464 if( sect->FileSize < sect->MemSize ) {
465 mapflags |= MMAP_MAP_ANONYMOUS;
467 (void*)(addr + sect->FileSize), sect->MemSize - sect->FileSize,
468 protflags, MMAP_MAP_PRIVATE|mapflags,
474 Log_Debug("Binary", "PID %i - Mapped '%s' to %p", Threads_GetPID(), Path, base);
483 * \fn Uint Binary_IsMapped(tBinary *binary)
484 * \brief Check if a binary is already mapped into the address space
485 * \param binary Binary information to check
486 * \return Current Base or 0
488 Uint Binary_IsMapped(tBinary *binary)
492 // Check prefered base
493 iBase = binary->Base;
494 if(MM_GetPage( iBase ) == (binary->Pages[0].Physical & ~0xFFF))
497 for(iBase = BIN_HIGHEST;
499 iBase -= BIN_GRANUALITY)
501 if(MM_GetPage( iBase ) == (binary->Pages[0].Physical & ~0xFFF))
510 * \fn tBinary *Binary_DoLoad(char *truePath)
511 * \brief Loads a binary file into memory
512 * \param truePath Absolute filename of binary
514 tBinary *Binary_DoLoad(tMount MountID, tInode Inode, const char *Path)
519 tBinaryType *bt = gRegBinTypes;
521 ENTER("iMountID XInode sPath", MountID, Inode, Path);
526 fp = VFS_OpenInode(MountID, Inode, VFS_OPENFLAG_READ);
530 fp = VFS_Open(Path, VFS_OPENFLAG_READ);
533 LOG("Unable to load file, access denied");
538 LOG("fp = 0x%x", fp);
541 VFS_Read(fp, 4, &ident);
542 VFS_Seek(fp, 0, SEEK_SET);
544 LOG("ident = 0x%x", ident);
546 // Determine the type
547 for(; bt; bt = bt->Next)
549 if( (ident & bt->Mask) != (Uint32)bt->Ident )
551 LOG("bt = %p (%s)", bt, bt->Name);
552 pBinary = bt->Load(fp);
561 Log_Warning("Binary", "'%s' is an unknown file type. (%02x %02x %02x %02x)",
562 Path, ident&0xFF, (ident>>8)&0xFF, (ident>>16)&0xFF, (ident>>24)&0xFF);
567 LOG("pBinary = %p", pBinary);
570 if(pBinary == NULL) {
575 // Initialise Structure
576 pBinary->ReferenceCount = 0;
577 pBinary->MountID = MountID;
578 pBinary->Inode = Inode;
581 LOG("Interpreter: '%s'", pBinary->Interpreter);
582 LOG("Base: 0x%x, Entry: 0x%x", pBinary->Base, pBinary->Entry);
583 LOG("NumSections: %i", pBinary->NumSections);
586 SHORTLOCK(&glBinListLock);
587 pBinary->Next = glLoadedBinaries;
588 glLoadedBinaries = pBinary;
589 SHORTREL(&glBinListLock);
591 // TODO: Register the path with the binary
599 * \fn void Binary_Unload(void *Base)
600 * \brief Unload / Unmap a binary
601 * \param Base Loaded Base
602 * \note Currently used only for kernel libaries
604 void Binary_Unload(void *Base)
607 tKernelBin *prev = NULL;
610 if((Uint)Base < 0xC0000000)
612 // TODO: User Binaries
613 Log_Warning("BIN", "Unloading user binaries is currently unimplemented");
618 for(pKBin = glLoadedKernelLibs;
620 prev = pKBin, pKBin = pKBin->Next)
623 if(pKBin->Base != Base) continue;
625 for(i = 0; i < pKBin->Info->NumSections; i++)
627 // TODO: VFS_MUnmap();
629 // Dereference Binary
630 Binary_Dereference( pKBin->Info );
632 if(prev) prev->Next = pKBin->Next;
633 else glLoadedKernelLibs = pKBin->Next;
641 * \fn void Binary_Dereference(tBinary *Info)
642 * \brief Dereferences and if nessasary, deletes a binary
643 * \param Info Binary information structure
645 void Binary_Dereference(tBinary *Info)
647 // Decrement reference count
648 Info->ReferenceCount --;
650 // Check if it is still in use
651 if(Info->ReferenceCount) return;
653 /// \todo Implement binary freeing
657 * \fn char *Binary_RegInterp(char *Path)
658 * \brief Registers an Interpreter
659 * \param Path Path to interpreter provided by executable
661 char *Binary_RegInterp(char *Path)
664 // NULL Check Argument
665 if(Path == NULL) return NULL;
666 // NULL Check the array
667 if(gsaRegInterps == NULL)
670 gsaRegInterps = malloc( sizeof(char*) );
671 gsaRegInterps[0] = malloc( strlen(Path) );
672 strcpy(gsaRegInterps[0], Path);
673 return gsaRegInterps[0];
677 for( i = 0; i < giRegInterps; i++ )
679 if(strcmp(gsaRegInterps[i], Path) == 0)
680 return gsaRegInterps[i];
683 // Interpreter is not in list
685 gsaRegInterps = malloc( sizeof(char*)*giRegInterps );
686 gsaRegInterps[i] = malloc( strlen(Path) );
687 strcpy(gsaRegInterps[i], Path);
688 return gsaRegInterps[i];
692 // Kernel Binary Handling
695 * \fn void *Binary_LoadKernel(const char *File)
696 * \brief Load a binary into kernel space
697 * \note This function shares much with #Binary_Load, but does it's own mapping
698 * \param File File to load into the kernel
700 void *Binary_LoadKernel(const char *File)
703 tKernelBin *pKBinary;
708 ENTER("sFile", File);
710 // Sanity Check Argument
717 int fd = VFS_Open(File, VFS_OPENFLAG_READ);
720 LOG("Opening failed");
724 VFS_FInfo(fd, &info, 0);
725 mount_id = info.mount;
728 LOG("Mount %i, Inode %lli", mount_id, inode);
731 // Check if the binary has already been loaded
732 if( (pBinary = Binary_GetInfo(mount_id, inode)) )
734 for(pKBinary = glLoadedKernelLibs;
736 pKBinary = pKBinary->Next )
738 if(pKBinary->Info == pBinary) {
739 LOG("Already loaded");
740 LEAVE('p', pKBinary->Base);
741 return pKBinary->Base;
746 pBinary = Binary_DoLoad(mount_id, inode, File); // Else load it
749 if(pBinary == NULL) {
754 LOG("Loaded as %p", pBinary);
756 // Now pBinary is valid (either freshly loaded or only user mapped)
757 // So, map it into kernel space
760 // Reference Executable (Makes sure that it isn't unloaded)
761 pBinary->ReferenceCount ++;
763 base = Binary_MapIn(pBinary, File, KLIB_LOWEST, KLIB_HIGHEST);
770 // TODO: Could this cause race conditions if a binary isn't fully loaded when used
771 pKBinary = malloc(sizeof(*pKBinary));
772 pKBinary->Base = (void*)base;
773 pKBinary->Info = pBinary;
774 SHORTLOCK( &glKBinListLock );
775 pKBinary->Next = glLoadedKernelLibs;
776 glLoadedKernelLibs = pKBinary;
777 SHORTREL( &glKBinListLock );
784 * \fn Uint Binary_Relocate(void *Base)
785 * \brief Relocates a loaded binary (used by kernel libraries)
786 * \param Base Loaded base address of binary
787 * \return Boolean Success
789 Uint Binary_Relocate(void *Base)
791 Uint32 ident = *(Uint32*) Base;
792 tBinaryType *bt = gRegBinTypes;
794 for( ; bt; bt = bt->Next)
796 if( (ident & bt->Mask) == (Uint)bt->Ident )
797 return bt->Relocate( (void*)Base);
800 Log_Warning("BIN", "%p is an unknown file type. (%02x %02x %02x %02x)",
801 Base, ident&0xFF, (ident>>8)&0xFF, (ident>>16)&0xFF, (ident>>24)&0xFF);
806 * \fn int Binary_GetSymbol(char *Name, Uint *Val)
807 * \brief Get a symbol value
808 * \return Value of symbol or -1 on error
810 * Gets the value of a symbol from either the currently loaded
811 * libraries or the kernel's exports.
813 int Binary_GetSymbol(const char *Name, Uint *Val)
815 if( Binary_GetSymbolEx(Name, Val) ) return 1;
820 * \fn Uint Binary_GetSymbolEx(char *Name, Uint *Value)
821 * \brief Get a symbol value
823 * Gets the value of a symbol from either the currently loaded
824 * libraries or the kernel's exports.
826 Uint Binary_GetSymbolEx(const char *Name, Uint *Value)
829 int numKSyms = ((Uint)&gKernelSymbolsEnd-(Uint)&gKernelSymbols)/sizeof(tKernelSymbol);
832 for( int i = 0; i < numKSyms; i++ )
834 if(strcmp(Name, gKernelSymbols[i].Name) == 0) {
835 LOG("KSym %s = %p", gKernelSymbols[i].Name, gKernelSymbols[i].Value);
836 *Value = gKernelSymbols[i].Value;
842 // Scan Loaded Libraries
843 for(pKBin = glLoadedKernelLibs;
845 pKBin = pKBin->Next )
847 if( Binary_FindSymbol(pKBin->Base, Name, Value) ) {
852 Log_Warning("BIN", "Unable to find symbol '%s'", Name);
857 * \fn Uint Binary_FindSymbol(void *Base, char *Name, Uint *Val)
858 * \brief Get a symbol from the specified library
859 * \param Base Base address
860 * \param Name Name of symbol to find
861 * \param Val Pointer to place final value
863 Uint Binary_FindSymbol(void *Base, const char *Name, Uint *Val)
865 Uint32 ident = *(Uint32*) Base;
866 tBinaryType *bt = gRegBinTypes;
868 for(; bt; bt = bt->Next)
870 if( (ident & bt->Mask) == (Uint)bt->Ident )
871 return bt->GetSymbol(Base, Name, Val);
874 Log_Warning("BIN", "Binary_FindSymbol - %p is an unknown file type. (%02x %02x %02x %02x)",
875 Base, ident&0xFF, ident>>8, ident>>16, ident>>24);
880 * \brief Check if a range of memory is fully free
881 * \return Inverse boolean free (0 if all pages are unmapped)
883 int Binary_int_CheckMemFree( tVAddr _start, size_t _len )
885 ENTER("p_start x_len", _start, _len);
887 _len += _start & (PAGE_SIZE-1);
888 _len = (_len + PAGE_SIZE - 1) & ~(PAGE_SIZE-1);
889 _start &= ~(PAGE_SIZE-1);
890 LOG("_start = %p, _len = 0x%x", _start, _len);
891 for( ; _len > PAGE_SIZE; _len -= PAGE_SIZE, _start += PAGE_SIZE ) {
892 if( MM_GetPhysAddr( (void*)_start ) != 0 ) {
897 if( _len == PAGE_SIZE && MM_GetPhysAddr( (void*)_start ) != 0 ) {
907 EXPORT(Binary_FindSymbol);
908 EXPORT(Binary_Unload);