Assembly Language for Intel-Based Computers, 4 th Edition. Lecture 25: Interface With High-Level Language

Similar documents
Assembly Language for Intel-Based Computers, 4 th Edition

Assembly Language for Intel-Based Computers, 4 th Edition

Assembly Language for Intel-Based Computers, 4 th Edition. Chapter 5: Procedures. Chapter Overview. The Book's Link Library

EECE.3170: Microprocessor Systems Design I Summer 2017 Homework 4 Solution

Islamic University Gaza Engineering Faculty Department of Computer Engineering ECOM 2125: Assembly Language LAB. Lab # 10. Advanced Procedures

Stack -- Memory which holds register contents. Will keep the EIP of the next address after the call

X86 Addressing Modes Chapter 3" Review: Instructions to Recognize"

Program Exploitation Intro

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

Assembly Language for Intel-Based Computers, 5 th Edition. Chapter 9: Strings and Arrays

EECE.3170: Microprocessor Systems Design I Summer 2017

CSC 8400: Computer Systems. Machine-Level Representation of Programs

COMPUTER ENGINEERING DEPARTMENT

16.317: Microprocessor Systems Design I Fall 2014

CSC 2400: Computer Systems. Towards the Hardware: Machine-Level Representation of Programs

16.317: Microprocessor Systems Design I Fall 2015

Assembly Language for Intel-Based Computers, 4 th Edition. Chapter 1: Basic Concepts

Assembly Language for Intel-Based Computers, 4 th Edition. Chapter 5: Procedures

COMPUTER ENGINEERING DEPARTMENT

16.317: Microprocessor Systems Design I Spring 2015

22 Assembly Language for Intel-Based Computers, 4th Edition. 3. Each edge is a transition from one state to another, caused by some input.

Microprocessors ( ) Fall 2010/2011 Lecture Notes # 15. Stack Operations. 10 top

Assembly Language for Intel-Based Computers, 4 th Edition. Chapter 8:Advanced Procedures

Macros in Pentium. Assembly Language. October 25

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

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

Overview of Compiler. A. Introduction

Marking Scheme. Examination Paper Department of CE. Module: Microprocessors (630313)

Islamic University Gaza Engineering Faculty Department of Computer Engineering ECOM 2125: Assembly Language LAB. Lab # 7. Procedures and the Stack

An Introduction to x86 ASM

Practical Malware Analysis

Machine Code and Assemblers November 6

We will first study the basic instructions for doing multiplications and divisions

Digital Forensics Lecture 3 - Reverse Engineering

16.317: Microprocessor Systems Design I Fall 2013

W4118: PC Hardware and x86. Junfeng Yang

Assembly Language for Intel-Based Computers, 4 th Edition

Conditional Processing

Assembler Programming. Lecture 10

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

Towards the Hardware"

Assembly Language for Intel-Based Computers, 4 th Edition. Chapter 3: Assembly Language Fundamentals

Computer Systems Lecture 9

CS61 Section Solutions 3

Assembly Language for Intel-Based Computers, 4 th Edition. Chapter 2: IA-32 Processor Architecture Included elements of the IA-64 bit

Computer Systems Organization V Fall 2009

Winter Compiler Construction T11 Activation records + Introduction to x86 assembly. Today. Tips for PA4. Today:

Dr. Ramesh K. Karne Department of Computer and Information Sciences, Towson University, Towson, MD /12/2014 Slide 1

CSE P 501 Compilers. x86 Lite for Compiler Writers Hal Perkins Autumn /25/ Hal Perkins & UW CSE J-1

/ 28 HLL assembly Q4: Conditional instructions / 40 TOTAL SCORE / 100 EXTRA CREDIT / 10

Chapter Overview. Assembly Language for Intel-Based Computers, 4 th Edition. Chapter 3: Assembly Language Fundamentals.

CPEG421/621 Tutorial

Lab 2: Introduction to Assembly Language Programming

Assembly Language. Lecture 5 Procedures

Assembly Language. Lecture 5 Procedures

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

Assembly Programmer s View Lecture 4A Machine-Level Programming I: Introduction

Islamic University Gaza Engineering Faculty Department of Computer Engineering ECOM 2125: Assembly Language LAB

Objectives. ICT106 Fundamentals of Computer Systems Topic 8. Procedures, Calling and Exit conventions, Run-time Stack Ref: Irvine, Ch 5 & 8

x86 assembly CS449 Fall 2017

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

Computer Architecture and Assembly Language. Practical Session 5

Assembly Language Programming: Procedures. EECE416 uc. Charles Kim Howard University. Fall

