30
Assembly Language Step by Step Programming with Linux ® Jeff Duntemann THIRD EDITION

Jeff Duntemann Assembly Language Step by Stepdownload.e-bookshelf.de/download/0000/5754/73/L-G-0000575473...Assembly Language Step by Step Programming with Linux ® Learn assembly

Embed Size (px)

Citation preview

Page 1: Jeff Duntemann Assembly Language Step by Stepdownload.e-bookshelf.de/download/0000/5754/73/L-G-0000575473...Assembly Language Step by Step Programming with Linux ® Learn assembly

Asse

mb

ly Lang

uag

e Ste

p b

y Step

Prog

ram

ming

with Linux

®

DuntemannLearn assembly language, and you learn the machineIn this third edition of his bestselling guide to Intel x86 assembly language under Linux, Jeff

Duntemann positions assembly not as unapproachable geek arcana but as a fi rst programming

language, suitable for readers who have no previous programming experience. As the fundamental

language of the CPU, assembly lays the groundwork for all other programming languages,

especially native-code C, C++, and Pascal. By mastering assembly, programmers will learn how

x86 computers operate all the way down to “the bare silicon,” at a level of detail that no other

approach can equal.

Assembly Language Step by Step, Third Edition, helps you:

• Review the fundamental concepts behind

computing and programming, including the

hexadecimal and binary number bases

• Understand the evolution of the Intel CPUs and

how modern x86 processors operate

• Grasp the process of programming itself, from

editing source code through assembly, linking,

and debugging

• Comprehend x86 32-bit protected-mode

memory addressing

• Learn the x86 instruction set by dissecting

numerous complete example programs

• Work with the wealth of free programming

utilities under Ubuntu Linux, including the Kate

editor, the NASM assembler, and the GNU toolset

• Master practical details of Linux programming,

including procedures, macros, the INT 80h call

gate, and calls to the standard C libraries

Jeff Duntemann has been writing about computing for over thirty years, and is the author of numerous books on

programming, wireless networking, and system administration. He has been a columnist in Dr. Dobb’s Journal, and has

edited well-known programming publications like PC Techniques and Visual Developer. After hours, he enjoys blogging,

astronomy, amateur radio, and writing science fi ction.

Software Development/General

Visit our Web site at www.wiley.com/compbooks

$65.00 US /$78.00 CAN

Assembly Language Step by StepProgramming with Linux®

Jeff Duntemann

T H I R D E D I T I O N

T H I R D E D I T I O N

Page 2: Jeff Duntemann Assembly Language Step by Stepdownload.e-bookshelf.de/download/0000/5754/73/L-G-0000575473...Assembly Language Step by Step Programming with Linux ® Learn assembly
Page 3: Jeff Duntemann Assembly Language Step by Stepdownload.e-bookshelf.de/download/0000/5754/73/L-G-0000575473...Assembly Language Step by Step Programming with Linux ® Learn assembly

Assembly LanguageStep-by-Step

Page 4: Jeff Duntemann Assembly Language Step by Stepdownload.e-bookshelf.de/download/0000/5754/73/L-G-0000575473...Assembly Language Step by Step Programming with Linux ® Learn assembly
Page 5: Jeff Duntemann Assembly Language Step by Stepdownload.e-bookshelf.de/download/0000/5754/73/L-G-0000575473...Assembly Language Step by Step Programming with Linux ® Learn assembly

Assembly LanguageStep-by-Step

Programming with Linux®

Third Edition

Jeff Duntemann

Wiley Publishing, Inc.

Page 6: Jeff Duntemann Assembly Language Step by Stepdownload.e-bookshelf.de/download/0000/5754/73/L-G-0000575473...Assembly Language Step by Step Programming with Linux ® Learn assembly

Assembly Language Step-by-Step

Published byWiley Publishing, Inc.10475 Crosspoint BoulevardIndianapolis, IN 46256www.wiley.com

Copyright © 2009 by Jeff Duntemann

Published by Wiley Publishing, Inc., Indianapolis, Indiana

Published simultaneously in Canada

ISBN: 978-0-470-49702-9

Manufactured in the United States of America

10 9 8 7 6 5 4 3 2 1

