What the CPU Sees Basic Flow Control Conditional Flow Control Structured Flow Control Functions and Scope. C Flow Control.

Similar documents
Function Calls COS 217. Reading: Chapter 4 of Programming From the Ground Up (available online from the course Web site)

CSC 2400: Computing Systems. X86 Assembly: Function Calls"

Assembly Language: Function Calls

x86 assembly CS449 Fall 2017

CIT Week13 Lecture

Assembly Language: Function Calls" Goals of this Lecture"

Assembly Language: Function Calls" Goals of this Lecture"

Assembly Language: Function Calls. Goals of this Lecture. Function Call Problems

CSC 2400: Computing Systems. X86 Assembly: Function Calls

Stacks and Frames Demystified. CSCI 3753 Operating Systems Spring 2005 Prof. Rick Han

administrivia today start assembly probably won t finish all these slides Assignment 4 due tomorrow any questions?

Implementing Threads. Operating Systems In Depth II 1 Copyright 2018 Thomas W. Doeppner. All rights reserved.

You may work with a partner on this quiz; both of you must submit your answers.

CS61 Section Solutions 3

Compiler Construction D7011E

What is a Compiler? Compiler Construction SMD163. Why Translation is Needed: Know your Target: Lecture 8: Introduction to code generation

Question 4.2 2: (Solution, p 5) Suppose that the HYMN CPU begins with the following in memory. addr data (translation) LOAD 11110

CS 31: Intro to Systems Functions and the Stack. Martin Gagne Swarthmore College February 23, 2016

Instructor: Alvin R. Lebeck

CPEG421/621 Tutorial

Intel assembly language using gcc

SPIM Procedure Calls

Machine-level Programming (3)

Instruction Set Architecture

CMSC 313 Lecture 12. Project 3 Questions. How C functions pass parameters. UMBC, CMSC313, Richard Chang

X86 Stack Calling Function POV

Credits and Disclaimers

CMSC 313 Lecture 12 [draft] How C functions pass parameters

CS 2505 Computer Organization I

Lecture #16: Introduction to Runtime Organization. Last modified: Fri Mar 19 00:17: CS164: Lecture #16 1

Y86 Processor State. Instruction Example. Encoding Registers. Lecture 7A. Computer Architecture I Instruction Set Architecture Assembly Language View

(2) Accidentally using the wrong instance of a variable (sometimes very hard one to find).

Computer Systems Lecture 9

Assembly III: Procedures. Jin-Soo Kim Computer Systems Laboratory Sungkyunkwan University

System Software Assignment 1 Runtime Support for Procedures

Procedure Calls. Young W. Lim Sat. Young W. Lim Procedure Calls Sat 1 / 27

Systems I. Machine-Level Programming V: Procedures

ASSEMBLY III: PROCEDURES. Jo, Heeseung

Process Layout, Function Calls, and the Heap

Assembly III: Procedures. Jo, Heeseung

Low-Level Essentials for Understanding Security Problems Aurélien Francillon

AS08-C++ and Assembly Calling and Returning. CS220 Logic Design AS08-C++ and Assembly. AS08-C++ and Assembly Calling Conventions

Object-oriented features

CS 33: Week 3 Discussion. x86 Assembly (v1.0) Section 1G

X86 Assembly -Procedure II:1

4) C = 96 * B 5) 1 and 3 only 6) 2 and 4 only

CS213. Machine-Level Programming III: Procedures

Compilation /15a Lecture 7. Activation Records Noam Rinetzky

Process Layout and Function Calls

The course that gives CMU its Zip! Machine-Level Programming III: Procedures Sept. 17, 2002

Instruction Set Architecture

Instruction Set Architecture

CMSC 313 COMPUTER ORGANIZATION & ASSEMBLY LANGUAGE PROGRAMMING PREVIEW SLIDES 16, SPRING 2013

Final exam. Scores. Fall term 2012 KAIST EE209 Programming Structures for EE. Thursday Dec 20, Student's name: Student ID:

Introduction to Computer Systems. Exam 1. February 22, Model Solution fp

System Programming and Computer Architecture (Fall 2009)

CIS 2107 Computer Systems and Low-Level Programming Spring 2012 Final

