On heap/stack and OS page swapping

863 views Asked by At

I am trying to understand few linux-related concepts Can anyone help me answer the following questions.

[Question I] I am aware that the compiler gives Virtual Address (VA) for a program's data and code segment. The OS uses these VA's and try to fit them into physical memory. This is what ELF loader (fs/binfmt_elf.c in source code) does in linux. When does the VA for stack and heap gets allocated for a process? I guess its dynamic, but from where does the VA come for those segments? If possible, can anyone point me to source codes.

[Question II] While I know that, physical memory is limited in size. Hence the OS has to swap out pages at times to keep several processes running. When it needs to swap out a page, it pulls the page from memory and writes it into disk. I completely agree that data and code pages can be written into disk (perhaps they get written back in the same area where they came from disk). But can the OS swap out the heap and stack pages as well? If yes, where will it store in disk?

2

There are 2 answers

1
user3344003 On

Question I:

You need to start with a simplified view. For question 1, think about it in terms of logical memory rather than virtual memory. Let's say we are doing this in 32bit mode, you will have a theoretical maximum of 3/4ths of 2^32 logical memory available to your process.

When your new process loads an executable, that entire address space is going to be null. By that I mean there is no memory at all (conceptually). The program loader will then read the instructions in the executable file to build the logical address space at the start of execution.

The loader will create a user stack. You've got to have one for the program to run. By that, I mean that the loader will allocate logical pages for the stack.

The loader will probably not create a heap. There will be an address range for the heap but the loader will probably not map pages to it. You can explicitly map pages using system calls to create pages for your own heap. Alternatively, you can call a library function like malloc() that will map pages for you.

Question II:

All user pages can be swapped out, including heap and stack. They go to the page file, which on Linux is a swap partition.

4
Alex Hoppus On

1.) In load_elf_binary

850         /* Do this so that we can load the interpreter, if need be.  We will
851            change some of these later */
852         retval = setup_arg_pages(bprm, randomize_stack_top(STACK_TOP),
853                                  executable_stack);

2.) In swap partition / file