No part of this publication may be reproduced, stored in a retrieval system or transmitted in any form or by any means,electronic, mechanical, photocopying, recording, scanning or otherwise, except as permitted under Sections 107 or 108of the 1976 United States Copyright Act, without either the prior written permission of the Publisher, or authorizationthrough payment of the appropriate per-copy fee to the Copyright Clearance Center, 222 Rosewood Drive, Danvers,MA 01923, (978) 750-8400, fax (978) 646-8600. Requests to the Publisher for permission should be addressed to thePermissions Department, John Wiley & Sons, Inc., 111 River Street, Hoboken, NJ 07030, (201) 748-6011, fax (201) 748-6008,or online at http://www.wiley.com/go/permissions.

Limit of Liability/Disclaimer of Warranty: The publisher and the author make no representations or warranties withrespect to the accuracy or completeness of the contents of this work and specifically disclaim all warranties, includingwithout limitation warranties of fitness for a particular purpose. No warranty may be created or extended by sales orpromotional materials. The advice and strategies contained herein may not be suitable for every situation. This workis sold with the understanding that the publisher is not engaged in rendering legal, accounting, or other professionalservices. If professional assistance is required, the services of a competent professional person should be sought. Neitherthe publisher nor the author shall be liable for damages arising herefrom. The fact that an organization or Web site isreferred to in this work as a citation and/or a potential source of further information does not mean that the author or thepublisher endorses the information the organization or Web site may provide or recommendations it may make. Further,readers should be aware that Internet Web sites listed in this work may have changed or disappeared between when thiswork was written and when it is read.

For general information on our other products and services please contact our Customer Care Department within theUnited States at (877) 762-2974, outside the United States at (317) 572-3993 or fax (317) 572-4002.

Wiley also publishes its books in a variety of electronic formats. Some content that appears in print may not be availablein electronic books.

Library of Congress Control Number: 2009933745

Trademarks: Wiley and the Wiley logo are trademarks or registered trademarks of John Wiley & Sons, Inc. and/or itsaffiliates, in the United States and other countries, and may not be used without written permission. Linux is a registeredtrademark of Linus Torvalds. All other trademarks are the property of their respective owners. Wiley Publishing, Inc. isnot associated with any product or vendor mentioned in this book.

Page 7: Jeff Duntemann Assembly Language Step by Stepdownload.e-bookshelf.de/download/0000/5754/73/L-G-0000575473...Assembly Language Step by Step Programming with Linux ® Learn assembly

To the eternal memory ofKathleen M. Duntemann, Godmother

1920–1999who gave me books when all I could do was put teeth marks on them.

There are no words for how much I owe you!

Page 8: Jeff Duntemann Assembly Language Step by Stepdownload.e-bookshelf.de/download/0000/5754/73/L-G-0000575473...Assembly Language Step by Step Programming with Linux ® Learn assembly
Page 9: Jeff Duntemann Assembly Language Step by Stepdownload.e-bookshelf.de/download/0000/5754/73/L-G-0000575473...Assembly Language Step by Step Programming with Linux ® Learn assembly

About the Author

Jeff Duntemann is a writer, editor, lecturer, and publishing industry analyst. Inhis thirty years in the technology industry he has been a computer programmerand systems analyst for Xerox Corporation, a technical journal editor forZiff-Davis Publications, and Editorial Director for Coriolis Group Books andlater Paraglyph Press. He is currently a technical publishing consultant and alsoowns Copperwood Press, a POD imprint hosted on lulu.com. Jeff lives withhis wife Carol in Colorado Springs, Colorado.

vii

Page 10: Jeff Duntemann Assembly Language Step by Stepdownload.e-bookshelf.de/download/0000/5754/73/L-G-0000575473...Assembly Language Step by Step Programming with Linux ® Learn assembly
Page 11: Jeff Duntemann Assembly Language Step by Stepdownload.e-bookshelf.de/download/0000/5754/73/L-G-0000575473...Assembly Language Step by Step Programming with Linux ® Learn assembly

Credits

Executive EditorCarol Long

Project EditorBrian Herrmann

Production EditorRebecca Anderson

Copy EditorLuann Rouff

Editorial DirectorRobyn B. Siesky

Editorial ManagerMary Beth Wakefield

Production ManagerTim Tate

Vice President and ExecutiveGroup PublisherRichard Swadley

Vice President and ExecutivePublisherBarry Pruett

Associate PublisherJim Minatel

