Skip to content

Latest commit

 

History

History
35 lines (19 loc) · 2.79 KB

16_writing_user_programs_in_C.md

File metadata and controls

35 lines (19 loc) · 2.79 KB

Writing User Programs in C

Overview

Enabling users to write their own programs in C requires stdlib which provides a set of functions for memory allocation, string manipulation, and other functions which involves calling the kernel system calls. The stdlib library is not part of the kernel, so we need to implement it. Any user program written in C must be linked with the stdlib library.

The very first step in implementing the stdlib is the entry point of a user program, which is the main function. In the assembly code, we declare _start as the entry point of a user program. The _start function calls main which is declared as extern in the assembly code. The main function is defined in the user's C code.

The user program file is processed by our ELF loader, where the entry point is set to stdlib's _start address. The _start function then calls main which is the entry point of the user's C code.

Note that running hello in this commit will cause a page fault. This is because we have not implemented the exit system call yet. The exit system call is called when the main function returns. The exit system call will be responsible for terminating tasks and the process and freeing the memory allocated by the user program.

Standard Library

print function and getchar, putchar functions

The first function we implement is the print function. The print function is a wrapper of the INT80h command 1, sys_print, system call. Note that this is for testing purposes only. We will implement the standard library's printf function later.

malloc & free functions

Implementing malloc and free functions is similar to what we did with the print function. Each time the malloc function is called, we allocate a page of memory and record the address of the allocated memory in the current process's allocations array.

In this commit, we don't map the allocated memory to the user's virtual address space. That is because, in our system, the heap area's user space virtual address is the same as the kernel's virtual address. We will fix this later.

  • malloc and free commit
  • Abstracting standard library system calls with make_syscall commit

Previous | Next | Home