11 #define BIN_LOWEST MM_USER_MIN // 1MiB
12 #define BIN_GRANUALITY 0x10000 // 64KiB
13 //! \todo Move 0xBC000000 to mm_virt.h
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 int Proc_Clone(Uint *Err, Uint Flags);
28 extern char *Threads_GetName(int ID);
29 extern void Threads_Exit(int, int);
30 extern Uint MM_ClearUser();
31 extern void Proc_StartUser(Uint Entrypoint, Uint *Bases, int ArgC, char **ArgV, char **EnvP, int DataSize);
32 extern tKernelSymbol gKernelSymbols[];
33 extern void gKernelSymbolsEnd;
34 extern tBinaryType gELF_Info;
37 int Proc_Execve(char *File, char **ArgV, char **EnvP);
38 Uint Binary_Load(char *file, Uint *entryPoint);
39 tBinary *Binary_GetInfo(char *truePath);
40 Uint Binary_MapIn(tBinary *binary);
41 Uint Binary_IsMapped(tBinary *binary);
42 tBinary *Binary_DoLoad(char *truePath);
43 void Binary_Dereference(tBinary *Info);
44 Uint Binary_Relocate(void *Base);
45 Uint Binary_GetSymbolEx(char *Name, Uint *Value);
46 Uint Binary_FindSymbol(void *Base, char *Name, Uint *Val);
49 int glBinListLock = 0;
50 tBinary *glLoadedBinaries = NULL;
51 char **gsaRegInterps = NULL;
53 int glKBinListLock = 0;
54 tKernelBin *glLoadedKernelLibs;
55 tBinaryType *gRegBinTypes = &gELF_Info;
59 * \brief Registers a binary type
61 int Binary_RegisterType(tBinaryType *Type)
63 Type->Next = gRegBinTypes;
69 * \fn int Proc_Spawn(char *Path)
71 int Proc_Spawn(char *Path)
73 char stackPath[strlen(Path)+1];
75 strcpy(stackPath, Path);
77 LOG("stackPath = '%s'\n", stackPath);
79 if(Proc_Clone(NULL, CLONE_VM) == 0)
82 char *args[2] = {stackPath, NULL};
83 LOG("stackPath = '%s'\n", stackPath);
84 Proc_Execve(stackPath, args, &args[1]);
91 * \fn int Proc_Execve(char *File, char **ArgV, char **EnvP)
92 * \brief Replace the current user image with another
93 * \param File File to load as the next image
94 * \param ArgV Arguments to pass to user
95 * \param EnvP User's environment
96 * \note Called Proc_ for historical reasons
98 int Proc_Execve(char *File, char **ArgV, char **EnvP)
102 char *argenvBuf, *strBuf;
103 char **argvSaved, **envpSaved;
108 ENTER("sFile pArgV pEnvP", File, ArgV, EnvP);
110 // --- Save File, ArgV and EnvP (also get argc)
112 // Count Arguments, Environment Variables and total string sizes
114 for( argc = 0; ArgV && ArgV[argc]; argc++ )
115 argenvBytes += strlen(ArgV[argc])+1;
116 for( envc = 0; EnvP && EnvP[envc]; envc++ )
117 argenvBytes += strlen(EnvP[envc])+1;
118 argenvBytes = (argenvBytes + sizeof(void*)-1) & ~(sizeof(void*)-1);
119 argenvBytes += (argc+1)*sizeof(void*) + (envc+1)*sizeof(void*);
122 argenvBuf = malloc(argenvBytes);
123 if(argenvBuf == NULL) {
124 Warning("Proc_Execve - What the hell? The kernel is out of heap space");
127 strBuf = argenvBuf + (argc+1)*sizeof(void*) + (envc+1)*sizeof(void*);
130 argvSaved = (char **) argenvBuf;
131 for( i = 0; i < argc; i++ )
133 argvSaved[i] = strBuf;
134 strcpy(argvSaved[i], ArgV[i]);
135 strBuf += strlen(ArgV[i])+1;
138 envpSaved = &argvSaved[i+1];
139 for( i = 0; i < envc; i++ )
141 envpSaved[i] = strBuf;
142 strcpy(envpSaved[i], EnvP[i]);
143 strBuf += strlen(EnvP[i])+1;
146 savedFile = malloc(strlen(File)+1);
147 strcpy(savedFile, File);
149 // --- Set Process Name
150 Threads_SetName(File);
152 // --- Clear User Address space
155 // --- Load new binary
156 bases[0] = Binary_Load(savedFile, &entry);
160 Warning("Proc_Execve - Unable to load '%s'", Threads_GetName(-1));
165 LOG("entry = 0x%x, bases[0] = 0x%x", entry, bases[0]);
167 // --- And... Jump to it
168 Proc_StartUser(entry, bases, argc, argvSaved, envpSaved, argenvBytes);
169 for(;;); // Tell GCC that we never return
173 * \fn Uint Binary_Load(char *file, Uint *entryPoint)
175 Uint Binary_Load(char *file, Uint *entryPoint)
181 ENTER("sfile", file);
183 // Sanity Check Argument
189 // Get True File Path
190 sTruePath = VFS_GetTruePath(file);
192 if(sTruePath == NULL) {
193 Warning("[BIN ] '%s' does not exist.", file);
198 LOG("sTruePath = '%s'", sTruePath);
200 // Check if the binary has already been loaded
201 if( !(pBinary = Binary_GetInfo(sTruePath)) )
202 pBinary = Binary_DoLoad(sTruePath); // Else load it
208 if(pBinary == NULL) {
214 if( (base = Binary_IsMapped(pBinary)) ) {
220 // Map into process space
221 base = Binary_MapIn(pBinary); // If so then map it in
230 if(pBinary->Interpreter) {
232 if( Binary_Load(pBinary->Interpreter, &start) == 0 ) {
239 *entryPoint = pBinary->Entry - pBinary->Base + base;
242 LOG("*entryPoint = 0x%x", *entryPoint);
244 return base; // Pass the base as an argument to the user if there is an interpreter
248 * \brief Finds a matching binary entry
249 * \param TruePath File Identifier (True path name)
251 tBinary *Binary_GetInfo(char *TruePath)
254 pBinary = glLoadedBinaries;
257 if(strcmp(pBinary->TruePath, TruePath) == 0)
259 pBinary = pBinary->Next;
265 \fn Uint Binary_MapIn(tBinary *binary)
266 \brief Maps an already-loaded binary into an address space.
267 \param binary Pointer to globally stored data.
269 Uint Binary_MapIn(tBinary *binary)
275 // Reference Executable (Makes sure that it isn't unloaded)
276 binary->ReferenceCount ++;
281 // Check if base is free
284 for(i=0;i<binary->NumPages;i++)
286 if( MM_GetPhysAddr( binary->Pages[i].Virtual & ~0xFFF ) ) {
288 LOG("Address 0x%x is taken\n", binary->Pages[i].Virtual & ~0xFFF);
294 // Check if the executable has no base or it is not free
297 // If so, give it a base
299 while(base >= BIN_LOWEST)
301 for(i=0;i<binary->NumPages;i++)
303 addr = binary->Pages[i].Virtual & ~0xFFF;
304 addr -= binary->Base;
306 if( MM_GetPhysAddr( addr ) ) break;
308 // If space was found, break
309 if(i == binary->NumPages) break;
310 // Else decrement pointer and try again
311 base -= BIN_GRANUALITY;
316 if(base < BIN_LOWEST) {
317 Warning("[BIN ] Executable '%s' cannot be loaded, no space", binary->TruePath);
322 for(i=0;i<binary->NumPages;i++)
324 addr = binary->Pages[i].Virtual & ~0xFFF;
325 addr -= binary->Base;
327 LOG("%i - 0x%x to 0x%x", i, addr, binary->Pages[i].Physical);
328 MM_Map( addr, (Uint) (binary->Pages[i].Physical) );
331 if( binary->Pages[i].Flags & BIN_PAGEFLAG_RO)
332 MM_SetFlags( addr, MM_PFLAG_RO, -1 );
334 MM_SetFlags( addr, MM_PFLAG_COW, -1 );
337 if( binary->Pages[i].Flags & BIN_PAGEFLAG_EXEC )
338 MM_SetFlags( addr, MM_PFLAG_EXEC, -1 );
340 MM_SetFlags( addr, MM_PFLAG_EXEC, 0 );
344 //Log("Mapped '%s' to 0x%x", binary->TruePath, base);
346 //LOG("*0x%x = 0x%x\n", binary->Pages[0].Virtual, *(Uint*)binary->Pages[0].Virtual);
353 * \fn Uint Binary_IsMapped(tBinary *binary)
354 * \brief Check if a binary is already mapped into the address space
355 * \param binary Binary information to check
356 * \return Current Base or 0
358 Uint Binary_IsMapped(tBinary *binary)
362 // Check prefered base
363 iBase = binary->Base;
364 if(MM_GetPage( iBase ) == (binary->Pages[0].Physical & ~0xFFF))
367 for(iBase = BIN_HIGHEST;
369 iBase -= BIN_GRANUALITY)
371 if(MM_GetPage( iBase ) == (binary->Pages[0].Physical & ~0xFFF))
380 * \fn tBinary *Binary_DoLoad(char *truePath)
381 * \brief Loads a binary file into memory
382 * \param truePath Absolute filename of binary
384 tBinary *Binary_DoLoad(char *truePath)
389 tBinaryType *bt = gRegBinTypes;
391 ENTER("struePath", truePath);
394 fp = VFS_Open(truePath, VFS_OPENFLAG_READ);
396 LOG("Unable to load file, access denied");
402 VFS_Read(fp, 4, &ident);
403 VFS_Seek(fp, 0, SEEK_SET);
405 for(; bt; bt = bt->Next)
407 if( (ident & bt->Mask) != (Uint)bt->Ident )
409 pBinary = bt->Load(fp);
413 Warning("[BIN ] '%s' is an unknown file type. (0x%x 0x%x 0x%x 0x%x)",
414 truePath, ident&0xFF, (ident>>8)&0xFF, (ident>>16)&0xFF, (ident>>24)&0xFF);
420 if(pBinary == NULL) {
425 // Initialise Structure
426 pBinary->ReferenceCount = 0;
427 pBinary->TruePath = malloc( strlen(truePath) + 1 );
428 strcpy(pBinary->TruePath, truePath);
431 LOG("Interpreter: '%s'", pBinary->Interpreter);
432 LOG("Base: 0x%x, Entry: 0x%x", pBinary->Base, pBinary->Entry);
433 LOG("NumPages: %i", pBinary->NumPages);
436 for(i=0;i<pBinary->NumPages;i++)
440 paddr = (Uint)MM_AllocPhys();
442 Warning("Binary_DoLoad - Physical memory allocation failed");
444 MM_DerefPhys( pBinary->Pages[i].Physical );
448 MM_RefPhys( paddr ); // Make sure it is _NOT_ freed until we want it to be
449 dest = MM_MapTemp( paddr );
450 dest += pBinary->Pages[i].Virtual & 0xFFF;
451 LOG("dest = 0x%x, paddr = 0x%x", dest, paddr);
452 LOG("Pages[%i]={Physical:0x%llx,Virtual:%p,Size:0x%x}",
453 i, pBinary->Pages[i].Physical, pBinary->Pages[i].Virtual, pBinary->Pages[i].Size);
456 if(pBinary->Pages[i].Physical == -1) {
458 memset( (void*)dest, 0, 1024 - (pBinary->Pages[i].Virtual & 0xFFF) );
462 VFS_Seek( fp, pBinary->Pages[i].Physical, 1 );
463 if(pBinary->Pages[i].Size != 0x1000) {
464 LOG("%i - 0x%llx - 0x%x bytes",
465 i, pBinary->Pages[i].Physical, pBinary->Pages[i].Size);
466 memset( (void*)dest, 0, 0x1000 -(dest&0xFFF) );
467 VFS_Read( fp, pBinary->Pages[i].Size, (void*)dest );
469 LOG("%i - 0x%x", i, pBinary->Pages[i].Physical);
470 VFS_Read( fp, 0x1000, (void*)dest );
473 pBinary->Pages[i].Physical = paddr;
476 LOG("Page Count: %i", pBinary->NumPages);
482 LOCK(&glBinListLock);
483 pBinary->Next = glLoadedBinaries;
484 glLoadedBinaries = pBinary;
485 RELEASE(&glBinListLock);
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 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->NumPages; i++) {
520 MM_Deallocate( (Uint)Base + (i << 12) );
522 // Dereference Binary
523 Binary_Dereference( pKBin->Info );
525 if(prev) prev->Next = pKBin->Next;
526 else glLoadedKernelLibs = pKBin->Next;
534 * \fn void Binary_Dereference(tBinary *Info)
535 * \brief Dereferences and if nessasary, deletes a binary
536 * \param Info Binary information structure
538 void Binary_Dereference(tBinary *Info)
540 // Decrement reference count
541 Info->ReferenceCount --;
543 // Check if it is still in use
544 if(Info->ReferenceCount) return;
546 /// \todo Implement binary freeing
550 * \fn char *Binary_RegInterp(char *Path)
551 * \brief Registers an Interpreter
552 * \param Path Path to interpreter provided by executable
554 char *Binary_RegInterp(char *Path)
557 // NULL Check Argument
558 if(Path == NULL) return NULL;
559 // NULL Check the array
560 if(gsaRegInterps == NULL)
563 gsaRegInterps = malloc( sizeof(char*) );
564 gsaRegInterps[0] = malloc( strlen(Path) );
565 strcpy(gsaRegInterps[0], Path);
566 return gsaRegInterps[0];
570 for( i = 0; i < giRegInterps; i++ )
572 if(strcmp(gsaRegInterps[i], Path) == 0)
573 return gsaRegInterps[i];
576 // Interpreter is not in list
578 gsaRegInterps = malloc( sizeof(char*)*giRegInterps );
579 gsaRegInterps[i] = malloc( strlen(Path) );
580 strcpy(gsaRegInterps[i], Path);
581 return gsaRegInterps[i];
585 // Kernel Binary Handling
588 * \fn void *Binary_LoadKernel(char *File)
589 * \brief Load a binary into kernel space
590 * \note This function shares much with #Binary_Load, but does it's own mapping
591 * \param File File to load into the kernel
593 void *Binary_LoadKernel(char *File)
597 tKernelBin *pKBinary;
602 ENTER("sfile", File);
604 // Sanity Check Argument
610 // Get True File Path
611 sTruePath = VFS_GetTruePath(File);
612 if(sTruePath == NULL) {
617 // Check if the binary has already been loaded
618 if( (pBinary = Binary_GetInfo(sTruePath)) )
620 for(pKBinary = glLoadedKernelLibs;
622 pKBinary = pKBinary->Next )
624 if(pKBinary->Info == pBinary) {
625 LEAVE('p', pKBinary->Base);
626 return pKBinary->Base;
631 pBinary = Binary_DoLoad(sTruePath); // Else load it
634 if(pBinary == NULL) {
640 // Now pBinary is valid (either freshly loaded or only user mapped)
641 // So, map it into kernel space
644 // Reference Executable (Makes sure that it isn't unloaded)
645 pBinary->ReferenceCount ++;
647 // Check compiled base
648 base = pBinary->Base;
650 if(base < KLIB_LOWEST || base > KLIB_HIGHEST || base + (pBinary->NumPages<<12) > KLIB_HIGHEST) {
653 // - Check if it is a valid base address
656 for(i=0;i<pBinary->NumPages;i++)
658 if( MM_GetPhysAddr( pBinary->Pages[i].Virtual & ~0xFFF ) ) {
660 LOG("Address 0x%x is taken\n", pBinary->Pages[i].Virtual & ~0xFFF);
666 // Check if the executable has no base or it is not free
669 // If so, give it a base
671 while(base < KLIB_HIGHEST)
673 for(i = 0; i < pBinary->NumPages; i++)
675 addr = pBinary->Pages[i].Virtual & ~0xFFF;
676 addr -= pBinary->Base;
678 if( MM_GetPhysAddr( addr ) ) break;
680 // If space was found, break
681 if(i == pBinary->NumPages) break;
682 // Else decrement pointer and try again
683 base += KLIB_GRANUALITY;
688 if(base >= KLIB_HIGHEST) {
689 Warning("[BIN ] Executable '%s' cannot be loaded into kernel, no space", pBinary->TruePath);
690 Binary_Dereference( pBinary );
695 LOG("base = 0x%x", base);
698 LOG("pBinary = {NumPages:%i, Pages=%p}", pBinary->NumPages, pBinary->Pages);
699 for(i = 0; i < pBinary->NumPages; i++)
701 addr = pBinary->Pages[i].Virtual & ~0xFFF;
702 addr -= pBinary->Base;
704 LOG("%i - 0x%x to 0x%x", i, addr, pBinary->Pages[i].Physical);
705 MM_Map( addr, (Uint) (pBinary->Pages[i].Physical) );
706 MM_SetFlags( addr, MM_PFLAG_KERNEL, MM_PFLAG_KERNEL );
708 if( pBinary->Pages[i].Flags & BIN_PAGEFLAG_RO) // Read-Only?
709 MM_SetFlags( addr, MM_PFLAG_RO, MM_PFLAG_KERNEL );
713 if( !Binary_Relocate( (void*)base ) )
715 Warning("[BIN ] Relocation of '%s' failed, unloading", sTruePath);
716 Binary_Unload( (void*)base );
717 Binary_Dereference( pBinary );
722 // Add to list (relocator must look at itself manually, not via Binary_GetSymbol)
723 pKBinary = malloc(sizeof(*pKBinary));
724 pKBinary->Base = (void*)base;
725 pKBinary->Info = pBinary;
726 LOCK( &glKBinListLock );
727 pKBinary->Next = glLoadedKernelLibs;
728 glLoadedKernelLibs = pKBinary;
729 RELEASE( &glKBinListLock );
736 * \fn Uint Binary_Relocate(void *Base)
737 * \brief Relocates a loaded binary (used by kernel libraries)
738 * \param Base Loaded base address of binary
739 * \return Boolean Success
741 Uint Binary_Relocate(void *Base)
743 Uint32 ident = *(Uint32*) Base;
744 tBinaryType *bt = gRegBinTypes;
746 for(; bt; bt = bt->Next)
748 if( (ident & bt->Mask) == (Uint)bt->Ident )
749 return bt->Relocate( (void*)Base);
752 Warning("[BIN ] 0x%x is an unknown file type. (0x%x 0x%x 0x%x 0x%x)",
753 Base, ident&0xFF, (ident>>8)&0xFF, (ident>>16)&0xFF, (ident>>24)&0xFF);
758 * \fn int Binary_GetSymbol(char *Name, Uint *Val)
759 * \brief Get a symbol value
760 * \return Value of symbol or -1 on error
762 * Gets the value of a symbol from either the currently loaded
763 * libraries or the kernel's exports.
765 int Binary_GetSymbol(char *Name, Uint *Val)
767 if( Binary_GetSymbolEx(Name, Val) ) return 1;
772 * \fn Uint Binary_GetSymbolEx(char *Name, Uint *Value)
773 * \brief Get a symbol value
775 * Gets the value of a symbol from either the currently loaded
776 * libraries or the kernel's exports.
778 Uint Binary_GetSymbolEx(char *Name, Uint *Value)
782 int numKSyms = ((Uint)&gKernelSymbolsEnd-(Uint)&gKernelSymbols)/sizeof(tKernelSymbol);
785 for( i = 0; i < numKSyms; i++ )
787 if(strcmp(Name, gKernelSymbols[i].Name) == 0) {
788 *Value = gKernelSymbols[i].Value;
793 // Scan Loaded Libraries
794 for(pKBin = glLoadedKernelLibs;
796 pKBin = pKBin->Next )
798 if( Binary_FindSymbol(pKBin->Base, Name, Value) ) {
803 Warning("[BIN ] Unable to find symbol '%s'", Name);
808 * \fn Uint Binary_FindSymbol(void *Base, char *Name, Uint *Val)
809 * \brief Get a symbol from the specified library
810 * \param Base Base address
811 * \param Name Name of symbol to find
812 * \param Val Pointer to place final value
814 Uint Binary_FindSymbol(void *Base, char *Name, Uint *Val)
816 Uint32 ident = *(Uint32*) Base;
817 tBinaryType *bt = gRegBinTypes;
819 for(; bt; bt = bt->Next)
821 if( (ident & bt->Mask) == (Uint)bt->Ident )
822 return bt->GetSymbol(Base, Name, Val);
825 Warning("[BIN ] 0x%x is an unknown file type. (0x%x 0x%x 0x%x 0x%x)",
826 Base, ident&0xFF, ident>>8, ident>>16, ident>>24);
831 EXPORT(Binary_FindSymbol);
832 EXPORT(Binary_Unload);