Geekos tour-project2 (start a new user address process)

Source: Internet
Author: User

The compilation of this project and the configuration of bochrc are nothing special, so the following interface is displayed when bochs is started after compilation:

OK, you can seeUnimplemented feature.: switch to a new user address space, if necessary.This is our task.

This statement is concise: a new user address space is created. but let's take a look at the attached document, Project synopsis. you will find that there are more than one task. read this section carefully and organize the specific tasks as follows:

1. InSrc/geekos/user. cTo implement the spawn () and switch_to_user_context () functions, the spawn () function is mainly used to start a new user process, switch_to_user_context () it is used to enable a new thread to switch user address space before being scheduled.

2. InSrc/geekos/elf. cYou must implement the parse_elf_executable () function, which is the same as that processed by project1, including the offset, length, user address, and data segments of the executable ELF file to be read. based on this information, it is filled in the exe_format struct, which is called by the spawn () function. of course, this depends on how to load the executable file.
You can directly use the previous project1 code.

3. In src/geekos/userseg. C, many functions are implemented, including destroy_user_context (), load_user_program (), copy_from_user (), copy_to_user (), and switch_to_address_space ()

Destroy_user_context (): releases memory resources of user processes.

Load_user_program (): load some executable programs to the memory.

Copy_from_user () and copy_to_user (): Copy data between the user address space and the kernel address space.

Switch_to_address_space (): activates the user address space when loading the LDT register of the processor.

4. InSrc/geekos/kthread. cSetup_user_thread () and start_user_thread () must be implemented. setup_user_thread is the kernel initialization stack of the process, that is, when the process enters the user State for the first time, to initialize the content in the register of the processor. start_user_thread () mainly uses the user_conect object to start a new process.

According to the above analysis, the basic goal has been clarified. The following code needs to be filled in step by step.

Start by starting a new user process. Let's take a look at the spawn prototype:

 int Spawn(const char *program, const char *command, struct Kernel_Thread **pThread);

Program: Path of the executable file

Command: this parameter includes the program name and parameters.

Pthread: kernel_thread pointer

Returned value: the ID of the new process otherwise return erro code

You can use hints in the spwan function to complete the entire function:

 88     /* 89      * Hints: 90      * - Call Read_Fully() to load the entire executable into a memory buffer 91      * - Call Parse_ELF_Executable() to verify that the executable is 92      *   valid, and to populate an Exe_Format data structure describing 93      *   how the executable should be loaded 94      * - Call Load_User_Program() to create a User_Context with the loaded 95      *   program 96      * - Call Start_User_Thread() with the new User_Context 97      * 98      * If all goes well, store the pointer to the new thread in 99      * pThread and return 0.  Otherwise, return an error code.100      */

Read_fully () loads the entire executable file to the memory. The prototype isVFS. hMedium

char* exeFileData; //reference to variable where pointer to allocated bufferulong_t exeFileLen; //reference to variable where length of file should be storedint ret = Read_Fully(program, &exeFileData,  &exeFileLen);if (ret != 0) {     Print("Load Program %s failed!\n", program);     return -1;}

Parse_elf_executable () checks whether the elf executable file is valid. The prototype is
Elf. h
This function also needs to be implemented by ourselves. However, previously implemented project1 can be used directly.

