15 213 The course that gives CMU its

  • Slides: 36
Download presentation
15 -213 “The course that gives CMU its Zip!” Exceptional Control Flow Part I

15 -213 “The course that gives CMU its Zip!” Exceptional Control Flow Part I Mar. 11, 2003 Topics n n n class 16. ppt Exceptions Process context switches Creating and destroying processes

Control Flow Computers do Only One Thing n n From startup to shutdown, a

Control Flow Computers do Only One Thing n n From startup to shutdown, a CPU simply reads and executes (interprets) a sequence of instructions, one at a time. This sequence is the system’s physical control flow (or flow of control). Physical control flow Time – 2– <startup> inst 1 inst 2 inst 3 … instn <shutdown> 15 -213, S’ 03

Altering the Control Flow Up to Now: two mechanisms for changing control flow: n

Altering the Control Flow Up to Now: two mechanisms for changing control flow: n Jumps and branches n Call and return using the stack discipline. Both react to changes in program state. n Insufficient for a useful system n Difficult for the CPU to react to changes in system state. l data arrives from a disk or a network adapter. l Instruction divides by zero l User hits ctl-c at the keyboard l System timer expires System needs mechanisms for “exceptional control flow” – 3– 15 -213, S’ 03

Exceptional Control Flow n Mechanisms for exceptional control flow exists at all levels of

Exceptional Control Flow n Mechanisms for exceptional control flow exists at all levels of a computer system. Low level Mechanism n exceptions l change in control flow in response to a system event (i. e. , change in system state) n Combination of hardware and OS software Higher Level Mechanisms n n Process context switch Signals Nonlocal jumps (setjmp/longjmp) Implemented by either: l OS software (context switch and signals). l C language runtime library: nonlocal jumps. – 4– 15 -213, S’ 03

System context for exceptions Keyboard Processor Interrupt controller Mouse Keyboard controller Modem Serial port

System context for exceptions Keyboard Processor Interrupt controller Mouse Keyboard controller Modem Serial port controller Printer Parallel port controller Local/IO Bus Memory IDE disk controller SCSI controller Video adapter Network adapter Display Network SCSI bus disk – 5– CDROM 15 -213, S’ 03

Exceptions An exception is a transfer of control to the OS in response to

Exceptions An exception is a transfer of control to the OS in response to some event (i. e. , change in processor state) User Process event current next OS exception processing by exception handler exception return (optional) – 6– 15 -213, S’ 03

Interrupt Vectors Exception numbers interrupt vector 0 1 2 n-1 . . . n

Interrupt Vectors Exception numbers interrupt vector 0 1 2 n-1 . . . n code for exception handler 0 Each type of event has a unique exception number k n code for exception handler 1 n Index into jump table (a. k. a. , interrupt vector) Jump table entry k points to a function (exception handler). Handler k is called each time exception k occurs. code for exception handler 2 . . . n code for exception handler n-1 – 7– 15 -213, S’ 03

Asynchronous Exceptions (Interrupts) Caused by events external to the processor n Indicated by setting

Asynchronous Exceptions (Interrupts) Caused by events external to the processor n Indicated by setting the processor’s interrupt pin n handler returns to “next” instruction. Examples: n I/O interrupts l hitting ctl-c at the keyboard l arrival of a packet from a network l arrival of a data sector from a disk n Hard reset interrupt l hitting the reset button n Soft reset interrupt l hitting ctl-alt-delete on a PC – 8– 15 -213, S’ 03

Synchronous Exceptions Caused by events that occur as a result of executing an instruction:

Synchronous Exceptions Caused by events that occur as a result of executing an instruction: n Traps l Intentional l Examples: system calls, breakpoint traps, special instructions l Returns control to “next” instruction n Faults l Unintentional but possibly recoverable l Examples: page faults (recoverable), protection faults (unrecoverable). l Either re-executes faulting (“current”) instruction or aborts. n Aborts l unintentional and unrecoverable l Examples: parity error, machine check. l Aborts current program – 9– 15 -213, S’ 03

Trap Example Opening a File n User calls open(filename, options) 0804 d 070 <__libc_open>:

Trap Example Opening a File n User calls open(filename, options) 0804 d 070 <__libc_open>: . . . 804 d 082: cd 80 804 d 084: 5 b. . . int pop $0 x 80 %ebx l Function open executes system call instruction int n OS must find or create file, get it ready for reading or writing n Returns integer file descriptor User Process int pop – 10 – OS exception Open file return 15 -213, S’ 03

Fault Example #1 Memory Reference n User writes to memory location n That portion

Fault Example #1 Memory Reference n User writes to memory location n That portion (page) of user’s memory is currently on disk 80483 b 7: n n n c 7 05 10 9 d 04 08 0 d movl OS page fault return – 11 – $0 xd, 0 x 8049 d 10 Page handler must load page into physical memory Returns to faulting instruction Successful on second try User Process event movl int a[1000]; main () { a[500] = 13; } Create page and load into memory 15 -213, S’ 03

Fault Example #2 int a[1000]; main () { a[5000] = 13; } Memory Reference

Fault Example #2 int a[1000]; main () { a[5000] = 13; } Memory Reference n User writes to memory location n Address is not valid 80483 b 7: c 7 05 60 e 3 04 08 0 d $0 xd, 0 x 804 e 360 n Page handler detects invalid address Sends SIGSEG signal to user process n User process exits with “segmentation fault” n User Process event movl OS page fault Detect invalid address Signal process – 12 – 15 -213, S’ 03

Processes Def: A process is an instance of a running program. n One of

Processes Def: A process is an instance of a running program. n One of the most profound ideas in computer science. n Not the same as “program” or “processor” Process provides each program with two key abstractions: n Logical control flow l Each program seems to have exclusive use of the CPU. n Private address space l Each program seems to have exclusive use of main memory. How are these Illusions maintained? n n – 13 – Process executions interleaved (multitasking) Address spaces managed by virtual memory system 15 -213, S’ 03

Logical Control Flows Each process has its own logical control flow Process A Process

Logical Control Flows Each process has its own logical control flow Process A Process B Process C Time – 14 – 15 -213, S’ 03

Concurrent Processes Two processes run concurrently (are concurrent) if their flows overlap in time.

Concurrent Processes Two processes run concurrently (are concurrent) if their flows overlap in time. Otherwise, they are sequential. Examples: n n Concurrent: A & B, A & C Sequential: B & C Process A Process B Process C Time – 15 -213, S’ 03

User View of Concurrent Processes Control flows for concurrent processes are physically disjoint in

User View of Concurrent Processes Control flows for concurrent processes are physically disjoint in time. However, we can think of concurrent processes are running in parallel with each other. Process A Process B Process C Time – 16 – 15 -213, S’ 03

Context Switching Processes are managed by a shared chunk of OS code called the

Context Switching Processes are managed by a shared chunk of OS code called the kernel n Important: the kernel is not a separate process, but rather runs as part of some user process Control flow passes from one process to another via a context switch. Process A code Process B code user code Time kernel code context switch user code – 17 – 15 -213, S’ 03

Private Address Spaces Each process has its own private address space. 0 xffff kernel

Private Address Spaces Each process has its own private address space. 0 xffff kernel virtual memory (code, data, heap, stack) 0 xc 0000000 0 x 40000000 user stack (created at runtime) read/write segment (. data, . bss) – 18 – 0 %esp (stack pointer) memory mapped region for shared libraries run-time heap (managed by malloc) 0 x 08048000 memory invisible to user code read-only segment (. init, . text, . rodata) brk loaded from the executable file unused 15 -213, S’ 03