Project Coordinator, CoverLynsey Stanford

ProofreaderDr. Nate Pritts, Word One

IndexerJ&J Indexing

Cover Image© Jupiter Images/Corbis/Lawrence Manning

ix

Page 12: Jeff Duntemann Assembly Language Step by Stepdownload.e-bookshelf.de/download/0000/5754/73/L-G-0000575473...Assembly Language Step by Step Programming with Linux ® Learn assembly
Page 13: Jeff Duntemann Assembly Language Step by Stepdownload.e-bookshelf.de/download/0000/5754/73/L-G-0000575473...Assembly Language Step by Step Programming with Linux ® Learn assembly

Acknowledgments

First of all, thanks are due to Carol Long and Brian Herrmann at Wiley, forallowing this book another shot, and then making sure it happened, on a muchmore aggressive schedule than last time.

As for all three previous editions, I owe Michael Abrash a debt of gratitudefor constant sane advice on many things, especially the arcane differencesbetween modern Intel microarchitectures.

Although they might not realize it, Randy Hyde, Frank Kotler, Beth, andall the rest of the gang on alt.lang.asm were very helpful in several ways, notleast of which was hearing and answering requests from assembly languagenewcomers, thus helping me decide what must be covered in a book like thisand what need not.

Finally, and as always, a toast to Carol for the support and sacramentalfriendship that has enlivened me now for 40 years, and enabled me to take onprojects like this and see them through to the end.

xi

Page 14: Jeff Duntemann Assembly Language Step by Stepdownload.e-bookshelf.de/download/0000/5754/73/L-G-0000575473...Assembly Language Step by Step Programming with Linux ® Learn assembly
Page 15: Jeff Duntemann Assembly Language Step by Stepdownload.e-bookshelf.de/download/0000/5754/73/L-G-0000575473...Assembly Language Step by Step Programming with Linux ® Learn assembly

Contents at a Glance

Introduction: ‘‘Why Would You Want to Do That?’’ xxvii

Chapter 1 Another Pleasant Valley Saturday 1

Chapter 2 Alien Bases 15

Chapter 3 Lifting the Hood 45

Chapter 4 Location, Location, Location 77

Chapter 5 The Right to Assemble 109

Chapter 6 A Place to Stand, with Access to Tools 155

Chapter 7 Following Your Instructions 201

Chapter 8 Our Object All Sublime 237

Chapter 9 Bits, Flags, Branches, and Tables 279

Chapter 10 Dividing and Conquering 327

Chapter 11 Strings and Things 393

Chapter 12 Heading Out to C 439

Conclusion: Not the End, But Only the Beginning 503

Appendix A Partial x86 Instruction Set Reference 507

Appendix B Character Set Charts 583

Index 587

xiii

Page 16: Jeff Duntemann Assembly Language Step by Stepdownload.e-bookshelf.de/download/0000/5754/73/L-G-0000575473...Assembly Language Step by Step Programming with Linux ® Learn assembly
Page 17: Jeff Duntemann Assembly Language Step by Stepdownload.e-bookshelf.de/download/0000/5754/73/L-G-0000575473...Assembly Language Step by Step Programming with Linux ® Learn assembly

Contents

Introduction: ‘‘Why Would You Want to Do That?’’ xxvii

Chapter 1 Another Pleasant Valley Saturday 1It’s All in the Plan 1

Steps and Tests 2More Than Two Ways? 3Computers Think Like Us 4

Had This Been the Real Thing . . . 4Do Not Pass Go 5

The Game of Big Bux 6Playing Big Bux 8

Assembly Language Programming As a Board Game 9Code and Data 10Addresses 11Metaphor Check! 12

Chapter 2 Alien Bases 15The Return of the New Math Monster 15Counting in Martian 16

Dissecting a Martian Number 18The Essence of a Number Base 20

Octal: How the Grinch Stole Eight and Nine 20Who Stole Eight and Nine? 21

Hexadecimal: Solving the Digit Shortage 24From Hex to Decimal and from Decimal to Hex 28

From Hex to Decimal 28From Decimal to Hex 29Practice. Practice! PRACTICE! 31

xv

Page 18: Jeff Duntemann Assembly Language Step by Stepdownload.e-bookshelf.de/download/0000/5754/73/L-G-0000575473...Assembly Language Step by Step Programming with Linux ® Learn assembly