Procedure Calls. Young W. Lim Mon. Young W. Lim Procedure Calls Mon 1 / 29

Sungkyunkwan University

ECE 391 Exam 1 Review Session - Spring Brought to you by HKN

CIS 341 Midterm February 28, Name (printed): Pennkey (login id): SOLUTIONS

Buffer Overflows. Buffer Overflow. Many of the following slides are based on those from

Giving credit where credit is due

Secure Programming Lecture 3: Memory Corruption I (Stack Overflows)

UW CSE 351, Winter 2013 Midterm Exam

CPS104 Recitation: Assembly Programming

Section 4: Threads CS162. September 15, Warmup Hello World Vocabulary 2

Machine-Level Programming II: Control and Arithmetic

CS241 Computer Organization Spring 2015 IA

G Programming Languages - Fall 2012

Introduction to Computer Systems. Exam 1. February 22, This is an open-book exam. Notes are permitted, but not computers.

X86 Review Process Layout, ISA, etc. CS642: Computer Security. Drew Davidson

IA32 Stack. Lecture 5 Machine-Level Programming III: Procedures. IA32 Stack Popping. IA32 Stack Pushing. Topics. Pushing. Popping

CS24: INTRODUCTION TO COMPUTING SYSTEMS. Spring 2016 Lecture 12

Lab 10: Introduction to x86 Assembly

Second Part of the Course

238P: Operating Systems. Lecture 3: Calling conventions. Anton Burtsev October, 2018

Roadmap: Security in the software lifecycle. Memory corruption vulnerabilities

Control Structures. Code can be purely arithmetic assignments. At some point we will need some kind of control or decision making process to occur

Program Exploitation Intro

Chapter 4 Processor Architecture: Y86 (Sections 4.1 & 4.3) with material from Dr. Bin Ren, College of William & Mary

Practical Malware Analysis

IA32 Stack The course that gives CMU its Zip! Machine-Level Programming III: Procedures Sept. 17, IA32 Stack Popping. IA32 Stack Pushing

Assembly Language: Overview!

by Marina Cholakyan, Hyduke Noshadi, Sepehr Sahba and Young Cha

Objectives. Explain non-preemptive scheduling Explain step-by-step how a context switch works in TOS

ICS143A: Principles of Operating Systems. Midterm recap, sample questions. Anton Burtsev February, 2017

CSCI 334: Principles of Programming Languages. Computer Architecture (a really really fast introduction) Lecture 11: Control Structures II

CS61, Fall 2012 Midterm Review Section

CS 3843 Final Exam Fall 2012

CS412/CS413. Introduction to Compilers Tim Teitelbaum. Lecture 21: Generating Pentium Code 10 March 08

143A: Principles of Operating Systems. Lecture 4: Calling conventions. Anton Burtsev October, 2017

THEORY OF COMPILATION

CSE 351: Week 4. Tom Bergan, TA

CSC 8400: Computer Systems. Using the Stack for Function Calls

SYSTEM CALL IMPLEMENTATION. CS124 Operating Systems Fall , Lecture 14

An Experience Like No Other. Stack Discipline Aug. 30, 2006

x86 assembly CS449 Spring 2016

Buffer Overflows Defending against arbitrary code insertion and execution

Assignment 11: functions, calling conventions, and the stack

Transcription:

C Flow Control David Chisnall February 1, 2011

Outline What the CPU Sees Basic Flow Control Conditional Flow Control Structured Flow Control Functions and Scope

Disclaimer! These slides contain a lot of x86 assembly! If you don t understand the details, don t worry They are there to give you an idea of how the compiler works You aren t expected to remember the details

Machine Code Execution 1. CPU reads an instruction from address in program counter register 2. CPU increments program counter 3. CPU executes instruction 4. Repeat from step 1

Nonlinear Code Execution Instruction modifies program counter as part of operation Simplest case: jump instruction, just sets program counter value. Exposed in C as goto statement.

C goto Statement // This loops forever int main ( void ) { // Jump target start : goto start ; return 0; } The label defines a location in the instruction stream The goto statement says jump to this label