struct  Exe_Format exeFmt;int ret = Parse_ELF_Executable(exeFileData, exeFileLen,  &exeFmt) ;if (ret != 0) {Print("Parse ELF_Executable File failed!\n);return -1;}

Load_user_program () creates a user_context to load the program. The prototype isUserseg. h. This function needs to be implemented

struct User_Context* userContext;int ret = Load_User_Program(exeFileData, exeFileLen, &exeFmt, command, &userContext);if (ret !=0) {   Print("Load User Program failed!\n);   return -1;}

Start_user_thread () uses the created user_context and enables the process to enter the prototype in the preparation queue.Kthread. h, This function is also implemented below

struct Kernel_Thread* t;t = Start_User_Thread(userContext, false);if (t ==null) {   Print("Start User thread failed\n");   return -1;}

The rest is to sort out the spawn function, so far.

Continue to view switch_to_user_context ()

void Switch_To_User_Context(struct Kernel_Thread* kthread, struct Interrupt_State* state);

Kthread:The thread that is about to execute

State:Saved processor registers describing the state when the thread WSA interrupted

143     /*144      * Hint: Before executing in user mode, you will need to call145      * the Set_Kernel_Stack_Pointer() and Switch_To_Address_Space()146      * functions.147      */

The prototype of the set_kernel_stack_pointer () function isTss. hTo set the kernel stack pointer, that is, the core stack of the new process. here we need to know that part of the hardware context of the Process exists in the TSS segment, and the rest is stored in the kernel state stack.

Switch_to_address_space () is a prototype of the function inUserseg. hTo switch the address space.

Here, we need to know that usercontext is the context of user-State processes. For kernel processes, this pointer is null, and all user processes have their own user_context. therefore, to determine whether a process is a kernel process or a user-state process, you only need to determine whether the usercontext field is null. the implementation of switch_to_user_context is as follows:

141  void Switch_To_User_Context(struct Kernel_Thread* kthread, struct Interrupt_State* state)142  {143      /*144      * Hint: Before executing in user mode, you will need to call145      * the Set_Kernel_Stack_Pointer() and Switch_To_Address_Space()146      * functions.147      */148      struct User_Context* curUserContext;149      struct User_Context* userContext = kthread->userContext;150      if(!userContext) return; //Kernel process151      if (userContext != curUserContext) {152          ulong_t stack;153          Switch_To_Address_Space(userContext);154          esp0 = kthread->stackPage + PAGE_SIZE;155          Set_Kernel_Stack_Pointer(esp0); //start new 156          curUserContext = userContext;157      }   158  }   

The following functions are implemented in src/geekos/userseg. C:

// Destroy a user_context object, including all memory and other resources allocated within it.

 68 void Destroy_User_Context(struct User_Context* userContext) 69 { 70     /* 71      * Hints: 72      * - you need to free the memory allocated for the user process 73      * - don't forget to free the segment descriptor allocated 74      *   for the process's LDT 75      */ 76     //TODO("Destroy a User_Context"); 77     Free_Segment_Descriptor(userContext->ldtDescriptor); //free LDT 78     Disable_Interrupts(); 79     Free(userContext->memory);  80     Free(userContext); 81     Enable_Interrupts(); 82 }

For more information about load_user_program (), see:

Besides loading the executable's text and data segments into memory, you will also need to create two other data structures in theprocess's memory space.

You will need to createStackFor the new process. The stack will reside at the top of the user address space. You can useDefault_user_stack_size
Macro inSrc/geekos/userseg. cAs the stack size.

You will also need to createArgument BlockDatastructure. This data structure createsArgcAndArgvArguments that are passed toMain ()Function
Of the user process. Two functions are defined to help you build theargument block (prototypes in<Geekos/argblock. h>).Get_argument_block_size ()TakesCommand stringPassed
ToSpawn ()Function and determines how manycommand line arguments there will be, and how manybytes are required to store the argument block.Format_argument_block ()Function takes the number of arguments
And Argument block size fromGet_argument_block_size ()And builds the argument block data structure in the memory location you haveallocated for it.

Note that you will need to take the size of the stack and argument blockinto account when you decide how much memory to allocate for theprocess.

Then you can write the statement based on hint:

   /*     * Hints:     * - Determine where in memory each executable segment will be placed     * - Determine size of argument block and where it memory it will     *   be placed     * - Copy each executable segment into memory     * - Format argument block in memory     * - In the created User_Context object, set code entry point     *   address, argument block address, and initial kernel stack pointer     *   address     */

User process block size = round_up_to_page (maxva) + default_user_stack_size; // round_up_to_page indicates the total size of the parameter block

Then obtain the size, create a context for the user process through create_user_context (size), and copy each executable segment into memory. copy the content of exeformat-> segment [I] To usercontext. finally, initialize data, entry address, and stack pointer operations.

The two functions copy_from_user and copy_to_user copy data between the user address space and the kernel address space are implemented based on the user_context, g_currentthread-> usercontext of the current process.

Both use the validate_user_memory function, which plays a defensive role. If the function is incorrect, perform memcpy again. The following is the implementation:

bool Copy_From_User(void* destInKernel, ulong_t srcInUser, ulong_t bufSize)198 {199     /*200      * Hints:201      * - the User_Context of the current process can be found202      *   from g_currentThread->userContext203      * - the user address is an index relative to the chunk204      *   of memory you allocated for it205      * - make sure the user buffer lies entirely in memory belonging206      *   to the process207      */208     //TODO("Copy memory from user buffer to kernel buffer");209     //Validate_User_Memory(NULL,0,0); /* delete this; keeps gcc happy */210     struct User_Context* UserContext = g_currentThread->userContext;211     if (!Validate_User_Memory(UserContext, srcInUser, bufSize)) return false;212     memcpy(destInKernel, UserContext->memory + srcInUser, bufSize);213 214     return true;215 }

229 bool Copy_To_User(ulong_t destInUser, void* srcInKernel, ulong_t bufSize)230 {231     /*232      * Hints: same as for Copy_From_User()233      */234     //TODO("Copy memory from kernel buffer to user buffer");235     struct User_Context* UserContext = g_currentThread->userContext;236     if (!Validate_User_Memory(UserContext, destInUser, bufSize)) return false;237     memcpy(UserContext->memory + destInUser, srcInKernel, bufSize);238 

Switch_to_address_space: Use LDT, that is, usercontext-> ldtselector, to switch to the Local Descriptor Table.

Use the following ASM:

 __asm__ __volatile__ ("lldt %0"::"a"(ldtSelector));

There are a lot of content to fill in for this project. There are implementation of kthread and syscall. I will not elaborate on it here. If you need it, please leave a message to ask.

The final implementation figure is as follows:

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.