Exceptional Control Flow:  Exceptional Control Flow Exceptions and Processes  Processes

Total Page:16

File Type:pdf, Size:1020Kb

Exceptional Control Flow:  Exceptional Control Flow Exceptions and Processes  Processes Carnegie Mellon Carnegie Mellon Today Exceptional Control Flow: Exceptional Control Flow Exceptions and Processes Processes 15‐213 / 18‐213: Introduction to Computer Systems 13th Lecture, Feb 26, 2013 Instructors: Seth Copen Goldstein, Anthony Rowe, and Greg Kesden 1 2 Carnegie Mellon Carnegie Mellon Control Flow Altering the Control Flow Processors do only one thing: Up to now: two mechanisms for changing control flow: . From startup to shutdown, a CPU simply reads and executes . Jumps and branches (interprets) a sequence of instructions, one at a time . Call and return . This sequence is the CPU’s control flow (or flow of control) Both react to changes in program state Physical control flow Insufficient for a useful system: Difficult to react to changes in system state <startup> . data arrives from a disk or a network adapter inst1 . instruction divides by zero inst Time 2 . user hits Ctrl‐C at the keyboard inst3 . System timer expires … instn <shutdown> System needs mechanisms for “exceptional control flow” 3 4 Carnegie Mellon Carnegie Mellon Exceptional Control Flow ECF Exists at All Levels of a System Exists at all levels of a computer system Exceptions Low level mechanisms . Hardware and operating system kernel software . Exceptions Process Context Switch This Lecture . change in control flow in response to a system event . Hardware timer and kernel software (i.e., change in system state) Signals . Combination of hardware and OS software . Kernel software and application software Higher level mechanisms Nonlocal jumps . Process context switch Next Lecture . Application code . Signals What about . Nonlocal jumps: setjmp()/longjmp() try/catch/throw? . Implemented by either: . OS software (context switch and signals) . C language runtime library (nonlocal jumps) 5 6 Carnegie Mellon Carnegie Mellon Exceptions Exception Tables An exception is a transfer of control to the OS in response to Exception some event (i.e., change in processor state) numbers code for Each type of event has a User Process OS exception handler 0 unique exception number k Exception code for event I_current exception Table exception handler 1 k = index into exception table I_next exception processing 0 (a.k.a. interrupt vector) by exception handler 1 code for almost 2 • return to I_current ... exception handler 2 Handler k is called each time • return to I_next n-1 ... exception k occurs • abort code for exception handler n‐1 Examples: div by 0, arithmetic overflow, page fault, I/O request completes, Ctrl‐C 7 8 Carnegie Mellon Carnegie Mellon Asynchronous Exceptions (Interrupts) Synchronous Exceptions Caused by events that occur as a result of executing an Caused by events external to the processor instruction: . Indicated by setting the processor’s interrupt pin . Traps . Handler returns to “next” instruction . Intentional . Examples: system calls, breakpoint traps, special instructions Examples: . Returns control to “next” instruction . I/O interrupts . Faults . hitting Ctrl‐C at the keyboard . Unintentional but possibly recoverable . arrival of a packet from a network . Examples: page faults (recoverable), protection faults . arrival of data from a disk (unrecoverable), floating point exceptions . Hard reset interrupt . Either re‐executes faulting (“current”) instruction or aborts . hitting the reset button . Aborts . Soft reset interrupt . unintentional and unrecoverable . hitting Ctrl‐Alt‐Delete on a PC . Examples: parity error, machine check . Aborts current program 9 10 Carnegie Mellon Carnegie Mellon Trap Example: Opening File Fault Example: Page Fault int a[1000]; User calls: open(filename, options) User writes to memory location main () { Function open executes system call instruction int That portion (page) of user’s memory a[500] = 13; 0804d070 <__libc_open>: is currently on disk } . 804d082: cd 80 int $0x80 80483b7: c7 05 10 9d 04 08 0d movl $0xd,0x8049d10 804d084: 5b pop %ebx . User Process OS User Process OS exception: page fault movl exception Create page and int returns pop Different privilege load into memory open file levels! returns Page handler must load page into physical memory Returns to faulting instruction Different privilege OS must find or create file, get it ready for reading or writing Successful on second try levels! Returns integer file descriptor 11 12 Carnegie Mellon Carnegie Mellon Fault Example: Invalid Memory Reference Exception Table IA32 (Excerpt) int a[1000]; main () { Exception Number Description Exception Class a[5000] = 13; 0 Divide error Fault } 13 General protection fault Fault 80483b7: c7 05 60 e3 04 08 0d movl $0xd,0x804e360 14 Page fault Fault 18 Machine check Abort User Process OS 32‐127 OS‐defined Interrupt or trap exception: page fault 128 (0x80) System call Trap movl 129‐255 OS‐defined Interrupt or trap detect invalid address signal process Check Table 6‐1: Page handler detects invalid address http://download.intel.com/design/processor/manuals/253665.pdf Sends SIGSEGV signal to user process Different privilege User process exits with “segmentation fault” levels! 13 14 Carnegie Mellon Carnegie Mellon Altering the Control Flow (revisited) Today Up to now: two mechanisms for changing control flow: Exceptional Control Flow . Jumps and branches Is there an alternative? Processes . Call and return - For general purpose processors? Both react to changes in program state - For embedded processors? Insufficient for a useful system: Difficult to react to changes in system state . data arrives from a disk or a network adapter . instruction divides by zero . user hits Ctrl‐C at the keyboard . System timer expires System needs mechanisms for “exceptional control flow” 15 16 Carnegie Mellon Carnegie Mellon Processes Concurrent Processes Definition: A process is an instance of a running program. Two processes run concurrently (are concurrent) if their . One of the most profound ideas in computer science flows overlap in time . Not the same as “program” or “processor” Otherwise, they are sequential Examples (running on single core): Process provides each program with two key abstractions: . Concurrent: A & B, A & C . Logical control flow . Sequential: B & C . Each program seems to have exclusive use of the CPU . Private virtual address space Process AProcess BProcess C . Each program seems to have exclusive use of main memory Time How are these Illusions maintained? . Process executions interleaved (multitasking) or run on separate cores . Address spaces managed by virtual memory system . we’ll talk about this in a couple of weeks 17 18 Carnegie Mellon Carnegie Mellon User View of Concurrent Processes Context Switching Processes are managed by a shared chunk of OS code Control flows for concurrent processes are physically called the kernel disjoint in time . Important: the kernel is not a separate process, but rather runs as part of some user process However, we can think of concurrent processes as Control flow passes from one process to another via a running in parallel with each other context switch Process AProcess B Process AProcess BProcess C Time user code kernel code context switch Time user code kernel code context switch user code 19 20 Carnegie Mellon Carnegie Mellon fork: Creating New Processes Understanding fork Process n Child Process m int fork(void) pid_t pid = fork(); pid_t pid = fork(); . creates a new process (child process) that is identical to the calling if (pid == 0) { if (pid == 0) { process (parent process) printf("hello from child\n"); printf("hello from child\n"); } else { } else { . returns 0 to the child process printf("hello from parent\n"); printf("hello from parent\n"); } } . returns child’s pid (process id) to the parent process pid_t pid = fork(); pid_t pid = fork(); pid_t pid = fork(); if (pid == 0) { if (pid == 0) { if (pid == 0) { pid = m printf("hello from child\n"); pid = 0 printf("hello from child\n"); printf("hello from child\n"); } else { } else { printf("hello from parent\n"); printf("hello from parent\n"); } else { } } printf("hello from parent\n"); } pid_t pid = fork(); pid_t pid = fork(); if (pid == 0) { if (pid == 0) { printf("hello from child\n"); printf("hello from child\n"); Fork is interesting (and often confusing) because } else { } else { printf("hello from parent\n"); printf("hello from parent\n"); it is called once but returns twice } } hello from parent Which one is first? hello from child 21 22 Carnegie Mellon Carnegie Mellon Fork Example #1 Fork Example #2 Parent and child both run same code Two consecutive forks . Distinguish parent from child by return value from fork void fork2() Start with same state, but each has private copy { . Including shared output file descriptor printf("L0\n"); Bye . Relative ordering of their print statements undefined fork(); L1 Bye printf("L1\n"); Bye fork(); void fork1() L0 L1 Bye { printf("Bye\n"); int x = 1; } pid_t pid = fork(); if (pid == 0) { printf("Child has x = %d\n", ++x); } else { printf("Parent has x = %d\n", --x); } printf("Bye from process %d with x = %d\n", getpid(), x); } 23 24 Carnegie Mellon Carnegie Mellon Fork Example #3 Fork Example #4 Three consecutive forks Nested forks in parent void fork3() Bye void fork4() { { L2 Bye printf("L0\n"); printf("L0\n"); fork(); Bye if (fork() != 0) { printf("L1\n"); L1 L2 Bye printf("L1\n"); Bye fork(); Bye if (fork() != 0) { printf("L2\n"); L2 Bye printf("L2\n"); Bye fork(); fork(); Bye printf("Bye\n"); Bye } L0 L1 L2 Bye } L0 L1 L2 Bye } printf("Bye\n"); } 25 26 Carnegie Mellon Carnegie Mellon Fork Example #5 exit: Ending a process Nested forks in children void exit(int status) . exits a process void fork5() . Normally return with status 0 { printf("L0\n"); . atexit() registers functions to be executed upon exit if (fork() == 0) { printf("L1\n"); Bye if (fork() == 0) { L2 Bye void cleanup(void) { printf("L2\n"); printf("cleaning up\n"); L1 Bye fork(); } } L0 Bye } void fork6() { printf("Bye\n“); atexit(cleanup); } fork(); exit(0); } 27 28 Carnegie Mellon Carnegie Mellon void fork7() Zombies Zombie { if (fork() == 0) { Idea /* Child */ Example printf("Terminating Child, PID = %d\n", . When process terminates, still consumes system resources getpid()); exit(0); .
Recommended publications
  • University of California at Berkeley College of Engineering Department of Electrical Engineering and Computer Science
    University of California at Berkeley College of Engineering Department of Electrical Engineering and Computer Science EECS 61C, Fall 2003 Lab 2: Strings and pointers; the GDB debugger PRELIMINARY VERSION Goals To learn to use the gdb debugger to debug string and pointer programs in C. Reading Sections 5.1-5.5, in K&R GDB Reference Card (linked to class page under “resources.”) Optional: Complete GDB documentation (http://www.gnu.org/manual/gdb-5.1.1/gdb.html) Note: GDB currently only works on the following machines: • torus.cs.berkeley.edu • rhombus.cs.berkeley.edu • pentagon.cs.berkeley.edu Please ssh into one of these machines before starting the lab. Basic tasks in GDB There are two ways to start the debugger: 1. In EMACS, type M-x gdb, then type gdb <filename> 2. Run gdb <filename> from the command line The following are fundamental operations in gdb. Please make sure you know the gdb commands for the following operations before you proceed. 1. How do you run a program in gdb? 2. How do you pass arguments to a program when using gdb? 3. How do you set a breakpoint in a program? 4. How do you set a breakpoint which which only occurs when a set of conditions is true (eg when certain variables are a certain value)? 5. How do you execute the next line of C code in the program after a break? 1 6. If the next line is a function call, you'll execute the call in one step. How do you execute the C code, line by line, inside the function call? 7.
    [Show full text]
  • Tricore™ Tricore™ V1.6 Microcontrollers User Manual
    TriCore™ 32-bit TriCore™ V1.6 Core Architecture 32-bit Unified Processor Core User Manual (Volume 1) V1.0, 2012-05 Microcontrollers Edition 2012-05 Published by Infineon Technologies AG 81726 Munich, Germany © 2012 Infineon Technologies AG All Rights Reserved. Legal Disclaimer The information given in this document shall in no event be regarded as a guarantee of conditions or characteristics. With respect to any examples or hints given herein, any typical values stated herein and/or any information regarding the application of the device, Infineon Technologies hereby disclaims any and all warranties and liabilities of any kind, including without limitation, warranties of non-infringement of intellectual property rights of any third party. Information For further information on technology, delivery terms and conditions and prices, please contact the nearest Infineon Technologies Office (www.infineon.com). Warnings Due to technical requirements, components may contain dangerous substances. For information on the types in question, please contact the nearest Infineon Technologies Office. Infineon Technologies components may be used in life-support devices or systems only with the express written approval of Infineon Technologies, if a failure of such components can reasonably be expected to cause the failure of that life-support device or system or to affect the safety or effectiveness of that device or system. Life support devices or systems are intended to be implanted in the human body or to support and/or maintain and sustain and/or protect human life. If they fail, it is reasonable to assume that the health of the user or other persons may be endangered.
    [Show full text]
  • PRE LIM INARY KDII-D Processor Manual (PDP-Ll/04)
    PRE LIM I N A R Y KDII-D Processor Manual (PDP-ll/04) The information in this document is subject to change without notice and should not be construed as a commitment by Digital Equipment Corporation. Digital Equipment Corporation assumes no responsibility for any errors that may appear in this manual. Copyright C 1975 by Digital Equipment Corporation Written by PDP-II Engineering PREFACE OVE~ALt DESCRIPTION 3 8 0 INsT~UCTION SET 3~1 Introduction 1~2 Addressing ModIs 3.3 Instruction Timing l@4 In~truet1on Dtlcriptlonl le!5 Dlffer~ncei a,tween KOlle and KOllS ]0 6 Programming Diftereneel B~twlen pepita ).7 SUI L~tency Tim@1 CPu OPERlTING 5PECIFICATID~S 5 e 0 DETAILED HARDWARE DESC~ltTION 5.1 IntrOduction 5 m2 Data path Circuitry 5.2g1 General D~serlpt1on 5.2,,2 ALU 5,2 .. 3 Scratch Pad Mtmory 5.2,.3.1 Scratch P~d Circuitry 5.2.3.2 SCrateh P~d Addr~11 MUltlplex.r 5.2.3.3 SCrateh Pad Regilter 5 0 2 .. 4 B J:H'!qilil ter 5.2 .. 4.1 B ReQister CircuItry 5.2 .. 4.2 8 L~G MUltl~lex@r 5,2.5 AMUX 5.2.6 Pfoeellof statuI Word (PSW) 5.3 Con<Htion COd@i 5.3.1 G~neral De~erl~tlon 5.3.2 Carry and overflow Decode 5.3.3 Ayte Multiplexing 5.4 UNIBUS Addf@$5 and Data Interfaces S.4 g 1 U~IBUS Dr1v~rl and ~lee1Vtrl 5.4@2 Bus Addr~s~ Generation 5 8 4111 Internal Addrf$$ D@coder 5 0 4,.4 Bus Data Line Interface S.5 Instruet10n DeCoding 5.5,,1 General De~er1pt1nn 5;5.2 Instruction Re91lt~r 5.5,,3 Instruetlon Decoder 5.5.3 0 1 Doubl~ O~erand InltrYetions 5.5.3.2 Single Operand Inltruetlons 5,5.3.3 Branch In$truetionl 5 8 5.3 6 4 Op~rate rn~truet1ons 5.6 Auil11ary ALU Control 5.6.1 G~ntral Delcrlptlon 5.6.2 COntrol Circuitry 5.6.2.1 Double Op@rand Instructions 5.6.2.2 Singl@ nDef~nd Instruet10ns PaQe 3 5.7 Data Transfer Control 5,7,1 General Descr1ption 5,7,2 Control CIrcuItry 5,7,2,1 Procelsor Cloek Inhibit 5,7,2.2 UNIBUS Synchronization 5,7.2,3 BUs Control 5.7,2.4 MSyN/SSYN Timeout 5,7.2.5 Bus Error.
    [Show full text]
  • Debugging a Program
    Debugging a Program SunPro A Sun Microsystems, Inc. Business 2550 Garcia Avenue Mountain View, CA 94043 U.S.A. Part No: 801-5106-10 Revision A December 1993 1993 Sun Microsystems, Inc. 2550 Garcia Avenue, Mountain View, California 94043-1100 U.S.A. All rights reserved. This product and related documentation are protected by copyright and distributed under licenses restricting its use, copying, distribution, and decompilation. No part of this product or related documentation may be reproduced in any form by any means without prior written authorization of Sun and its licensors, if any. Portions of this product may be derived from the UNIX® and Berkeley 4.3 BSD systems, licensed from UNIX System Laboratories, Inc. and the University of California, respectively. Third-party font software in this product is protected by copyright and licensed from Sun’s Font Suppliers. RESTRICTED RIGHTS LEGEND: Use, duplication, or disclosure by the United States Government is subject to the restrictions set forth in DFARS 252.227-7013 (c)(1)(ii) and FAR 52.227-19. The product described in this manual may be protected by one or more U.S. patents, foreign patents, or pending applications. TRADEMARKS Sun, Sun Microsystems, the Sun logo, SunPro, SunPro logo, Sun-4, SunOS, Solaris, ONC, OpenWindows, ToolTalk, AnswerBook, and Magnify Help are trademarks or registered trademarks of Sun Microsystems, Inc. UNIX and OPEN LOOK are registered trademarks of UNIX System Laboratories, Inc., a wholly owned subsidiary of Novell, Inc. All other product names mentioned herein are the trademarks of their respective owners. All SPARC trademarks, including the SCD Compliant Logo, are trademarks or registered trademarks of SPARC International, Inc.
    [Show full text]
  • Exceptions and Processes
    Exceptions and Processes! Jennifer Rexford! The material for this lecture is drawn from! Computer Systems: A Programmerʼs Perspective (Bryant & O"Hallaron) Chapter 8! 1 Goals of this Lecture! •#Help you learn about:! •# Exceptions! •# The process concept! … and thereby…! •# How operating systems work! •# How applications interact with OS and hardware! The process concept is one of the most important concepts in systems programming! 2 Context of this Lecture! Second half of the course! Previously! Starting Now! C Language! Application Program! language! service! levels! Assembly Language! levels! Operating System! tour! tour! Machine Language! Hardware! Application programs, OS,! and hardware interact! via exceptions! 3 Motivation! Question:! •# How does a program get input from the keyboard?! •# How does a program get data from a (slow) disk?! Question:! •# Executing program thinks it has exclusive control of CPU! •# But multiple programs share one CPU (or a few CPUs)! •# How is that illusion implemented?! Question:! •# Executing program thinks it has exclusive use of memory! •# But multiple programs must share one memory! •# How is that illusion implemented?! Answers: Exceptions…! 4 Exceptions! •# Exception! •# An abrupt change in control flow in response to a change in processor state! •# Examples:! •# Application program:! •# Requests I/O! •# Requests more heap memory! •# Attempts integer division by 0! •# Attempts to access privileged memory! Synchronous! •# Accesses variable that is not$ in real memory (see upcoming $ “Virtual Memory” lecture)! •# User presses key on keyboard! Asynchronous! •# Disk controller finishes reading data! 5 Exceptions Note! •# Note:! ! !Exceptions in OS % exceptions in Java! Implemented using! try/catch! and throw statements! 6 Exceptional Control Flow! Application! Exception handler! program! in operating system! exception! exception! processing! exception! return! (optional)! 7 Exceptions vs.
    [Show full text]
  • Providing Memory Performance Feedback in Modern Processors
    Informing Memory Operations: Providing Memory Performance Feedback in Modern Processors Mark Horowitz Margaret Martonosi Todd C. Mowry Michael D. Smith Computer Systems Department of Department of Electrical Division of Laboratory Electrical Engineering and Computer Engineering Applied Sciences Stanford University Princeton University University of Toronto Harvard University [email protected] [email protected] [email protected] [email protected] Abstract other purely hardware-based mechanisms (e.g., stream buffers [Jou90]) are complete solutions. Memory latency is an important bottleneck in system performance that cannot be adequately solved by hardware alone. Several prom- In addition to hardware mechanisms, a number of promising soft- ising software techniques have been shown to address this problem ware techniques have been proposed to avoid or tolerate memory successfully in specific situations. However, the generality of these latency. These software techniques have resorted to a variety of software approaches has been limited because current architectures different approaches for gathering information and reasoning about do not provide a fine-grained, low-overhead mechanism for memory performance. Compiler-based techniques, such as cache observing and reacting to memory behavior directly. To fill this blocking [AKL79,GJMS87,WL91] and prefetching [MLG92, need, we propose a new class of memory operations called inform- Por89] use static program analysis to predict which references are ing memory operations, which essentially consist of a memory likely to suffer misses. Memory performance tools have relied on operation combined (either implicitly or explicitly) with a condi- sampling or simulation-based approaches to gather memory statis- tional branch-and-link operation that is taken only if the reference tics [CMM+88,DBKF90,GH93,LW94,MGA95].
    [Show full text]
  • Compiling and Debugging Basics
    Compiling and Debugging Basics Service CoSiNus IMFT P. Elyakime H. Neau A. Pedrono A. Stoukov Avril 2015 Outline ● Compilers available at IMFT? (Fortran, C and C++) ● Good practices ● Debugging Why? Compilation errors and warning Run time errors and wrong results Fortran specificities C/C++ specificities ● Basic introduction to gdb, valgrind and TotalView IMFT - CoSiNus 2 Compilers on linux platforms ● Gnu compilers: gcc, g++, gfortran ● Intel compilers ( 2 licenses INPT): icc, icpc, ifort ● PGI compiler fortran only (2 licenses INPT): pgf77, pgf90 ● Wrappers mpich2 for MPI codes: mpicc, mpicxx, mpif90 IMFT - CoSiNus 3 Installation ● Gnu compilers: included in linux package (Ubuntu 12.04 LTS, gcc/gfortran version 4.6.3) ● Intel and PGI compilers installed on a centralized server (/PRODCOM), to use it: source /PRODCOM/bin/config.sh # in bash source /PRODCOM/bin/config.csh # in csh/tcsh ● Wrappers mpich2 installed on PRODCOM: FORTRAN : mympi intel # (or pgi or gnu) C/C++ : mympi intel # (or gnu) IMFT - CoSiNus 4 Good practices • Avoid too long source files! • Use a makefile if you have more than one file to compile • In Fortran : ” implicit none” mandatory at the beginning of each program, module and subroutine! • Use compiler’s check options IMFT - CoSiNus 5 Why talk about debugging ? Yesterday, my program was running well: % gfortran myprog.f90 % ./a.out % vmax= 3.3e-2 And today: % gfortran myprog.f90 % ./a.out % Segmentation fault Yet I have not changed anything… Because black magic is not the reason most often, debugging could be helpful! (If you really think that the cause of your problem is evil, no need to apply to CoSiNus, we are not God!) IMFT - CoSiNus 6 Debugging Methodical process to find and fix flows in a code.
    [Show full text]
  • Lecture 15 15.1 Paging
    CMPSCI 377 Operating Systems Fall 2009 Lecture 15 Lecturer: Emery Berger Scribe: Bruno Silva,Jim Partan 15.1 Paging In recent lectures, we have been discussing virtual memory. The valid addresses in a process' virtual address space correspond to actual data or code somewhere in the system, either in physical memory or on the disk. Since physical memory is fast and is a limited resource, we use the physical memory as a cache for the disk (another way of saying this is that the physical memory is \backed by" the disk, just as the L1 cache is \backed by" the L2 cache). Just as with any cache, we need to specify our policies for when to read a page into physical memory, when to evict a page from physical memory, and when to write a page from physical memory back to the disk. 15.1.1 Reading Pages into Physical Memory For reading, most operating systems use demand paging. This means that pages are only read from the disk into physical memory when they are needed. In the page table, there is a resident status bit, which says whether or not a valid page resides in physical memory. If the MMU tries to get a physical page number for a valid page which is not resident in physical memory, it issues a pagefault to the operating system. The OS then loads that page from disk, and then returns to the MMU to finish the translation.1 In addition, many operating systems make some use of pre-fetching, which is called pre-paging when used for pages.
    [Show full text]
  • Chapter 3 Protected-Mode Memory Management
    CHAPTER 3 PROTECTED-MODE MEMORY MANAGEMENT This chapter describes the Intel 64 and IA-32 architecture’s protected-mode memory management facilities, including the physical memory requirements, segmentation mechanism, and paging mechanism. See also: Chapter 5, “Protection” (for a description of the processor’s protection mechanism) and Chapter 20, “8086 Emulation” (for a description of memory addressing protection in real-address and virtual-8086 modes). 3.1 MEMORY MANAGEMENT OVERVIEW The memory management facilities of the IA-32 architecture are divided into two parts: segmentation and paging. Segmentation provides a mechanism of isolating individual code, data, and stack modules so that multiple programs (or tasks) can run on the same processor without interfering with one another. Paging provides a mech- anism for implementing a conventional demand-paged, virtual-memory system where sections of a program’s execution environment are mapped into physical memory as needed. Paging can also be used to provide isolation between multiple tasks. When operating in protected mode, some form of segmentation must be used. There is no mode bit to disable segmentation. The use of paging, however, is optional. These two mechanisms (segmentation and paging) can be configured to support simple single-program (or single- task) systems, multitasking systems, or multiple-processor systems that used shared memory. As shown in Figure 3-1, segmentation provides a mechanism for dividing the processor’s addressable memory space (called the linear address space) into smaller protected address spaces called segments. Segments can be used to hold the code, data, and stack for a program or to hold system data structures (such as a TSS or LDT).
    [Show full text]
  • NASM for Linux
    1 NASM for Linux Microprocessors II 2 NASM for Linux Microprocessors II NASM Package nasm package available as source or as executables Typically /usr/bin/nasm and /usr/bin/ndisasm Assembly NASM Linux requires elf format for object files ELF = Executable and Linking Format Typical header size = 330h bytes for nasm −f elf [−o <output>] <filename> Linking Linux Object files can be linked with gcc gcc [−options] <filename.o> [other_files.o] Disassembly View executable as 32-bit assembly code ndisasm −e 330h –b 32 a.out | less objdump –d a.out | less Fall 2007 Hadassah College Dr. Martin Land Fall 2007 Hadassah College Dr. Martin Land 3 NASM for Linux Microprocessors II 4 NASM for Linux Microprocessors II gcc Stages Example — 1 Stages of Gnu C compilation factorial2.c #include <math.h> main #include <stdio.h> sets j = 12 main() Source Translation Assembly Object Executable calls factorial 10,000,000 times Code Unit Code Code File { int times; prog.c prog.i prog.s prog.o a.out int i , j = 12; preprocess compile assemble link for (times = 0 ; times < 10000000 ; ++times){ i = factorial(j); gcc -E } gcc -S printf("%d\n",i); gcc -c } gcc int factorial(n) int n; factorial calculates n! by recursion { if (n == 0) return 1; else return n * factorial(n-1); } Fall 2007 Hadassah College Dr. Martin Land Fall 2007 Hadassah College Dr. Martin Land 5 NASM for Linux Microprocessors II 6 NASM for Linux Microprocessors II Example — 2 Example — 3 ~/gcc$ gcc factorial2.c Compile program as separate files produces executable a.out factorial2a.c ~/gcc$ time a.out main() { 479001600 int times; int i,j=12; for (times = 0 ; times < 10000000 ; ++times){ real 0m9.281s i = factorial(j); factorial2b.c } #include <math.h> printf("%d\n",i); user 0m8.339s #include <stdio.h> } sys 0m0.008s int factorial(n) int n; { Program a.out runs in 8.339 seconds on 300 MHz if (n == 0) Pentium II return 1; else return n * factorial(n-1); } Fall 2007 Hadassah College Dr.
    [Show full text]
  • Definition of Terms Introduction Trap Are a Mechanism To
    Eidgenössische Definition of Terms Technische Hochschule Zürich Interrupt: Asynchronous interruption of the instruction flow Programming in Systems Caused by external event! (37-023) Hit program execution in Programming in Assembler «between» 2 Instructions Basics of Operating Systems Exception: Unexpected event during Models of Computer Architecture program execution (division by zero, page fault) Lecturer today: Prof. Thomas M. Stricker Hits «during» an instruction Text-/Reference-Books: Trap: Software generated Inter- R.P.Paul: SPARC Architecture... and C rupt Sun SPARC V8 Manual and K&R C Reference Caused by an exception or by an explicit trap instruction Topics of Today: (e.g. for a system call) • Traps, Exceptions and Supervisor Mode Supervisor Privileged execution mode • SPARC V8 Trap Model Mode: in contrast to User Mode • Traps in tkisem System Calls, Interrupt-, • Register Window Trap-Handlers Exception- and Traphandler execute in supervisor mode. 9/14.1.02 - 1 37-023 Systemprogrammierung © Alonso/Stricker 9/14.1.02 - 2 37-023 Systemprogrammierung © Alonso/Stricker Introduction Trap are a mechanism to... Standard library in C (libc.a) provides ... avoid programming mistakes with sys- two different kind of functions: tem resources. • pure library functions ... share common system resources in a fair way under OS control. • self contained code (sin, printf...) ... prevent access to protected memory • «visible» execution in user mode. segments. • examination in single-step mode of ... catch Instructions which would lead to the debugger possible. error conditions and inconsistent sys- • glue code to system calls tem state (z.B. Division by 0, Window- (read, write, open, close...) Overflow). • «invisible» execution ➜ Two modes of execution: Supervisor and User Mode • call some code in the operating system (Trap) ➜ Traps: • execute in supervisor mode Mechanism to get into/return from supervisor mode.
    [Show full text]
  • Memory Management
    Memory management Virtual address space ● Each process in a multi-tasking OS runs in its own memory sandbox called the virtual address space. ● In 32-bit mode this is a 4GB block of memory addresses. ● These virtual addresses are mapped to physical memory by page tables, which are maintained by the operating system kernel and consulted by the processor. ● Each process has its own set of page tables. ● Once virtual addresses are enabled, they apply to all software running in the machine, including the kernel itself. ● Thus a portion of the virtual address space must be reserved to the kernel Kernel and user space ● Kernel might not use 1 GB much physical memory. ● It has that portion of address space available to map whatever physical memory it wishes. ● Kernel space is flagged in the page tables as exclusive to privileged code (ring 2 or lower), hence a page fault is triggered if user-mode programs try to touch it. ● In Linux, kernel space is constantly present and maps the same physical memory in all processes. ● Kernel code and data are always addressable, ready to handle interrupts or system calls at any time. ● By contrast, the mapping for the user-mode portion of the address space changes whenever a process switch happens Kernel virtual address space ● Kernel address space is the area above CONFIG_PAGE_OFFSET. ● For 32-bit, this is configurable at kernel build time. The kernel can be given a different amount of address space as desired. ● Two kinds of addresses in kernel virtual address space – Kernel logical address – Kernel virtual address Kernel logical address ● Allocated with kmalloc() ● Holds all the kernel data structures ● Can never be swapped out ● Virtual addresses are a fixed offset from their physical addresses.
    [Show full text]