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 bases[2] = {0}; // 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 bases[0] = Binary_Load(savedFile, &entry);
165 Log_Warning("Binary", "Proc_Execve - Unable to load '%s'", Threads_GetName(-1));
167 Threads_Exit(0, -10);
171 LOG("entry = 0x%x, bases[0] = 0x%x", entry, bases[0]);
173 // --- And... Jump to it
174 Proc_StartUser(entry, bases, argc, argvSaved, envpSaved, argenvBytes);
175 for(;;); // Tell GCC that we never return
179 * \fn tVAddr Binary_Load(char *Path, tVAddr *EntryPoint)
180 * \brief Load a binary into the current address space
181 * \param Path Path to binary to load
182 * \param EntryPoint Pointer for exectuable entry point
184 tVAddr Binary_Load(const char *Path, tVAddr *EntryPoint)
191 ENTER("sPath pEntryPoint", Path, EntryPoint);
193 // Sanity Check Argument
199 // Check if this path has been loaded before.
201 // TODO: Implement a list of string/tBinary pairs for loaded bins
208 fd = VFS_Open(Path, VFS_OPENFLAG_READ|VFS_OPENFLAG_EXEC);
210 LOG("%s does not exist", Path);
213 VFS_FInfo(fd, &info, 0);
215 mount_id = info.mount;
219 // TODO: Also get modifcation time?
221 // Check if the binary has already been loaded
222 if( !(pBinary = Binary_GetInfo(mount_id, inode)) )
223 pBinary = Binary_DoLoad(mount_id, inode, Path); // Else load it
226 if(pBinary == NULL) {
231 // Map into process space
232 base = Binary_MapIn(pBinary, Path, BIN_LOWEST, BIN_HIGHEST);
241 if(pBinary->Interpreter) {
243 if( Binary_Load(pBinary->Interpreter, &start) == 0 ) {
250 *EntryPoint = pBinary->Entry - pBinary->Base + base;
253 LOG("*EntryPoint = 0x%x", *EntryPoint);
255 return base; // Pass the base as an argument to the user if there is an interpreter
259 * \brief Finds a matching binary entry
260 * \param TruePath File Identifier (True path name)
262 tBinary *Binary_GetInfo(tMount MountID, tInode InodeID)
265 pBinary = glLoadedBinaries;
268 if(pBinary->MountID == MountID && pBinary->Inode == InodeID)
270 pBinary = pBinary->Next;
276 \fn Uint Binary_MapIn(tBinary *binary)
277 \brief Maps an already-loaded binary into an address space.
278 \param binary Pointer to globally stored data.
280 tVAddr Binary_MapIn(tBinary *Binary, const char *Path, tVAddr LoadMin, tVAddr LoadMax)
285 ENTER("pBinary sPath pLoadMin pLoadMax", Binary, Path, LoadMin, LoadMax);
287 // Reference Executable (Makes sure that it isn't unloaded)
288 Binary->ReferenceCount ++;
293 // Check if base is free
296 for(i=0;i<Binary->NumSections;i++)
298 if( Binary_int_CheckMemFree( Binary->LoadSections[i].Virtual, Binary->LoadSections[i].MemSize ) )
301 LOG("Address 0x%x is taken\n", Binary->LoadSections[i].Virtual);
307 // Check if the executable has no base or it is not free
310 // If so, give it a base
312 while(base >= LoadMin)
314 for( i = 0; i < Binary->NumSections; i ++ )
316 tVAddr addr = Binary->LoadSections[i].Virtual - Binary->Base + base;
317 if( Binary_int_CheckMemFree( addr, Binary->LoadSections[i].MemSize ) )
320 // If space was found, break
321 if(i == Binary->NumSections) break;
322 // Else decrement pointer and try again
323 base -= BIN_GRANUALITY;
329 Log_Warning("Binary", "Executable '%s' cannot be loaded, no space", Path);
335 fd = VFS_OpenInode(Binary->MountID, Binary->Inode, VFS_OPENFLAG_READ);
336 for( i = 0; i < Binary->NumSections; i ++ )
338 tBinarySection *sect = &Binary->LoadSections[i];
339 Uint protflags, mapflags;
340 tVAddr addr = sect->Virtual - Binary->Base + base;
341 LOG("%i - 0x%x to 0x%x", i, addr, sect->Offset);
343 protflags = MMAP_PROT_READ;
344 mapflags = MMAP_MAP_FIXED;
346 if( sect->Flags & BIN_SECTFLAG_EXEC )
347 protflags |= MMAP_PROT_EXEC;
348 if( sect->Flags & BIN_SECTFLAG_RO ) {
349 VFS_MMap( (void*)addr, sect->FileSize, protflags, MMAP_MAP_SHARED|mapflags, fd, sect->Offset );
352 protflags |= MMAP_PROT_WRITE;
353 VFS_MMap( (void*)addr, sect->FileSize, protflags, MMAP_MAP_PRIVATE|mapflags, fd, sect->Offset );
355 if( sect->FileSize < sect->MemSize ) {
356 mapflags |= MMAP_MAP_ANONYMOUS;
358 (void*)(addr + sect->FileSize), sect->MemSize - sect->FileSize,
359 protflags, MMAP_MAP_PRIVATE|mapflags,
365 Log_Debug("Binary", "PID %i - Mapped '%s' to 0x%x", Threads_GetPID(), Path, base);
367 //LOG("*0x%x = 0x%x\n", binary->Pages[0].Virtual, *(Uint*)binary->Pages[0].Virtual);
375 * \fn Uint Binary_IsMapped(tBinary *binary)
376 * \brief Check if a binary is already mapped into the address space
377 * \param binary Binary information to check
378 * \return Current Base or 0
380 Uint Binary_IsMapped(tBinary *binary)
384 // Check prefered base
385 iBase = binary->Base;
386 if(MM_GetPage( iBase ) == (binary->Pages[0].Physical & ~0xFFF))
389 for(iBase = BIN_HIGHEST;
391 iBase -= BIN_GRANUALITY)
393 if(MM_GetPage( iBase ) == (binary->Pages[0].Physical & ~0xFFF))
402 * \fn tBinary *Binary_DoLoad(char *truePath)
403 * \brief Loads a binary file into memory
404 * \param truePath Absolute filename of binary
406 tBinary *Binary_DoLoad(tMount MountID, tInode Inode, const char *Path)
411 tBinaryType *bt = gRegBinTypes;
413 ENTER("iMountID XInode sPath", MountID, Inode, Path);
416 fp = VFS_OpenInode(MountID, Inode, VFS_OPENFLAG_READ);
418 LOG("Unable to load file, access denied");
424 VFS_Read(fp, 4, &ident);
425 VFS_Seek(fp, 0, SEEK_SET);
427 // Determine the type
428 for(; bt; bt = bt->Next)
430 if( (ident & bt->Mask) != (Uint)bt->Ident )
432 pBinary = bt->Load(fp);
441 Log_Warning("Binary", "'%s' is an unknown file type. (%02x %02x %02x %02x)",
442 Path, ident&0xFF, (ident>>8)&0xFF, (ident>>16)&0xFF, (ident>>24)&0xFF);
448 if(pBinary == NULL) {
453 // Initialise Structure
454 pBinary->ReferenceCount = 0;
455 pBinary->MountID = MountID;
456 pBinary->Inode = Inode;
459 LOG("Interpreter: '%s'", pBinary->Interpreter);
460 LOG("Base: 0x%x, Entry: 0x%x", pBinary->Base, pBinary->Entry);
461 LOG("NumSections: %i", pBinary->NumSections);
464 SHORTLOCK(&glBinListLock);
465 pBinary->Next = glLoadedBinaries;
466 glLoadedBinaries = pBinary;
467 SHORTREL(&glBinListLock);
469 // TODO: Register the path with the binary
477 * \fn void Binary_Unload(void *Base)
478 * \brief Unload / Unmap a binary
479 * \param Base Loaded Base
480 * \note Currently used only for kernel libaries
482 void Binary_Unload(void *Base)
485 tKernelBin *prev = NULL;
488 if((Uint)Base < 0xC0000000)
490 // TODO: User Binaries
491 Log_Warning("BIN", "Unloading user binaries is currently unimplemented");
496 for(pKBin = glLoadedKernelLibs;
498 prev = pKBin, pKBin = pKBin->Next)
501 if(pKBin->Base != Base) continue;
503 for(i = 0; i < pKBin->Info->NumSections; i++)
505 // TODO: VFS_MUnmap();
507 // Dereference Binary
508 Binary_Dereference( pKBin->Info );
510 if(prev) prev->Next = pKBin->Next;
511 else glLoadedKernelLibs = pKBin->Next;
519 * \fn void Binary_Dereference(tBinary *Info)
520 * \brief Dereferences and if nessasary, deletes a binary
521 * \param Info Binary information structure
523 void Binary_Dereference(tBinary *Info)
525 // Decrement reference count
526 Info->ReferenceCount --;
528 // Check if it is still in use
529 if(Info->ReferenceCount) return;
531 /// \todo Implement binary freeing
535 * \fn char *Binary_RegInterp(char *Path)
536 * \brief Registers an Interpreter
537 * \param Path Path to interpreter provided by executable
539 char *Binary_RegInterp(char *Path)
542 // NULL Check Argument
543 if(Path == NULL) return NULL;
544 // NULL Check the array
545 if(gsaRegInterps == NULL)
548 gsaRegInterps = malloc( sizeof(char*) );
549 gsaRegInterps[0] = malloc( strlen(Path) );
550 strcpy(gsaRegInterps[0], Path);
551 return gsaRegInterps[0];
555 for( i = 0; i < giRegInterps; i++ )
557 if(strcmp(gsaRegInterps[i], Path) == 0)
558 return gsaRegInterps[i];
561 // Interpreter is not in list
563 gsaRegInterps = malloc( sizeof(char*)*giRegInterps );
564 gsaRegInterps[i] = malloc( strlen(Path) );
565 strcpy(gsaRegInterps[i], Path);
566 return gsaRegInterps[i];
570 // Kernel Binary Handling
573 * \fn void *Binary_LoadKernel(const char *File)
574 * \brief Load a binary into kernel space
575 * \note This function shares much with #Binary_Load, but does it's own mapping
576 * \param File File to load into the kernel
578 void *Binary_LoadKernel(const char *File)
581 tKernelBin *pKBinary;
586 ENTER("sFile", File);
588 // Sanity Check Argument
595 int fd = VFS_Open(File, VFS_OPENFLAG_READ);
601 VFS_FInfo(fd, &info, 0);
602 mount_id = info.mount;
607 // Check if the binary has already been loaded
608 if( (pBinary = Binary_GetInfo(mount_id, inode)) )
610 for(pKBinary = glLoadedKernelLibs;
612 pKBinary = pKBinary->Next )
614 if(pKBinary->Info == pBinary) {
615 LEAVE('p', pKBinary->Base);
616 return pKBinary->Base;
621 pBinary = Binary_DoLoad(mount_id, inode, File); // Else load it
624 if(pBinary == NULL) {
630 // Now pBinary is valid (either freshly loaded or only user mapped)
631 // So, map it into kernel space
634 // Reference Executable (Makes sure that it isn't unloaded)
635 pBinary->ReferenceCount ++;
637 Binary_MapIn(pBinary, File, KLIB_LOWEST, KLIB_HIGHEST);
640 if( !Binary_Relocate( (void*)base ) )
642 Log_Warning("Binary", "Relocation of '%s' failed, unloading", File);
643 Binary_Unload( (void*)base );
644 Binary_Dereference( pBinary );
649 // Add to list (relocator must look at itself manually, not via Binary_GetSymbol)
650 pKBinary = malloc(sizeof(*pKBinary));
651 pKBinary->Base = (void*)base;
652 pKBinary->Info = pBinary;
653 SHORTLOCK( &glKBinListLock );
654 pKBinary->Next = glLoadedKernelLibs;
655 glLoadedKernelLibs = pKBinary;
656 SHORTREL( &glKBinListLock );
663 * \fn Uint Binary_Relocate(void *Base)
664 * \brief Relocates a loaded binary (used by kernel libraries)
665 * \param Base Loaded base address of binary
666 * \return Boolean Success
668 Uint Binary_Relocate(void *Base)
670 Uint32 ident = *(Uint32*) Base;
671 tBinaryType *bt = gRegBinTypes;
673 for(; bt; bt = bt->Next)
675 if( (ident & bt->Mask) == (Uint)bt->Ident )
676 return bt->Relocate( (void*)Base);
679 Log_Warning("BIN", "%p is an unknown file type. (%02x %02x %02x %02x)",
680 Base, ident&0xFF, (ident>>8)&0xFF, (ident>>16)&0xFF, (ident>>24)&0xFF);
685 * \fn int Binary_GetSymbol(char *Name, Uint *Val)
686 * \brief Get a symbol value
687 * \return Value of symbol or -1 on error
689 * Gets the value of a symbol from either the currently loaded
690 * libraries or the kernel's exports.
692 int Binary_GetSymbol(const char *Name, Uint *Val)
694 if( Binary_GetSymbolEx(Name, Val) ) return 1;
699 * \fn Uint Binary_GetSymbolEx(char *Name, Uint *Value)
700 * \brief Get a symbol value
702 * Gets the value of a symbol from either the currently loaded
703 * libraries or the kernel's exports.
705 Uint Binary_GetSymbolEx(const char *Name, Uint *Value)
709 int numKSyms = ((Uint)&gKernelSymbolsEnd-(Uint)&gKernelSymbols)/sizeof(tKernelSymbol);
712 for( i = 0; i < numKSyms; i++ )
714 if(strcmp(Name, gKernelSymbols[i].Name) == 0) {
715 *Value = gKernelSymbols[i].Value;
720 // Scan Loaded Libraries
721 for(pKBin = glLoadedKernelLibs;
723 pKBin = pKBin->Next )
725 if( Binary_FindSymbol(pKBin->Base, Name, Value) ) {
730 Log_Warning("BIN", "Unable to find symbol '%s'", Name);
735 * \fn Uint Binary_FindSymbol(void *Base, char *Name, Uint *Val)
736 * \brief Get a symbol from the specified library
737 * \param Base Base address
738 * \param Name Name of symbol to find
739 * \param Val Pointer to place final value
741 Uint Binary_FindSymbol(void *Base, const char *Name, Uint *Val)
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->GetSymbol(Base, Name, Val);
752 Log_Warning("BIN", "Binary_FindSymbol - %p is an unknown file type. (%02x %02x %02x %02x)",
753 Base, ident&0xFF, ident>>8, ident>>16, ident>>24);
758 * \brief Check if a range of memory is fully free
759 * \return Inverse boolean free (0 if all pages are unmapped)
761 int Binary_int_CheckMemFree( tVAddr _start, size_t _len )
763 _len += _start & (PAGE_SIZE-1);
764 _start &= ~(PAGE_SIZE-1);
765 for( ; _len > PAGE_SIZE; _len -= PAGE_SIZE, _start += PAGE_SIZE ) {
766 if( MM_GetPhysAddr(_start) != 0 )
769 if( _len == PAGE_SIZE && MM_GetPhysAddr(_start) != 0 )
776 EXPORT(Binary_FindSymbol);
777 EXPORT(Binary_Unload);