xvi Contents

Arithmetic in Hex 32Columns and Carries 35Subtraction and Borrows 35Borrows across Multiple Columns 37What’s the Point? 38

Binary 38Values in Binary 40Why Binary? 42

Hexadecimal As Shorthand for Binary 43Prepare to Compute 44

Chapter 3 Lifting the Hood 45RAXie, We Hardly Knew Ye . . . 45

Gus to the Rescue 46Switches, Transistors, and Memory 47

One If by Land . . . 48Transistor Switches 48The Incredible Shrinking Bit 50Random Access 52Memory Access Time 53Bytes, Words, Double Words, and Quad Words 54Pretty Chips All in a Row 55

The Shop Foreman and the Assembly Line 57Talking to Memory 58Riding the Data Bus 59The Foreman’s Pockets 60The Assembly Line 61

The Box That Follows a Plan 61Fetch and Execute 63The Foreman’s Innards 64Changing Course 65

What vs. How: Architecture and Microarchitecture 66Evolving Architectures 67The Secret Machinery in the Basement 68

Enter the Plant Manager 70Operating Systems: The Corner Office 70BIOS: Software, Just Not as Soft 71Multitasking Magic 71Promotion to Kernel 73The Core Explosion 73The Plan 74

Page 19: Jeff Duntemann Assembly Language Step by Stepdownload.e-bookshelf.de/download/0000/5754/73/L-G-0000575473...Assembly Language Step by Step Programming with Linux ® Learn assembly

Contents xvii

Chapter 4 Location, Location, Location 77The Joy of Memory Models 77

16 Bits’ll Buy You 64K 79The Nature of a Megabyte 82Backward Compatibility and Virtual 86 Mode 8316-Bit Blinders 83

The Nature of Segments 85A Horizon, Not a Place 88Making 20-Bit Addresses out of 16-Bit Registers 88

16-Bit and 32-Bit Registers 90General-Purpose Registers 91Register Halves 93The Instruction Pointer 95The Flags Register 96

The Three Major Assembly Programming Models 96Real Mode Flat Model 97Real Mode Segmented Model 99Protected Mode Flat Model 101

What Protected Mode Won’t Let Us Do Anymore 104Memory-Mapped Video 104Direct Access to Port Hardware 105Direct Calls into the BIOS 106

Looking Ahead: 64-Bit ‘‘Long Mode’’ 10664-Bit Memory: What May Be Possible Someday vs.

What We Can Do Now 107

Chapter 5 The Right to Assemble 109Files and What’s Inside Them 110

Binary Files vs. Text Files 111Looking at File Internals with the Bless Editor 112Interpreting Raw Data 116‘‘Endianness’’ 117

Text In, Code Out 121Assembly Language 121Comments 124Beware ‘‘Write-Only’’ Source Code! 124Object Code and Linkers 125Relocatability 128

The Assembly Language Development Process 128The Discipline of Working Directories 129Editing the Source Code File 131

Page 20: Jeff Duntemann Assembly Language Step by Stepdownload.e-bookshelf.de/download/0000/5754/73/L-G-0000575473...Assembly Language Step by Step Programming with Linux ® Learn assembly

xviii Contents

Assembling the Source Code File 131Assembler Errors 132Back to the Editor 133Assembler Warnings 134Linking the Object Code File 135Linker Errors 136Testing the .EXE File 136Errors versus Bugs 137Are We There Yet? 138Debuggers and Debugging 138

Taking a Trip Down Assembly Lane 139Installing the Software 139Step 1: Edit the Program in an Editor 142Step 2: Assemble the Program with NASM 143Step 3: Link the Program with LD 146Step 4: Test the Executable File 147Step 5: Watch It Run in the Debugger 147Ready to Get Serious? 153

Chapter 6 A Place to Stand, with Access to Tools 155The Kate Editor 157

Installing Kate 157Launching Kate 158Configuration 160Kate Sessions 162

Creating a New Session 162Opening an Existing Session 163Deleting or Renaming Sessions 163

Kate’s File Management 164Filesystem Browser Navigation 165Adding a File to the Current Session 165Dropping a File from the Current Session 166Switching Between Session Files in the Editor 166Creating a Brand-New File 166Creating a Brand-New Folder on Disk 166Deleting a File from Disk (Move File to Trash) 166Reloading a File from Disk 167Saving All Unsaved Changes in Session Files 167Printing the File in the Editor Window 167Exporting a File As HTML 167