Islamic University Gaza Engineering Faculty Department of Computer Engineering ECOM 2125: Assembly Language LAB. Lab # 8. Conditional Processing

Assembly Language for Intel-Based Computers, 5 th Edition. Chapter 3: Assembly Language Fundamentals

Inline Assembler. Willi-Hans Steeb and Yorick Hardy. International School for Scientific Computing

EECE416 :Microcomputer Fundamentals and Design. X86 Assembly Programming Part 1. Dr. Charles Kim

SOEN228, Winter Revision 1.2 Date: October 25,

Assembly Language for Intel-Based Computers, 5 th Edition

Machine and Assembly Language Principles

Reverse Engineering Low Level Software. CS5375 Software Reverse Engineering Dr. Jaime C. Acosta

Marking Scheme. Examination Paper. Module: Microprocessors (630313)

Lecture 15 Intel Manual, Vol. 1, Chapter 3. Fri, Mar 6, Hampden-Sydney College. The x86 Architecture. Robb T. Koether. Overview of the x86

COE 205. Computer Organization and Assembly Language Dr. Aiman El-Maleh

Summary: Direct Code Generation

Second Part of the Course

Writing 32-Bit Applications

Assembly Language: Function Calls

Module 3 Instruction Set Architecture (ISA)

Marking Scheme. Examination Paper. Module: Microprocessors (630313)

Libraries and Procedures

The x86 Architecture

Addressing Modes. Outline

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

Macros. Introducing Macros Defining Macros Invoking Macros Macro Examples Nested Macros Example Program: Wrappers

Experiment 8 8 Subroutine Handling Instructions and Macros

Assembly Language for Intel-Based Computers, 4 th Edition

Assembly Language: Function Calls" Goals of this Lecture"

Marking Scheme. Examination Paper Department of CE. Module: Microprocessors (630313)

CNIT 127: Exploit Development. Ch 1: Before you begin. Updated

Comparison Of File Infection On The Windows And Linux lclee_vx / F-13 Labs, lychan25/f-13 Labs

Summer 2003 Lecture 15 07/03/03

CS Bootcamp x86-64 Autumn 2015

CS24: INTRODUCTION TO COMPUTING SYSTEMS. Spring 2016 Lecture 12

Assembly Language: Function Calls" Goals of this Lecture"

Summer 2003 Lecture 14 07/02/03

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

Procedure-Calling Conventions October 30

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

A4 Sample Solution Ch3

Transcription:

Assembly Language for Intel-Based Computers, 4 th Edition Kip R. Irvine Lecture 25: Interface With High-Level Language Slide show prepared by Kip R. Irvine, Revision date: 07/07/2002 Modified on April 23.2005 by Dr. Nikolay Metodiev Sirakov Chapter corrections (Web) Assembly language sources (Web) (c) Pearson Education, 2002. All rights reserved. You may modify and copy this slide show for your personal use, or for use in the classroom, as long as this copyright statement, the author's name, and the title are not changed.

Chapter Overview Why Link ASM and HLL Programs? General and Calling Conventions External Identifiers Inline Assembly Code asm Directive File Encryption Example Linking to C++ Programs Linking to Borland C++ ReadSector Example Special Section: Optimizing Your Code Loop Optimization Example FindArray Example Creating the FindArray Project 2

Why Link ASM and HLL Programs? Use high-level language for overall project development Relieves programmer from low-level details Use assembly language code Speed up critical sections of code Access nonstandard hardware devices Write platform-specific code Extend the HLL's capabilities 3

General Conventions Considerations when calling assembly language procedures from high-level languages: Both must use the same naming convention (rules regarding the naming of variables and procedures) Both must use the same memory model, with compatible segment names Both must use the same calling convention 4

Calling Convention Identifies specific registers that must be preserved by procedures Determines how arguments are passed to procedures: in registers, on the stack, in shared memory, etc. Determines the order in which arguments are passed by calling programs to procedures Determines whether arguments are passed by value or by reference Determines how the stack pointer is restored after a procedure call Determines how functions return values 5

External Identifiers An external identifier is a name that has been placed in a module s object file in such a way that the linker can make the name available to other program modules. The linker resolves references to external identifiers, but can only do so if the same naming convention is used in all program modules. 6

Inline Assembly Code Assembly language source code that is inserted directly into a HLL program. Compilers such as Microsoft Visual C++ and Borland C++ have compiler-specific directives that identify inline ASM code. Efficient inline code executes quickly because CALL and RET instructions are not required. Simple to code because there are no external names, memory models, or naming conventions involved. Disadvantage: Decidedly not portable because it is written for a single platform. 7

