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 base; // 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 base = Binary_Load(savedFile, &entry);
166 Log_Warning("Binary", "Proc_Execve - Unable to load '%s'", Threads_GetName(-1));
168 Threads_Exit(0, -10);
172 LOG("entry = 0x%x, base = 0x%x", entry, base);
174 // MM_DumpTables(0, KERNEL_BASE);
177 // --- And... Jump to it
178 Proc_StartUser(entry, base, argc, argvSaved, argenvBytes);
179 for(;;); // Tell GCC that we never return
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
186 * \return Virtual address where the binary has been loaded
188 tVAddr Binary_Load(const char *Path, tVAddr *EntryPoint)
195 ENTER("sPath pEntryPoint", Path, EntryPoint);
197 // Sanity Check Argument
203 // Check if this path has been loaded before.
205 // TODO: Implement a list of string/tBinary pairs for loaded bins
212 fd = VFS_Open(Path, VFS_OPENFLAG_READ|VFS_OPENFLAG_EXEC);
214 LOG("%s does not exist", Path);
217 VFS_FInfo(fd, &info, 0);
219 mount_id = info.mount;
221 LOG("mount_id = %i, inode = %i", mount_id, inode);
224 // TODO: Also get modifcation time?
226 // Check if the binary has already been loaded
227 if( !(pBinary = Binary_GetInfo(mount_id, inode)) )
228 pBinary = Binary_DoLoad(mount_id, inode, Path); // Else load it
231 if(pBinary == NULL) {
236 // Map into process space
237 base = Binary_MapIn(pBinary, Path, BIN_LOWEST, BIN_HIGHEST);
246 if(pBinary->Interpreter) {
248 if( Binary_Load(pBinary->Interpreter, &start) == 0 ) {
255 *EntryPoint = pBinary->Entry - pBinary->Base + base;
258 LOG("*EntryPoint = 0x%x", *EntryPoint);
260 return base; // Pass the base as an argument to the user if there is an interpreter
264 * \brief Finds a matching binary entry
265 * \param TruePath File Identifier (True path name)
267 tBinary *Binary_GetInfo(tMount MountID, tInode InodeID)
270 pBinary = glLoadedBinaries;
273 if(pBinary->MountID == MountID && pBinary->Inode == InodeID)
275 pBinary = pBinary->Next;
281 \fn Uint Binary_MapIn(tBinary *binary)
282 \brief Maps an already-loaded binary into an address space.
283 \param binary Pointer to globally stored data.
285 tVAddr Binary_MapIn(tBinary *Binary, const char *Path, tVAddr LoadMin, tVAddr LoadMax)
290 ENTER("pBinary sPath pLoadMin pLoadMax", Binary, Path, LoadMin, LoadMax);
292 // Reference Executable (Makes sure that it isn't unloaded)
293 Binary->ReferenceCount ++;
298 // Check if base is free
301 LOG("Checking base %p", base);
302 for(i=0;i<Binary->NumSections;i++)
304 if( Binary_int_CheckMemFree( Binary->LoadSections[i].Virtual, Binary->LoadSections[i].MemSize ) )
307 LOG("Address 0x%x is taken\n", Binary->LoadSections[i].Virtual);
313 // Check if the executable has no base or it is not free
316 // If so, give it a base
318 while(base >= LoadMin)
320 for( i = 0; i < Binary->NumSections; i ++ )
322 tVAddr addr = Binary->LoadSections[i].Virtual - Binary->Base + base;
323 if( Binary_int_CheckMemFree( addr, Binary->LoadSections[i].MemSize ) )
326 // If space was found, break
327 if(i == Binary->NumSections) break;
328 // Else decrement pointer and try again
329 base -= BIN_GRANUALITY;
331 LOG("Allocated base %p", base);
336 Log_Warning("Binary", "Executable '%s' cannot be loaded, no space", Path);
342 fd = VFS_OpenInode(Binary->MountID, Binary->Inode, VFS_OPENFLAG_READ);
343 for( i = 0; i < Binary->NumSections; i ++ )
345 tBinarySection *sect = &Binary->LoadSections[i];
346 Uint protflags, mapflags;
347 tVAddr addr = sect->Virtual - Binary->Base + base;
348 LOG("%i - %p to offset 0x%llx (%x)", i, addr, sect->Offset, sect->Flags);
350 protflags = MMAP_PROT_READ;
351 mapflags = MMAP_MAP_FIXED;
353 if( sect->Flags & BIN_SECTFLAG_EXEC )
354 protflags |= MMAP_PROT_EXEC;
355 if( sect->Flags & BIN_SECTFLAG_RO ) {
356 VFS_MMap( (void*)addr, sect->FileSize, protflags, MMAP_MAP_SHARED|mapflags, fd, sect->Offset );
359 protflags |= MMAP_PROT_WRITE;
360 VFS_MMap( (void*)addr, sect->FileSize, protflags, MMAP_MAP_PRIVATE|mapflags, fd, sect->Offset );
362 if( sect->FileSize < sect->MemSize ) {
363 mapflags |= MMAP_MAP_ANONYMOUS;
365 (void*)(addr + sect->FileSize), sect->MemSize - sect->FileSize,
366 protflags, MMAP_MAP_PRIVATE|mapflags,
369 // memset((void*)(addr + sect->FileSize), 0, sect->MemSize - sect->FileSize);
373 Log_Debug("Binary", "PID %i - Mapped '%s' to 0x%x", Threads_GetPID(), Path, base);
376 //LOG("*0x%x = 0x%x\n", binary->Pages[0].Virtual, *(Uint*)binary->Pages[0].Virtual);
384 * \fn Uint Binary_IsMapped(tBinary *binary)
385 * \brief Check if a binary is already mapped into the address space
386 * \param binary Binary information to check
387 * \return Current Base or 0
389 Uint Binary_IsMapped(tBinary *binary)
393 // Check prefered base
394 iBase = binary->Base;
395 if(MM_GetPage( iBase ) == (binary->Pages[0].Physical & ~0xFFF))
398 for(iBase = BIN_HIGHEST;
400 iBase -= BIN_GRANUALITY)
402 if(MM_GetPage( iBase ) == (binary->Pages[0].Physical & ~0xFFF))
411 * \fn tBinary *Binary_DoLoad(char *truePath)
412 * \brief Loads a binary file into memory
413 * \param truePath Absolute filename of binary
415 tBinary *Binary_DoLoad(tMount MountID, tInode Inode, const char *Path)
420 tBinaryType *bt = gRegBinTypes;
422 ENTER("iMountID XInode sPath", MountID, Inode, Path);
425 fp = VFS_OpenInode(MountID, Inode, VFS_OPENFLAG_READ);
427 LOG("Unable to load file, access denied");
432 LOG("fp = 0x%x", fp);
435 VFS_Read(fp, 4, &ident);
436 VFS_Seek(fp, 0, SEEK_SET);
438 LOG("ident = 0x%x", ident);
440 // Determine the type
441 for(; bt; bt = bt->Next)
443 if( (ident & bt->Mask) != (Uint32)bt->Ident )
445 LOG("bt = %p (%s)", bt, bt->Name);
446 pBinary = bt->Load(fp);
450 LOG("pBinary = %p", pBinary);
457 Log_Warning("Binary", "'%s' is an unknown file type. (%02x %02x %02x %02x)",
458 Path, ident&0xFF, (ident>>8)&0xFF, (ident>>16)&0xFF, (ident>>24)&0xFF);
464 if(pBinary == NULL) {
469 // Initialise Structure
470 pBinary->ReferenceCount = 0;
471 pBinary->MountID = MountID;
472 pBinary->Inode = Inode;
475 LOG("Interpreter: '%s'", pBinary->Interpreter);
476 LOG("Base: 0x%x, Entry: 0x%x", pBinary->Base, pBinary->Entry);
477 LOG("NumSections: %i", pBinary->NumSections);
480 SHORTLOCK(&glBinListLock);
481 pBinary->Next = glLoadedBinaries;
482 glLoadedBinaries = pBinary;
483 SHORTREL(&glBinListLock);
485 // TODO: Register the path with the binary
493 * \fn void Binary_Unload(void *Base)
494 * \brief Unload / Unmap a binary
495 * \param Base Loaded Base
496 * \note Currently used only for kernel libaries
498 void Binary_Unload(void *Base)
501 tKernelBin *prev = NULL;
504 if((Uint)Base < 0xC0000000)
506 // TODO: User Binaries
507 Log_Warning("BIN", "Unloading user binaries is currently unimplemented");
512 for(pKBin = glLoadedKernelLibs;
514 prev = pKBin, pKBin = pKBin->Next)
517 if(pKBin->Base != Base) continue;
519 for(i = 0; i < pKBin->Info->NumSections; i++)
521 // TODO: VFS_MUnmap();
523 // Dereference Binary
524 Binary_Dereference( pKBin->Info );
526 if(prev) prev->Next = pKBin->Next;
527 else glLoadedKernelLibs = pKBin->Next;
535 * \fn void Binary_Dereference(tBinary *Info)
536 * \brief Dereferences and if nessasary, deletes a binary
537 * \param Info Binary information structure
539 void Binary_Dereference(tBinary *Info)
541 // Decrement reference count
542 Info->ReferenceCount --;
544 // Check if it is still in use
545 if(Info->ReferenceCount) return;
547 /// \todo Implement binary freeing
551 * \fn char *Binary_RegInterp(char *Path)
552 * \brief Registers an Interpreter
553 * \param Path Path to interpreter provided by executable
555 char *Binary_RegInterp(char *Path)
558 // NULL Check Argument
559 if(Path == NULL) return NULL;
560 // NULL Check the array
561 if(gsaRegInterps == NULL)
564 gsaRegInterps = malloc( sizeof(char*) );
565 gsaRegInterps[0] = malloc( strlen(Path) );
566 strcpy(gsaRegInterps[0], Path);
567 return gsaRegInterps[0];
571 for( i = 0; i < giRegInterps; i++ )
573 if(strcmp(gsaRegInterps[i], Path) == 0)
574 return gsaRegInterps[i];
577 // Interpreter is not in list
579 gsaRegInterps = malloc( sizeof(char*)*giRegInterps );
580 gsaRegInterps[i] = malloc( strlen(Path) );
581 strcpy(gsaRegInterps[i], Path);
582 return gsaRegInterps[i];
586 // Kernel Binary Handling
589 * \fn void *Binary_LoadKernel(const char *File)
590 * \brief Load a binary into kernel space
591 * \note This function shares much with #Binary_Load, but does it's own mapping
592 * \param File File to load into the kernel
594 void *Binary_LoadKernel(const char *File)
597 tKernelBin *pKBinary;
602 ENTER("sFile", File);
604 // Sanity Check Argument
611 int fd = VFS_Open(File, VFS_OPENFLAG_READ);
617 VFS_FInfo(fd, &info, 0);
618 mount_id = info.mount;
623 // Check if the binary has already been loaded
624 if( (pBinary = Binary_GetInfo(mount_id, inode)) )
626 for(pKBinary = glLoadedKernelLibs;
628 pKBinary = pKBinary->Next )
630 if(pKBinary->Info == pBinary) {
631 LEAVE('p', pKBinary->Base);
632 return pKBinary->Base;
637 pBinary = Binary_DoLoad(mount_id, inode, File); // Else load it
640 if(pBinary == NULL) {
646 // Now pBinary is valid (either freshly loaded or only user mapped)
647 // So, map it into kernel space
650 // Reference Executable (Makes sure that it isn't unloaded)
651 pBinary->ReferenceCount ++;
653 Binary_MapIn(pBinary, File, KLIB_LOWEST, KLIB_HIGHEST);
656 if( !Binary_Relocate( (void*)base ) )
658 Log_Warning("Binary", "Relocation of '%s' failed, unloading", File);
659 Binary_Unload( (void*)base );
660 Binary_Dereference( pBinary );
665 // Add to list (relocator must look at itself manually, not via Binary_GetSymbol)
666 pKBinary = malloc(sizeof(*pKBinary));
667 pKBinary->Base = (void*)base;
668 pKBinary->Info = pBinary;
669 SHORTLOCK( &glKBinListLock );
670 pKBinary->Next = glLoadedKernelLibs;
671 glLoadedKernelLibs = pKBinary;
672 SHORTREL( &glKBinListLock );
679 * \fn Uint Binary_Relocate(void *Base)
680 * \brief Relocates a loaded binary (used by kernel libraries)
681 * \param Base Loaded base address of binary
682 * \return Boolean Success
684 Uint Binary_Relocate(void *Base)
686 Uint32 ident = *(Uint32*) Base;
687 tBinaryType *bt = gRegBinTypes;
689 for(; bt; bt = bt->Next)
691 if( (ident & bt->Mask) == (Uint)bt->Ident )
692 return bt->Relocate( (void*)Base);
695 Log_Warning("BIN", "%p is an unknown file type. (%02x %02x %02x %02x)",
696 Base, ident&0xFF, (ident>>8)&0xFF, (ident>>16)&0xFF, (ident>>24)&0xFF);
701 * \fn int Binary_GetSymbol(char *Name, Uint *Val)
702 * \brief Get a symbol value
703 * \return Value of symbol or -1 on error
705 * Gets the value of a symbol from either the currently loaded
706 * libraries or the kernel's exports.
708 int Binary_GetSymbol(const char *Name, Uint *Val)
710 if( Binary_GetSymbolEx(Name, Val) ) return 1;
715 * \fn Uint Binary_GetSymbolEx(char *Name, Uint *Value)
716 * \brief Get a symbol value
718 * Gets the value of a symbol from either the currently loaded
719 * libraries or the kernel's exports.
721 Uint Binary_GetSymbolEx(const char *Name, Uint *Value)
725 int numKSyms = ((Uint)&gKernelSymbolsEnd-(Uint)&gKernelSymbols)/sizeof(tKernelSymbol);
728 for( i = 0; i < numKSyms; i++ )
730 if(strcmp(Name, gKernelSymbols[i].Name) == 0) {
731 *Value = gKernelSymbols[i].Value;
736 // Scan Loaded Libraries
737 for(pKBin = glLoadedKernelLibs;
739 pKBin = pKBin->Next )
741 if( Binary_FindSymbol(pKBin->Base, Name, Value) ) {
746 Log_Warning("BIN", "Unable to find symbol '%s'", Name);
751 * \fn Uint Binary_FindSymbol(void *Base, char *Name, Uint *Val)
752 * \brief Get a symbol from the specified library
753 * \param Base Base address
754 * \param Name Name of symbol to find
755 * \param Val Pointer to place final value
757 Uint Binary_FindSymbol(void *Base, const char *Name, Uint *Val)
759 Uint32 ident = *(Uint32*) Base;
760 tBinaryType *bt = gRegBinTypes;
762 for(; bt; bt = bt->Next)
764 if( (ident & bt->Mask) == (Uint)bt->Ident )
765 return bt->GetSymbol(Base, Name, Val);
768 Log_Warning("BIN", "Binary_FindSymbol - %p is an unknown file type. (%02x %02x %02x %02x)",
769 Base, ident&0xFF, ident>>8, ident>>16, ident>>24);
774 * \brief Check if a range of memory is fully free
775 * \return Inverse boolean free (0 if all pages are unmapped)
777 int Binary_int_CheckMemFree( tVAddr _start, size_t _len )
779 _len += _start & (PAGE_SIZE-1);
780 _len = (_len + PAGE_SIZE - 1) & ~(PAGE_SIZE-1);
781 _start &= ~(PAGE_SIZE-1);
782 for( ; _len > PAGE_SIZE; _len -= PAGE_SIZE, _start += PAGE_SIZE ) {
783 if( MM_GetPhysAddr(_start) != 0 )
786 if( _len == PAGE_SIZE && MM_GetPhysAddr(_start) != 0 )
793 EXPORT(Binary_FindSymbol);
794 EXPORT(Binary_Unload);