assembly language for intel -based...

26
Assembly Language for Intel ® -Based Computers Fifth Edition KIP R. IRVINE Florida International University School of Computing and Information Sciences Pearson Education, Inc. Upper Saddle River, NJ 07458

Upload: nguyenanh

Post on 26-Jun-2018

255 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Assembly Language for Intel -Based Computersapi.ning.com/.../Assemblylanguageforintelbasedcomputers.pdf7.4.1 MUL Instruction 204 7.4.2 IMUL Instruction 205 7.4.3 Benchmarking Multiplication

Assembly Language for Intel®-Based Computers

Fifth Edition

KIP R. IRVINE

Florida International UniversitySchool of Computing and Information Sciences

Pearson Education, Inc.Upper Saddle River, NJ 07458

Page 2: Assembly Language for Intel -Based Computersapi.ning.com/.../Assemblylanguageforintelbasedcomputers.pdf7.4.1 MUL Instruction 204 7.4.2 IMUL Instruction 205 7.4.3 Benchmarking Multiplication

Library of Congress Cataloging-in-Publication Data

Irvine, Kip R.Assembly language for intel-based computers/Kip R. Irvine.—5th ed.

p. cm.Includes index.ISBN 0-13-238310-1

1. IBM Personal Computer—Programming. 2. Assembler language (Computer program language) I. Title.QA76.8.I77 2006005.265—dc22 2006012500

Vice President and Editorial Director, ECS: Marcia J. HortonExecutive Editor: Tracy DunkelbergerAssociate Editor: Carole SnyderEditorial Assistant: Christianna LeeExecutive Managing Editor: Vince O’BrienManaging Editor: Camille TrentacosteProduction Editor: Karen EttingerDirector of Creative Services: Paul BelfantiCreative Director: Juan LopezManaging Editor, AV Management and Production: Patricia BurnsArt Editor: Gregory DullesManufacturing Manager, ESM: Alexis Heydt-LongManufacturing Buyer: Lisa McDowellExecutive Marketing Manager: Robin O’BrienMarketing Assistant: Mack Patterson

All rights reserved. No part of this book may be reproduced, in any form or by any means, without permission in writingfrom the publisher.

Pearson Prentice Hall® is a trademark of Pearson Education, Inc.

The author and publisher of this book have used their best efforts in preparing this book. These efforts include thedevelopment, research, and testing of the theories and programs to determine their effectiveness. The author and publishermake no warranty of any kind, expressed or implied, with regard to these programs or the documentation contained inthis book. The author and publisher shall not be liable in any event for incidental or consequential damages in connectionwith, or arising out of, the furnishing, performance, or use of these programs.

Printed in the United States of AmericaAll other trademarks or product names are the property of their respective owners.

TRADEMARK INFORMATION

IA-32, Pentium, and Intel 386 are trademarks of Intel Corporation.TASM and Turbo Debugger are trademarks of Borland International.Microsoft Assembler (MASM),Windows NT, Windows Me, Windows 95, Windows 98, Windows 2000, Windows XP,

MS-Windows, PowerPoint, Win32, DEBUG, WinDbg, MS-DOS, Visual Studio, Visual C++, and CodeView areregistered trademarks of Microsoft Corporation.

Autocad is a trademark of Autodesk.PartitionMagic is a trademark of Symantec.

10 9 8 7 6 5 4 3 2 1

ISBN 0-13-238310-1

Pearson Education Ltd., LondonPearson Education Australia Pty. Ltd., SydneyPearson Education Singapore, Pte. Ltd.Pearson Education North Asia Ltd., Hong KongPearson Education Canada, Inc., TorontoPearson Educación de Mexico, S.A. de C.V.Pearson Education—Japan, TokyoPearson Education—Malaysia, Pte. Ltd.Pearson Education, Inc., Upper Saddle River, New Jersey

© 2007, 2003, 1999 Pearson Education, Inc.Pearson Prentice HallPearson Education, Inc.Upper Saddle River, New Jersey 07458

Page 3: Assembly Language for Intel -Based Computersapi.ning.com/.../Assemblylanguageforintelbasedcomputers.pdf7.4.1 MUL Instruction 204 7.4.2 IMUL Instruction 205 7.4.3 Benchmarking Multiplication

To Jack and Candy Irvine

Page 4: Assembly Language for Intel -Based Computersapi.ning.com/.../Assemblylanguageforintelbasedcomputers.pdf7.4.1 MUL Instruction 204 7.4.2 IMUL Instruction 205 7.4.3 Benchmarking Multiplication
Page 5: Assembly Language for Intel -Based Computersapi.ning.com/.../Assemblylanguageforintelbasedcomputers.pdf7.4.1 MUL Instruction 204 7.4.2 IMUL Instruction 205 7.4.3 Benchmarking Multiplication

v

ContentsPreface xxiii

1 Basic Concepts 11.1 Welcome to Assembly Language 1

1.1.1 Good Questions to Ask 21.1.2 Assembly Language Applications 51.1.3 Section Review 6

1.2 Virtual Machine Concept 71.2.1 History of PC Assemblers 91.2.2 Section Review 9

1.3 Data Representation 91.3.1 Binary Numbers 101.3.2 Binary Addition 111.3.3 Integer Storage Sizes 121.3.4 Hexadecimal Integers 131.3.5 Signed Integers 141.3.6 Character Storage 161.3.7 Section Review 18

1.4 Boolean Operations 201.4.1 Truth Tables for Boolean Functions 221.4.2 Section Review 23

1.5 Chapter Summary 23

2 IA-32 Processor Architecture 252.1 General Concepts 25

2.1.1 Basic Microcomputer Design 262.1.2 Instruction Execution Cycle 272.1.3 Reading from Memory 302.1.4 How Programs Run 312.1.5 Section Review 32

2.2 IA-32 Processor Architecture 332.2.1 Modes of Operation 332.2.2 Basic Execution Environment 34

