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'\n", stackPath);
81 if(Proc_Clone(CLONE_VM) == 0)
84 const char *args[2] = {stackPath, NULL};
85 LOG("stackPath = '%s'\n", 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)
284 // Reference Executable (Makes sure that it isn't unloaded)
285 Binary->ReferenceCount ++;
290 // Check if base is free
293 for(i=0;i<Binary->NumSections;i++)
295 if( Binary_int_CheckMemFree( Binary->LoadSections[i].Virtual, Binary->LoadSections[i].MemSize ) )
298 LOG("Address 0x%x is taken\n", Binary->LoadSections[i].Virtual);
304 // Check if the executable has no base or it is not free
307 // If so, give it a base
309 while(base >= LoadMin)
311 for( i = 0; i < Binary->NumSections; i ++ )
313 tVAddr addr = Binary->LoadSections[i].Virtual - Binary->Base + base;
314 if( Binary_int_CheckMemFree( addr, Binary->LoadSections[i].MemSize ) )
317 // If space was found, break
318 if(i == Binary->NumSections) break;
319 // Else decrement pointer and try again
320 base -= BIN_GRANUALITY;
326 Log_Warning("Binary", "Executable '%s' cannot be loaded, no space", Path);
331 fd = VFS_OpenInode(Binary->MountID, Binary->Inode, VFS_OPENFLAG_READ);
332 for( i = 0; i < Binary->NumSections; i ++ )
334 tBinarySection *sect = &Binary->LoadSections[i];
335 Uint protflags, mapflags;
336 tVAddr addr = sect->Virtual - Binary->Base + base;
337 LOG("%i - 0x%x to 0x%x", i, addr, sect->Offset);
339 protflags = MMAP_PROT_READ;
340 mapflags = MMAP_MAP_FIXED;
342 if( sect->Flags & BIN_SECTFLAG_EXEC )
343 protflags |= MMAP_PROT_EXEC;
344 if( sect->Flags & BIN_SECTFLAG_RO ) {
345 VFS_MMap( (void*)addr, sect->FileSize, protflags, MMAP_MAP_SHARED|mapflags, fd, sect->Offset );
348 protflags |= MMAP_PROT_WRITE;
349 VFS_MMap( (void*)addr, sect->FileSize, protflags, MMAP_MAP_PRIVATE|mapflags, fd, sect->Offset );
351 if( sect->FileSize < sect->MemSize ) {
352 mapflags |= MMAP_MAP_ANONYMOUS;
354 (void*)(addr + sect->FileSize), sect->MemSize - sect->FileSize,
355 protflags, MMAP_MAP_PRIVATE|mapflags,
361 Log_Debug("Binary", "PID %i - Mapped '%s' to 0x%x", Threads_GetPID(), Path, base);
363 //LOG("*0x%x = 0x%x\n", binary->Pages[0].Virtual, *(Uint*)binary->Pages[0].Virtual);
370 * \fn Uint Binary_IsMapped(tBinary *binary)
371 * \brief Check if a binary is already mapped into the address space
372 * \param binary Binary information to check
373 * \return Current Base or 0
375 Uint Binary_IsMapped(tBinary *binary)
379 // Check prefered base
380 iBase = binary->Base;
381 if(MM_GetPage( iBase ) == (binary->Pages[0].Physical & ~0xFFF))
384 for(iBase = BIN_HIGHEST;
386 iBase -= BIN_GRANUALITY)
388 if(MM_GetPage( iBase ) == (binary->Pages[0].Physical & ~0xFFF))
397 * \fn tBinary *Binary_DoLoad(char *truePath)
398 * \brief Loads a binary file into memory
399 * \param truePath Absolute filename of binary
401 tBinary *Binary_DoLoad(tMount MountID, tInode Inode, const char *Path)
406 tBinaryType *bt = gRegBinTypes;
408 ENTER("iMountID XInode sPath", Path);
411 fp = VFS_OpenInode(MountID, Inode, VFS_OPENFLAG_READ);
413 LOG("Unable to load file, access denied");
419 VFS_Read(fp, 4, &ident);
420 VFS_Seek(fp, 0, SEEK_SET);
422 // Determine the type
423 for(; bt; bt = bt->Next)
425 if( (ident & bt->Mask) != (Uint)bt->Ident )
427 pBinary = bt->Load(fp);
436 Log_Warning("Binary", "'%s' is an unknown file type. (%02x %02x %02x %02x)",
437 Path, ident&0xFF, (ident>>8)&0xFF, (ident>>16)&0xFF, (ident>>24)&0xFF);
443 if(pBinary == NULL) {
448 // Initialise Structure
449 pBinary->ReferenceCount = 0;
450 pBinary->MountID = MountID;
451 pBinary->Inode = Inode;
454 LOG("Interpreter: '%s'", pBinary->Interpreter);
455 LOG("Base: 0x%x, Entry: 0x%x", pBinary->Base, pBinary->Entry);
456 LOG("NumSections: %i", pBinary->NumSections);
459 SHORTLOCK(&glBinListLock);
460 pBinary->Next = glLoadedBinaries;
461 glLoadedBinaries = pBinary;
462 SHORTREL(&glBinListLock);
464 // TODO: Register the path with the binary
472 * \fn void Binary_Unload(void *Base)
473 * \brief Unload / Unmap a binary
474 * \param Base Loaded Base
475 * \note Currently used only for kernel libaries
477 void Binary_Unload(void *Base)
480 tKernelBin *prev = NULL;
483 if((Uint)Base < 0xC0000000)
485 // TODO: User Binaries
486 Log_Warning("BIN", "Unloading user binaries is currently unimplemented");
491 for(pKBin = glLoadedKernelLibs;
493 prev = pKBin, pKBin = pKBin->Next)
496 if(pKBin->Base != Base) continue;
498 for(i = 0; i < pKBin->Info->NumSections; i++)
500 // TODO: VFS_MUnmap();
502 // Dereference Binary
503 Binary_Dereference( pKBin->Info );
505 if(prev) prev->Next = pKBin->Next;
506 else glLoadedKernelLibs = pKBin->Next;
514 * \fn void Binary_Dereference(tBinary *Info)
515 * \brief Dereferences and if nessasary, deletes a binary
516 * \param Info Binary information structure
518 void Binary_Dereference(tBinary *Info)
520 // Decrement reference count
521 Info->ReferenceCount --;
523 // Check if it is still in use
524 if(Info->ReferenceCount) return;
526 /// \todo Implement binary freeing
530 * \fn char *Binary_RegInterp(char *Path)
531 * \brief Registers an Interpreter
532 * \param Path Path to interpreter provided by executable
534 char *Binary_RegInterp(char *Path)
537 // NULL Check Argument
538 if(Path == NULL) return NULL;
539 // NULL Check the array
540 if(gsaRegInterps == NULL)
543 gsaRegInterps = malloc( sizeof(char*) );
544 gsaRegInterps[0] = malloc( strlen(Path) );
545 strcpy(gsaRegInterps[0], Path);
546 return gsaRegInterps[0];
550 for( i = 0; i < giRegInterps; i++ )
552 if(strcmp(gsaRegInterps[i], Path) == 0)
553 return gsaRegInterps[i];
556 // Interpreter is not in list
558 gsaRegInterps = malloc( sizeof(char*)*giRegInterps );
559 gsaRegInterps[i] = malloc( strlen(Path) );
560 strcpy(gsaRegInterps[i], Path);
561 return gsaRegInterps[i];
565 // Kernel Binary Handling
568 * \fn void *Binary_LoadKernel(const char *File)
569 * \brief Load a binary into kernel space
570 * \note This function shares much with #Binary_Load, but does it's own mapping
571 * \param File File to load into the kernel
573 void *Binary_LoadKernel(const char *File)
576 tKernelBin *pKBinary;
581 ENTER("sFile", File);
583 // Sanity Check Argument
590 int fd = VFS_Open(File, VFS_OPENFLAG_READ);
596 VFS_FInfo(fd, &info, 0);
597 mount_id = info.mount;
602 // Check if the binary has already been loaded
603 if( (pBinary = Binary_GetInfo(mount_id, inode)) )
605 for(pKBinary = glLoadedKernelLibs;
607 pKBinary = pKBinary->Next )
609 if(pKBinary->Info == pBinary) {
610 LEAVE('p', pKBinary->Base);
611 return pKBinary->Base;
616 pBinary = Binary_DoLoad(mount_id, inode, File); // Else load it
619 if(pBinary == NULL) {
625 // Now pBinary is valid (either freshly loaded or only user mapped)
626 // So, map it into kernel space
629 // Reference Executable (Makes sure that it isn't unloaded)
630 pBinary->ReferenceCount ++;
632 Binary_MapIn(pBinary, File, KLIB_LOWEST, KLIB_HIGHEST);
635 if( !Binary_Relocate( (void*)base ) )
637 Log_Warning("Binary", "Relocation of '%s' failed, unloading", File);
638 Binary_Unload( (void*)base );
639 Binary_Dereference( pBinary );
644 // Add to list (relocator must look at itself manually, not via Binary_GetSymbol)
645 pKBinary = malloc(sizeof(*pKBinary));
646 pKBinary->Base = (void*)base;
647 pKBinary->Info = pBinary;
648 SHORTLOCK( &glKBinListLock );
649 pKBinary->Next = glLoadedKernelLibs;
650 glLoadedKernelLibs = pKBinary;
651 SHORTREL( &glKBinListLock );
658 * \fn Uint Binary_Relocate(void *Base)
659 * \brief Relocates a loaded binary (used by kernel libraries)
660 * \param Base Loaded base address of binary
661 * \return Boolean Success
663 Uint Binary_Relocate(void *Base)
665 Uint32 ident = *(Uint32*) Base;
666 tBinaryType *bt = gRegBinTypes;
668 for(; bt; bt = bt->Next)
670 if( (ident & bt->Mask) == (Uint)bt->Ident )
671 return bt->Relocate( (void*)Base);
674 Log_Warning("BIN", "%p is an unknown file type. (%02x %02x %02x %02x)",
675 Base, ident&0xFF, (ident>>8)&0xFF, (ident>>16)&0xFF, (ident>>24)&0xFF);
680 * \fn int Binary_GetSymbol(char *Name, Uint *Val)
681 * \brief Get a symbol value
682 * \return Value of symbol or -1 on error
684 * Gets the value of a symbol from either the currently loaded
685 * libraries or the kernel's exports.
687 int Binary_GetSymbol(const char *Name, Uint *Val)
689 if( Binary_GetSymbolEx(Name, Val) ) return 1;
694 * \fn Uint Binary_GetSymbolEx(char *Name, Uint *Value)
695 * \brief Get a symbol value
697 * Gets the value of a symbol from either the currently loaded
698 * libraries or the kernel's exports.
700 Uint Binary_GetSymbolEx(const char *Name, Uint *Value)
704 int numKSyms = ((Uint)&gKernelSymbolsEnd-(Uint)&gKernelSymbols)/sizeof(tKernelSymbol);
707 for( i = 0; i < numKSyms; i++ )
709 if(strcmp(Name, gKernelSymbols[i].Name) == 0) {
710 *Value = gKernelSymbols[i].Value;
715 // Scan Loaded Libraries
716 for(pKBin = glLoadedKernelLibs;
718 pKBin = pKBin->Next )
720 if( Binary_FindSymbol(pKBin->Base, Name, Value) ) {
725 Log_Warning("BIN", "Unable to find symbol '%s'", Name);
730 * \fn Uint Binary_FindSymbol(void *Base, char *Name, Uint *Val)
731 * \brief Get a symbol from the specified library
732 * \param Base Base address
733 * \param Name Name of symbol to find
734 * \param Val Pointer to place final value
736 Uint Binary_FindSymbol(void *Base, const char *Name, Uint *Val)
738 Uint32 ident = *(Uint32*) Base;
739 tBinaryType *bt = gRegBinTypes;
741 for(; bt; bt = bt->Next)
743 if( (ident & bt->Mask) == (Uint)bt->Ident )
744 return bt->GetSymbol(Base, Name, Val);
747 Log_Warning("BIN", "Binary_FindSymbol - %p is an unknown file type. (%02x %02x %02x %02x)",
748 Base, ident&0xFF, ident>>8, ident>>16, ident>>24);
753 * \brief Check if a range of memory is fully free
754 * \return Inverse boolean free (0 if all pages are unmapped)
756 int Binary_int_CheckMemFree( tVAddr _start, size_t _len )
758 _len += _start & (PAGE_SIZE-1);
759 _start &= ~(PAGE_SIZE-1);
760 for( ; _len > PAGE_SIZE; _len -= PAGE_SIZE, _start += PAGE_SIZE ) {
761 if( MM_GetPhysAddr(_start) != 0 )
764 if( _len == PAGE_SIZE && MM_GetPhysAddr(_start) != 0 )
771 EXPORT(Binary_FindSymbol);
772 EXPORT(Binary_Unload);