Skip to content

Instantly share code, notes, and snippets.

@jvns
Last active August 30, 2024 17:24
Show Gist options
  • Save jvns/7688286 to your computer and use it in GitHub Desktop.
Save jvns/7688286 to your computer and use it in GitHub Desktop.
What happens when I run ./hello

(You can comment here.)

Here I'm trying to understand what happens when I run

./hello
#include <stdio.h>

int main() {
    printf("Hello!\n");
}

a simple "Hello World" program written in C, in Unix -- what I'd have to do if I wanted to write an OS that could execute it.

I'm going to assume that ./hello is statically linked, because that sounds simpler to deal with. It's worth noting that a statically linked hello is 868K on my machine. Eep.

I compiled it using

gcc -static hello.c -o hello

Any (nice!) comments or clarifications are appreciated.

Read from the filesystem

To run a program, I have to be able to find the program. So there would need to be some kind of filesystem and I would need to read the file from somewhere.

Copy the text into memory

In a Unix system, executables are in the ELF format.

So I would need to copy the "text" of the program somewhere.

Copy the data into memory

There is a string in the program. It needs to go somewhere.

Give the program a stack pointer

This program doesn't actually allocate memory, so perhaps it does not need a heap and it doesn't matter where the heap pointer is. It does need a stack. stack overflow question on how the stack works in assembly

Implement system calls

hello has some system calls in it. I found this out by running

objdump -d -M intel hello | grep 'syscall'

syscall is an assembly instruction for making a system call. That looks like

  401385:       b8 03 00 00 00          mov    eax,0x3
  40138a:       0f 05                   syscall 

The number stored in eax is the system call that is called. In this case, 3

There are 119 instances of syscall, and it's using several different system calls. This is worrying.

(Explained more in this stackoverflow question)

Making sure a stack overflow doesn't happen

I have no idea how the OS would check up on the program. I guess it doesn't just let the program run, but takes away control periodically and makes sure the stack pointer hasn't moved too far. How would it take away control? Hmm.

When there is a stack overflow I guess it sends a signal to the program, which is a POSIX thing.

I do not understand this.

???

There are no mallocs in the program, so I would not need to allocate memory for it or anything.

What else?!??

Outstanding questions

  • How long would this take for a human (where human = me) to write from scratch?
  • Is there a way to write a smaller program with less system calls and magic? There are like 50 system calls and what are they even doing?
  • Do I need a heap if I never use malloc?
  • Could I write my own printf in assembly that does less and is simpler? Just printing a string is pretty easy...
  • How do I kill a program?

Useful links

@danellis
Copy link

" if the CPU is busy executing something, how does the interrupt get called?"

It's done by the hardware. The timer is a physical unit within the CPU. When it reaches a preset value (or zero if it's counting downwards), it generates an interrupt, which causes the CPU to stop whatever it's doing and jump to the interrupt handler. I don't know the details of how this is done on x86, but on ARM it stacks a few registers for you (including the program counter), then loads an address from the "vector table" (a table that has the addresses of all your fault handlers and interrupt handlers), switches to privileged mode and jumps to that address. That would be the addresses of your scheduler, which choose the next task to run and switches the stack pointer to the one for that task. Then, when it returns, the CPU unstacks the registers, but this time they're the saved ones of a different process, including a different saved program counter, so it "returns" to a different process. Of course, in a x86 system you also have to change the virtual-to-physical page mappings to those of the next process so that it's mapped into the same virtual memory space.

@danluu
Copy link

danluu commented Nov 28, 2013

I don't know the details of how this is done on x86, but on ARM

x86 has the same mechanism as ARM[1].

If the question is what actually keeps track of the time in order to trigger a timer interrupt, there are a few different mechanisms on x86. Modern OSes will use APIC or x2APIC timer interrupts. But if you just want to do something simple yourself, setting up the PIT is much simpler.

[1] Well, pretty much. The IDT is more general; more entires, and it has a gate descriptor, instead of just being basically a pointer.

@mjdominus
Copy link