Adding Items to the Toolbar 167Kate’s Editing Controls 168

Cursor Movement 169Bookmarks 169Selecting Text 170

Page 21: Jeff Duntemann Assembly Language Step by Stepdownload.e-bookshelf.de/download/0000/5754/73/L-G-0000575473...Assembly Language Step by Step Programming with Linux ® Learn assembly

Contents xix

Searching the Text 171Using Search and Replace 172

Using Kate While Programming 172Creating and Using Project Directories 173Focus! 175

Linux and Terminals 176The Linux Console 176Character Encoding in Konsole 177The Three Standard Unix Files 178I/O Redirection 180Simple Text Filters 182Terminal Control with Escape Sequences 183So Why Not GUI Apps? 185

Using Linux Make 186Dependencies 187When a File Is Up to Date 189Chains of Dependencies 189Invoking Make from Inside Kate 191Using Touch to Force a Build 193

The Insight Debugger 194Running Insight 195Insight’s Many Windows 195A Quick Insight Run-Through 197Pick Up Your Tools . . . 200

Chapter 7 Following Your Instructions 201Build Yourself a Sandbox 201

A Minimal NASM Program 202Instructions and Their Operands 204

Source and Destination Operands 204Immediate Data 205Register Data 207Memory Data 209Confusing Data and Its Address 210The Size of Memory Data 211The Bad Old Days 211

Rally Round the Flags, Boys! 212Flag Etiquette 215Adding and Subtracting One with INC and DEC 215Watching Flags from Insight 216How Flags Change Program Execution 218

Signed and Unsigned Values 221Two’s Complement and NEG 221Sign Extension and MOVSX 224

Page 22: Jeff Duntemann Assembly Language Step by Stepdownload.e-bookshelf.de/download/0000/5754/73/L-G-0000575473...Assembly Language Step by Step Programming with Linux ® Learn assembly

xx Contents

Implicit Operands and MUL 225MUL and the Carry Flag 227Unsigned Division with DIV 228The x86 Slowpokes 229

Reading and Using an Assembly Language Reference 230Memory Joggers for Complex Memories 230An Assembly Language Reference for Beginners 231Flags 232

NEG: Negate (Two’s Complement; i.e., Multiply by -1) 233Flags affected 233Legal forms 233Examples 233Notes 233Legal Forms 234Operand Symbols 234Examples 235Notes 235What’s Not Here . . . 235

Chapter 8 Our Object All Sublime 237The Bones of an Assembly Language Program 237

The Initial Comment Block 239The .data Section 240The .bss Section 240The .text Section 241Labels 241Variables for Initialized Data 242String Variables 242Deriving String Length with EQU and $ 244

Last In, First Out via the Stack 246Five Hundred Plates per Hour 246Stacking Things Upside Down 248Push-y Instructions 249POP Goes the Opcode 251Storage for the Short Term 253

Using Linux Kernel Services Through INT80 254An Interrupt That Doesn’t Interrupt Anything 254Getting Home Again 259Exiting a Program via INT 80h 260Software Interrupts versus Hardware Interrupts 261INT 80h and the Portability Fetish 262

Designing a Non-Trivial Program 264Defining the Problem 264Starting with Pseudo-code 265

Page 23: Jeff Duntemann Assembly Language Step by Stepdownload.e-bookshelf.de/download/0000/5754/73/L-G-0000575473...Assembly Language Step by Step Programming with Linux ® Learn assembly

Contents xxi

Successive Refinement 266Those Inevitable ‘‘Whoops!’’ Moments 270Scanning a Buffer 271‘‘Off By One’’ Errors 273Going Further 277

Chapter 9 Bits, Flags, Branches, and Tables 279Bits Is Bits (and Bytes Is Bits) 279

Bit Numbering 280‘‘It’s the Logical Thing to Do, Jim. . .’’ 280The AND Instruction 281Masking Out Bits 282The OR Instruction 283The XOR Instruction 284The NOT Instruction 285Segment Registers Don’t Respond to Logic! 285

Shifting Bits 286Shift By What? 286How Bit Shifting Works 287Bumping Bits into the Carry Flag 287The Rotate Instructions 288Setting a Known Value into the Carry Flag 289