_asm Directive in Microsoft Visual C++ Can be placed at the beginning of a single statement Or, It can mark the beginning of a block of assembly language statements Syntax: asm statement asm { statement-1 statement-2... statement-n } 8

Commenting Styles All of the following comment styles are acceptable, but the latter two are preferred: mov esi,buf ; initialize index register mov esi,buf // initialize index register mov esi,buf /* initialize index register */ 9

You Can Do the Following... Use any instruction from the Intel instruction set Use register names as operands Reference function parameters by name Reference code labels and variables that were declared outside the asm block Use numeric literals that incorporate either assembler-style or C-style radix notation Use the PTR operator in statements such as inc BYTE PTR [esi] Use the EVEN and ALIGN directives Use LENGTH, TYPE, and SIZE directives 10

You Cannot Do the Following... Use data definition directives such as DB, DW, or BYTE Use assembler operators other than PTR Use STRUCT, RECORD, WIDTH, and MASK Use macro directives such as MACRO, REPT, IRC, IRP Reference segments by name. (You can, however, use segment register names as operands.) 11

Register Usage In general, you can modify EAX, EBX, ECX, and EDX in your inline code because the compiler does not expect these values to be preserved between statements Conversely, always save and restore ESI, EDI, and EBP. See the Inline Test demonstration program. 12

File Encryption Example Reads a file, encrypts it, and writes the output to another file. The TranslateBuffer function uses an asm block to define statements that loop through a character array and XOR each character with a predefined value. View the Encode2.cpp program listing 13

Linking Assembly Language to C++ Basic Structure - Two Modules The first module, written in assembly language, contains the external procedure The second module contains the C/C++ code that starts and ends the program The C++ module adds the extern qualifier to the external assembly language function prototype. The "C" specifier must be included to prevent name decoration by the C++ compiler: extern "C" functionname( parameterlist ); 14

Name Decoration Also known as name mangling. HLL compilers do this to uniquely identify overloaded functions. A function such as: int ArraySum( int * p, int count ) would be exported as a decorated name that encodes the return type, function name, and parameter types. For example: int_arraysum_pint_int The C++ compilers problem vary with in name the way decoration they decorate is that function the C++ compiler names. assumes that your assembly language function's name is decorated. The C++ compiler tells the linker to look for a decorated name. 15

Special Section: Optimizing Your Code The 90/10 rule: 90% of a program's CPU time is spent executing 10% of the program's code We will concentrate on optimizing ASM code for speed of execution Loops are the most effective place to optimize code Two simple ways to optimize a loop: Move invariant code out of the loop Substitute registers for variables to reduce the number of memory accesses Take advantage of high-level instructions such as XLAT, SCASB, and MOVSD. 16

Loop Optimization Example We will write a short program that calculates and displays the number of elapsed minutes, over a period of n days. The following variables are used:.data days DWORD? minutesinday DWORD? totalminutes DWORD? str1 BYTE "Daily total minutes: ",0 17

Sample Program Output Daily total minutes: +1440 Daily total minutes: +2880 Daily total minutes: +4320 Daily total minutes: +5760 Daily total minutes: +7200 Daily total minutes: +8640 Daily total minutes: +10080 Daily total minutes: +11520.. Daily total minutes: +67680 Daily total minutes: +69120 Daily total minutes: +70560 Daily total minutes: +72000 View the complete source code. 18

Version 1 No optimization. mov days,0 mov totalminutes,0 L1: ; loop contains 15 instructions mov eax,24 ; minutesinday = 24 * 60 mov ebx,60 mul ebx mov minutesinday,eax mov edx,totalminutes ; totalminutes += minutesinday add edx,minutesinday mov totalminutes,edx mov edx,offset str1 ; "Daily total minutes: " call WriteString mov eax,totalminutes ; display totalminutes call WriteInt call Crlf inc days ; days++ cmp days,50 ; if days < 50, jb L1 ; repeat the loop 19

Version 2 Move calculation of minutesinday outside the loop, and assign EDX before the loop. The loop now contains 10 instructions. mov days,0 mov totalminutes,0 mov eax,24 ; minutesinday = 24 * 60 mov ebx,60 mul ebx mov minutesinday,eax mov edx,offset str1 ; "Daily total minutes: " L1: mov edx,totalminutes ; totalminutes += minutesinday add edx,minutesinday mov totalminutes,edx call WriteString ; display str1 (offset in EDX) mov eax,totalminutes ; display totalminutes call WriteInt call Crlf inc days ; days++ cmp days,50 ; if days < 50, jb L1 ; repeat the loop 20