Page 6: Assembly Language for Intel -Based Computersapi.ning.com/.../Assemblylanguageforintelbasedcomputers.pdf7.4.1 MUL Instruction 204 7.4.2 IMUL Instruction 205 7.4.3 Benchmarking Multiplication

vi Contents

2.2.3 Floating-Point Unit 362.2.4 Intel Microprocessor History 372.2.5 Section Review 38

2.3 IA-32 Memory Management 392.3.1 Real-Address Mode 392.3.2 Protected Mode 412.3.3 Section Review 43

2.4 Components of an IA-32 Microcomputer 432.4.1 Motherboard 432.4.2 Video Output 442.4.3 Memory 452.4.4 Input-Output Ports and Device Interfaces 452.4.5 Section Review 46

2.5 Input-Output System 462.5.1 How It All Works 462.5.2 Section Review 48

2.6 Chapter Summary 49

3 Assembly Language Fundamentals 513.1 Basic Elements of Assembly Language 51

3.1.1 Integer Constants 523.1.2 Integer Expressions 523.1.3 Real Number Constants 533.1.4 Character Constants 543.1.5 String Constants 543.1.6 Reserved Words 543.1.7 Identifiers 543.1.8 Directives 553.1.9 Instructions 553.1.10 The NOP (No Operation) Instruction 573.1.11 Section Review 58

3.2 Example: Adding Three Integers 583.2.1 Alternative Version of AddSub 603.2.2 Program Template 613.2.3 Section Review 61

3.3 Assembling, Linking, and Running Programs 623.3.1 The Assemble-Link-Execute Cycle 623.3.2 Section Review 64

3.4 Defining Data 643.4.1 Intrinsic Data Types 643.4.2 Data Definition Statement 643.4.3 Defining BYTE and SBYTE Data 66

Page 7: Assembly Language for Intel -Based Computersapi.ning.com/.../Assemblylanguageforintelbasedcomputers.pdf7.4.1 MUL Instruction 204 7.4.2 IMUL Instruction 205 7.4.3 Benchmarking Multiplication

Contents vii

3.4.4 Defining WORD and SWORD Data 673.4.5 Defining DWORD and SDWORD Data 683.4.6 Defining QWORD Data 693.4.7 Defining TBYTE Data 693.4.8 Defining Real Number Data 693.4.9 Little Endian Order 693.4.10 Adding Variables to the AddSub Program 703.4.11 Declaring Uninitialized Data 713.4.12 Section Review 71

3.5 Symbolic Constants 723.5.1 Equal-Sign Directive 723.5.2 Calculating the Sizes of Arrays and Strings 733.5.3 EQU Directive 743.5.4 TEXTEQU Directive 743.5.5 Section Review 75

3.6 Real-Address Mode Programming (Optional) 753.6.1 Basic Changes 75

3.7 Chapter Summary 76

3.8 Programming Exercises 77

4 Data Transfers, Addressing,and Arithmetic 794.1 Data Transfer Instructions 79

4.1.1 Introduction 794.1.2 Operand Types 804.1.3 Direct Memory Operands 804.1.4 MOV Instruction 814.1.5 Zero/Sign Extension of Integers 824.1.6 LAHF and SAHF Instructions 844.1.7 XCHG Instruction 844.1.8 Direct-Offset Operands 844.1.9 Example Program (Moves) 854.1.10 Section Review 86

4.2 Addition and Subtraction 874.2.1 INC and DEC Instructions 874.2.2 ADD Instruction 874.2.3 SUB Instruction 884.2.4 NEG Instruction 884.2.5 Implementing Arithmetic Expressions 894.2.6 Flags Affected by Addition and Subtraction 894.2.7 Example Program (AddSub3) 924.2.8 Section Review 93

Page 8: Assembly Language for Intel -Based Computersapi.ning.com/.../Assemblylanguageforintelbasedcomputers.pdf7.4.1 MUL Instruction 204 7.4.2 IMUL Instruction 205 7.4.3 Benchmarking Multiplication

viii Contents

4.3 Data-Related Operators and Directives 944.3.1 OFFSET Operator 944.3.2 ALIGN Directive 954.3.3 PTR Operator 954.3.4 TYPE Operator 964.3.5 LENGTHOF Operator 974.3.6 SIZEOF Operator 974.3.7 LABEL Directive 974.3.8 Section Review 98

4.4 Indirect Addressing 994.4.1 Indirect Operands 994.4.2 Arrays 1004.4.3 Indexed Operands 1014.4.4 Pointers 1024.4.5 Section Review 103

4.5 JMP and LOOP Instructions 1044.5.1 JMP Instruction 1044.5.2 LOOP Instruction 1054.5.3 Summing an Integer Array 1064.5.4 Copying a String 1064.5.5 Section Review 107

4.6 Chapter Summary 108

4.7 Programming Exercises 109

5 Procedures 1115.1 Introduction 111

5.2 Linking to an External Library 1115.2.1 Background Information 1125.2.2 Section Review 112

5.3 The Book’s Link Library 1135.3.1 Overview 1135.3.2 Individual Procedure Descriptions 1155.3.3 Library Test Programs 1255.3.4 Section Review 129

5.4 Stack Operations 1295.4.1 Runtime Stack 1295.4.2 PUSH and POP Instructions 1315.4.3 Section Review 134

5.5 Defining and Using Procedures 1345.5.1 PROC Directive 1345.5.2 CALL and RET Instructions 136

Page 9: Assembly Language for Intel -Based Computersapi.ning.com/.../Assemblylanguageforintelbasedcomputers.pdf7.4.1 MUL Instruction 204 7.4.2 IMUL Instruction 205 7.4.3 Benchmarking Multiplication

Contents ix

5.5.3 Example: Summing an Integer Array 1395.5.4 Flowcharts 1405.5.5 Saving and Restoring Registers 1405.5.6 Section Review 142

