Processes and Exceptions While (1) { /* Waste CPU Time */ } }

Total Page:16

File Type:pdf, Size:1020Kb

Processes and Exceptions While (1) { /* Waste CPU Time */ } } an infinite loop int main(void){ Processes and Exceptions while (1) { /* waste CPU time */ } } If I run this on a lab machine, can you still use it? …even if the machine only has one core? 1 2 timing nothing doing nothing on a busy system long times[NUM_TIMINGS]; time for empty loop body 108 int main(void){ for (int i = 0; i < N; ++i) { 107 long start, end; 106 start = get_time(); /* do nothing */ 105 end = get_time(); 104 times[i] = end − start; time (ns) } 103 output_timings(times); 2 } 10 same instructions — same difference each time? 101 3 0 200000 400000 600000 800000 1000000 4 sample # ... call get_time // whatever get_time does movq %rax, %rbp million cycle delay call get_time // whatever get_time does subq %rbp, %rax ... doing nothing on a busy system time multiplexing time for empty loop body loop.exe ssh.exe firefox.exe loop.exe ssh.exe 108 CPU: time 107 106 105 104 time (ns) 103 102 101 0 200000 400000 600000 800000 1000000 5 6 sample # time multiplexing time multiplexing CPU: loop.exe ssh.exe firefox.exe loop.exe ssh.exe CPU: loop.exe ssh.exe firefox.exe loop.exe ssh.exe time time ... ... call get_time call get_time // whatever get_time does // whatever get_time does movq %rax, %rbp movq %rax, %rbp million cycle delay million cycle delay call get_time call get_time // whatever get_time does // whatever get_time does subq %rbp, %rax subq %rbp, %rax ... ... 6 6 exception happens return from exception illusion: dedicated processor time multiplexing really time multiplexing: illusion of dedicated processor loop.exe ssh.exe firefox.exe loop.exe ssh.exe including dedicated registers sometimes called a thread = operating system illusion is perfect — except for performance 7 8 time multiplexing really OS and time multiplexing loop.exe ssh.exe firefox.exe loop.exe ssh.exe starts running instead of normal program mechanism for this: exceptions (later) saves old program counter, registers somewhere = operating system sets new registers, jumps to new program counter called context switch saved information called context exception happens return from exception 8 9 address space: map from program to real addresses context context switch pseudocode all registers values context_switch(last, next): %rax %rbx, …, %rsp,… copy_preexception_pc last−>pc mov rax,last−>rax condition codes mov rcx, last−>rcx mov rdx, last−>rdx program counter ... mov next−>rdx, rdx i.e. all visible state in your CPU except memory mov next−>rcx, rcx mov next−>rax, rax jmp next−>pc 10 11 contexts (A running) contexts (B running) in Memory in Memory Process A memory: Process A memory: in CPU code, stack, etc. in CPU code, stack, etc. %rax %rax %rbx %rbx %rcx %rcx %rsp Process B memory: %rsp Process B memory: … code, stack, etc. … code, stack, etc. SF SF ZF OS memory: ZF OS memory: PC PC %rax SF %rax SF %rbx ZF %rbx ZF %rcx PC %rcx PC … … … … 12 13 result: %rax is 42 (always) result: might crash memory protection memory protection reading from another program’s memory? reading from another program’s memory? Program A Program B Program A Program B 0x10000: .word 42 0x10000: .word 42 // while A is working: // while A is working: // ... // ... movq $99, %rax movq $99, %rax // do work // do work movq %rax, 0x10000 movq %rax, 0x10000 // ... // ... ... ... movq 0x10000, %rax movq 0x10000, %rax result: %rax is 42 (always) result: might crash 14 14 Recall: program memory program memory (two programs) 0xFFFF FFFF FFFF FFFF Program A Program B Used by OS 0xFFFF 8000 0000 0000 Used by OS Used by OS 0x7F… Stack Stack Stack Heap / other dynamic Heap / other dynamic Heap / other dynamic Writable data Writable data Writable data Code + Constants Code + Constants Code + Constants 0x0000 0000 0040 0000 15 16 = kernel-mode only trigger error = kernel-mode only address space program memory (two programs) programs have illusion of own memory Program A Program B called a program’s address space Used by OS Used by OS real memory Program A mapping Program A code (set by OS) Stack Stack addresses Program B code Program A data Heap / other dynamic Heap / other dynamic Program B mapping Program B data addresses (set by OS) Writable data Writable data OS data … Code + Constants Code + Constants 17 18 address space address space mechanisms programs have illusion of own memory next week’s topic called a program’s address space called virtual memory real memory Program A mapping Program A code mapping called page tables addresses (set by OS) Program B code mapping part of what is changed in context switch Program A data Program B mapping Program B data addresses (set by OS) OS data … trigger error 19 20 context The Process all registers values process = thread(s) + address space %rax %rbx, …, %rsp,… illusion of dedicated machine: condition codes thread = illusion of own CPU address space = illusion of own memory program counter i.e. all visible state in your CPU except memory address space: map from program to real addresses 21 22 time multiplexing really exceptions loop.exe ssh.exe firefox.exe loop.exe ssh.exe special control transfer similar effect to function call but often not requested by the program = operating system usually from user programs to the OS example: from timer expiring keeps our infinite loop from running forever exception happens return from exception 23 24 types of exceptions timer interrupt interrupts — externally-triggered (conceptually) external timer device timer — keep program from hogging CPU I/O devices — key presses, hard drives, networks, … OS configures before starting program faults — errors/events in programs sends signal to CPU after a fixed interval memory not in address space (“Segmentation fault”) divide by zero invalid instruction traps — intentionally triggered exceptions system calls — ask OS to do something aborts 25 26 types of exceptions protection fault interrupts — externally-triggered when program tries to access memory it doesn’t own timer — keep program from hogging CPU I/O devices — key presses, hard drives, networks, … e.g. trying to write to bad address faults — errors/events in programs OS gets control — can crash the program memory not in address space (“Segmentation fault”) or more interesting things divide by zero invalid instruction traps — intentionally triggered exceptions system calls — ask OS to do something aborts 27 28 synchronous versus asynchronous exception implementation synchronous — triggered by a particular instruction detect condition (program error or external event) particular mov instruction save current value of PC somewhere asynchronous — comes from outside the program timer event jump to exception handler (part of OS) keypress, other input event jump done without program instruction to do so 29 30 exception implementation: notes locating exception handlers exception table I/textbook describe a simplified version base register handle_divide_by_zero: movq %rax, save_rax real x86/x86-64 is a bit more complicated movq %rbx, save_rbx exception table (in memory) ... (mostly for historical reasons) address pointer base + 0x00 base + 0x08 … base + 0x10 … base + 0x18 … … … base + 0x40 … … handle_timer_interrupt: movq %rax, save_rax movq %rbx, save_rbx ... 31 32 running the exception handler exception handler structure hardware saves the old program counter 1. save process’s state somewhere identifies location of exception handler via table 2. do work to handle exception 3. restore a process’s state (maybe a different one) then jumps to that location 4. jump back to program OS code can save registers, etc., etc. handle_timer_interrupt: mov_from_saved_pc save_pc_loc movq %rax, save_rax_loc ... // choose new process to run here movq new_rax_loc, %rax mov_to_saved_pc new_pc return_from_exception 33 34 added to CPU for exceptions added to CPU for exceptions new instruction: set exception table base new instruction: set exception table base new logic: jump based on exception table new logic: jump based on exception table new logic: save the old PC new logic: save the old PC to special register or to memory to special register or to memory new instruction: return from exception new instruction: return from exception i.e. jump to saved PC i.e. jump to saved PC 35 35 added to CPU for exceptions why return from exception? new instruction: set exception table base not just ret — can’t modify process’s stack would break the illusion of dedicated CPU new logic: jump based on exception table reasons related to address spaces, protection (later) new logic: save the old PC to special register or to memory new instruction: return from exception i.e. jump to saved PC 35 36 exceptions and time slicing defeating time slices? loop.exe ssh.exe firefox.exe loop.exe ssh.exe my_exception_table: ... my_handle_timer_interrupt: timer interrupt // HA! Keep running me! return_from_exception exception table lookup main: set_exception_table_base my_exception_table loop: handle_timer_interrupt: jmp loop ... ... set_address_space ssh_address_space mov_to_saved_pc saved_ssh_pc return_from_exception 37 38 defeating time slices? privileged instructions wrote a program that tries to set the exception table: can’t let any program run some instructions my_exception_table: allows machines to be shared between users (e.g. lab ... servers) examples: main: set exception table // "Load Interrupt // Descriptor Table" set address space // x86 instruction to set exception table talk to I/O device (hard drive, keyboard, display, …) lidt my_exception_table … ret processor has two modes: kernel mode — privileged instructions work result: Segmentation fault (exception!)
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]
  • While Statement in C
    While Statement In C EnricoIs Reg alwaysdisheartening deplete or his novel aspects when chagrined luminesced disputatiously, some crayfishes he orbits clump so temporizingly? grindingly. Solid Ring-necked and comose Bennet Brendan tarnishes never tensehalf-and-half his Stuttgart! while Thank you use a counter is a while loop obscures the condition which is evaluated to embed videos in while c program C while loops statement allows to repeatedly run at same recipient of code until a wrap is met while loop is empty most basic loop in C programming while loop. We then hand this variable c in the statement block and represent your value for each. While adultery in C Set of instructions given coil the compiler to night set of statements until condition becomes false is called loops. If it is negative number added to the condition in c language including but in looping structures, but is executed infinite loop! While Loop Definition Example & Results Video & Lesson. While talking in C Know Program. What is the while eternal in C? A while loop around loop continuously and infinitely until the policy inside the parenthesis becomes false money must guard the. C while and dowhile Loop Programiz. Programming While Loop. The widow while redeem in the C language is basically a post tested loop upon the execution of several parts of the statements can be repeated by reckless use children do-while. 43 Loops Applications in C for Engineering Technology. Do it Loop in C Programming with Examples Phptpoint. Statements and display control C Tutorials Cpluspluscom. Do while just in c example program.
    [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]
  • Detecting and Escaping Infinite Loops Using Bolt
    Detecting and Escaping Infinite Loops Using Bolt by Michael Kling Submitted to the Department of Electrical Engineering and Computer Science in partial fulfillment of the requirements for the degree of Masters of Engineering in Electical Engineering and Computer Science at the MASSACHUSETTS INSTITUTE OF TECHNOLOGY February 2012 c Massachusetts Institute of Technology 2012. All rights reserved. Author.............................................................. Department of Electrical Engineering and Computer Science February 1, 2012 Certified by. Martin Rinard Professor Thesis Supervisor Accepted by . Prof. Dennis M. Freeman Chairman, Masters of Engineering Thesis Committee 2 Detecting and Escaping Infinite Loops Using Bolt by Michael Kling Submitted to the Department of Electrical Engineering and Computer Science on February 1, 2012, in partial fulfillment of the requirements for the degree of Masters of Engineering in Electical Engineering and Computer Science Abstract In this thesis we present Bolt, a novel system for escaping infinite loops. If a user suspects that an executing program is stuck in an infinite loop, the user can use the Bolt user interface, which attaches to the running process and determines if the program is executing in an infinite loop. If that is the case, the user can direct the interface to automatically explore multiple strategies to escape the infinite loop, restore the responsiveness of the program, and recover useful output. Bolt operates on stripped x86 and x64 binaries, analyzes both single-thread and multi-threaded programs, dynamically attaches to the program as-needed, dynami- cally detects the loops in a program and creates program state checkpoints to enable exploration of different escape strategies. This makes it possible for Bolt to detect and escape infinite loops in off-the-shelf software, without available source code, or overhead in standard production use.
    [Show full text]
  • CS 161, Lecture 8: Error Handling and Functions – 29 January 2018 Revisit Error Handling
    CS 161, Lecture 8: Error Handling and Functions – 29 January 2018 Revisit Error Handling • Prevent our program from crashing • Reasons programs will crash or have issues: • Syntax Error – prevents compilation, the programmer caused this by mistyping or breaking language rules • Logic Errors – the code does not perform as expected because the underlying logic is incorrect such as off by one, iterating in the wrong direction, having conditions which will never end or be met, etc. • Runtime Errors – program stops running due to segmentation fault or infinite loop potentially caused by trying to access memory that is not allocated, bad user input that was not handled, etc. check_length • The end of a string is determined by the invisible null character ‘\0’ • while the character in the string is not null, keep counting Assignment 3 Notes • Allowed functions: • From <string>: .length(), getline(), [], += • From <cmath>: pow() • Typecasting allowed only if the character being converted fits the stated criterion (i.e. character was confirmed as an int, letter, etc.) • ASCII Chart should be used heavily http://www.asciitable.com/ Debugging Side Bar • Read compiler messages when you have a syntax error • If you suspect a logic error -> print everything! • Allows you to track the values stored in your variables, especially in loops and changing scopes • Gives you a sense of what is executing when in your program Decomposition • Divide problem into subtasks • Procedural Decomposition: get ready in the morning, cooking, etc. • Incremental Programming:
    [Show full text]
  • Automatic Repair of Infinite Loops
    Automatic Repair of Infinite Loops Sebastian R. Lamelas Marcote Martin Monperrus University of Buenos Aires University of Lille & INRIA Argentina France Abstract Research on automatic software repair is concerned with the develop- ment of systems that automatically detect and repair bugs. One well-known class of bugs is the infinite loop. Every computer programmer or user has, at least once, experienced this type of bug. We state the problem of repairing infinite loops in the context of test-suite based software repair: given a test suite with at least one failing test, generate a patch that makes all test cases pass. Consequently, repairing infinites loop means having at least one test case that hangs by triggering the infinite loop. Our system to automatically repair infinite loops is called Infinitel. We develop a technique to manip- ulate loops so that one can dynamically analyze the number of iterations of loops; decide to interrupt the loop execution; and dynamically examine the state of the loop on a per-iteration basis. Then, in order to synthesize a new loop condition, we encode this set of program states as a code synthesis problem using a technique based on Satisfiability Modulo Theory (SMT). We evaluate our technique on seven seeded-bugs and on seven real-bugs. Infinitel is able to repair all of them, within seconds up to one hour on a standard laptop configuration. 1 Introduction Research on automatic software repair is concerned with the development of sys- tems that automatically detect and repair bugs. We consider as bug a behavior arXiv:1504.05078v1 [cs.SE] 20 Apr 2015 observed during program execution that does not correspond to the expected one.
    [Show full text]
  • Chapter 6 Flow of Control
    Chapter 6 Flow of Control 6.1 INTRODUCTION “Don't you hate code that's In Figure 6.1, we see a bus carrying the children to not properly indented? school. There is only one way to reach the school. The Making it [indenting] part of driver has no choice, but to follow the road one milestone the syntax guarantees that all after another to reach the school. We learnt in Chapter code is properly indented.” 5 that this is the concept of sequence, where Python executes one statement after another from beginning to – G. van Rossum the end of the program. These are the kind of programs we have been writing till now. In this chapter Figure 6.1: Bus carrying students to school » Introduction to Flow of Control Let us consider a program 6-1 that executes in » Selection sequence, that is, statements are executed in an order in which they are written. » Indentation The order of execution of the statements in a program » Repetition is known as flow of control. The flow of control can be » Break and Continue implemented using control structures. Python supports Statements two types of control structures—selection and repetition. » Nested Loops 2021-22 Ch 6.indd 121 08-Apr-19 12:37:51 PM 122 COMPUTER SCIENCE – CLASS XI Program 6-1 Program to print the difference of two numbers. #Program 6-1 #Program to print the difference of two input numbers num1 = int(input("Enter first number: ")) num2 = int(input("Enter second number: ")) diff = num1 - num2 print("The difference of",num1,"and",num2,"is",diff) Output: Enter first number 5 Enter second number 7 The difference of 5 and 7 is -2 6.2 SELECTION Now suppose we have `10 to buy a pen.
    [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]