Bit-Bashing in Action 289Splitting a Byte into Two Nybbles 292Shifting the High Nybble into the Low Nybble 293Using a Lookup Table 293Multiplying by Shifting and Adding 295

Flags, Tests, and Branches 298Unconditional Jumps 298Conditional Jumps 299Jumping on the Absence of a Condition 300Flags 301Comparisons with CMP 301A Jungle of Jump Instructions 302‘‘Greater Than‘‘ Versus ’’Above’’ 303Looking for 1-Bits with TEST 304Looking for 0 Bits with BT 306

Protected Mode Memory Addressing in Detail 307Effective Address Calculations 308Displacements 309Base + Displacement Addressing 310Base + Index Addressing 310Index × Scale + Displacement Addressing 312Other Addressing Schemes 313

Page 24: Jeff Duntemann Assembly Language Step by Stepdownload.e-bookshelf.de/download/0000/5754/73/L-G-0000575473...Assembly Language Step by Step Programming with Linux ® Learn assembly

xxii Contents

LEA: The Top-Secret Math Machine 315The Burden of 16-Bit Registers 317

Character Table Translation 318Translation Tables 318Translating with MOV or XLAT 320

Tables Instead of Calculations 325

Chapter 10 Dividing and Conquering 327Boxes within Boxes 328

Procedures As Boxes for Code 329Calling and Returning 336

Calls within Calls 338The Dangers of Accidental Recursion 340A Flag Etiquette Bug to Beware Of 341Procedures and the Data They Need 342Saving the Caller’s Registers 343Local Data 346More Table Tricks 347Placing Constant Data in Procedure Definitions 349

Local Labels and the Lengths of Jumps 350’’Forcing’’ Local Label Access 353Short, Near, and Far Jumps 354

Building External Procedure Libraries 355Global and External Declarations 356The Mechanics of Globals and Externals 357Linking Libraries into Your Programs 365The Dangers of Too Many Procedures and Too Many

Libraries 366The Art of Crafting Procedures 367

Maintainability and Reuse 367Deciding What Should Be a Procedure 368Use Comment Headers! 370

Simple Cursor Control in the Linux Console 371Console Control Cautions 377

Creating and Using Macros 378The Mechanics of Macro Definition 379Defining Macros with Parameters 385The Mechanics of Invoking Macros 386Local Labels Within Macros 387Macro Libraries As Include Files 388Macros versus Procedures: Pros and Cons 389

Page 25: Jeff Duntemann Assembly Language Step by Stepdownload.e-bookshelf.de/download/0000/5754/73/L-G-0000575473...Assembly Language Step by Step Programming with Linux ® Learn assembly

Contents xxiii

Chapter 11 Strings and Things 393The Notion of an Assembly Language String 393

Turning Your ‘‘String Sense’’ Inside-Out 394Source Strings and Destination Strings 395A Text Display Virtual Screen 395

REP STOSB, the Software Machine Gun 402Machine-Gunning the Virtual Display 403Executing the STOSB Instruction 404STOSB and the Direction Flag (DF) 405Defining Lines in the Display Buffer 406Sending the Buffer to the Linux Console 406

The Semiautomatic Weapon: STOSB without REP 407Who Decrements ECX? 407The LOOP Instructions 408Displaying a Ruler on the Screen 409MUL Is Not IMUL 410Adding ASCII Digits 411Adjusting AAA’s Adjustments 413Ruler’s Lessons 41416-bit and 32-bit Versions of STOS 414

MOVSB: Fast Block Copies 414DF and Overlapping Block Moves 416Single-Stepping REP String Instructions with Insight 418

Storing Data to Discontinuous Strings 419Displaying an ASCII Table 419Nested Instruction Loops 420Jumping When ECX Goes to 0 421Closing the Inner Loop 421Closing the Outer Loop 422Showchar Recap 423

Command-Line Arguments and Examining the Stack 424Virtual Memory in Two Chunks 424Anatomy of the Linux Stack 427Why Stack Addresses Aren’t Predictable 429Setting Command-Line Arguments with Insight 429Examining the Stack with Insight’s Memory View 430

String Searches with SCASB 432REPNE vs. REPE 435Pop the Stack or Address It? 436For Extra Credit . . . 438