5.6 Program Design Using Procedures 1435.6.1 Integer Summation Program (Design) 1435.6.2 Integer Summation Implementation 1455.6.3 Section Review 147

5.7 Chapter Summary 147

5.8 Programming Exercises 148

6 Conditional Processing 1506.1 Introduction 150

6.2 Boolean and Comparison Instructions 1516.2.1 The CPU Flags 1516.2.2 AND Instruction 1526.2.3 OR Instruction 1536.2.4 XOR Instruction 1546.2.5 NOT Instruction 1556.2.6 TEST Instruction 1556.2.7 CMP Instruction 1566.2.8 Setting and Clearing Individual CPU Flags 1576.2.9 Section Review 157

6.3 Conditional Jumps 1586.3.1 Conditional Structures 1586.3.2 Jcond Instruction 1586.3.3 Types of Conditional Jump Instructions 1596.3.4 Conditional Jump Applications 1636.3.5 Bit Testing Instructions (Optional) 1676.3.6 Section Review 168

6.4 Conditional Loop Instructions 1696.4.1 LOOPZ and LOOPE Instructions 1696.4.2 LOOPNZ and LOOPNE Instructions 1696.4.3 Section Review 170

6.5 Conditional Structures 1706.5.1 Block-Structured IF Statements 1706.5.2 Compound Expressions 1736.5.3 WHILE Loops 1746.5.4 Table-Driven Selection 1776.5.5 Section Review 178

6.6 Application: Finite-State Machines 1796.6.1 Validating an Input String 180

Page 10: Assembly Language for Intel -Based Computersapi.ning.com/.../Assemblylanguageforintelbasedcomputers.pdf7.4.1 MUL Instruction 204 7.4.2 IMUL Instruction 205 7.4.3 Benchmarking Multiplication

x Contents

6.6.2 Validating a Signed Integer 1806.6.3 Section Review 183

6.7 Decision Directives 1846.7.1 Signed and Unsigned Comparisons 1856.7.2 Compound Expressions 1866.7.3 .REPEAT and .WHILE Directives 188

6.8 Chapter Summary 189

6.9 Programming Exercises 190

7 Integer Arithmetic 1937.1 Introduction 193

7.2 Shift and Rotate Instructions 1947.2.1 Logical Shifts and Arithmetic Shifts 1947.2.2 SHL Instruction 1957.2.3 SHR Instruction 1967.2.4 SAL and SAR Instructions 1967.2.5 ROL Instruction 1977.2.6 ROR Instruction 1987.2.7 RCL and RCR Instructions 1987.2.8 Signed Overflow 1997.2.9 SHLD/SHRD Instructions 1997.2.10 Section Review 200

7.3 Shift and Rotate Applications 2017.3.1 Shifting Multiple Doublewords 2017.3.2 Binary Multiplication 2027.3.3 Displaying Binary Bits 2027.3.4 Isolating MS-DOS File Date Fields 2037.3.5 Section Review 203

7.4 Multiplication and Division Operations 2047.4.1 MUL Instruction 2047.4.2 IMUL Instruction 2057.4.3 Benchmarking Multiplication Operations 2077.4.4 DIV Instruction 2087.4.5 Signed Integer Division 2097.4.6 Implementing Arithmetic Expressions 2117.4.7 Section Review 212

7.5 Extended Addition and Subtraction 2137.5.1 ADC Instruction 2137.5.2 Extended Addition Example 2137.5.3 SBB Instruction 2147.5.4 Section Review 215

Page 11: Assembly Language for Intel -Based Computersapi.ning.com/.../Assemblylanguageforintelbasedcomputers.pdf7.4.1 MUL Instruction 204 7.4.2 IMUL Instruction 205 7.4.3 Benchmarking Multiplication

Contents xi

7.6 ASCII and Unpacked Decimal Arithmetic 2157.6.1 AAA Instruction 2167.6.2 AAS Instruction 2187.6.3 AAM Instruction 2187.6.4 AAD Instruction 2187.6.5 Section Review 219

7.7 Packed Decimal Arithmetic 2197.7.1 DAA Instruction 2197.7.2 DAS Instruction 2207.7.3 Section Review 220

7.8 Chapter Summary 221

7.9 Programming Exercises 222

8 Advanced Procedures 2248.1 Introduction 224

8.2 Stack Frames 2258.2.1 Stack Parameters 2258.2.2 Local Variables 2338.2.3 ENTER and LEAVE Instructions 2368.2.4 LOCAL Directive 2378.2.5 WriteStackFrame Procedure 2408.2.6 Section Review 241

8.3 Recursion 2428.3.1 Recursively Calculating a Sum 2438.3.2 Calculating a Factorial 2438.3.3 Section Review 245

8.4 .MODEL Directive 2468.4.1 Language Specifiers 2478.4.2 Section Review 248

8.5 INVOKE, ADDR, PROC, and PROTO (Optional) 2488.5.1 INVOKE Directive 2488.5.2 ADDR Operator 2498.5.3 PROC Directive 2508.5.4 PROTO Directive 2538.5.5 Parameter Classifications 2558.5.6 Example: Exchanging Two Integers 2568.5.7 Debugging Tips 2568.5.8 Section Review 257

8.6 Creating Multimodule Programs 2588.6.1 Hiding and Exporting Procedure Names 2588.6.2 Calling External Procedures 258

Page 12: Assembly Language for Intel -Based Computersapi.ning.com/.../Assemblylanguageforintelbasedcomputers.pdf7.4.1 MUL Instruction 204 7.4.2 IMUL Instruction 205 7.4.3 Benchmarking Multiplication

xii Contents

8.6.3 Using Variables and Symbols Across Module Boundaries 2598.6.4 Example: ArraySum Program 2608.6.5 Creating the Modules Using Extern 2618.6.6 Creating the Modules Using INVOKE and PROTO 2648.6.7 Section Review 266

8.7 Chapter Summary 267

8.8 Programming Exercises 268