Version 3 Move totalminutes to EAX, use EAX throughout loop. Use constant expresion for minutesinday calculation. The loop now contains 7 instructions. C_minutesInDay = 24 * 60 ; constant expression mov days,0 mov totalminutes,0 mov eax,totalminutes mov edx,offset str1 ; "Daily total minutes: " L1: add eax,c_minutesinday ; totalminutes += minutesinday call WriteString ; display str1 (offset in EDX) call WriteInt ; display totalminutes (EAX) call Crlf inc days ; days++ cmp days,50 ; if days < 50, jb L1 ; repeat the loop mov totalminutes,eax ; update variable 21

Using Assembly Language to Optimize C++ Find out how to make your C++ compiler produce an assembly language source listing /FAs command-line option in Visual C++, for example Optimize loops for speed Use hardware-level I/O for optimum speed Use BIOS-level I/O for medium speed 22

FindArray Example Let's write a C++ function that searches for the first matching integer in an array. The function returns true if the integer is found, and false if it is not: #include "findarr.h" bool FindArray( long searchval, long array[], long count ) { for(int i = 0; i < count; i++) if( searchval == array[i] ) return true; return false; } 23

Code Produced by C++ Compiler optimization switch turned off (1 of 3) _searchval$ = 8 _array$ = 12 _count$ = 16 _i$ = -4 _FindArray PROC NEAR ; 29 : { push ebp mov ebp, esp push ecx ; 30 : for(int i = 0; i < count; i++) mov DWORD PTR _i$[ebp], 0 jmp SHORT $L174 $L175: mov eax, DWORD PTR _i$[ebp] add eax, 1 mov DWORD PTR _i$[ebp], eax 24

Code Produced by C++ Compiler (2 of 3) $L174: mov ecx, DWORD PTR _i$[ebp] cmp ecx, DWORD PTR _count$[ebp] jge SHORT $L176 ; 31 : if( searchval == array[i] ) mov edx, DWORD PTR _i$[ebp] mov eax, DWORD PTR _array$[ebp] mov ecx, DWORD PTR _searchval$[ebp] cmp ecx, DWORD PTR [eax+edx*4] jne SHORT $L177 ; 32 : return true; mov al, 1 jmp SHORT $L172 $L177: ; 33 : ; 34 : return false; jmp SHORT $L175 25

Code Produced by C++ Compiler (3 of 3) $L176: xor al, al ; AL = 0 $L172: ; 35 : } mov esp, ebp pop ebp ret 0 _FindArray ENDP ; restore stack pointer 26

Hand-Coded Assembly Language (1 of 2) true = 1 false = 0 ; Stack parameters: srchval equ [ebp+08] arrayptr equ [ebp+12] count equ [ebp+16].code _FindArray PROC near push ebp mov ebp,esp push edi mov eax, srchval ; search value mov ecx, count ; number of items mov edi, arrayptr ; pointer to array 27

Hand-Coded Assembly Language (2 of 2) repne scasd ; do the search jz returntrue ; ZF = 1 if found returnfalse: mov al, false jmp short exit returntrue: mov al, true exit: pop edi pop ebp ret _FindArray ENDP 28

Creating the FindArray Project (using Microsoft Visual Studio 6.0) Run Visual C++ and create a project named FindArray. Add a CPP source file to the project named main.cpp. This file should contain the C++ main() function that calls FindArray. View a sample. Add a new header file named FindArr.h to the project. This file contains the function prototype for FindArray. View a sample. Create a file named Scasd.asm and place it in the project directory. This file contains the source code for the FindArray procedure. View a sample. Use ML.EXE to assemble the Scasd.asm file, producing Scasd.obj. Do not try to link the program. Insert Scasd.obj into your C++ project. (Select Add Files... from the Project menu.) (this needs to be verified) Build and run the project. 29

Creating the FindArray Project (using Microsoft Visual Studio) Run Visual C++.Net and create a new project named FindArray. Add a blank C++ source file to the project named main.cpp. Type the main() function that calls FindArray. View a sample. Add a new header file named FindArr.h to the project. This file contains the function prototype for FindArray. View a sample. Create a file named Scasd.asm and place it in the project directory. This file contains the source code for the FindArray procedure. View a sample. Use ML.EXE to assemble the Scasd.asm file, producing Scasd.obj. Do not try to link the program. Insert Scasd.obj into your C++ project. Build and run the project. 30