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 * \fn tVAddr Binary_Load(char *Path, tVAddr *EntryPoint)
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
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;
222 // TODO: Also get modifcation time?
224 // Check if the binary has already been loaded
225 if( !(pBinary = Binary_GetInfo(mount_id, inode)) )
226 pBinary = Binary_DoLoad(mount_id, inode, Path); // Else load it
229 if(pBinary == NULL) {
234 // Map into process space
235 base = Binary_MapIn(pBinary, Path, BIN_LOWEST, BIN_HIGHEST);
244 if(pBinary->Interpreter) {
246 if( Binary_Load(pBinary->Interpreter, &start) == 0 ) {
253 *EntryPoint = pBinary->Entry - pBinary->Base + base;
256 LOG("*EntryPoint = 0x%x", *EntryPoint);
258 return base; // Pass the base as an argument to the user if there is an interpreter
262 * \brief Finds a matching binary entry
263 * \param TruePath File Identifier (True path name)
265 tBinary *Binary_GetInfo(tMount MountID, tInode InodeID)
268 pBinary = glLoadedBinaries;
271 if(pBinary->MountID == MountID && pBinary->Inode == InodeID)
273 pBinary = pBinary->Next;
279 \fn Uint Binary_MapIn(tBinary *binary)
280 \brief Maps an already-loaded binary into an address space.
281 \param binary Pointer to globally stored data.
283 tVAddr Binary_MapIn(tBinary *Binary, const char *Path, tVAddr LoadMin, tVAddr LoadMax)
288 ENTER("pBinary sPath pLoadMin pLoadMax", Binary, Path, LoadMin, LoadMax);
290 // Reference Executable (Makes sure that it isn't unloaded)
291 Binary->ReferenceCount ++;
296 // Check if base is free
299 LOG("Checking base %p", base);
300 for(i=0;i<Binary->NumSections;i++)
302 if( Binary_int_CheckMemFree( Binary->LoadSections[i].Virtual, Binary->LoadSections[i].MemSize ) )
305 LOG("Address 0x%x is taken\n", Binary->LoadSections[i].Virtual);
311 // Check if the executable has no base or it is not free
314 // If so, give it a base
316 while(base >= LoadMin)
318 for( i = 0; i < Binary->NumSections; i ++ )
320 tVAddr addr = Binary->LoadSections[i].Virtual - Binary->Base + base;
321 if( Binary_int_CheckMemFree( addr, Binary->LoadSections[i].MemSize ) )
324 // If space was found, break
325 if(i == Binary->NumSections) break;
326 // Else decrement pointer and try again
327 base -= BIN_GRANUALITY;
329 LOG("Allocated base %p", base);
334 Log_Warning("Binary", "Executable '%s' cannot be loaded, no space", Path);
340 fd = VFS_OpenInode(Binary->MountID, Binary->Inode, VFS_OPENFLAG_READ);
341 for( i = 0; i < Binary->NumSections; i ++ )
343 tBinarySection *sect = &Binary->LoadSections[i];
344 Uint protflags, mapflags;
345 tVAddr addr = sect->Virtual - Binary->Base + base;
346 LOG("%i - %p to 0x%llx (%x)", i, addr, sect->Offset, sect->Flags);
348 protflags = MMAP_PROT_READ;
349 mapflags = MMAP_MAP_FIXED;
351 if( sect->Flags & BIN_SECTFLAG_EXEC )
352 protflags |= MMAP_PROT_EXEC;
353 if( sect->Flags & BIN_SECTFLAG_RO ) {
354 VFS_MMap( (void*)addr, sect->FileSize, protflags, MMAP_MAP_SHARED|mapflags, fd, sect->Offset );
357 protflags |= MMAP_PROT_WRITE;
358 VFS_MMap( (void*)addr, sect->FileSize, protflags, MMAP_MAP_PRIVATE|mapflags, fd, sect->Offset );
360 if( sect->FileSize < sect->MemSize ) {
361 mapflags |= MMAP_MAP_ANONYMOUS;
363 (void*)(addr + sect->FileSize), sect->MemSize - sect->FileSize,
364 protflags, MMAP_MAP_PRIVATE|mapflags,
367 // memset((void*)(addr + sect->FileSize), 0, sect->MemSize - sect->FileSize);
371 Log_Debug("Binary", "PID %i - Mapped '%s' to 0x%x", Threads_GetPID(), Path, base);
374 //LOG("*0x%x = 0x%x\n", binary->Pages[0].Virtual, *(Uint*)binary->Pages[0].Virtual);
382 * \fn Uint Binary_IsMapped(tBinary *binary)
383 * \brief Check if a binary is already mapped into the address space
384 * \param binary Binary information to check
385 * \return Current Base or 0
387 Uint Binary_IsMapped(tBinary *binary)
391 // Check prefered base
392 iBase = binary->Base;
393 if(MM_GetPage( iBase ) == (binary->Pages[0].Physical & ~0xFFF))
396 for(iBase = BIN_HIGHEST;
398 iBase -= BIN_GRANUALITY)
400 if(MM_GetPage( iBase ) == (binary->Pages[0].Physical & ~0xFFF))
409 * \fn tBinary *Binary_DoLoad(char *truePath)
410 * \brief Loads a binary file into memory
411 * \param truePath Absolute filename of binary
413 tBinary *Binary_DoLoad(tMount MountID, tInode Inode, const char *Path)
418 tBinaryType *bt = gRegBinTypes;
420 ENTER("iMountID XInode sPath", MountID, Inode, Path);
423 fp = VFS_OpenInode(MountID, Inode, VFS_OPENFLAG_READ);
425 LOG("Unable to load file, access denied");
430 LOG("fp = 0x%x", fp);
433 VFS_Read(fp, 4, &ident);
434 VFS_Seek(fp, 0, SEEK_SET);
436 LOG("ident = 0x%x", ident);
438 // Determine the type
439 for(; bt; bt = bt->Next)
441 if( (ident & bt->Mask) != (Uint32)bt->Ident )
443 LOG("bt = %p (%s)", bt, bt->Name);
444 pBinary = bt->Load(fp);
448 LOG("pBinary = %p", pBinary);
455 Log_Warning("Binary", "'%s' is an unknown file type. (%02x %02x %02x %02x)",
456 Path, ident&0xFF, (ident>>8)&0xFF, (ident>>16)&0xFF, (ident>>24)&0xFF);
462 if(pBinary == NULL) {
467 // Initialise Structure
468 pBinary->ReferenceCount = 0;
469 pBinary->MountID = MountID;
470 pBinary->Inode = Inode;
473 LOG("Interpreter: '%s'", pBinary->Interpreter);
474 LOG("Base: 0x%x, Entry: 0x%x", pBinary->Base, pBinary->Entry);
475 LOG("NumSections: %i", pBinary->NumSections);
478 SHORTLOCK(&glBinListLock);
479 pBinary->Next = glLoadedBinaries;
480 glLoadedBinaries = pBinary;
481 SHORTREL(&glBinListLock);
483 // TODO: Register the path with the binary
491 * \fn void Binary_Unload(void *Base)
492 * \brief Unload / Unmap a binary
493 * \param Base Loaded Base
494 * \note Currently used only for kernel libaries
496 void Binary_Unload(void *Base)
499 tKernelBin *prev = NULL;
502 if((Uint)Base < 0xC0000000)
504 // TODO: User Binaries
505 Log_Warning("BIN", "Unloading user binaries is currently unimplemented");
510 for(pKBin = glLoadedKernelLibs;
512 prev = pKBin, pKBin = pKBin->Next)
515 if(pKBin->Base != Base) continue;
517 for(i = 0; i < pKBin->Info->NumSections; i++)
519 // TODO: VFS_MUnmap();
521 // Dereference Binary
522 Binary_Dereference( pKBin->Info );
524 if(prev) prev->Next = pKBin->Next;
525 else glLoadedKernelLibs = pKBin->Next;
533 * \fn void Binary_Dereference(tBinary *Info)
534 * \brief Dereferences and if nessasary, deletes a binary
535 * \param Info Binary information structure
537 void Binary_Dereference(tBinary *Info)
539 // Decrement reference count
540 Info->ReferenceCount --;
542 // Check if it is still in use
543 if(Info->ReferenceCount) return;
545 /// \todo Implement binary freeing
549 * \fn char *Binary_RegInterp(char *Path)
550 * \brief Registers an Interpreter
551 * \param Path Path to interpreter provided by executable
553 char *Binary_RegInterp(char *Path)
556 // NULL Check Argument
557 if(Path == NULL) return NULL;
558 // NULL Check the array
559 if(gsaRegInterps == NULL)
562 gsaRegInterps = malloc( sizeof(char*) );
563 gsaRegInterps[0] = malloc( strlen(Path) );
564 strcpy(gsaRegInterps[0], Path);
565 return gsaRegInterps[0];
569 for( i = 0; i < giRegInterps; i++ )
571 if(strcmp(gsaRegInterps[i], Path) == 0)
572 return gsaRegInterps[i];
575 // Interpreter is not in list
577 gsaRegInterps = malloc( sizeof(char*)*giRegInterps );
578 gsaRegInterps[i] = malloc( strlen(Path) );
579 strcpy(gsaRegInterps[i], Path);
580 return gsaRegInterps[i];
584 // Kernel Binary Handling
587 * \fn void *Binary_LoadKernel(const char *File)
588 * \brief Load a binary into kernel space
589 * \note This function shares much with #Binary_Load, but does it's own mapping
590 * \param File File to load into the kernel
592 void *Binary_LoadKernel(const char *File)
595 tKernelBin *pKBinary;
600 ENTER("sFile", File);
602 // Sanity Check Argument
609 int fd = VFS_Open(File, VFS_OPENFLAG_READ);
615 VFS_FInfo(fd, &info, 0);
616 mount_id = info.mount;
621 // Check if the binary has already been loaded
622 if( (pBinary = Binary_GetInfo(mount_id, inode)) )
624 for(pKBinary = glLoadedKernelLibs;
626 pKBinary = pKBinary->Next )
628 if(pKBinary->Info == pBinary) {
629 LEAVE('p', pKBinary->Base);
630 return pKBinary->Base;
635 pBinary = Binary_DoLoad(mount_id, inode, File); // Else load it
638 if(pBinary == NULL) {
644 // Now pBinary is valid (either freshly loaded or only user mapped)
645 // So, map it into kernel space
648 // Reference Executable (Makes sure that it isn't unloaded)
649 pBinary->ReferenceCount ++;
651 Binary_MapIn(pBinary, File, KLIB_LOWEST, KLIB_HIGHEST);
654 if( !Binary_Relocate( (void*)base ) )
656 Log_Warning("Binary", "Relocation of '%s' failed, unloading", File);
657 Binary_Unload( (void*)base );
658 Binary_Dereference( pBinary );
663 // Add to list (relocator must look at itself manually, not via Binary_GetSymbol)
664 pKBinary = malloc(sizeof(*pKBinary));
665 pKBinary->Base = (void*)base;
666 pKBinary->Info = pBinary;
667 SHORTLOCK( &glKBinListLock );
668 pKBinary->Next = glLoadedKernelLibs;
669 glLoadedKernelLibs = pKBinary;
670 SHORTREL( &glKBinListLock );
677 * \fn Uint Binary_Relocate(void *Base)
678 * \brief Relocates a loaded binary (used by kernel libraries)
679 * \param Base Loaded base address of binary
680 * \return Boolean Success
682 Uint Binary_Relocate(void *Base)
684 Uint32 ident = *(Uint32*) Base;
685 tBinaryType *bt = gRegBinTypes;
687 for(; bt; bt = bt->Next)
689 if( (ident & bt->Mask) == (Uint)bt->Ident )
690 return bt->Relocate( (void*)Base);
693 Log_Warning("BIN", "%p is an unknown file type. (%02x %02x %02x %02x)",
694 Base, ident&0xFF, (ident>>8)&0xFF, (ident>>16)&0xFF, (ident>>24)&0xFF);
699 * \fn int Binary_GetSymbol(char *Name, Uint *Val)
700 * \brief Get a symbol value
701 * \return Value of symbol or -1 on error
703 * Gets the value of a symbol from either the currently loaded
704 * libraries or the kernel's exports.
706 int Binary_GetSymbol(const char *Name, Uint *Val)
708 if( Binary_GetSymbolEx(Name, Val) ) return 1;
713 * \fn Uint Binary_GetSymbolEx(char *Name, Uint *Value)
714 * \brief Get a symbol value
716 * Gets the value of a symbol from either the currently loaded
717 * libraries or the kernel's exports.
719 Uint Binary_GetSymbolEx(const char *Name, Uint *Value)
723 int numKSyms = ((Uint)&gKernelSymbolsEnd-(Uint)&gKernelSymbols)/sizeof(tKernelSymbol);
726 for( i = 0; i < numKSyms; i++ )
728 if(strcmp(Name, gKernelSymbols[i].Name) == 0) {
729 *Value = gKernelSymbols[i].Value;
734 // Scan Loaded Libraries
735 for(pKBin = glLoadedKernelLibs;
737 pKBin = pKBin->Next )
739 if( Binary_FindSymbol(pKBin->Base, Name, Value) ) {
744 Log_Warning("BIN", "Unable to find symbol '%s'", Name);
749 * \fn Uint Binary_FindSymbol(void *Base, char *Name, Uint *Val)
750 * \brief Get a symbol from the specified library
751 * \param Base Base address
752 * \param Name Name of symbol to find
753 * \param Val Pointer to place final value
755 Uint Binary_FindSymbol(void *Base, const char *Name, Uint *Val)
757 Uint32 ident = *(Uint32*) Base;
758 tBinaryType *bt = gRegBinTypes;
760 for(; bt; bt = bt->Next)
762 if( (ident & bt->Mask) == (Uint)bt->Ident )
763 return bt->GetSymbol(Base, Name, Val);
766 Log_Warning("BIN", "Binary_FindSymbol - %p is an unknown file type. (%02x %02x %02x %02x)",
767 Base, ident&0xFF, ident>>8, ident>>16, ident>>24);
772 * \brief Check if a range of memory is fully free
773 * \return Inverse boolean free (0 if all pages are unmapped)
775 int Binary_int_CheckMemFree( tVAddr _start, size_t _len )
777 _len += _start & (PAGE_SIZE-1);
778 _len = (_len + PAGE_SIZE - 1) & ~(PAGE_SIZE-1);
779 _start &= ~(PAGE_SIZE-1);
780 for( ; _len > PAGE_SIZE; _len -= PAGE_SIZE, _start += PAGE_SIZE ) {
781 if( MM_GetPhysAddr(_start) != 0 )
784 if( _len == PAGE_SIZE && MM_GetPhysAddr(_start) != 0 )
791 EXPORT(Binary_FindSymbol);
792 EXPORT(Binary_Unload);