fork: Creating new processes int fork(void) n n n creates a new process (child

fork: Creating new processes int fork(void) n n n creates a new process (child process) that is identical to the calling process (parent process) returns 0 to the child process returns child’s pid to the parent process if (fork() == 0) { printf("hello from childn"); } else { printf("hello from parentn"); } – 19 – Fork is interesting (and often confusing) because it is called once but returns twice 15 -213, S’ 03

Fork Example #1 Key Points n Parent and child both run same code l

Fork Example #1 Key Points n Parent and child both run same code l Distinguish parent from child by return value from fork n Start with same state, but each has private copy l Including shared output file descriptor l Relative ordering of their print statements undefined void fork 1() { int x = 1; pid_t pid = fork(); if (pid == 0) { printf("Child has x = %dn", ++x); } else { printf("Parent has x = %dn", --x); } printf("Bye from process %d with x = %dn", getpid(), x); } – 20 – 15 -213, S’ 03

Fork Example #2 Key Points n Both parent and child can continue forking void

Fork Example #2 Key Points n Both parent and child can continue forking void fork 2() { printf("L 0n"); fork(); printf("L 1n"); fork(); printf("Byen"); } – 21 – L 0 L 1 Bye Bye 15 -213, S’ 03

Fork Example #3 Key Points n Both parent and child can continue forking void

Fork Example #3 Key Points n Both parent and child can continue forking void fork 3() { printf("L 0n"); fork(); printf("L 1n"); fork(); printf("L 2n"); fork(); printf("Byen"); } L 1 L 0 – 22 – L 1 L 2 Bye Bye 15 -213, S’ 03

Fork Example #4 Key Points n Both parent and child can continue forking void

Fork Example #4 Key Points n Both parent and child can continue forking void fork 4() { printf("L 0n"); if (fork() != 0) { printf("L 1n"); if (fork() != 0) { printf("L 2n"); fork(); } } printf("Byen"); } – 23 – Bye L 0 L 1 L 2 Bye 15 -213, S’ 03

Fork Example #5 Key Points n Both parent and child can continue forking void

Fork Example #5 Key Points n Both parent and child can continue forking void fork 5() { printf("L 0n"); if (fork() == 0) { printf("L 1n"); if (fork() == 0) { printf("L 2n"); fork(); } } printf("Byen"); } – 24 – Bye L 2 L 1 L 0 Bye Bye 15 -213, S’ 03

exit: Destroying Process void exit(int status) n exits a process l Normally return with

exit: Destroying Process void exit(int status) n exits a process l Normally return with status 0 n atexit() registers functions to be executed upon exit void cleanup(void) { printf("cleaning upn"); } void fork 6() { atexit(cleanup); fork(); exit(0); } – 25 – 15 -213, S’ 03

Zombies Idea n When process terminates, still consumes system resources l Various tables maintained

Zombies Idea n When process terminates, still consumes system resources l Various tables maintained by OS n Called a “zombie” l Living corpse, half alive and half dead Reaping n n n Performed by parent on terminated child Parent is given exit status information Kernel discards process What if Parent Doesn’t Reap? n If any parent terminates without reaping a child, then child will be reaped by init process n Only need explicit reaping for long-running processes l E. g. , shells and servers – 26 – 15 -213, S’ 03

Zombie Example void fork 7() { if (fork() == 0) { /* Child */

Zombie Example void fork 7() { if (fork() == 0) { /* Child */ printf("Terminating Child, PID = %dn", getpid()); exit(0); } else { printf("Running Parent, PID = %dn", getpid()); linux>. /forks 7 & while (1) [1] 6639 ; /* Infinite loop */ Running Parent, PID = 6639 } Terminating Child, PID = 6640 } linux> ps PID TTY TIME 6585 ttyp 9 00: 00 6639 ttyp 9 00: 03 6640 ttyp 9 00: 00 6641 ttyp 9 00: 00 linux> kill 6639 [1] Terminated linux> ps PID TTY TIME 6585 ttyp 9 00: 00 6642 ttyp 9 00: 00 – 27 – CMD tcsh forks <defunct> ps n ps shows child process as “defunct” n Killing parent allows child to be reaped CMD tcsh ps 15 -213, S’ 03

Nonterminating Child Example void fork 8() { if (fork() == 0) { /* Child

Nonterminating Child Example void fork 8() { if (fork() == 0) { /* Child */ printf("Running Child, PID = %dn", getpid()); while (1) ; /* Infinite loop */ } else { printf("Terminating Parent, PID = %dn", getpid()); linux>. /forks 8 exit(0); Terminating Parent, PID = 6675 } } Running Child, PID = 6676 linux> ps PID TTY TIME 6585 ttyp 9 00: 00 6676 ttyp 9 00: 06 6677 ttyp 9 00: 00 linux> kill 6676 linux> ps PID TTY TIME 6585 ttyp 9 00: 00 6678 ttyp 9 00: 00 – 28 – CMD tcsh forks ps CMD tcsh ps n n Child process still active even though parent has terminated Must kill explicitly, or else will keep running indefinitely 15 -213, S’ 03

wait: Synchronizing with children int wait(int *child_status) n n n – 29 – suspends

wait: Synchronizing with children int wait(int *child_status) n n n – 29 – suspends current process until one of its children terminates return value is the pid of the child process that terminated if child_status != NULL, then the object it points to will be set to a status indicating why the child process terminated 15 -213, S’ 03

wait: Synchronizing with children void fork 9() { int child_status; if (fork() == 0)

wait: Synchronizing with children void fork 9() { int child_status; if (fork() == 0) { printf("HC: hello from childn"); } else { printf("HP: hello from parentn"); wait(&child_status); printf("CT: child has terminatedn"); } printf("Byen"); exit(); } – 30 – HC Bye HP CT Bye 15 -213, S’ 03

Wait Example n n If multiple children completed, will take in arbitrary order Can

Wait Example n n If multiple children completed, will take in arbitrary order Can use macros WIFEXITED and WEXITSTATUS to get information about exit status void fork 10() { pid_t pid[N]; int i; int child_status; for (i = 0; i < N; i++) if ((pid[i] = fork()) == 0) exit(100+i); /* Child */ for (i = 0; i < N; i++) { pid_t wpid = wait(&child_status); if (WIFEXITED(child_status)) printf("Child %d terminated with exit status %dn", wpid, WEXITSTATUS(child_status)); else printf("Child %d terminate abnormallyn", wpid); 15 -213, S’ 03 – 31 – } }

Waitpid n waitpid(pid, &status, options) l Can wait for specific process l Various options

Waitpid n waitpid(pid, &status, options) l Can wait for specific process l Various options void fork 11() { pid_t pid[N]; int i; int child_status; for (i = 0; i < N; i++) if ((pid[i] = fork()) == 0) exit(100+i); /* Child */ for (i = 0; i < N; i++) { pid_t wpid = waitpid(pid[i], &child_status, 0); if (WIFEXITED(child_status)) printf("Child %d terminated with exit status %dn", wpid, WEXITSTATUS(child_status)); else printf("Child %d terminated abnormallyn", wpid); } – 32 – 15 -213, S’ 03

Wait/Waitpid Example Outputs Using wait (fork 10) Child Child 3565 3564 3563 3562 3566

Wait/Waitpid Example Outputs Using wait (fork 10) Child Child 3565 3564 3563 3562 3566 terminated terminated with with exit exit status status 103 102 101 100 104 Using waitpid (fork 11) Child Child – 33 – 3568 3569 3570 3571 3572 terminated terminated with with exit exit status status 100 101 102 103 104 15 -213, S’ 03

exec: Running new programs int execl(char *path, char *arg 0, char *arg 1, …,

exec: Running new programs int execl(char *path, char *arg 0, char *arg 1, …, 0) n loads and runs executable at path with args arg 0, arg 1, … l path is the complete path of an executable l arg 0 becomes the name of the process » typically arg 0 is either identical to path, or else it contains only the executable filename from path l “real” arguments to the executable start with arg 1, etc. l list of args is terminated by a (char *)0 argument n returns -1 if error, otherwise doesn’t return! main() { if (fork() == 0) { execl("/usr/bin/cp", "foo", "bar", 0); } wait(NULL); printf("copy completedn"); exit(); } – 34 – 15 -213, S’ 03

Summarizing Exceptions n Events that require nonstandard control flow n Generated externally (interrupts) or

Summarizing Exceptions n Events that require nonstandard control flow n Generated externally (interrupts) or internally (traps and faults) Processes n n n – 35 – At any given time, system has multiple active processes Only one can execute at a time, though Each process appears to have total control of processor + private memory space 15 -213, S’ 03

Summarizing (cont. ) Spawning Processes n Call to fork l One call, two returns

Summarizing (cont. ) Spawning Processes n Call to fork l One call, two returns Terminating Processes n Call exit l One call, no return Reaping Processes n Call wait or waitpid Replacing Program Executed by Process n Call execl (or variant) l One call, (normally) no return – 36 – 15 -213, S’ 03