Page 26: Jeff Duntemann Assembly Language Step by Stepdownload.e-bookshelf.de/download/0000/5754/73/L-G-0000575473...Assembly Language Step by Step Programming with Linux ® Learn assembly

xxiv Contents

Chapter 12 Heading Out to C 439What’s GNU? 440

The Swiss Army Compiler 441Building Code the GNU Way 441How to Use gcc in Assembly Work 443Why Not gas? 444

Linking to the Standard C Library 445C Calling Conventions 446A Framework to Build On 447Saving and Restoring Registers 447Setting Up a Stack Frame 448Destroying a Stack Frame 450Characters Out via puts() 451

Formatted Text Output with printf() 452Passing Parameters to printf() 454

Data In with fgets() and scanf() 456Using scanf() for Entry of Numeric Values 458

Be a Time Lord 462The C Library’s Time Machine 462Fetching time_t Values from the System Clock 464Converting a time_t Value to a Formatted String 464Generating Separate Local Time Values 465Making a Copy of glibc’s tm Struct with MOVSD 466

Understanding AT&T Instruction Mnemonics 470AT&T Mnemonic Conventions 470Examining gas Source Files Created by gcc 471AT&T Memory Reference Syntax 474

Generating Random Numbers 475Seeding the Generator with srand() 476Generating Pseudorandom Numbers 477Some Bits Are More Random Than Others 482Calls to Addresses in Registers 483

How C Sees Command-Line Arguments 484Simple File I/O 487

Converting Strings into Numbers with sscanf() 487Creating and Opening Files 489Reading Text from Files with fgets() 490Writing Text to Files with fprintf() 493Notes on Gathering Your Procedures into Libraries 494

Conclusion: Not the End, But Only the Beginning 503Where to Now? 504Stepping off Square One 506

Page 27: Jeff Duntemann Assembly Language Step by Stepdownload.e-bookshelf.de/download/0000/5754/73/L-G-0000575473...Assembly Language Step by Step Programming with Linux ® Learn assembly

Contents xxv

Appenix A Partial x86 Instruction Set Reference 507Notes on the Instruction Set Reference 510AAA: Adjust AL after BCD Addition 512ADC: Arithmetic Addition with Carry 513ADD: Arithmetic Addition 515AND: Logical AND 517BT: Bit Test 519CALL: Call Procedure 521CLC: Clear Carry Flag (CF) 523CLD: Clear Direction Flag (DF) 524CMP: Arithmetic Comparison 525DEC: Decrement Operand 527DIV: Unsigned Integer Division 528INC: Increment Operand 529INT: Software Interrupt 530IRET: Return from Interrupt 531J?: Jump on Condition 532JCXZ: Jump If CX=0 534JECXZ: Jump If ECX=0 535JMP: Unconditional Jump 536LEA: Load Effective Address 537LOOP: Loop until CX/ECX=0 538LOOPNZ/LOOPNE: Loop While CX/ECX > 0 and ZF=0 540LOOPZ/LOOPE: Loop While CX/ECX > 0 and ZF=1 541MOV: Move (Copy) Right Operand into Left Operand 542MOVS: Move String 544MOVSX: Move (Copy) with Sign Extension 546MUL: Unsigned Integer Multiplication 547NEG: Negate (Two’s Complement; i.e., Multiply by -1) 549NOP: No Operation 550NOT: Logical NOT (One’s Complement) 551OR: Logical OR 552POP: Pop Top of Stack into Operand 554POPA/POPAD: Pop All GP Registers 555POPF: Pop Top of Stack into 16-Bit Flags 556POPFD: Pop Top of Stack into EFlags 557PUSH: Push Operand onto Top of Stack 558PUSHA: Push All 16-Bit GP Registers 559PUSHAD: Push All 32-Bit GP Registers 560PUSHF: Push 16-Bit Flags onto Stack 561PUSHFD: Push 32-Bit EFlags onto Stack 562RET: Return from Procedure 563ROL: Rotate Left 564

Page 28: Jeff Duntemann Assembly Language Step by Stepdownload.e-bookshelf.de/download/0000/5754/73/L-G-0000575473...Assembly Language Step by Step Programming with Linux ® Learn assembly

xxvi Contents