9 Strings and Arrays 2699.1 Introduction 269

9.2 String Primitive Instructions 2709.2.1 MOVSB, MOVSW, and MOVSD 2719.2.2 CMPSB, CMPSW, and CMPSD 2729.2.3 SCASB, SCASW, and SCASD 2749.2.4 STOSB, STOSW, and STOSD 2749.2.5 LODSB, LODSW, and LODSD 2759.2.6 Section Review 275

9.3 Selected String Procedures 2769.3.1 Str_compare Procedure 2769.3.2 Str_length Procedure 2779.3.3 Str_copy Procedure 2789.3.4 Str_trim Procedure 2789.3.5 Str_ucase Procedure 2799.3.6 String Library Demo Program 2809.3.7 Section Review 282

9.4 Two-Dimensional Arrays 2829.4.1 Ordering of Rows and Columns 2829.4.2 Base-Index Operands 2839.4.3 Base-Index-Displacement Operands 2859.4.4 Section Review 285

9.5 Searching and Sorting Integer Arrays 2859.5.1 Bubble Sort 2869.5.2 Binary Search 2879.5.3 Section Review 293

9.6 Chapter Summary 294

9.7 Programming Exercises 295

10 Structures and Macros 29910.1 Structures 299

10.1.1 Defining Structures 300

Page 13: Assembly Language for Intel -Based Computersapi.ning.com/.../Assemblylanguageforintelbasedcomputers.pdf7.4.1 MUL Instruction 204 7.4.2 IMUL Instruction 205 7.4.3 Benchmarking Multiplication

Contents xiii

10.1.2 Declaring Structure Variables 30110.1.3 Referencing Structure Variables 30210.1.4 Example: Displaying the System Time 30510.1.5 Structures Containing Structures 30710.1.6 Example: Drunkard’s Walk 30710.1.7 Declaring and Using Unions 31010.1.8 Section Review 312

10.2 Macros 31310.2.1 Overview 31310.2.2 Defining Macros 31310.2.3 Invoking Macros 31410.2.4 Additional Macro Features 31510.2.5 Using the Book’s Macro Library 31810.2.6 Example Program: Wrappers 32410.2.7 Section Review 325

10.3 Conditional-Assembly Directives 32610.3.1 Checking for Missing Arguments 32610.3.2 Default Argument Initializers 32810.3.3 Boolean Expressions 32810.3.4 IF, ELSE, and ENDIF Directives 32810.3.5 The IFIDN and IFIDNI Directives 32910.3.6 Example: Summing a Matrix Row 33010.3.7 Special Operators 33310.3.8 Macro Functions 33610.3.9 Section Review 337

10.4 Defining Repeat Blocks 33810.4.1 WHILE Directive 33810.4.2 REPEAT Directive 33810.4.3 FOR Directive 33910.4.4 FORC Directive 34010.4.5 Example: Linked List 34010.4.6 Section Review 342

10.5 Chapter Summary 342

10.6 Programming Exercises 343

11 MS-Windows Programming 34611.1 Win32 Console Programming 346

11.1.1 Background Information 34711.1.2 Win32 Console Functions 35011.1.3 Displaying a Message Box 35211.1.4 Console Input 35411.1.5 Console Output 36011.1.6 Reading and Writing Files 361

Page 14: Assembly Language for Intel -Based Computersapi.ning.com/.../Assemblylanguageforintelbasedcomputers.pdf7.4.1 MUL Instruction 204 7.4.2 IMUL Instruction 205 7.4.3 Benchmarking Multiplication

xiv Contents

11.1.7 File I/O in the Irvine32 Library 36511.1.8 Testing the File I/O Procedures 36711.1.9 Console Window Manipulation 37011.1.10 Controlling the Cursor 37311.1.11 Controlling the Text Color 37311.1.12 Time and Date Functions 37511.1.13 Section Review 379

11.2 Writing a Graphical Windows Application 37911.2.1 Necessary Structures 38011.2.2 The MessageBox Function 38111.2.3 The WinMain Procedure 38211.2.4 The WinProc Procedure 38211.2.5 The ErrorHandler Procedure 38311.2.6 Program Listing 38311.2.7 Section Review 386

11.3 Dynamic Memory Allocation 38711.3.1 HeapTest Programs 39011.3.2 Section Review 393

11.4 IA-32 Memory Management 39311.4.1 Linear Addresses 39411.4.2 Page Translation 39711.4.3 Section Review 398

11.5 Chapter Summary 399

11.6 Programming Exercises 400

12 High-Level Language Interface 40212.1 Introduction 402

12.1.1 General Conventions 40212.1.2 Section Review 403

12.2 Inline Assembly Code 40412.2.1 __asm Directive in Microsoft Visual C++ 40412.2.2 File Encryption Example 40612.2.3 Section Review 409

12.3 Linking to C/C++ in Protected Mode 40912.3.1 Using Assembly Language to Optimize C++ Code 41012.3.2 Calling C and C++ Functions 41512.3.3 Multiplication Table Example 41612.3.4 Calling C Library Functions 41912.3.5 Directory Listing Program 42212.3.6 Section Review 423

12.4 Linking to C/C++ in Real-Address Mode 42312.4.1 Linking to Borland C++ 424

Page 15: Assembly Language for Intel -Based Computersapi.ning.com/.../Assemblylanguageforintelbasedcomputers.pdf7.4.1 MUL Instruction 204 7.4.2 IMUL Instruction 205 7.4.3 Benchmarking Multiplication

Contents xv

12.4.2 ReadSector Example 42512.4.3 Example: Large Random Integers 42812.4.4 Section Review 430

12.5 Chapter Summary 430

12.6 Programming Exercises 431

13 16-Bit MS-DOS Programming 43213.1 MS-DOS and the IBM-PC 432

13.1.1 Memory Organization 43313.1.2 Redirecting Input-Output 43413.1.3 Software Interrupts 43513.1.4 INT Instruction 43513.1.5 Coding for 16-Bit Programs 43613.1.6 Section Review 437

