nixawk / hello-c

c programming
9 stars 11 forks source link

c - memory layout #1

Open nixawk opened 7 years ago

nixawk commented 7 years ago

References

nixawk commented 7 years ago

Notice: please use x86 platform or -m32.

#!/bin/bash

for file in `ls *.c`;do gcc $file -o "${file/\.c/\.out}";done

ls *.out | xargs size

   text    data     bss     dec     hex filename
   1484     300       4    1788     6fc main.out

   1484     304       4    1792     700 global_var_init.out
   1484     304       4    1792     700 static_var_init.out

   1484     300       8    1792     700 global_var_uninit.out
   1484     300       8    1792     700 static_var_uninit.out
nixawk commented 7 years ago
screen shot 2017-08-28 at 02 38 02

References

  1. https://www.youtube.com/watch?v=0jhQBQcGnuM
nixawk commented 7 years ago

screen shot 2017-08-28 at 03 02 44

Processes running under the user space have access only to a limited part of memory, whereas the kernel has access to all of the memory. Processes running in user space also don't have access to the kernel space. User space processes can only access a small part of the kernel via an interface exposed by the kernel - the system calls. If a process performs a system call, a software interrupt is sent to the kernel, which then dispatches the appropriate interrupt handler and continues its work after the handler has finished.

Kernel space code has the property to run in "kernel mode", which (in your typical desktop -x86- computer) is what you call code that executes under ring 0. Typically in x86 architecture, there are 4 rings of protection. Ring 0 (kernel mode), Ring 1 (may be used by virtual machine hypervisors or drivers), Ring 2 (may be used by drivers, I am not so sure about that though). Ring 3 is what typical applications run under. It is the least privileged ring, and applications running on it have access to a subset of the processor's instructions. Ring 0 (kernel space) is the most privileged ring, and has access to all of the machine's instructions. For example to this, a "plain" application (like a browser) can not use x86 assembly instructions lgdt to load the global descriptor table or hlt to halt a processor.

References

  1. https://en.wikipedia.org/wiki/User_space
  2. https://unix.stackexchange.com/questions/87625/what-is-difference-between-user-space-and-kernel-space
  3. https://en.wikipedia.org/wiki/Protection_ring
  4. https://www.usna.edu/Users/cs/aviv/classes/ic221/s16/lec/11/lec.html