Transcription of PC Assembly Language - Stanford University
1 PCAssemblyLanguagePaul A. CarterMarch 20, 2005 Copyrightc 2001, 2002, 2003, 2004 by Paul CarterThis may be reproduced and distributed in its entirety (including this au-thorship, copyright and permission notice), provided that no charge is madefor the document itself, without the author s consent. This includes fairuse excerpts like reviews and advertising, and derivative works like that this restriction is not intended to prohibit charging for the serviceof printing or copying the are encouraged to use this document as a class resource; however,the author would appreciate being notified in this Number Systems .. Decimal .. Binary .. Hexadecimal .. Computer Organization .. Memory .. The CPU .. The 80x86 family of CPUs .. 8086 16-bit Registers .. 80386 32-bit registers .. Real Mode .. 16-bit Protected Mode .. 32-bit Protected Mode .. Interrupts .. Assembly Language .. Machine Language .. Assembly Language .. Instruction operands.
2 Basic instructions .. Directives .. Input and Output .. Debugging .. Creating a Program .. First program .. Compiler dependencies .. Assembling the code .. Compiling the C code .. Linking the object files .. Understanding an Assembly listing file .. Skeleton File ..252 Basic Assembly Working with Integers .. Integer representation .. Sign extension .. Two s complement arithmetic .. Example program .. Extended precision arithmetic .. Control Structures .. Comparisons .. Branch instructions .. The loop instructions .. Translating Standard Control Structures .. If statements .. While loops .. Do while loops .. Example: Finding Prime Numbers ..433 Bit Shift Operations .. Logical shifts .. Use of shifts .. Arithmetic shifts .. Rotate shifts .. Simple application .. Boolean Bitwise Operations .. TheANDoperation .. TheORoperation .. TheXORoperation .. TheNOToperation .. TheTEST instruction.
3 Uses of bit operations .. Avoiding Conditional Branches .. Manipulating bits in C .. The bitwise operators of C .. Using bitwise operators in C .. Big and Little Endian Representations .. When to Care About Little and Big Endian .. Counting Bits .. Method one .. Method two .. Method three ..62 CONTENTSiii4 Indirect Addressing .. Simple Subprogram Example .. The Stack .. The CALL and RET Instructions .. Calling Conventions .. Passing parameters on the stack .. Local variables on the stack .. Multi-Module Programs .. Interfacing Assembly with C .. Saving registers .. Labels of functions .. Passing parameters .. Calculating addresses of local variables .. Returning values .. Other calling conventions .. Examples .. Calling C functions from Assembly .. Reentrant and Recursive Subprograms .. Recursive subprograms .. Review of C variable storage types ..915 Introduction .. Defining arrays .. Accessing elements of arrays.
4 More advanced indirect addressing .. Example .. Multidimensional Arrays .. Array/String Instructions .. Reading and writing memory .. TheREPinstruction prefix .. Comparison string instructions .. TheREPxinstruction prefixes .. Example ..1116 Floating Floating Point Representation .. Non-integral binary numbers .. IEEE floating point representation .. Floating Point Arithmetic .. Addition .. Subtraction .. Multiplication and division .. Ramifications for programming .. The Numeric Coprocessor .. Hardware .. Instructions .. Examples .. Quadratic formula .. Reading array from file .. Finding primes ..1357 Structures and C++ Structures .. Introduction .. Memory alignment .. Bit Fields .. Using structures in Assembly .. Assembly and C++ .. Overloading and Name Mangling .. References .. Inline functions .. Classes .. Inheritance and Polymorphism .. Other C++ features ..171A 80x86 Non-floating Point Instructions.
5 Floating Point Instructions ..179 Index181 PrefacePurposeThe purpose of this book is to give the reader a better understanding ofhow computers really work at a lower level than in programming languageslike Pascal. By gaining a deeper understanding of how computers work, thereader can often be much more productive developing software in higher levellanguages such as C and C++. Learning to program in Assembly languageis an excellent way to achieve this goal. Other PC Assembly Language booksstill teach how to program the 8086 processor that the original PC used in1981! The 8086 processor only supportedrealmode. In this mode, anyprogram may address any memory or device in the computer. This mode isnot suitable for a secure, multitasking operating system. This book insteaddiscusses how to program the 80386 and later processors inprotectedmode(the mode that Windows and Linux runs in). This mode supports thefeatures that modern operating systems expect, such as virtual memory andmemory protection.
6 There are several reasons to use protected is easier to program in protected mode than in the 8086 real modethat other books modern PC operating systems run in protected is free software available that runs in this lack of textbooks for protected mode PC Assembly programming is themain reason that the author wrote this alluded to above, this text makes use of Free/Open Source software:namely, the NASM assembler and the DJGPP C/C++ compiler. Bothof these are available to download from the Internet. The text also dis-cusses how to use NASM Assembly code under the Linux operating sys-tem and with Borland s and Microsoft s C/C++ compilers under Win-dows. Examples for all of these platforms can be found on my web site: Youmustdownload the examplecode if you wish to assemble and run many of the examples in this aware that this text does not attempt to cover every aspect of assem-bly programming. The author has tried to cover the most important topicsthatallprogrammers should be acquainted author would like to thank the many programmers around the worldthat have contributed to the Free/Open Source movement.
7 All the programsand even this book itself were produced using free software. Specifically, theauthor would like to thank John S. Fine, Simon Tatham, Julian Hall andothers for developing the NASM assembler that all the examples in thisbook are based on; DJ Delorie for developing the DJGPP C/C++ compilerused; the numerous people who have contributed to the GNU gcc compileron which DJGPP is based on; Donald Knuth and others for developing theTEX and LATEX 2 typesetting languages that were used to produce the book;Richard Stallman (founder of the Free Software Foundation), Linus Torvalds(creator of the Linux kernel) and others who produced the underlying soft-ware the author used to produce this to the following people for corrections: John S. Fine Marcelo Henrique Pinto de Almeida Sam Hopkins Nick D Imperio Jeremiah Lawrence Ed Beroset Jerry Gembarowski Ziqiang Peng Eno Compton Josh I Cates Mik Mifflin Luke Wallis Gaku Ueda Brian Hewardvii Chad Gorshing F. Gotti Bob Wilkinson Markus Koegel Louis Taber Dave Kiddell Eduardo HorowitzResources on the InternetAuthor s SourceForge Art of author welcomes any feedback on this Number SystemsMemory in a computer consists of numbers.
8 Computer memory doesnot store these numbers in decimal (base 10). Because it greatly simplifiesthe hardware, computers store all information in a binary (base 2) let s review the decimal DecimalBase 10 numbers are composed of 10 possible digits (0-9). Each digit ofa number has a power of 10 associated with it based on its position in thenumber. For example:234 = 2 102+ 3 101+ 4 BinaryBase 2 numbers are composed of 2 possible digits (0 and 1). Each digitof a number has a power of 2 associated with it based on its position in thenumber. (A single binary digit is called a bit.) For example:110012= 1 24+ 1 23+ 0 22+ 0 21+ 1 20= 16 + 8 + 1= 25 This shows how binary may be converted to decimal. Table showshow the first few numbers are represented in shows how individual binary digits ( , bits) are s an example:12 CHAPTER 1. INTRODUCTIOND ecimalBinaryDecimalBinary000008100010001 9100120010101010300111110114010012110050 1011311016011014111070111151111 Table : Decimal 0 to 15 in BinaryNo previous carryPrevious carry00110011+0+1+0+1+0+1+0+101101001ccc cFigure : Binary addition (c stands forcarry)110112+1000121011002If one considers the following decimal division:1234 10 = 123r4he can see that this division strips off the rightmost decimal digit of thenumber and shifts the other decimal digits one position to the right.
9 Dividingby two performs a similar operation, but for the binary digits of the the following binary division1:11012 102= 1102r1 This fact can be used to convert a decimal number to its equivalent binaryrepresentation as Figure shows. This method finds the rightmost digitfirst, this digit is called theleast significant bit(lsb). The leftmost digit iscalled themost significant bit(msb). The basic unit of memory consists of8 bits and is called 2 subscript is used to show that the number is represented in binary, not NUMBER SYSTEMS3 DecimalBinary25 2 = 12r1 11001 10 = 1100r112 2 = 6r0 1100 10 = 110r06 2 = 3r0 110 10 = 11r03 2 = 1r111 10 = 1r11 2 = 0r11 10 = 0r1 Thus 2510= 110012 Figure : Decimal conversion589 16 = 36r1336 16 = 2r42 16 = 0r2 Thus 589 = 24D16 Figure HexadecimalHexadecimal numbers use base 16. Hexadecimal (orhexfor short) canbe used as a shorthand for binary numbers. Hex has 16 possible digits. Thiscreates a problem since there are no symbols to use for these extra digitsafter 9.
10 By convention, letters are used for these extra digits. The 16 hexdigits are 0-9 then A, B, C, D, E and F. The digit A is equivalent to 10in decimal, B is 11, etc. Each digit of a hex number has a power of 16associated with it. Example:2BD16= 2 162+ 11 161+ 13 160= 512 + 176 + 13= 701To convert from decimal to hex, use the same idea that was used for binaryconversion except divide by 16. See Figure for an reason that hex is useful is that there is a very simple way to convert4 CHAPTER 1. INTRODUCTION between hex and binary. Binary numbers get large and cumbersome provides a much more compact way to represent convert a hex number to binary, simply convert each hex digit to a4-bit binary number. For example, 24D16is converted to 0010 0100 that the leading zeros of the 4-bits are important! If the leading zerofor the middle digit of 24D16is not used the result is wrong. Convertingfrom binary to hex is just as easy. One does the process in reverse. Converteach 4-bit segments of the binary to hex.