13.2 MS-DOS Function Calls (INT 21h) 43813.2.1 Selected Output Functions 43913.2.2 Hello World Program Example 44113.2.3 Selected Input Functions 44213.2.4 Date/Time Functions 44613.2.5 Section Review 449

13.3 Standard MS-DOS File I/O Services 44913.3.1 Create or Open File (716Ch) 45113.3.2 Close File Handle (3Eh) 45213.3.3 Move File Pointer (42h) 45213.3.4 Get File Creation Date and Time 45313.3.5 Selected Library Procedures 45313.3.6 Example: Read and Copy a Text File 45413.3.7 Reading the MS-DOS Command Tail 45613.3.8 Example: Creating a Binary File 45813.3.9 Section Review 461

13.4 Chapter Summary 461

13.5 Chapter Exercises 463

14 Disk Fundamentals 46414.1 Disk Storage Systems 464

14.1.1 Tracks, Cylinders, and Sectors 46514.1.2 Disk Partitions (Volumes) 46614.1.3 Section Review 468

14.2 File Systems 46814.2.1 FAT12 469

Page 16: Assembly Language for Intel -Based Computersapi.ning.com/.../Assemblylanguageforintelbasedcomputers.pdf7.4.1 MUL Instruction 204 7.4.2 IMUL Instruction 205 7.4.3 Benchmarking Multiplication

xvi Contents

14.2.2 FAT16 46914.2.3 FAT32 46914.2.4 NTFS 47014.2.5 Primary Disk Areas 47014.2.6 Section Review 471

14.3 Disk Directory 47214.3.1 MS-DOS Directory Structure 47314.3.2 Long Filenames in MS-Windows 47514.3.3 File Allocation Table (FAT) 47614.3.4 Section Review 477

14.4 Reading and Writing Disk Sectors (7305h) 47714.4.1 Sector Display Program 47814.4.2 Section Review 482

14.5 System-Level File Functions 48214.5.1 Get Disk Free Space (7303h) 48314.5.2 Create Subdirectory (39h) 48514.5.3 Remove Subdirectory (3Ah) 48614.5.4 Set Current Directory (3Bh) 48614.5.5 Get Current Directory (47h) 48614.5.6 Get and Set File Attributes (7143h) 48614.5.7 Section Review 487

14.6 Chapter Summary 487

14.7 Programming Exercises 488

15 BIOS-Level Programming 49015.1 Introduction 490

15.1.1 BIOS Data Area 491

15.2 Keyboard Input with INT 16h 49215.2.1 How the Keyboard Works 49215.2.2 INT 16h Functions 49315.2.3 Section Review 497

15.3 VIDEO Programming with INT 10h 49815.3.1 Basic Background 49815.3.2 Controlling the Color 49915.3.3 INT 10h Video Functions 50115.3.4 Library Procedure Examples 51115.3.5 Section Review 512

15.4 Drawing Graphics Using INT 10h 51215.4.1 INT 10h Pixel-Related Functions 51315.4.2 DrawLine Program 514

Page 17: Assembly Language for Intel -Based Computersapi.ning.com/.../Assemblylanguageforintelbasedcomputers.pdf7.4.1 MUL Instruction 204 7.4.2 IMUL Instruction 205 7.4.3 Benchmarking Multiplication

Contents xvii

15.4.3 Cartesian Coordinates Program 51515.4.4 Converting Cartesian Coordinates to Screen Coordinates 51715.4.5 Section Review 518

15.5 Memory-Mapped Graphics 51915.5.1 Mode 13h: 320 � 200, 256 Colors 51915.5.2 Memory-Mapped Graphics Program 52015.5.3 Section Review 523

15.6 Mouse Programming 52315.6.1 Mouse INT 33h Functions 52315.6.2 Mouse Tracking Program 52815.6.3 Section Review 532

15.7 Chapter Summary 533

15.8 Chapter Exercises 534

16 Expert MS-DOS Programming 53616.1 Introduction 536

16.2 Defining Segments 53716.2.1 Simplified Segment Directives 53716.2.2 Explicit Segment Definitions 53816.2.3 Segment Overrides 54216.2.4 Combining Segments 54216.2.5 Section Review 543

16.3 Runtime Program Structure 54416.3.1 Program Segment Prefix 54416.3.2 COM Programs 54516.3.3 EXE Programs 54616.3.4 Section Review 547

16.4 Interrupt Handling 54816.4.1 Hardware Interrupts 54916.4.2 Interrupt Control Instructions 55016.4.3 Writing a Custom Interrupt Handler 55116.4.4 Terminate and Stay Resident Programs 55316.4.5 Application: The No_Reset Program 55416.4.6 Section Review 557

16.5 Hardware Control Using I/O Ports 55816.5.1 Input-Output Ports 55816.5.2 PC Sound Program 558

16.6 Chapter Summary 560

Page 18: Assembly Language for Intel -Based Computersapi.ning.com/.../Assemblylanguageforintelbasedcomputers.pdf7.4.1 MUL Instruction 204 7.4.2 IMUL Instruction 205 7.4.3 Benchmarking Multiplication

xviii Contents

17 Floating-Point Processing and Instruction Encoding 562

17.1 Floating-Point Binary Representation 56217.1.1 IEEE Binary Floating-Point Representation 56317.1.2 The Exponent 56417.1.3 Normalized Binary Floating-Point Numbers 56517.1.4 Creating the IEEE Representation 56517.1.5 Converting Decimal Fractions to Binary Reals 56717.1.6 Section Review 568

17.2 Floating-Point Unit 56917.2.1 FPU Register Stack 56917.2.2 Rounding 57117.2.3 Floating-Point Exceptions 57317.2.4 Floating-Point Instruction Set 57317.2.5 Arithmetic Instructions 57617.2.6 Comparing Floating-Point Values 57917.2.7 Reading and Writing Floating-Point Values 58217.2.8 Exception Synchronization 58317.2.9 Code Examples 58417.2.10 Mixed-Mode Arithmetic 58517.2.11 Masking and Unmasking Exceptions 58617.2.12 Section Review 587