Regarding those 50 system calls you see in the object dump, and the large size, my guess is that the linker is including a bunch of subroutines that you never call, and most of the stuff you see is not actually related to your program. For example, when I run nm on my executable, I get a huge listing of functions, including a bunch of time zone functions and Yacc parser functions that I certainly don't use. (There's probably some incantation you can give to the linker to prevent this, but I hate the linker and never touch it unless I have to.)

To see the system calls that your program actually performs as it executes, use strace as I described above.

@mjdominus
Copy link

Regarding your #2 above, the interrupt gets called periodically by the hardware, as @danellis remarked. But there's also a very important additional circumstance in which an interrupt occurs: there is a machine instruction which causes one when it is executed, and this is precisely how the hello program notifies the kernel that it wants to perform the write call. (At least, that's definitely how it works on a System/360 machine, which I am ashamed to say is the most recent architecture I am really familiar with. Most of my career has been at the source code level.)

You also asked about stack overflows. @danellis described how the stack grows downwards in memory. When your program tries to access an address off the bottom of the stack, the MMU generates an interrupt. The kernel gets control, and checks to see if your process is allowed to have another page of stack space; if so it gets the MMU to allocate one and map it into your process's address space, and then everything continues normally. But if it decides to refuse the request, perhaps because your process is marked in the kernel as only being allowed a limited amount of stack space, it instead sends your process a SEGV (‘segmentation violation’) signal, which then gets handled as usual; the default is for the process to exit immediately and the kernel copies its entire address space into a file named core in the process's working directory. The shell command ulimit, which is a thin wrapper around the kernel's ulimit system call, is for setting the stack size and other limits.

I don't know if there's any way for the process to find out how big its stack is. It can use ulimit to find out the maximum allowed size. I don't think there's a way for it to catch the interrupt generated by the MMU when it starts a new stack page. It can change the way it handles the SEGV signal. One thing it can do is to ask the kernel to transfer control to a "signal handler" function in case of SEGV, instead of killing the process instantly. The signal handler can try to reduce the size of the data segment so that the stack has more room to grow.

@jvns
Copy link
Author

jvns commented Nov 29, 2013

from @nevyn on Twitter:

afaik, the system does no bounds checks of memory. Instead, the hardware MMU starts a signal chain when bad access happens.

@jvns
Copy link
Author

jvns commented Nov 29, 2013

@danellis suggested

By the way, you might find 'Advanced Programming in the Unix Environment' by W Richard Stevens to be useful. It's a classic.

@danellis
Copy link

"I don't know if there's any way for the process to find out how big its stack is."

I don't know of a portable way. You can get the address of the bottom of the stack using a function that returns the address of an argument of local variable, but the top not only differs per platform, but is randomized slightly for security purposes. You can see how much memory is reserved for your stack space in /proc/self/maps, though:

$ grep '\[stack]' /proc/self/maps 
7fff227eb000-7fff2280c000 rw-p 00000000 00:00 0                          [stack]

@rythie
Copy link

rythie commented Nov 29, 2013

On your query about interrupts...

Interrupts can be called by any hardware that has a IRQ line. Interrupts are sent directly to one of the CPUs and they have a location in memory setup to jump to handle that interrupt quickly and get back to what they were doing.

Network interfaces, USB, disk controllers usually do interrupts when they have something ready to send, i.e. a new packet has come in the network interface (though sometimes they batch them which is called interrupt mitigation). There is also a programable timer chip on the motherboard, which in Linux OS is typically programmed to interrupt a set number of times a second (e.g. 1000 on my box) which calls the scheduler to run.

Processes run until they block (by doing a system call) or run out of their timeslice (~20ms). When a process blocks, the system handles the system call and typically that has some wait in it, e.g. it asks for something from disk that might take 1-10ms. The OS then does something else in that 1-10ms. When the data comes back from the disk an interrupt is raised and the system puts that into memory. The original process is now runable again and will be ran by the scheduler based on it's algorithm. If the process runs over it's timeslice (yours wouldn't - a but one doing some CPU intensive stuff would) some thing else can be scheduled for a bit before it get a chance to run again.

@lenary
Copy link

lenary commented Dec 5, 2013

Here's another resource for ELF Files: http://i.imgur.com/GZ5a0sb.png

I think it's really neat, how helpful it is though, remains to be seen.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment