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 // MM_DumpTables(0, KERNEL_BASE);
176 // --- And... Jump to it
177 Proc_StartUser(entry, bases, argc, argvSaved, envpSaved, argenvBytes);
178 for(;;); // Tell GCC that we never return
182 * \brief Load a binary into the current address space
183 * \param Path Path to binary to load
184 * \param EntryPoint Pointer for exectuable entry point
185 * \return Virtual address where the binary has been loaded
187 tVAddr Binary_Load(const char *Path, tVAddr *EntryPoint)
194 ENTER("sPath pEntryPoint", Path, EntryPoint);
196 // Sanity Check Argument
202 // Check if this path has been loaded before.
204 // TODO: Implement a list of string/tBinary pairs for loaded bins
211 fd = VFS_Open(Path, VFS_OPENFLAG_READ|VFS_OPENFLAG_EXEC);
213 LOG("%s does not exist", Path);
216 VFS_FInfo(fd, &info, 0);
218 mount_id = info.mount;
220 LOG("mount_id = %i, inode = %i", mount_id, inode);
223 // TODO: Also get modifcation time?
225 // Check if the binary has already been loaded
226 if( !(pBinary = Binary_GetInfo(mount_id, inode)) )
227 pBinary = Binary_DoLoad(mount_id, inode, Path); // Else load it
230 if(pBinary == NULL) {
235 // Map into process space
236 base = Binary_MapIn(pBinary, Path, BIN_LOWEST, BIN_HIGHEST);
245 if(pBinary->Interpreter) {
247 if( Binary_Load(pBinary->Interpreter, &start) == 0 ) {
254 *EntryPoint = pBinary->Entry - pBinary->Base + base;
257 LOG("*EntryPoint = 0x%x", *EntryPoint);
259 return base; // Pass the base as an argument to the user if there is an interpreter
263 * \brief Finds a matching binary entry
264 * \param TruePath File Identifier (True path name)
266 tBinary *Binary_GetInfo(tMount MountID, tInode InodeID)
269 pBinary = glLoadedBinaries;
272 if(pBinary->MountID == MountID && pBinary->Inode == InodeID)
274 pBinary = pBinary->Next;
280 \fn Uint Binary_MapIn(tBinary *binary)
281 \brief Maps an already-loaded binary into an address space.
282 \param binary Pointer to globally stored data.
284 tVAddr Binary_MapIn(tBinary *Binary, const char *Path, tVAddr LoadMin, tVAddr LoadMax)
289 ENTER("pBinary sPath pLoadMin pLoadMax", Binary, Path, LoadMin, LoadMax);
291 // Reference Executable (Makes sure that it isn't unloaded)
292 Binary->ReferenceCount ++;
297 // Check if base is free
300 LOG("Checking base %p", base);
301 for(i=0;i<Binary->NumSections;i++)
303 if( Binary_int_CheckMemFree( Binary->LoadSections[i].Virtual, Binary->LoadSections[i].MemSize ) )
306 LOG("Address 0x%x is taken\n", Binary->LoadSections[i].Virtual);
312 // Check if the executable has no base or it is not free
315 // If so, give it a base
317 while(base >= LoadMin)
319 for( i = 0; i < Binary->NumSections; i ++ )
321 tVAddr addr = Binary->LoadSections[i].Virtual - Binary->Base + base;
322 if( Binary_int_CheckMemFree( addr, Binary->LoadSections[i].MemSize ) )
325 // If space was found, break
326 if(i == Binary->NumSections) break;
327 // Else decrement pointer and try again
328 base -= BIN_GRANUALITY;
330 LOG("Allocated base %p", base);
335 Log_Warning("Binary", "Executable '%s' cannot be loaded, no space", Path);
341 fd = VFS_OpenInode(Binary->MountID, Binary->Inode, VFS_OPENFLAG_READ);
342 for( i = 0; i < Binary->NumSections; i ++ )
344 tBinarySection *sect = &Binary->LoadSections[i];
345 Uint protflags, mapflags;
346 tVAddr addr = sect->Virtual - Binary->Base + base;
347 LOG("%i - %p to 0x%llx (%x)", i, addr, sect->Offset, sect->Flags);
349 protflags = MMAP_PROT_READ;
350 mapflags = MMAP_MAP_FIXED;
352 if( sect->Flags & BIN_SECTFLAG_EXEC )
353 protflags |= MMAP_PROT_EXEC;
354 if( sect->Flags & BIN_SECTFLAG_RO ) {
355 VFS_MMap( (void*)addr, sect->FileSize, protflags, MMAP_MAP_SHARED|mapflags, fd, sect->Offset );
358 protflags |= MMAP_PROT_WRITE;
359 VFS_MMap( (void*)addr, sect->FileSize, protflags, MMAP_MAP_PRIVATE|mapflags, fd, sect->Offset );
361 if( sect->FileSize < sect->MemSize ) {
362 mapflags |= MMAP_MAP_ANONYMOUS;
364 (void*)(addr + sect->FileSize), sect->MemSize - sect->FileSize,
365 protflags, MMAP_MAP_PRIVATE|mapflags,
368 // memset((void*)(addr + sect->FileSize), 0, sect->MemSize - sect->FileSize);
372 Log_Debug("Binary", "PID %i - Mapped '%s' to 0x%x", Threads_GetPID(), Path, base);
375 //LOG("*0x%x = 0x%x\n", binary->Pages[0].Virtual, *(Uint*)binary->Pages[0].Virtual);
383 * \fn Uint Binary_IsMapped(tBinary *binary)
384 * \brief Check if a binary is already mapped into the address space
385 * \param binary Binary information to check
386 * \return Current Base or 0
388 Uint Binary_IsMapped(tBinary *binary)
392 // Check prefered base
393 iBase = binary->Base;
394 if(MM_GetPage( iBase ) == (binary->Pages[0].Physical & ~0xFFF))
397 for(iBase = BIN_HIGHEST;
399 iBase -= BIN_GRANUALITY)
401 if(MM_GetPage( iBase ) == (binary->Pages[0].Physical & ~0xFFF))
410 * \fn tBinary *Binary_DoLoad(char *truePath)
411 * \brief Loads a binary file into memory
412 * \param truePath Absolute filename of binary
414 tBinary *Binary_DoLoad(tMount MountID, tInode Inode, const char *Path)
419 tBinaryType *bt = gRegBinTypes;
421 ENTER("iMountID XInode sPath", MountID, Inode, Path);
424 fp = VFS_OpenInode(MountID, Inode, VFS_OPENFLAG_READ);
426 LOG("Unable to load file, access denied");
431 LOG("fp = 0x%x", fp);
434 VFS_Read(fp, 4, &ident);
435 VFS_Seek(fp, 0, SEEK_SET);
437 LOG("ident = 0x%x", ident);
439 // Determine the type
440 for(; bt; bt = bt->Next)
442 if( (ident & bt->Mask) != (Uint32)bt->Ident )
444 LOG("bt = %p (%s)", bt, bt->Name);
445 pBinary = bt->Load(fp);
449 LOG("pBinary = %p", pBinary);
456 Log_Warning("Binary", "'%s' is an unknown file type. (%02x %02x %02x %02x)",
457 Path, ident&0xFF, (ident>>8)&0xFF, (ident>>16)&0xFF, (ident>>24)&0xFF);
463 if(pBinary == NULL) {
468 // Initialise Structure
469 pBinary->ReferenceCount = 0;
470 pBinary->MountID = MountID;
471 pBinary->Inode = Inode;
474 LOG("Interpreter: '%s'", pBinary->Interpreter);
475 LOG("Base: 0x%x, Entry: 0x%x", pBinary->Base, pBinary->Entry);
476 LOG("NumSections: %i", pBinary->NumSections);
479 SHORTLOCK(&glBinListLock);
480 pBinary->Next = glLoadedBinaries;
481 glLoadedBinaries = pBinary;
482 SHORTREL(&glBinListLock);
484 // TODO: Register the path with the binary
492 * \fn void Binary_Unload(void *Base)
493 * \brief Unload / Unmap a binary
494 * \param Base Loaded Base
495 * \note Currently used only for kernel libaries
497 void Binary_Unload(void *Base)
500 tKernelBin *prev = NULL;
503 if((Uint)Base < 0xC0000000)
505 // TODO: User Binaries
506 Log_Warning("BIN", "Unloading user binaries is currently unimplemented");
511 for(pKBin = glLoadedKernelLibs;
513 prev = pKBin, pKBin = pKBin->Next)
516 if(pKBin->Base != Base) continue;
518 for(i = 0; i < pKBin->Info->NumSections; i++)
520 // TODO: VFS_MUnmap();
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(const 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(const char *File)
596 tKernelBin *pKBinary;
601 ENTER("sFile", File);
603 // Sanity Check Argument
610 int fd = VFS_Open(File, VFS_OPENFLAG_READ);
616 VFS_FInfo(fd, &info, 0);
617 mount_id = info.mount;
622 // Check if the binary has already been loaded
623 if( (pBinary = Binary_GetInfo(mount_id, inode)) )
625 for(pKBinary = glLoadedKernelLibs;
627 pKBinary = pKBinary->Next )
629 if(pKBinary->Info == pBinary) {
630 LEAVE('p', pKBinary->Base);
631 return pKBinary->Base;
636 pBinary = Binary_DoLoad(mount_id, inode, File); // Else load it
639 if(pBinary == NULL) {
645 // Now pBinary is valid (either freshly loaded or only user mapped)
646 // So, map it into kernel space
649 // Reference Executable (Makes sure that it isn't unloaded)
650 pBinary->ReferenceCount ++;
652 Binary_MapIn(pBinary, File, KLIB_LOWEST, KLIB_HIGHEST);
655 if( !Binary_Relocate( (void*)base ) )
657 Log_Warning("Binary", "Relocation of '%s' failed, unloading", File);
658 Binary_Unload( (void*)base );
659 Binary_Dereference( pBinary );
664 // Add to list (relocator must look at itself manually, not via Binary_GetSymbol)
665 pKBinary = malloc(sizeof(*pKBinary));
666 pKBinary->Base = (void*)base;
667 pKBinary->Info = pBinary;
668 SHORTLOCK( &glKBinListLock );
669 pKBinary->Next = glLoadedKernelLibs;
670 glLoadedKernelLibs = pKBinary;
671 SHORTREL( &glKBinListLock );
678 * \fn Uint Binary_Relocate(void *Base)
679 * \brief Relocates a loaded binary (used by kernel libraries)
680 * \param Base Loaded base address of binary
681 * \return Boolean Success
683 Uint Binary_Relocate(void *Base)
685 Uint32 ident = *(Uint32*) Base;
686 tBinaryType *bt = gRegBinTypes;
688 for(; bt; bt = bt->Next)
690 if( (ident & bt->Mask) == (Uint)bt->Ident )
691 return bt->Relocate( (void*)Base);
694 Log_Warning("BIN", "%p is an unknown file type. (%02x %02x %02x %02x)",
695 Base, ident&0xFF, (ident>>8)&0xFF, (ident>>16)&0xFF, (ident>>24)&0xFF);
700 * \fn int Binary_GetSymbol(char *Name, Uint *Val)
701 * \brief Get a symbol value
702 * \return Value of symbol or -1 on error
704 * Gets the value of a symbol from either the currently loaded
705 * libraries or the kernel's exports.
707 int Binary_GetSymbol(const char *Name, Uint *Val)
709 if( Binary_GetSymbolEx(Name, Val) ) return 1;
714 * \fn Uint Binary_GetSymbolEx(char *Name, Uint *Value)
715 * \brief Get a symbol value
717 * Gets the value of a symbol from either the currently loaded
718 * libraries or the kernel's exports.
720 Uint Binary_GetSymbolEx(const char *Name, Uint *Value)
724 int numKSyms = ((Uint)&gKernelSymbolsEnd-(Uint)&gKernelSymbols)/sizeof(tKernelSymbol);
727 for( i = 0; i < numKSyms; i++ )
729 if(strcmp(Name, gKernelSymbols[i].Name) == 0) {
730 *Value = gKernelSymbols[i].Value;
735 // Scan Loaded Libraries
736 for(pKBin = glLoadedKernelLibs;
738 pKBin = pKBin->Next )
740 if( Binary_FindSymbol(pKBin->Base, Name, Value) ) {
745 Log_Warning("BIN", "Unable to find symbol '%s'", Name);
750 * \fn Uint Binary_FindSymbol(void *Base, char *Name, Uint *Val)
751 * \brief Get a symbol from the specified library
752 * \param Base Base address
753 * \param Name Name of symbol to find
754 * \param Val Pointer to place final value
756 Uint Binary_FindSymbol(void *Base, const char *Name, Uint *Val)
758 Uint32 ident = *(Uint32*) Base;
759 tBinaryType *bt = gRegBinTypes;
761 for(; bt; bt = bt->Next)
763 if( (ident & bt->Mask) == (Uint)bt->Ident )
764 return bt->GetSymbol(Base, Name, Val);
767 Log_Warning("BIN", "Binary_FindSymbol - %p is an unknown file type. (%02x %02x %02x %02x)",
768 Base, ident&0xFF, ident>>8, ident>>16, ident>>24);
773 * \brief Check if a range of memory is fully free
774 * \return Inverse boolean free (0 if all pages are unmapped)
776 int Binary_int_CheckMemFree( tVAddr _start, size_t _len )
778 _len += _start & (PAGE_SIZE-1);
779 _len = (_len + PAGE_SIZE - 1) & ~(PAGE_SIZE-1);
780 _start &= ~(PAGE_SIZE-1);
781 for( ; _len > PAGE_SIZE; _len -= PAGE_SIZE, _start += PAGE_SIZE ) {
782 if( MM_GetPhysAddr(_start) != 0 )
785 if( _len == PAGE_SIZE && MM_GetPhysAddr(_start) != 0 )
792 EXPORT(Binary_FindSymbol);
793 EXPORT(Binary_Unload);