17.3 Intel Instruction Encoding 58817.3.1 IA-32 Instruction Format 58817.3.2 Single-Byte Instructions 58917.3.3 Move Immediate to Register 59017.3.4 Register-Mode Instructions 59117.3.5 IA-32 Processor Operand-Size Prefix 59117.3.6 Memory-Mode Instructions 59217.3.7 Section Review 595

17.4 Chapter Summary 596

17.5 Programming Exercises 597

Appendix A MASM Reference 600

Appendix B The IA-32 Instruction Set 619

Appendix C BIOS and MS-DOS Interrupts 650

Appendix D Answers to Review Questions 659

Index 705

Page 19: Assembly Language for Intel -Based Computersapi.ning.com/.../Assemblylanguageforintelbasedcomputers.pdf7.4.1 MUL Instruction 204 7.4.2 IMUL Instruction 205 7.4.3 Benchmarking Multiplication

xix

Preface

Assembly Language for Intel-Based Computers, Fifth Edition, teaches assembly language program-ming and architecture for Intel IA-32 processors. It is an appropriate text for the following types ofcollege courses:

• Assembly Language Programming• Fundamentals of Computer Systems• Fundamentals of Computer Architecture

Students use Intel or AMD processors and program with Microsoft Macro Assembler (MASM)

8.0, running on any of the following MS-Windows platforms: Windows 95, 98, Millenium, NT, 2000,and XP.

Although this book was originally designed as a programming textbook for college students, it hasevolved over the last 15 years into much more. Many universities use the book for their introductorycomputer architecture courses. As a testament to its popularity, the fourth edition was translated intoKorean, Chinese, French, Russian, and Polish.

Emphasis of Topics This edition includes topics that lead naturally into subsequent courses incomputer architecture, operating systems, and compiler writing:

• Virtual machine concept• Elementary boolean operations• Instruction execution cycle• Memory access and handshaking• Interrupts and polling• Pipelining and superscalar concepts• Hardware-based I/O• Floating-point binary representation

Other topics relate specifically to Intel IA-32 architecture:

• IA-32 protected memory and paging• Memory segmentation in real-address mode• 16-bit interrupt handling• MS-DOS and BIOS system calls (interrupts)• IA-32 Floating-Point Unit architecture and programming• IA-32 Instruction encoding

Certain examples presented in the book lend themselves to courses that occur later in a computerscience curriculum:

• Searching and sorting algorithms• High-level language structures• Finite-state machines• Code optimization examples

Page 20: Assembly Language for Intel -Based Computersapi.ning.com/.../Assemblylanguageforintelbasedcomputers.pdf7.4.1 MUL Instruction 204 7.4.2 IMUL Instruction 205 7.4.3 Benchmarking Multiplication

xx Preface

Improvements in the Fifth Edition A number of improvements and new information have beenadded in this edition, listed in the following table by chapter number:

Still a Programming Book This book is still focused on its original mission: to teach students howto write and debug programs at the machine level. It will never replace a complete book on computerarchitecture, but it does give students the first-hand experience of writing software in an environmentthat teaches them how a computer works. Our premise is that students retain knowledge better whentheory is combined with experience. In an engineering course, students construct prototypes; in acomputer architecture course, students should write machine-level programs. In both cases, they have amemorable experience that gives them the confidence to work in any OS/machine-oriented environment.

Real Mode and Protected Mode This edition emphasizes 32-bit protected mode, but it still hasthree chapters devoted to real-mode programming. For example, there is an entire chapter on BIOSprogramming for the keyboard, video display (including graphics), and mouse. Another chapter cov-ers MS-DOS programming using interrupts (system calls). Students can benefit from programmingdirectly to hardware and the BIOS.

The examples in the first half of the book are nearly all presented as 32-bit text-oriented applicationsrunning in protected mode using the flat memory model. This approach is wonderfully simple because itavoids the complications of segment-offset addressing. Specially marked paragraphs and popup boxespoint out occasional differences between protected mode and real mode programming. Most differencesare abstracted by the book’s parallel link libraries for real mode and protected mode programming.

Link Libraries We supply two versions of the link library that students use for basic input-output,simulations, timing, and other useful stuff. The 32-bit version (Irvine32.lib) runs in protected mode,sending its output to the Win32 console. The 16-bit version (Irvine16.lib) runs in real-address mode.Full source code for the libraries is supplied on the book’s Web site. The link libraries are availableonly for convenience, not to prevent students from learning how to program input-output themselves.Students are encouraged to create their own libraries.

Chapter Improvements

2 Improved explanation of the instruction execution cycle.

5 An expanded link library with additional subroutines to write rich user interfaces, calculate programtimings, generate pseudorandom integers, and parse integer strings. The documentation of the libraryhas greatly improved.

6 Improved explanation of conditional jump encoding and relative jump ranges.

7 Two-operand and three-operand IMUL instructions are added. Performance comparisons are shownfor differing approaches to integer multiplication.

8 Completely redesigned so that low-level details of stack frames (activation records) are explained firstbefore introducing MASM’s high-level INVOKE and PROC directives.

10 Improved documentation of the book’s macro library.

11 New topic: Dynamic memory allocation in MS-Windows applications. Improved coverage of filehandling and error reporting in MS-Windows applications.

12 Improved coverage of calling C and C++ functions from assembly language.

17 Introduction to the IA-32 floating-point instruction set. Floating-point data types. IA-32 Instructionencoding and decoding.

Page 21: Assembly Language for Intel -Based Computersapi.ning.com/.../Assemblylanguageforintelbasedcomputers.pdf7.4.1 MUL Instruction 204 7.4.2 IMUL Instruction 205 7.4.3 Benchmarking Multiplication

