Procedures and the Call Stack the Call Stack Discipline X86 Procedure Call and Return Instructions X86 Calling Conventions X86 Register-Saving Conventions

Total Page:16

File Type:pdf, Size:1020Kb

Procedures and the Call Stack the Call Stack Discipline X86 Procedure Call and Return Instructions X86 Calling Conventions X86 Register-Saving Conventions CS 240251 SpringFall 2019 2020 FoundationsPrinciples of Programming of Computer Languages Systems λ Ben Wood Procedures and the Call Stack The call stack discipline x86 procedure call and return instructions x86 calling conventions x86 register-saving conventions https://cs.wellesley.edu/~cs240/s20/ x86 Procedures 1 Why procedures? Why Functions? Why methods? int contains_char(char* haystack, char needle) { while (*haystack != '\0') { if (*haystack == needle) return 1; haystack++; } return 0; } Procedural Abstraction x86 Procedures 2 Implementing procedures 1. How does a caller pass arguments to a procedure? ✓ 2. How does a caller receive a return value from a procedure? ✓ 3. Where does a procedure store local variables? ✓? 4. How does a procedure know where to return ?? (what code to execute next when done)? 5. How do procedures share limited registers and memory? ?? x86 Procedures 3 Call Chain Procedure call/return: Jump? yoo yoo(…) { who • • • who(); • • • } who(…) { yoo: • • • 1 2 who: • • • jmp who back: 5 3 • • • } 4 ru(…) { jmp back • • • } But what iF we want to call a Function From multiple places in the code? x86 Procedures 4 Call Chain Procedure call/return: Jump? Broken! yoo yoo(…) { who • • • who(); ru ru • • • } who(…) { who: • • • 1 ru(); 2 ru: • • • jmp ru back2: 6 ru(); 5 3,7 • • • } jmp ru 4 back2: ru(…) { 9 jmp back2 • • • 8 } But what iF we want to call a Function From multiple places in the code? Broken: needs to track context. x86 Procedures 5 Implementing procedures requires separate storage per call! (not just per procedure) 1. How does a caller pass arguments to a procedure? ✓ 2. How does a caller receive a return value from a procedure? ✓ 3. Where does a procedure store local variables? ✓? 4. How does a procedure know where to return ?? (what code to execute next when done)? 5. How do procedures share limited registers and memory? ?? x86 Procedures 6 Memory Layout reminder Addr Perm Contents Managed by Initialized N 2 -1 Stack RW Procedure context Compiler Run-time Programmer, Dynamic RW malloc/Free, Run-time Heap data structures new/GC Global variables/ Compiler/ RW Startup Statics static data structures Assembler/Linker Compiler/ R String literals Startup Literals Assembler/Linker Compiler/ X Instructions Startup Text Assembler/Linker 0 x86 Procedures 7 Call stack tracks context Example Call Chain yoo(…) yoo { • who • who(); • amI amI who(…) • { } • amI amI(); • amI(…) amI(); amI { • • } if(…){ amI() } • Procedure amI is recursive } (calls itselF) x86 Procedures 8 Call stack tracks context Stack yoo(…) yoo { • yooyoo who • %rsp who(); • amI amI • } amI amI x86 Procedures 9 Call stack tracks context Stack yoo(…) yoo { who(…) •{ yooyoo who • • • • who();amI(); • • • • amI amI who • amI(); %rsp } • • • } amI amI x86 Procedures 10 Call stack tracks context Stack yoo(…) yoo { who(…) •{ amI(…) yooyoo who • •{ • • who();amI();• • • •if( • …){ amI amI who • amI();amI() } • •} • } • amI amI } %rsp amI x86 Procedures 11 Call stack tracks context Stack yoo(…) yoo { who(…) •{ amI(…) yooyoo who • •{ •amI • (…) who();amI{();• • • •if( • …•){ amI amI who • amI();amIif(()…){ } • •} • amI() } •} amI amI } • } amI amI %rsp x86 Procedures 12 Call stack tracks context Stack yoo(…) yoo { who(…) •{ amI(…) yooyoo who • •{ •amI • (…) who();amI{();•amI(…) • • •if( •{…•){ amI amI who • amI();amIif(()…•){ } • •} • amIif(()…){ } •} amI() amI amI } •} } • amI } amI amI %rsp x86 Procedures 13 Call stack tracks context Stack yoo(…) yoo { who(…) •{ amI(…) yooyoo who • •{ •amI • (…) who();amI{();•amI(…) • • •if( •{…•){ amI amI who • amI();amIif(()…•){ } • •} • amIif(()…){ } •} amI() amI amI } •} } • amI } amI amI %rsp x86 Procedures 14 Call stack tracks context Stack yoo(…) yoo { who(…) •{ amI(…) yooyoo who • •{ •amI • (…) who();amI{();• • • •if( • …•){ amI amI who • amI();amIif(()…){ } • •} • amI() } •} amI amI } • } amI amI %rsp amI x86 Procedures 15 Call stack tracks context Stack yoo(…) yoo { who(…) •{ amI(…) yooyoo who • •{ • • who();amI();• • • •if( • …){ amI amI who • amI();amI() } • •} • } • amI amI } %rsp amI amI amI x86 Procedures 16 Call stack tracks context Stack yoo(…) yoo { who(…) •{ yoo yoo who • • who();amI(); • • amI amI who • amI(); %rsp } • } amI amI amI amI amI x86 Procedures 17 Call stack tracks context Stack yoo(…) yoo { who(…) •{ amI(…) yooyoo who • {• who();amI();• • • if(){ amI amI who • amI();amI() } • } } • amI amI } %rsp amI x86 Procedures 18 Call stack tracks context Stack yoo(…) yoo { who(…) •{ amI(…) yooyoo who • {• who();amI();• • • if(){ amI amI who • amI();amI() } • } } • amI amI } %rsp amI x86 Procedures 19 Call stack tracks context Stack yoo(…) yoo { who(…) •{ yooyoo who • • who();amI(); • • amI amI who • amI(); %rsp } • } amI amI amI x86 Procedures 20 Call stack tracks context Stack yoo(…) yoo { • yooyoo who • %rsp who(); • amI amI who • } amI amI amI x86 Procedures 21 The call stack supports procedures. Stack frame: section oF stack Saved Registers used by one procedure call to store context while running. Caller Local Variables Frame higher Extra Arguments addresses Procedure code manages to callee stack frames explicitly. Return Address • Setup: allocate space where to continue on return at start oF procedure. • Cleanup: deallocate space stack grows beFore return. Callee Saved Registers toward Frame lower addresses Local Variables Stack pointer . %rsp x86 Procedures 22 Procedure control flow instructions Procedure call: callq target 1. Push return address on stack 2. Jump to target Return address: Address oF instruction aFter call. 400544: callq 400550 <mult2> 400549: movq %rax,(%rbx) Procedure return: retq 1. Pop return address From stack 2. Jump to return address x86 Procedures 23 Call example Before callq Memory 0x7fdf30 • 0000000000400540 <multstore>: • 0x7fdf28 • • 0x7fdf20 • 400544: callq 400550 <mult2> 0x7fdf18 ??? 400549: mov %rax,(%rbx) • %rsp %rip 0000000000400550• <mult2>: 0x7fdf20 0x400544 400550: mov %rdi,%rax • • After callq Memory 400557: retq 0x7fdf30 • 0x7fdf28 • callq target 0x7fdf20 • 1. Push return address on stack 0x7fdf18 0x400549 2. Jump to target %rsp %rip 0x7fdf18 0x400550 x86 Procedures 24 Return example Before retq Memory 0x7fdf30 • 0000000000400540 <multstore>: • 0x7fdf28 • • 0x7fdf20 • 400544: callq 400550 <mult2> 0x7fdf18 0x400549 400549: mov %rax,(%rbx) • %rsp %rip 0000000000400550• <mult2>: 0x7fdf18 0x400557 400550: mov %rdi,%rax • • After retq Memory 400557: retq 0x7fdf30 • 0x7fdf28 • retq 0x7fdf20 • 1. Pop return address From stack 0x7fdf18 0x400549 2. Jump to return address %rsp %rip 0x7fdf20 0x400549 x86 Procedures 26 Procedure data flow conventions First 6 arguments: Remaining arguments: passed in registers passed on stack (in memory) Arg 1 %rdi High Diane’s • • • Addresses Arg 2 %rsi Silk Dress Arg n Arg 3 %rdx Costs Arg 4 %rcx $8 9 • • • Arg 5 %r8 Arg 8 Arg 6 %r9 Arg 7 Low Return Address Addresses Return value: Allocate stack space For arguments passed in %rax only when needed. %rax x86 Procedures 27 callq puzzle optional callq next next: popq %rax What gets stored into %rax? Why is there no ret instruction corresponding to the call? What does this code do? (Hint: unusual use oF call.) x86 Procedures 28 Procedure data flow puzzle ex C function body: huh( , , , ) { *p = d; return x - c; } Translated to x86 assembly: huh: Reverse engineer the x86 huh procedure movsbl %dl, %edx and the body oF the C huh function to fill huh movl %edx, (%rsi) blanks in the C function header with: • the parameter types / order; and movswl %di, %edi • the return type. subl %edi, %ecx movl %ecx, %eax retq movsbl = move sign-extending a byte to a long (4-byte) movswl = move sign-extending a word (2-byte) to a long (4-byte) x86 Procedures 29 Procedure data flow puzzle ex C function body: int huh(short c, int* p, char d, int x) { *p = d; return x - c; } Translated to x86 assembly: huh: Reverse engineer the x86 huh procedure movsbl %dl, %edx and the body oF the C huh function to fill huh movl %edx, (%rsi) blanks in the C function header with: • the parameter types / order; and movswl %di, %edi • the return type. subl %edi, %ecx movl %ecx, %eax retq movsbl = move sign-extending a byte to a long (4-byte) movswl = move sign-extending a word (2-byte) to a long (4-byte) x86 Procedures 30 Procedure call / stack frame example long step_up() { long v1 = 240; step_up: long v2 = increment(&v1, 61); 400509: subq $8, %rsp return v1+v2; 40050d: movq $240, (%rsp) } 400515: movq %rsp, %rdi 400518: movl $61, %esi Passes address oF local variable (in stack). 40051d: callq 4004cd <increment> 400522: addq (%rsp), %rax 400526: addq $8, %rsp 40052a: retq Uses memory through pointer. long increment(long* p, long val) { long x = *p; long y = x + val; increment: *p = y; 4004cd: movq (%rdi), %rax return x; 4004d0: addq %rax, %rsi } 4004d3: movq %rsi, (%rdi) 4004d6: retq x86 Procedures 31 main called step_up Procedure call example (step 0) Stack long step_up() { Frames Memory long v1 = 240; long v2 = increment(&v1, 61); • • • return v1+v2; } 0x40053b main 0x7fdf28 step_up: <main+8> 400509: subq $8, %rsp 40050d: movq $240, (%rsp) 0x7fdf20 400515: movq %rsp, %rdi 400518: movl $61, %esi 0x7fdf18 40051d: callq 4004cd <increment> 400522: addq (%rsp), %rax 400526: addq $8, %rsp 40052a: retq %rax %rdi %rsi increment: 4004cd: movq (%rdi), %rax 4004d0: addq %rax, %rsi %rsp %rip 4004d3: movq %rsi, (%rdi) 0x7fdf28 0x400509 4004d6: retq x86 Procedures 36 Allocate space Procedure call example (step 1) for local vars Stack long step_up() { Frames Memory long v1 = 240; long v2 = increment(&v1, 61); • • • return
Recommended publications
  • Stackwalkerapi Programmer's Guide
    Paradyn Parallel Performance Tools StackwalkerAPI Programmer’s Guide 9.2 Release June 2016 Computer Sciences Department University of Wisconsin–Madison Madison, WI 53706 Computer Science Department University of Maryland College Park, MD 20742 Email [email protected] Web www.dyninst.org Contents 1 Introduction 3 2 Abstractions 4 2.1 Stackwalking Interface . .5 2.2 Callback Interface . .5 3 API Reference 6 3.1 Definitions and Basic Types . .6 3.1.1 Definitions . .6 3.1.2 Basic Types . .9 3.2 Namespace StackwalkerAPI . 10 3.3 Stackwalking Interface . 10 3.3.1 Class Walker . 10 3.3.2 Class Frame . 14 3.4 Accessing Local Variables . 18 3.5 Callback Interface . 19 3.5.1 Default Implementations . 19 3.5.2 Class FrameStepper . 19 3.5.3 Class StepperGroup . 22 3.5.4 Class ProcessState . 24 3.5.5 Class SymbolLookup . 27 4 Callback Interface Default Implementations 27 4.1 Debugger Interface . 28 4.1.1 Class ProcDebug . 29 4.2 FrameSteppers . 31 4.2.1 Class FrameFuncStepper . 31 4.2.2 Class SigHandlerStepper . 32 4.2.3 Class DebugStepper . 33 1 4.2.4 Class AnalysisStepper . 33 4.2.5 Class StepperWanderer . 33 4.2.6 Class BottomOfStackStepper . 33 2 1 Introduction This document describes StackwalkerAPI, an API and library for walking a call stack. The call stack (also known as the run-time stack) is a stack found in a process that contains the currently active stack frames. Each stack frame is a record of an executing function (or function-like object such as a signal handler or system call).
    [Show full text]
  • Procedures & the Stack
    Procedures & The Stack Spring 2016 Procedures & The Stack Announcements ¢ Lab 1 graded § Late days § Extra credit ¢ HW 2 out ¢ Lab 2 prep in section tomorrow § Bring laptops! ¢ Slides HTTP://XKCD.COM/1270/ 1 Procedures & The Stack Spring 2016 Memory & data Roadmap Integers & floats C: Java: Machine code & C x86 assembly car *c = malloc(sizeof(car)); Car c = new Car(); Procedures & stacks c->miles = 100; c.setMiles(100); Arrays & structs c->gals = 17; c.setGals(17); float mpg = get_mpg(c); float mpg = Memory & caches free(c); c.getMPG(); Processes Virtual memory Assembly get_mpg: Memory allocation pushq %rbp Java vs. C language: movq %rsp, %rbp ... popq %rbp ret OS: Machine 0111010000011000 100011010000010000000010 code: 1000100111000010 110000011111101000011111 Computer system: 2 Procedures & The Stack Spring 2016 Mechanisms required for procedures ¢ Passing control P(…) { § To beginning oF procedure code • • § Back to return point y = Q(x); print(y) ¢ Passing data • § Procedure arguments } § Return value ¢ Memory management int Q(int i) § Allocate during procedure execution { § Deallocate upon return int t = 3*i; int v[10]; ¢ All implemented with machine • instructions • § An x86-64 procedure uses only those return v[t]; mechanisms required For that procedure } 3 Procedures & The Stack Spring 2016 Questions to answer about procedures ¢ How do I pass arguments to a procedure? ¢ How do I get a return value from a procedure? ¢ Where do I put local variables? ¢ When a function returns, how does it know where to return? ¢ To answer some of
    [Show full text]
  • MIPS Calling Convention
    MIPS Calling Convention CS 64: Computer Organization and Design Logic Lecture #9 Fall 2018 Ziad Matni, Ph.D. Dept. of Computer Science, UCSB Administrative • Lab #5 this week – due on Friday • Grades will be up on GauchoSpace today by noon! – If you want to review your exams, see your TAs: LAST NAMES A thru Q See Bay-Yuan (Th. 12:30 – 2:30 pm) LAST NAMES R thru Z See Harmeet (Th. 9:30 – 11:30 am) • Mid-quarter evaluations for T.As – Links on the last slide and will put up on Piazza too – Optional to do, but very appreciated by us all! 11/5/2018 Matni, CS64, Fa18 2 CS 64, Fall 18, Midterm Exam Average = 86.9% Median = 87% 26 22 8 5 3 11/5/2018 Matni, CS64, Fa18 3 Lecture Outline • MIPS Calling Convention – Functions calling functions – Recursive functions 11/5/2018 Matni, CS64, Fa18 4 Function Calls Within Functions… Given what we’ve said so far… • What about this code makes our previously discussed setup break? – You would need multiple copies of $ra • You’d have to copy the value of $ra to another register (or to mem) before calling another function • Danger: You could run out of registers! 11/5/2018 Matni, CS64, Fa18 5 Another Example… What about this code makes this setup break? • Can’t fit all variables in registers at the same time! • How do I know which registers are even usable without looking at the code? 11/5/2018 Matni, CS64, Fa18 6 Solution??!! • Store certain information in memory only at certain times • Ultimately, this is where the call stack comes from • So what (registers/memory) save what??? 11/5/2018 Matni, CS64, Fa18
    [Show full text]
  • UNDERSTANDING STACK ALIGNMENT in 64-BIT CALLING CONVENTIONS for X86-64 Assembly Programmers
    UNDERSTANDING STACK ALIGNMENT IN 64-BIT CALLING CONVENTIONS For x86-64 Assembly Programmers This article is part of CPU2.0 presentation Soffian Abdul Rasad Date : Oct 2nd, 2017 Updated: 2019 Note: This article is released in conjunction with CPU2.0 to enable users to use CPU2.0 correctly in regards to stack alignment. It does not present full stack programming materials. MS 64-bit Application Binary Interface (ABI) defines an x86_64 software calling convention known as the fastcall. System V also introduces similar software calling convention known as AMD64 calling convention. These calling conventions specify the standards and the requirements of the 64-bit APIs to enable codes to access and use them in a standardized and uniform fashion. This is the standard convention being employed by Win64 APIs and Linux64 respectively. While the two are radically different, they share similar stack alignment policy – the stack must be well-aligned to 16-byte boundaries prior to calling a 64-bit API. A memory address is said to be aligned to 16 if it is evenly divisible by 16, or if the last digit is 0, in hexadecimal notation. Please note that to simplify discussions, we ignore the requirement for shadow space or red zone when calling the 64-bit APIs for now. But still with or without the shadow space, the discussion below applies. Also note that the CPU honors no calling convention. Align 16 Ecosystem This requirement specifies that for the 64-bit APIs to function correctly it must work in an ecosystem or runtime environment in which the stack memory is always aligned to 16-byte boundaries.
    [Show full text]
  • Protecting Against Unexpected System Calls
    Protecting Against Unexpected System Calls C. M. Linn, M. Rajagopalan, S. Baker, C. Collberg, S. K. Debray, J. H. Hartman Department of Computer Science University of Arizona Tucson, AZ 85721 {linnc,mohan,bakers,collberg,debray,jhh}@cs.arizona.edu Abstract writing the return address on the stack with the address of the attack code). This then causes the various actions This paper proposes a comprehensive set of techniques relating to the attack to be carried out. which limit the scope of remote code injection attacks. These techniques prevent any injected code from mak- In order to do any real damage, e.g., create a root ing system calls and thus restrict the capabilities of an shell, change permissions on a file, or access proscribed attacker. In defending against the traditional ways of data, the attack code needs to execute one or more sys- harming a system these techniques significantly raise the tem calls. Because of this, and the well-defined system bar for compromising the host system forcing the attack call interface between application code and the underly- code to take extraordinary steps that may be impractical ing operating system kernel, many researchers have fo- in the context of a remote code injection attack. There cused on the system call interface as a convenient point are two main aspects to our approach. The first is to for detecting and disrupting such attacks (see, for exam- embed semantic information into executables identify- ple, [5, 13, 17, 19, 29, 32, 35, 38]; Section 7 gives a more ing the locations of legitimate system call instructions; extensive discussion).
    [Show full text]
  • Protecting the Stack with Metadata Policies and Tagged Hardware
    2018 IEEE Symposium on Security and Privacy Protecting the Stack with Metadata Policies and Tagged Hardware Nick Roessler Andre´ DeHon University of Pennsylvania University of Pennsylvania [email protected] [email protected] Abstract—The program call stack is a major source of ex- stack data, or hijack the exposed function call mechanism in ploitable security vulnerabilities in low-level, unsafe languages a host of other malicious ways. like C. In conventional runtime implementations, the underlying Consequently, protecting the stack abstraction is critical stack data is exposed and unprotected, allowing programming errors to turn into security violations. In this work, we design for application security. Currently deployed defenses such as W X and stack canaries [2] make attacks more difficult to novel metadata-tag based, stack-protection security policies for ⊕ a general-purpose tagged architecture. Our policies specifically conduct, but do not protect against more sophisticated attack exploit the natural locality of dynamic program call graphs to techniques. Full memory safety can be retrofitted onto existing achieve cacheability of the metadata rules that they require. C/C++ code through added software checks, but at a high cost Our simple Return Address Protection policy has a performance overhead of 1.2% but just protects return addresses. The two of 100% or more in runtime overhead [3]. These expensive richer policies we present, Static Authorities and Depth Isola- solutions are unused in practice due to their unacceptably high tion, provide object-level protection for all stack objects. When overheads [4]. enforcing memory safety, our Static Authorities policy has a There is a long history of accelerating security policies with performance overhead of 5.7% and our Depth Isolation policy hardware to bring their overheads to more bearable levels has a performance overhead of 4.5%.
    [Show full text]
  • X86-64 Calling Conventions
    CSE 351: The Hardware/Software Interface Section 4 Procedure calls Procedure calls In x86 assembly, values are passed to function calls on the stack Perks: Concise, easy to remember Drawbacks: Always requires memory accesses In x86-64 assembly, values are passed to function calls in registers Perks: Less wasted space, faster Drawbacks: Potentially requires a lot of register manipulation 2/23/2014 2 x86 calling conventions Simply push arguments onto the stack in order, then “call” the function! Suppose we define the following function: int sum(int a, int b) { return a + b; } (See also sum.c from the provided code) 2/23/2014 3 x86 calling conventions int sum(int a, int b) { return a + b; } In assembly, we have something like this: sum: pushl %ebp # Save base pointer movl %esp, %ebp # Save stack pointer movl 12(%ebp), %eax # Load b movl 8(%ebp), %edx # Load a addl %edx, %eax # Compute a + b popl %ebp # Restore base pointer ret # Return 2/23/2014 4 x86 calling conventions What is happening with %ebp and %esp? pushl %ebp The base pointer %ebp is the address of the caller, which is the location to which “ret” returns. The function pushes it into the stack so that it won’t be overwritten movl %esp, %ebp Functions often shift the stack pointer to allocate temporary stack space, so this instruction makes a backup of the original location. In the body of the function, %ebp is now the original start of the stack ret When sum() returns, execution picks up at the stored base pointer address.
    [Show full text]
  • Time-Travel Debugging for Javascript/Node.Js
    Time-Travel Debugging for JavaScript/Node.js Earl T. Barr Mark Marron Ed Maurer University College London, UK Microsoft Research, USA Microsoft, USA [email protected] [email protected] [email protected] Dan Moseley Gaurav Seth Microsoft, USA Microsoft, USA [email protected] [email protected] ABSTRACT Time-traveling in the execution history of a program during de- bugging enables a developer to precisely track and understand the sequence of statements and program values leading to an error. To provide this functionality to real world developers, we embarked on a two year journey to create a production quality time-traveling de- bugger in Microsoft’s open-source ChakraCore JavaScript engine and the popular Node.js application framework. CCS Concepts •Software and its engineering ! Software testing and debug- Figure 1: Visual Studio Code with extra time-travel functional- ging; ity (Step-Back button in top action bar) at a breakpoint. Keywords • Options for both using time-travel during local debugging Time-Travel Debugging, JavaScript, Node.js and for recording a trace in production for postmortem de- bugging or other analysis (Section 2.1). 1. INTRODUCTION • Reverse-Step Local and Dynamic operations (Section 2.2) Modern integrated development environments (IDEs) provide a that allow the developer to step-back in time to the previously range of tools for setting breakpoints, examining program state, and executed statement in the current function or to step-back in manually logging execution. These features enable developers to time to the previously executed statement in any frame in- quickly track down localized bugs, provided all of the relevant val- cluding exception throws or callee returns.
    [Show full text]
  • Sample Applications User Guides Release 20.05.0
    Sample Applications User Guides Release 20.05.0 May 26, 2020 CONTENTS 1 Introduction to the DPDK Sample Applications1 1.1 Running Sample Applications...............................1 1.2 The DPDK Sample Applications..............................1 2 Compiling the Sample Applications3 2.1 To compile all the sample applications...........................3 2.2 To compile a single application..............................3 2.3 To cross compile the sample application(s)........................4 3 Command Line Sample Application5 3.1 Overview..........................................5 3.2 Compiling the Application.................................5 3.3 Running the Application..................................6 3.4 Explanation.........................................6 4 Ethtool Sample Application8 4.1 Compiling the Application.................................8 4.2 Running the Application..................................8 4.3 Using the application....................................8 4.4 Explanation.........................................9 4.5 Ethtool interface......................................9 5 Hello World Sample Application 11 5.1 Compiling the Application................................. 11 5.2 Running the Application.................................. 11 5.3 Explanation......................................... 11 6 Basic Forwarding Sample Application 13 6.1 Compiling the Application................................. 13 6.2 Running the Application.................................. 13 6.3 Explanation........................................
    [Show full text]
  • Section 6: Implementing Coroutines
    Section 6: Implementing Coroutines In Section 5, we worked on the usage of coroutines. Today, we will be reviewing the basic concepts relating to how coroutines can be implemented. 1 def f() { 2 yield(1) 3 yield(2) 4 null 5 } 6 7 def g(unused) { 8 f() 9 } 10 11 def co = coroutine(g) 12 print(resume(co, null)) 13 print(resume(co, null)) 14 print(resume(co, null)) Part 1. What does the above program print? 1 2 null Part 2. Which piece of information about the coroutine co does the interpreter need to remember to continue execution when the second resume is invoked? To continue execution within f, the interpreter needs to remember: ● the coroutine call stack that contains frames for the calls to g and to f ● the next instruction to execute in each stack frame Part 3. What happens if we invoke resume a fourth time? Think about how the interpreter should implement the intended behavior. Invoking resume for a fourth time will result in an error. The interpreter can track this by distinguishing whether the coroutine has finished its execution or not. Part 4. Describe a data structure to maintain the state of the coroutine throughout program execution. For each coroutine, we must store: ● A coroutine state (running, suspended, or dead) ● A call stack ● For each frame in the call stack: ○ The program counter ○ The bytecode array into which the PC indexes ○ The environment Part 5. Now consider the following changes to the program above. 1 def f() { 2 yield(1) 3 print "between yields" 4 yield(2) 5 null 6 } 7 8 def g(unused) { 9 f() 10 } 11 12 def co = coroutine(g) 13 print "created coroutine" 14 resume(co, null) 15 print "between resumes" 16 resume(co, null) 17 resume(co, null) 18 print "end" Describe the state of coroutines maintained by the interpreter at each print statement.
    [Show full text]
  • X86 Assembly Language Reference Manual
    x86 Assembly Language Reference Manual Part No: 817–5477–11 March 2010 Copyright ©2010 Oracle and/or its affiliates. All rights reserved. This software and related documentation are provided under a license agreement containing restrictions on use and disclosure and are protected by intellectual property laws. Except as expressly permitted in your license agreement or allowed by law, you may not use, copy, reproduce, translate, broadcast, modify, license, transmit, distribute, exhibit, perform, publish, or display any part, in any form, or by any means. Reverse engineering, disassembly, or decompilation of this software, unless required by law for interoperability, is prohibited. The information contained herein is subject to change without notice and is not warranted to be error-free. If you find any errors, please report them to us in writing. If this is software or related software documentation that is delivered to the U.S. Government or anyone licensing it on behalf of the U.S. Government, the following notice is applicable: U.S. GOVERNMENT RIGHTS Programs, software, databases, and related documentation and technical data delivered to U.S. Government customers are “commercial computer software” or “commercial technical data” pursuant to the applicable Federal Acquisition Regulation and agency-specific supplemental regulations. As such, the use, duplication, disclosure, modification, and adaptation shall be subject to the restrictions and license terms setforth in the applicable Government contract, and, to the extent applicable by the terms of the Government contract, the additional rights set forth in FAR 52.227-19, Commercial Computer Software License (December 2007). Oracle USA, Inc., 500 Oracle Parkway, Redwood City, CA 94065.
    [Show full text]
  • Essentials of Compilation an Incremental Approach
    Essentials of Compilation An Incremental Approach Jeremy G. Siek, Ryan R. Newton Indiana University with contributions from: Carl Factora Andre Kuhlenschmidt Michael M. Vitousek Michael Vollmer Ryan Scott Cameron Swords April 2, 2019 ii This book is dedicated to the programming language wonks at Indiana University. iv Contents 1 Preliminaries 5 1.1 Abstract Syntax Trees and S-expressions . .5 1.2 Grammars . .7 1.3 Pattern Matching . .9 1.4 Recursion . 10 1.5 Interpreters . 12 1.6 Example Compiler: a Partial Evaluator . 14 2 Integers and Variables 17 2.1 The R1 Language . 17 2.2 The x86 Assembly Language . 20 2.3 Planning the trip to x86 via the C0 language . 24 2.3.1 The C0 Intermediate Language . 27 2.3.2 The dialects of x86 . 28 2.4 Uniquify Variables . 28 2.5 Remove Complex Operators and Operands . 30 2.6 Explicate Control . 31 2.7 Uncover Locals . 32 2.8 Select Instructions . 32 2.9 Assign Homes . 33 2.10 Patch Instructions . 34 2.11 Print x86 . 35 3 Register Allocation 37 3.1 Registers and Calling Conventions . 38 3.2 Liveness Analysis . 39 3.3 Building the Interference Graph . 40 3.4 Graph Coloring via Sudoku . 42 3.5 Print x86 and Conventions for Registers . 48 v vi CONTENTS 3.6 Challenge: Move Biasing∗ .................... 48 4 Booleans and Control Flow 53 4.1 The R2 Language . 54 4.2 Type Checking R2 Programs . 55 4.3 Shrink the R2 Language . 58 4.4 XOR, Comparisons, and Control Flow in x86 . 58 4.5 The C1 Intermediate Language .
    [Show full text]