Compiling goto.globl _main _ main : # Export main function L2: # Define a label jmp L2 # Jump to the label Structure of C is obvious in generated assembly Each C line maps to exactly one line of assembly (in this case) Important Difference: The jmp instruction can take any value. The goto statement can only take a label defined in this scope.

Conditional Jumps Similar to a jump instruction Sets the program counter, but only if the condition is met

Conditional Jumps int b = 0; if (a > 0) { b = a; } if statement defines a conditional. The next statement is only executed if the condition is true The next statement is often a block of code Another way of thinking about if: Jump over this statement if the condition if false

Compiling if movl $0, -12(% ebp ) # Store 0 in b cmpl $0, 8(% ebp ) # Compare 0 to a jle L2 # Jump if <= movl 8(% ebp ), % eax # Load a into register movl % eax, -12(% ebp )# Store register into b L2: Compare instruction sets condition flags. Conditional jump sets program counter if some of these flags are set Note: Assignment is two instructions, load value into a register, then store it into memory. C lets you avoid having to think about register allocation.

Loops for, while, and do...while loops All implemented as test-and-jump-to-start switch statements for choices Implemented jump table or as nested conditionals

Functions Decompose programs into subprograms One entry point, one or more exits Take parameters, return at most one value Java equivalent: Methods

How Functions Work 1. Save current instruction pointer 2. Jump to address of new function 3. Do stuff in that function 4. Load old instruction pointer

Emulating Functions With goto Don t ever do this in real code! void * stack [1024]; // Call stack int stackdepth = 0; // Stack pointer stack [ stackdepth ++] = && ret1 ; // Store return goto function ; // Call function ret1 : printf (" Returned \n"); return 0; function : printf (" Called Function \n"); stack [ stackdepth ++] = && ret2 ; goto function2 ; ret2 : goto * stack [-- stackdepth ]; function2 : printf (" Called Function2 \n"); goto * stack [-- stackdepth ];

And This is Why goto is Considered Harmful! The goto statement reflects how the machine works Humans don t really think like that though... Structured programming makes it much easier to understand the program design

Function Syntax // Returns int, takes two ints as arguments int foo ( int a, int b) { return a + b; } // Returns int, takes nothing as an argument int bar ( void ) { return foo (1, 2); }

Compiling a Function _ foo : # Entry point pushl % ebp # Store frame pointer movl % esp, % ebp # Set frame pointer subl $8, % esp # Allocate 8 bytes on stack movl 12(% ebp ), % eax # load a addl 8(% ebp ), % eax # add b to a leave # restore stack ret # return to caller _bar : pushl % ebp # Store frame pointer movl % esp, % ebp # Set frame pointer subl $24, % esp # Allocate 24 bytes movl $2, 4(% esp ) # Store 2 on stack movl $1, (% esp ) # Store 1 on stack call _ foo # Call foo ()

x86 Peculiarities Many architectures don t have ret and leave instructions. Stack is explicitly managed Return address pushed onto the stack (or stored in register, e.g. SPARC) jmp instruction used to return On some architectures, leaf functions are faster

Allocation on the Stack Very fast! Just change a value in a register Only for small amounts of data Typical stack size is under 1MB

Stack and Cache Reading data from main memory takes 150+ cycles Reading data from cache takes 2-10 cycles The top of the stack is (almost) always in cache

Stack Allocations and Scope int foo ( int arg ) { int a = 12; if ( arg > a) { int b = arg ; // c is not valid yet... int c; // c is valid from here... } // b and c are invalid after this point } // a is invalid after here

Scope and Lifecycle Variables are bits of memory The memory for stack variables is freed when they go out of scope What about pointers?

Pointers are (still) Just Numbers { // Allocate space for 100 ints int a* = malloc (100* sizeof ( int )); } // a goes out of scope A pointer going out of scope frees the pointer It does not free the pointee This is an example of a memory leak

Another Example int * a = NULL ; if ( somecondition ) { // b is on the stack int b = somecalculation (); // a points to b a = &b; } // b goes out of scope // a now points to an invalid pointer Freeing the pointee does not change the pointer This is an example of a dangling pointer

Summary All C flow control is a thin wrapper around machine instructions The stack is a hardware construct, used for storing return addresses and temporary state