Preface xxi

Included Software and Examples All the example programs were tested with Microsoft MacroAssembler Version 8.0. The 32-bit C++ applications in Chapter 12 were tested with Microsoft VisualC++ .NET. The real-address mode programs in Chapter 12 (linking to C++) were assembled withBorland Turbo Assembler (TASM).

Web Site Information Updates and corrections to this book may be found at the book’s Web site,http://www.asmirvine.com, including additional programming projects for instructors to assignat the ends of chapters. If for some reason you cannot access this site, information about the book anda link to its current Web site can be found at www.prenhall.com by searching for the book title or forthe author name “Kip Irvine.”

Overall Goals

The following goals of this book are designed to broaden the student’s interest and knowledge in top-ics related to assembly language:

• Intel IA-32 processor architecture and programming• Real-address mode and protected mode programming• Assembly language directives, macros, operators, and program structure• Programming methodology, showing how to use assembly language to create system-level soft-

ware tools and application programs• Computer hardware manipulation• Interaction between assembly language programs, the operating system, and other application programs

One of our goals is to help students approach programming problems with a machine-level mindset. It is important to think of the CPU as an interactive tool, and to learn to monitor its operation asdirectly as possible. A debugger is a programmer’s best friend, not only for catching errors, but as aneducational tool that teaches about the CPU and operating system. We encourage students to lookbeneath the surface of high-level languages and to realize that most programming languages aredesigned to be portable and, therefore, independent of their host machines.

In addition to the short examples, this book contains hundreds of ready-to-run programs that dem-onstrate instructions or ideas as they are presented in the text. Reference materials, such as guides toMS-DOS interrupts and instruction mnemonics, are available at the end of the book.

Required Background The reader should already be able to program confidently in at least oneother programming language, preferably Java, C, or C++. One chapter covers C++ interfacing, so it isvery helpful to have a compiler on hand. I have used this book in the classroom with majors in bothcomputer science and management information systems, and it has been used elsewhere in engineer-ing courses.

Features

Complete Program Listings A companion CD-ROM contains all the source code from the exam-ples in this book. Additional listings are available on the book’s Web page. An extensive link library issupplied with the book, containing more than 30 procedures that simplify user input-output, numericprocessing, disk and file handling, and string handling. In the beginning stages of the course, studentscan use this library to enhance their programs. Later, they can create their own procedures and addthem to the library.

Programming Logic Two chapters emphasize boolean logic and bit-level manipulation. A con-scious attempt is made to relate high-level programming logic to the low-level details of the machine.This approach helps students to create more efficient implementations and to better understand howcompilers generate object code.

Page 22: Assembly Language for Intel -Based Computersapi.ning.com/.../Assemblylanguageforintelbasedcomputers.pdf7.4.1 MUL Instruction 204 7.4.2 IMUL Instruction 205 7.4.3 Benchmarking Multiplication

xxii Preface

Hardware and Operating System Concepts The first two chapters introduce basic hardwareand data representation concepts, including binary numbers, CPU architecture, status flags, and memorymapping. A survey of the computer’s hardware and a historical perspective of the Intel processor familyhelps students to better understand their target computer system.

Structured Programming Approach Beginning with Chapter 5, procedures and functional decom-position are emphasized. Students are given more complex programming exercises, requiring them tofocus on design before starting to write code.

Disk Storage Concepts Students learn the fundamental principles behind the disk storage systemon MS-Windows–based systems from hardware and software points of view.

Creating Link Libraries Students are free to add their own procedures to the book’s link libraryand create new libraries. They learn to use a toolbox approach to programming and to write code thatis useful in more than one program.

Macros and Structures A chapter is devoted to creating structures, unions, and macros, which areesential in assembly language and systems programming. Conditional macros with advanced opera-tors serve to make the macros more professional.

Interfacing to High-Level Languages A chapter is devoted to interfacing assembly language to Cand C++. This is an important job skill for students who are likely to find jobs programming in high-levellanguages. They can learn to optimize their code and see examples of how C++ compilers optimize code.

Instructional Aids All the program listings are available on disk and on the Web. Instructors are pro-vided a test bank, answers to review questions, solutions to programming exercises, and a MicrosoftPowerPoint slide presentation for each chapter.

Summary of Chapters

Chapters 1 to 8 contain a basic foundation of assembly language and should be covered in sequence.After that, you have a fair amount of freedom. The following chapter dependency graph shows howlater chapters depend on knowledge gained from other chapters. Chapter 10 was split into two partsfor this graph because no other chapter depends on one’s knowing how to create macros:

1. Basic Concepts: Applications of assembly language, basic concepts, machine language, and datarepresentation.

2. IA-32 Processor Architecture: Basic microcomputer design, instruction execution cycle, IA-32processor architecture, IA-32 memory management, components of a microcomputer, and theinput-output system.

3. Assembly Language Fundamentals: Introduction to assembly language, linking and debugging,and defining constants and variables.

111 through 8 9

13 14

15

16

17

10(structs)

1210(macros)

Page 23: Assembly Language for Intel -Based Computersapi.ning.com/.../Assemblylanguageforintelbasedcomputers.pdf7.4.1 MUL Instruction 204 7.4.2 IMUL Instruction 205 7.4.3 Benchmarking Multiplication

Preface xxiii

4. Data Transfers, Addressing, and Arithmetic: Simple data transfer and arithmetic instructions,assemble-link-execute cycle, operators, directives, expressions, JMP and LOOP instructions, andindirect addressing.

5. Procedures: Linking to an external library, description of the book’s link library, stack opera-tions, defining and using procedures, flowcharts, and top-down structured design.

6. Conditional Processing: Boolean and comparison instructions, conditional jumps and loops,high-level logic structures, and finite state machines.

7. Integer Arithmetic: Shift and rotate instructions with useful applications, multiplication anddivision, extended addition and subtraction, and ASCII and packed decimal arithmetic.