ROR: Rotate Right 566SBB: Arithmetic Subtraction with Borrow 568SHL: Shift Left 570SHR: Shift Right 572STC: Set Carry Flag (CF) 574STD: Set Direction Flag (DF) 575STOS: Store String 576SUB: Arithmetic Subtraction 577XCHG: Exchange Operands 579XLAT: Translate Byte via Table 580XOR: Exclusive Or 581

Appendix B Character Set Charts 583

Index 587

Page 29: Jeff Duntemann Assembly Language Step by Stepdownload.e-bookshelf.de/download/0000/5754/73/L-G-0000575473...Assembly Language Step by Step Programming with Linux ® Learn assembly

Introduction: ‘‘Why Would YouWant to Do That?’’

It was 1985, and I was in a chartered bus in New York City, heading for apress reception with a bunch of other restless media egomaniacs. I was onlybeginning my media career (as Technical Editor for PC Tech Journal) and myfirst book was still months in the future. I happened to be sitting next to anestablished programming writer/guru, with whom I was impressed and towhom I was babbling about one thing or another. I won’t name him, as he’sdone a lot for the field, and may do a fair bit more if he doesn’t kill himselfsmoking first.

But I happened to let it slip that I was a Turbo Pascal fanatic, and what Ireally wanted to do was learn how to write Turbo Pascal programs that madeuse of the brand-new Microsoft Windows user interface. He wrinkled his noseand grimaced wryly, before speaking the Infamous Question:

‘‘Why would you want to do that?’’I had never heard the question before (though I would hear it many times

thereafter) and it took me aback. Why? Because, well, because . . . I wanted toknow how it worked.

‘‘Heh. That’s what C’s for.’’Further discussion got me nowhere in a Pascal direction. But some probing

led me to understand that you couldn’t write Windows apps in Turbo Pascal.It was impossible. Or . . . the programming writer/guru didn’t know how.Maybe both. I never learned the truth. But I did learn the meaning of theInfamous Question.

Note well: When somebody asks you, ‘‘Why would you want to do that?’’what it really means is this: ‘‘You’ve asked me how to do something that iseither impossible using tools that I favor or completely outside my experience,

xxvii

Page 30: Jeff Duntemann Assembly Language Step by Stepdownload.e-bookshelf.de/download/0000/5754/73/L-G-0000575473...Assembly Language Step by Step Programming with Linux ® Learn assembly

xxviii Introduction: ‘‘Why Would You Want to Do That?’’

but I don’t want to lose face by admitting it. So . . . how ‘bout those Black-hawks?’’

I heard it again and again over the years:

Q: How can I set up a C string so that I can read its length without scanning it?

A: Why would you want to do that?

Q: How can I write an assembly language subroutine callable from TurboPascal?

A: Why would you want to do that?

Q: How can I write Windows apps in assembly language?

A: Why would you want to do that?

You get the idea. The answer to the Infamous Question is always the same,and if the weasels ever ask it of you, snap back as quickly as possible, ‘‘BecauseI want to know how it works.’’

That is a completely sufficient answer. It’s the answer I’ve used every singletime, except for one occasion a considerable number of years ago, when I putforth that I wanted to write a book that taught people how to program inassembly language as their first experience in programming.

Q: Good grief, why would you want to do that?

A: Because it’s the best way there is to build the skills required to understandhow all the rest of the programming universe works.

Being a programmer is one thing above all else: it is understanding howthings work. Learning to be a programmer, furthermore, is almost entirelya process of leaning how things work. This can be done at various levels,depending on the tools you’re using. If you’re programming in Visual Basic,you have to understand how certain things work, but those things are by andlarge confined to Visual Basic itself. A great deal of machinery is hidden bythe layer that Visual Basic places between the programmer and the computer.(The same is true of Delphi, Java, Python, and many other very high levelprogramming environments.) If you’re using a C compiler, you’re a lot closerto the machine, and you see a lot more of that machinery—and must, therefore,understand how it works to be able to use it. However, quite a bit remainshidden, even from the hardened C programmer.

If, conversely, you’re working in assembly language, you’re as close to themachine as you can get. Assembly language hides nothing, and withholds nopower. The flip side, of course, is that no magical layer between you and themachine will absolve any ignorance and ‘‘take care of’’ things for you. If youdon’t understand how something works, you’re dead in the water—unlessyou know enough to be able to figure it out on your own.