8. Advanced Procedures: Stack parameters, local variables, advanced PROC and INVOKE direc-tives, and recursion.

9. Strings and Arrays: String primitives, manipulating arrays of characters and integers, two-dimensional arrays, sorting, and searching.

10. Structures and Macros: Structures, macros, conditional assembly directives, and defining repeat blocks.11. MS-Windows Programming: Protected mode memory management concepts, using the Microsoft

Windows API to display text and colors, and dynamic memory allocation. 12. High-Level Language Interface: Parameter passing conventions, inline assembly code, and linking

assembly language modules to C and C++ programs.13. 16-Bit MS-DOS Programming: Calling MS-DOS interrupts for console and file input-output.14. Disk Fundamentals: Disk storage systems, sectors, clusters, directories, file allocation tables, handling

MS-DOS error codes, and drive and directory manipulation.15. BIOS-Level Programming: Keyboard input, video text, graphics, and mouse programming.16. Expert MS-DOS Programming: Custom-designed segments, runtime program structure, and

Interrupt handling. Hardware control using I/O ports.17. Floating-Point Processing and Instruction Encoding: Floating-point binary representation and

floating-point arithmetic. Learning to program the IA-32 Floating-Point Unit. Understanding theencoding of IA-32 machine instructions.

Appendix A: MASM ReferenceAppendix B: The IA-32 Instruction SetAppendix C: BIOS and MS-DOS InterruptsAppendix D: Answers to Review Questions

Reference Materials

Web Site The author maintains an active Web site at www.asmirvine.com.

Help File Help file (in Windows Help Format) by Gerald Cahill of Antelope Valley College. Docu-ments the book’s link libraries, as well as Win32 data structures.

Assembly Language Workbook An interactive workbook is included on the book’s Web site, cover-ing such important topics as number conversions, addressing modes, register usage, Debug program-ming, and floating-point binary numbers. The content pages are HTML documents, making it easyfor students and instructors to add their own customized content. This workbook is also available onthe book’s Web site.

Debugging Tools Tutorials on using Microsoft CodeView, Microsoft Visual Studio, and MicrosoftWindows Debugger (WinDbg).

BIOS and MS-DOS Interrupts Appendix C contains a brief listing of the most-often-used INT 10h(video), INT 16h (keyboard), and INT 21h (MS-DOS) functions.

Instruction Set Appendix B lists most nonprivileged instructions for the IA-32 processor family.

Page 24: Assembly Language for Intel -Based Computersapi.ning.com/.../Assemblylanguageforintelbasedcomputers.pdf7.4.1 MUL Instruction 204 7.4.2 IMUL Instruction 205 7.4.3 Benchmarking Multiplication

xxiv Preface

For each instruction, we describe its effect, show its syntax, and show which flags are affected.

PowerPoint Presentations A complete set of Microsoft PowerPoint presentations written by the author.

Acknowledgments

Special thanks are due to Tracy Dunkleberger, Executive Editor for Computer Science at PrenticeHall, who provided friendly, helpful guidance during the writing of the fifth edition. Karen Ettingerdid a terrific job as production editor, constantly keeping track of numerous minute details. CamilleTrentacoste was the book’s managing editor.

Fifth Edition

I offer my special thanks and gratitude to the following professors who boosted my morale, gave megreat pedagogical tips, and tirelessly examined the entire book. They have been a huge influence onthe development of this book, in some cases across multiple editions:

• Gerald Cahill, Antelope Valley College• James Brink, Pacific Lutheran University• William Barrett, San Jose State University

Many thanks to Scott Blackledge and John Taylor, both professional programmers, who proofreadmost of the manuscript and flagged numerous errors. Several people reviewed individual chapters:

• Jerry Joyce, Keene State College• Tianzheng Wu, Mount Mercy College• Ron Davis, Kennedy-King College• David Topham, Ohlone College• Harvey Nice, DePaul University

Fourth Edition

The following people were tremendously helpful in creating the fourth edition:

• Gerald Cahill, Antelope Valley College• James Brink, Pacific Lutheran University• Maria Kolatis, County College of Morris• Tom Joyce, Chief Engineer at Premier Heart, LLC• Jeff Wothke, Purdue Calumet University• Tim Downey, Florida International University

The following individuals provided valuable proofreading help in the fourth edition:

• Andres Altamirano, Miami• Courtney Amor, Los Angeles• Scott Blackledge, Platform Solutions, Inc.• Ronald Davis, Kennedy-King College• Ata Elahi, Southern Connecticut State University• Jose Gonzalez, Miami• Leroy Highsmith, Southern Connecticut State University• Sajid Iqbal, Faran Institute of Technology• Charles Jones, Maryville College• Vincent Kayes, Mount St. Mary College• Eric Kobrin, Miami• Pablo Maurin, Miami• Barry Meaker, Design Engineer, Boeing Corporation• Ian Merkel, Miami• Sylvia Miner, Miami

Page 25: Assembly Language for Intel -Based Computersapi.ning.com/.../Assemblylanguageforintelbasedcomputers.pdf7.4.1 MUL Instruction 204 7.4.2 IMUL Instruction 205 7.4.3 Benchmarking Multiplication

Preface xxv

• M. Nawaz, OPSTEC College of Computer Science• Kam Ng, Chinese University of Hong Kong• Hien Nguyen, Miami• Ernie Philipp, Northern Virginia Community College• Boyd Stephens, UGMO Research, LLC• John Taylor, England• Zachary Taylor, Columbia College• Virginia Welsh, Community College of Baltimore County• Robert Workman, Southern Connecticut State University• Tianzheng Wu, Mount Mercy College• Matthew Zukoski, Lehigh University

Page 26: Assembly Language for Intel -Based Computersapi.ning.com/.../Assemblylanguageforintelbasedcomputers.pdf7.4.1 MUL Instruction 204 7.4.2 IMUL Instruction 205 7.4.3 Benchmarking Multiplication