Assembly Dökümanları... Basic Concepts • Basic description of a computer system o Central Processor o Central Memory o Input and Output Units o Auxiliary Memory Units • Assembler language Basic concepts o Information in the computers o Data representation methods • Using debug program o Program creation process o CPU registers o Debug program o Assembler structure o Creating basic assembler program o Storing and loading the programs o ________________________________________ Basic description of a computer system This section has the purpose of giving a brief outline of the main components of a computer system at a basic level, which will allow the user a greater understanding of the concepts which will be dealt with throughout the tutorial. Computer System We call computer system to the complete configuration of a computer, including the peripheral units and the system programming which make it a useful and functional machine for a determined task. Central Processor. This part is also known as central processing unit or CPU, which in turn is made by the control unit and the arithmetic and logic unit. Its functions consist in reading and writing the contents of the memory cells, to forward data between memory cells and special registers, and decode and execute the instructions of a program. The processor has a series of memory cells which are used very often and thus, are part of the CPU. These cells are known with the name of registers. A processor may have one or two dozen of these registers. The arithmetic and logic unit of the CPU realizes the operations related with numeric and symbolic calculations. Typically these units only have capacity of performing very elemental operations such as: the addition and subtraction of two whole numbers, whole number multiplication and division, handling of the registers' bits and the comparison of the content of two registers. Personal computers can be classified by what is known as word size, this is, the quantity of bits which the processor can handle at a time. Central Memory. It is a group of cells, now being fabricated with semi-conductors, used for general processes, such as the execution of programs and the storage of information for the operations. Each one of these cells may contain a numeric value and they have the property of being addressable, this is, that they can distinguish one from another by means of a unique number or an address for each cell. The generic name of these memories is Random Access Memory or RAM. The main disadvantage of this type of memory is that the integrated circuits lose the information they have stored when the electricity flow is interrupted. This was the reason for the creation of memories whose information is not lost when the system is turned off. These memories receive the name of Read Only Memory or ROM. Input and Output Units. In order for a computer to be useful to us it is necessary that the processor communicates with the exterior through interfaces which allow the input and output of information from the processor and the memory. Through the use of these communications it is possible to introduce information to be processed and to later visualize the processed data. Some of the most common input units are keyboards and mice. The most common output units are screens and printers. Auxiliary Memory Units. Since the central memory of a computer is costly, and considering today's applications it is also very limited. Thus, the need to create practical and economical information storage systems arises. Besides, the central memory loses its content when the machine is turned off, therefore making it inconvenient for the permanent storage of data. These and other inconvenience give place for the creation of peripheral units of memory which receive the name of auxiliary or secondary memory. Of these the most common are the tapes and magnetic discs. The stored information on these magnetic media means receive the name of files. A file is made of a variable number of registers, generally of a fixed size; the registers may contain information or programs. Assembler language Basic concepts Information in the computers 1) Information Units In order for the PC to process information, it is necessary that this information be in special cells called registers. The registers are groups of 8 or 16 flip-flops. A flip-flop is a device capable of storing two levels of voltage, a low one, regularly 0.5 volts, and another one, commonly of 5 volts. The low level of energy in the flip-flop is interpreted as off or 0, and the high level as on or 1. These states are usually known as bits, which are the smallest information unit in a computer. A group of 16 bits is known as word; a word can be divided in groups of 8 bits called bytes, and the groups of 4 bits are called nibbles. 2) Numeric systems The numeric system we use daily is the decimal system, but this system is not convenient for machines since the information is handled codified in the shape of on or off bits; this way of codifying takes us to the necessity of knowing the positional calculation which will allow us to express a number in any base where we need it. It is possible to represent a determined number in any base through the following formula: Where n is the position of the digit beginning from right to left and numbering from zero. D is the digit on which we operate and B is the used numeric base. 3) Converting binary numbers to decimals When working with assembly language we come on the necessity of converting numbers from the binary system, which is used by computers, to the decimal system used by people. The binary system is based on only two conditions or states, be it on(1) or off(0), thus its base is two. For the conversion we can use the positional value formula: For example, if we have the binary number of 10011, we take each digit from right to left and multiply it by the base, elevated to the new position they are: Binary: 1 1 0 0 1 Decimal: 1*2^0 + 1*2^1 + 0*2^2 + 0*2^3 + 1*2^4 = 1 + 2 + 0 + 0 + 16 = 19 decimal. The ^ character is used in computation as an exponent symbol and the * character is used to represent multiplication. 4) Converting decimal numbers to binary There are several methods to convert decimal numbers to binary; only one will be analyzed here. Naturally a conversion with a scientific calculator is much easier, but one cannot always count with one, so it is convenient to at least know one formula to do it. The method that will be explained uses the successive division of two, keeping the residue as a binary digit and the result as the next number to divide. Let us take for example the decimal number of 43. 43/2=21 and its residue is 1 21/2=10 and its residue is 1 10/2=5 and its residue is 0 5/2=2 and its residue is 1 2/2=1 and its residue is 0 1/2=0 and its residue is 1 Building the number from the bottom , we get that the binary result is 101011 Hexadecimal system On the hexadecimal base we have 16 digits which go from 0 to 9 and from the letter A to the F, these letters represent the numbers from 10 to 15. Thus we count 0,1,2,3,4,5,6,7,8,9,A,B,C,D,E, and F. The conversion between binary and hexadecimal numbers is easy. The first thing done to do a conversion of a binary number to a hexadecimal is to divide it in groups of 4 bits, beginning from the right to the left. In case the last group, the one most to the left, is under 4 bits, the missing places are filled with zeros. Taking as an example the binary number of 101011, we divide it in 4 bits groups and we are left with: 10;1011 Filling the last group with zeros (the one from the left): 0010;1011 Afterwards we take each group as an independent number and we consider its decimal value: 0010=2;1011=11 But since we cannot represent this hexadecimal number as 211 because it would be an error, we have to substitute all the values greater than 9 by their respective representation in hexadecimal, with which we obtain: 2BH, where the H represents the hexadecimal base. In order to convert a hexadecimal number to binary it is only necessary to invert the steps: the first hexadecimal digit is taken and converted to binary, and then the second, and so on. Data representation methods in a computer. ASCII code ASCII is an acronym of American Standard Code for Information Interchange. This code assigns the letters of the alphabet, decimal digits from 0 to 9 and some additional symbols a binary number of 7 bits, putting the 8th bit in its off state or 0. This way each letter, digit or special character occupies one byte in the computer memory. We can observe that this method of data representation is very inefficient on the numeric aspect, since in binary format one byte is not enough to represent numbers from 0 to 255, but on the other hand with the ASCII code one byte may represent only one digit. Due to this inefficiency, the ASCII code is mainly used in the memory to represent text. BCD Method BCD is an acronym of Binary Coded Decimal. In this notation groups of 4 bits are used to represent each decimal digit from 0 to 9. With this method we can represent two digits per byte of information. Even when this method is much more practical for number representation in the memory compared to the ASCII code, it still less practical than the binary since with the BCD method we can only represent digits from 0 to 99. On the other hand in binary format we can represent all digits from 0 to 255. This format is mainly used to represent very large numbers in mercantile applications since it facilitates operations avoiding mistakes. Floating point representation This representation is based on scientific notation, this is, to represent a number in two parts: its base and its exponent. As an example, the number 1234000, can be represented as 1.123*10^6, in this last notation the exponent indicates to us the number of spaces that the decimal point must be moved to the right to obtain the original result. In case the exponent was negative, it would be indicating to us the number of spaces that the decimal point must be moved to the left to obtain the original result. Using Debug program Program creation process For the creation of a program it is necessary to follow five steps: Design of the algorithm, stage the problem to be solved is established and the best solution is proposed, creating squematic diagrams used for the better solution proposal. Coding the algorithm, consists in writing the program in some programming language; assembly language in this specific case, taking as a base the proposed solution on the prior step. Translation to machine language, is the creation of the object program, in other words, the written program as a sequence of zeros and ones that can be interpreted by the processor. Test the program, after the translation the program into machine language, execute the program in the computer machine. The last stage is the elimination of detected faults on the program on the test stage. The correction of a fault normally requires the repetition of all the steps from the first or second. CPU Registers The CPU has 4 internal registers, each one of 16 bits. The first four, AX, BX, CX, and DX are general use registers and can also be used as 8 bit registers, if used in such a way it is necessary to refer to them for example as: AH and AL, which are the high and low bytes of the AX register. This nomenclature is also applicable to the BX, CX, and DX registers. The registers known by their specific names: AX Accumulator BX Base register CX Counting register DX Data register DS Data Segment register ES Extra Segment register SS Battery segment register CS Code Segment register BP Base Pointers register SI Source Index register DI Destiny Index register SP Battery pointer register IP Next Instruction Pointer register F Flag register Debug program To create a program in assembler two options exist, the first one is to use the TASM or Turbo Assembler, of Borland, and the second one is to use the debugger - on this first section we will use this last one since it is found in any PC with the MS-DOS, which makes it available to any user who has access to a machine with these characteristics. Debug can only create files with a .COM extension, and because of the characteristics of these kinds of programs they cannot be larger that 64 kb, and they also must start with displacement, offset, or 0100H memory direction inside the specific segment. Debug provides a set of commands that lets you perform a number of useful operations: A Assemble symbolic instructions into machine code D Display the contents of an area of memory E Enter data into memory, beginning at a specific location G Run the executable program in memory N Name a program P Proceed, or execute a set of related instructions Q Quit the debug program R Display the contents of one or more registers T Trace the contents of one instruction U Unassembled machine code into symbolic code W Write a program onto disk It is possible to visualize the values of the internal registers of the CPU using the Debug program. To begin working with Debug, type the following prompt in your computer: C:/> Debug [Enter] On the next line a dash will appear, this is the indicator of Debug, at this moment the instructions of Debug can be introduced using the following command: -r [Enter] AX=0000 BX=0000 CX=0000 DX=0000 SP=FFEE BP=0000 SI=0000 DI=0000 DS=0D62 ES=0D62 SS=0D62 CS=0D62 IP=0100 NV EI PL NZ NA PO NC 0D62:0100 2E CS: 0D62:0101 803ED3DF00 CMP BYTE PTR [DFD3],00 CShttp://www.supermp3.org/images/smilies/biggrin.gifFD3=03 All the contents of the internal registers of the CPU are displayed; an alternative of viewing them is to use the "r" command using as a parameter the name of the register whose value wants to be seen. For example: -rbx [Enter] BX 0000 : This instruction will only display the content of the BX register and the Debug indicator changes from "-" to ":" When the prompt is like this, it is possible to change the value of the register which was seen by typing the new value and [Enter], or the old value can be left by pressing [Enter] without typing any other value. |
Assembler structure In assembly language code lines have two parts, the first one is the name of the instruction which is to be executed, and the second one are the parameters of the command. For example: add ah bh Here "add" is the command to be executed, in this case an addition, and "ah" as well as "bh" are the parameters. For example: mov al, 25 In the above example, we are using the instruction mov, it means move the value 25 to al register. The name of the instructions in this language is made of two, three or four letters. These instructions are also called mnemonic names or operation codes, since they represent a function the processor will perform. Sometimes instructions are used as follows: add al,[170] The brackets in the second parameter indicate to us that we are going to work with the content of the memory cell number 170 and not with the 170 value, this is known as direct addressing. Creating basic assembler program The first step is to initiate the Debug, this step only consists of typing c:\> debug [Enter] on the operative system prompt. To assemble a program on the Debug, the "a" (assemble) command is used; when this command is used, the address where you want the assembling to begin can be given as a parameter, if the parameter is omitted the assembling will be initiated at the locality specified by CS:IP, usually 0100h, which is the locality where programs with .COM extension must be initiated. And it will be the place we will use since only Debug can create this specific type of programs. Even though at this moment it is not necessary to give the "a" command a parameter, it is recommendable to do so to avoid problems once the CS:IP registers are used, therefore we type: a 100 [Enter] mov ax,0002 [Enter] mov bx,0004 [Enter] add ax,bx [Enter] nop [Enter][Enter] What does the program do?, move the value 0002 to the ax register, move the value 0004 to the bx register, add the contents of the ax and bx registers, the instruction, no operation, to finish the program. In the debug program. After to do this, appear on the screen some like the follow lines: C:\> debug -a 100 0D62:0100 mov ax,0002 0D62:0103 mov bx,0004 0D62:0106 add ax,bx 0D62:0108 nop 0D62:0109 Type the command "t" (trace), to execute each instruction of this program, example: -t AX=0002 BX=0000 CX=0000 DX=0000 SP=FFEE BP=0000 SI=0000 DI=0000 DS=0D62 ES=0D62 SS=0D62 CS=0D62 IP=0103 NV EI PL NZ NA PO NC 0D62:0103 BB0400 MOV BX,0004 You see that the value 2 move to AX register. Type the command "t" (trace), again, and you see the second instruction is executed. -t AX=0002 BX=0004 CX=0000 DX=0000 SP=FFEE BP=0000 SI=0000 DI=0000 DS=0D62 ES=0D62 SS=0D62 CS=0D62 IP=0106 NV EI PL NZ NA PO NC 0D62:0106 01D8 ADD AX,BX Type the command "t" (trace) to see the instruction add is executed, you will see the follow lines: -t AX=0006 BX=0004 CX=0000 DX=0000 SP=FFEE BP=0000 SI=0000 DI=0000 DS=0D62 ES=0D62 SS=0D62 CS=0D62 IP=0108 NV EI PL NZ NA PE NC 0D62:0108 90 NOP The possibility that the registers contain different values exists, but AX and BX must be the same, since they are the ones we just modified. To exit Debug use the "q" (quit) command. Storing and loading the programs It would not seem practical to type an entire program each time it is needed, and to avoid this it is possible to store a program on the disk, with the enormous advantage that by being already assembled it will not be necessary to run Debug again to execute it. The steps to save a program that it is already stored on memory are: Obtain the length of the program subtracting the final address from the initial address, naturally in hexadecimal system. Give the program a name and extension. Put the length of the program on the CX register. Order Debug to write the program on the disk. By using as an example the following program, we will have a clearer idea of how to take these steps: When the program is finally assembled it would look like this: 0C1B:0100 mov ax,0002 0C1B:0103 mov bx,0004 0C1B:0106 add ax,bx 0C1B:0108 int 20 0C1B:010A To obtain the length of a program the "h" command is used, since it will show us the addition and subtraction of two numbers in hexadecimal. To obtain the length of ours, we give it as parameters the value of our program's final address (10A), and the program's initial address (100). The first result the command shows us is the addition of the parameters and the second is the subtraction. -h 10a 100 020a 000a The "n" command allows us to name the program. -n test.com The "rcx" command allows us to change the content of the CX register to the value we obtained from the size of the file with "h", in this case 000a, since the result of the subtraction of the final address from the initial address. -rcx CX 0000 :000a Lastly, the "w" command writes our program on the disk, indicating how many bytes it wrote. -w Writing 000A bytes To save an already loaded file two steps are necessary: Give the name of the file to be loaded. Load it using the "l" (load) command. To obtain the correct result of the following steps, it is necessary that the above program be already created. Inside Debug we write the following: -n test.com -l -u 100 109 0C3D:0100 B80200 MOV AX,0002 0C3D:0103 BB0400 MOV BX,0004 0C3D:0106 01D8 ADD AX,BX 0C3D:0108 CD20 INT 20 The last "u" command is used to verify that the program was loaded on memory. What it does is that it disassembles the code and shows it disassembled. The parameters indicate to Debug from where and to where to disassemble. Debug always loads the programs on memory on the address 100H, otherwise indicated. Assembler Programming • Building Assembler programs o Needed software o Assembler Programming • Assembly process o Segments o Table of symbols • More assembler programs • Types of instructions o Data movement o Logic and arithmetic operations o Jumps, loops and procedures ________________________________________ Building Assembler programs Needed software In order to be able to create a program, several tools are needed: First an editor to create the source program. Second a compiler, which is nothing more than a program that "translates" the source program into an object program. And third, a linker that generates the executable program from the object program. The editor can be any text editor at hand, and as a compiler we will use the TASM macro assembler from Borland, and as a linker we will use the Tlink program. The extension used so that TASM recognizes the source programs in assembler is .ASM; once translated the source program, the TASM creates a file with the .OBJ extension, this file contains an "intermediate format" of the program, called like this because it is not executable yet but it is not a program in source language either anymore. The linker generates, from a .OBJ or a combination of several of these files, an executable program, whose extension usually is .EXE though it can also be .COM, depending of the form it was assembled. Assembler Programming To build assembler programs using TASM programs is a different program structure than from using debug program. It's important to include the following assembler directives: .MODEL SMALL Assembler directive that defines the memory model to use in the program .CODE Assembler directive that defines the program instructions .STACK Assembler directive that reserves a memory space for program instructions in the stack END Assembler directive that finishes the assembler program Let's program First step use any editor program to create the source file. Type the following lines: First example ; use ; to put comments in the assembler program .MODEL SMALL ;memory model .STACK ;memory space for program instructions in the stack .CODE ;the following lines are program instructions mov ah,1h ;moves the value 1h to register ah mov cx,07h ;moves the value 07h to register cx int 10h ;10h interruption mov ah,4ch ;moves the value 4 ch to register ah int 21h ;21h interruption END ;finishes the program code This assembler program changes the size of the computer cursor. Second step Save the file with the following name: examp1.asm Don't forget to save this in ASCII format. Third step Use the TASM program to build the object program. Example: C:\>tasm exam1.asm Turbo Assembler Version 2.0 Copyright (c) 1988, 1990 Borland International Assembling file: exam1.asm Error messages: None Warning messages: None Passes: 1 Remaining memory: 471k The TASM can only create programs in .OBJ format, which are not executable by themselves, but rather it is necessary to have a linker which generates the executable code. Fourth step Use the TLINK program to build the executable program example: C:\>tlink exam1.obj Turbo Link Version 3.0 Copyright (c) 1987, 1990 Borland International C:\> Where exam1.obj is the name of the intermediate program, .OBJ. This generates a file directly with the name of the intermediate program and the .EXE extension. Fifth step Execute the executable program C:\>exam1[enter] Remember, this assembler program changes the size of the cursor. Assembly process. Segments The architecture of the x86 processors forces to the use of memory segments to manage the information, the size of these segments is of 64kb. The reason of being of these segments is that, considering that the maximum size of a number that the processor can manage is given by a word of 16 bits or register, it would not be possible to access more than 65536 localities of memory using only one of these registers, but now, if the PC's memory is divided into groups or segments, each one of 65536 localities, and we use an address on an exclusive register to find each segment, and then we make each address of a specific slot with two registers, it is possible for us to access a quantity of 4294967296 bytes of memory, which is, in the present day, more memory than what we will see installed in a PC. In order for the assembler to be able to manage the data, it is necessary that each piece of information or instruction be found in the area that corresponds to its respective segments. The assembler accesses this information taking into account the localization of the segment, given by the DS, ES, SS and CS registers and inside the register the address of the specified piece of information. It is because of this that when we create a program using the Debug on each line that we assemble, something like this appears: 1CB0:0102 MOV AX,BX Where the first number, 1CB0, corresponds to the memory segment being used, the second one refers to the address inside this segment, and the instructions which will be stored from that address follow. The way to indicate to the assembler with which of the segments we will work with is with the .CODE, .DATA and .STACK directives. The assembler adjusts the size of the segments taking as a base the number of bytes each assembled instruction needs, since it would be a waste of memory to use the whole segments. For example, if a program only needs 10kb to store data, the data segment will only be of 10kb and not the 64kb it can handle. |
Table of Symbols Each one of the parts on code line in assembler is known as token, for example on the code line: MOV AX,Var we have three tokens, the MOV instruction, the AX operator, and the VAR operator. What the assembler does to generate the OBJ code is to read each one of the tokens and look for it on an internal "*****alence" chart known as the reserved words chart, which is where all the mnemonic meanings we use as instructions are found. Following this process, the assembler reads MOV, looks for it on its chart and identifies it as a processor instruction. Likewise it reads AX and recognizes it as a register of the processor, but when it looks for the Var token on the reserved words chart, it does not find it, so then it looks for it on the symbols chart which is a table where the names of the variables, constants and labels used in the program where their addresses on memory are included and the sort of data it contains, are found. Sometimes the assembler comes on a token which is not defined on the program, therefore what it does in these cased is to pass a second time by the source program to verify all references to that symbol and place it on the symbols chart.There are symbols which the assembler will not find since they do not belong to that segment and the program does not know in what part of the memory it will find that segment, and at this time the linker comes into action, which will create the structure necessary for the loader so that the segment and the token be defined when the program is loaded and before it is executed. More assembler programs Another example First step use any editor program to create the source file. Type the following lines: ;example11 .model small .stack .code mov ah,2h ;moves the value 2h to register ah mov dl,2ah ;moves de value 2ah to register dl ;(Its the asterisk value in ASCII format) int 21h ;21h interruption mov ah,4ch ;4ch function, goes to operating system int 21h ;21h interruption end ;finishes the program code Second step Save the file with the following name: exam2.asm Don't forget to save this in ASCII format. Third step Use the TASM program to build the object program. C:\>tasm exam2.asm Turbo Assembler Version 2.0 Copyright (c) 1988, 1990 Borland International Assembling file: exam2.asm Error messages: None Warning messages: None Passes: 1 Remaining memory: 471k Fourth step Use the TLINK program to build the executable program C:\>tlink exam2.obj Turbo Link Version 3.0 Copyright (c) 1987, 1990 Borland International C:\> Fifth step Execute the executable program C:\>ejem11[enter] * C:\> This assembler program shows the asterisk character on the computer screen Types of instructions. Data movement In any program it is necessary to move the data in the memory and in the CPU registers; there are several ways to do this: it can copy data in the memory to some register, from register to register, from a register to a stack, from a stack to a register, to transmit data to external devices as well as vice versa. This movement of data is subject to rules and restrictions. The following are some of them: *It is not possible to move data from a memory locality to another directly; it is necessary to first move the data of the origin locality to a register and then from the register to the destiny locality. *It is not possible to move a constant directly to a segment register; it first must be moved to a register in the CPU. It is possible to move data blocks by means of the movs instructions, which copies a chain of bytes or words; movsb which copies n bytes from a locality to another; and movsw copies n words from a locality to another. The last two instructions take the values from the defined addresses by DS:SI as a group of data to move and EShttp://www.supermp3.org/images/smilies/biggrin.gifI as the new localization of the data. To move data there are also structures called batteries, where the data is introduced with the push instruction and are extracted with the pop instruction. In a stack the first data to be introduced is the last one we can take, this is, if in our program we use these instructions: PUSH AX PUSH BX PUSH CX To return the correct values to each register at the moment of taking them from the stack it is necessary to do it in the following order: POP CX POP BX POP AX For the communication with external devices the out command is used to send information to a port and the in command to read the information received from a port. The syntax of the out command is: OUT DX,AX Where DX contains the value of the port which will be used for the communication and AX contains the information which will be sent. The syntax of the in command is: IN AX,DX Where AX is the register where the incoming information will be kept and DX contains the address of the port by which the information will arrive. Logic and arithmetic operations The instructions of the logic operations are: and, not, or and xor. These work on the bits of their operators. To verify the result of the operations we turn to the cmp and test instructions. The instructions used for the algebraic operations are: to add, to subtract sub, to multiply mul and to divide div. Almost all the comparison instructions are based on the information contained in the flag register. Normally the flags of this register which can be directly handled by the programmer are the data direction flag DF, used to define the operations about chains. Another one which can also be handled is the IF flag by means of the sti and cli instructions, to activate and deactivate the interruptions. Jumps, loops and procedures The unconditional jumps in a written program in assembler language are given by the jmp instruction; a jump is to moves the flow of the execution of a program by sending the control to the indicated address. A loop, known also as iteration, is the repetition of a process a certain number of times until a condition is fulfilled. These loops are used. Assembler language instructions • Transfer instructions o MOV INSTRUCTION o MOVS (MOVSB) (MOVSW) Instruction • Loading instructions o LODS (LODSB) (LODSW) o LAHF o LDS o LEA o LES • Stack instructions o POP o POPF o PUSH o PUSHF • Logic instructions o AND o NEG o NOT o OR o TEST o XOR • Arithmetic instructions o ADC o ADD o DIV o IDIV o MUL o IMUL o SBB o SUB • Jump instructions • Instructions for cycles ( loops ) o LOOP o LOOPE o LOOPNE • Counting Instructions o DEC o INC • Comparison Instructions o CMP o CMPS (CMPSB) (CMPSW) • Flag Instructions ________________________________________ Transfer instructions They are used to move the contents of the operators. Each instruction can be used with different modes of addressing. MOV INSTRUCTION Purpose: Data transfer between memory cells, registers and the accumulator. Syntax: MOV Destiny, Source Where Destiny is the place where the data will be moved and Source is the place where the data is. The different movements of data allowed for this instruction are: *Destiny: memory. Source: accumulator *Destiny: accumulator. Source: memory *Destiny: segment register. Source: memory/register *Destiny: memory/register. Source: segment register *Destiny: register. Source: register *Destiny: register. Source: memory *Destiny: memory. Source: register *Destiny: register. Source: immediate data *Destiny: memory. Source: immediate data Example: MOV AX,0006h MOV BX,AX MOV AX,4C00h INT 21H This small program moves the value of 0006H to the AX register, then it moves the content of AX (0006h) to the BX register, and lastly it moves the 4C00h value to the AX register to end the execution with the 4C option of the 21h interruption. MOVS (MOVSB) (MOVSW) Instruction Purpose: To move byte or word chains from the source, addressed by SI, to the destiny addressed by DI. Syntax: MOVS This command does not need parameters since it takes as source address the content of the SI register and as destination the content of DI. The following sequence of instructions illustrates this: MOV SI, OFFSET VAR1 MOV DI, OFFSET VAR2 MOVS First we initialize the values of SI and DI with the addresses of the VAR1 and VAR2 variables respectively, then after executing MOVS the content of VAR1 is copied onto VAR2. The MOVSB and MOVSW are used in the same way as MOVS, the first one moves one byte and the second one moves a word. Loading instructions They are specific register instructions. They are used to load bytes or chains of bytes onto a register. LODS (LODSB) (LODSW) INSTRUCTION Purpose: To load chains of a byte or a word into the accumulator. |
Syntax: MOV Destiny, Source Where Destiny is the place where the data will be moved and Source is the place where the data is. The different movements of data allowed for this instruction are: *Destiny: memory. Source: accumulator *Destiny: accumulator. Source: memory *Destiny: segment register. Source: memory/register *Destiny: memory/register. Source: segment register *Destiny: register. Source: register *Destiny: register. Source: memory *Destiny: memory. Source: register *Destiny: register. Source: immediate data *Destiny: memory. Source: immediate data Example: MOV AX,0006h MOV BX,AX MOV AX,4C00h INT 21H This small program moves the value of 0006H to the AX register, then it moves the content of AX (0006h) to the BX register, and lastly it moves the 4C00h value to the AX register to end the execution with the 4C option of the 21h interruption. MOVS (MOVSB) (MOVSW) Instruction Purpose: To move byte or word chains from the source, addressed by SI, to the destiny addressed by DI. Syntax: MOVS This command does not need parameters since it takes as source address the content of the SI register and as destination the content of DI. The following sequence of instructions illustrates this: MOV SI, OFFSET VAR1 MOV DI, OFFSET VAR2 MOVS First we initialize the values of SI and DI with the addresses of the VAR1 and VAR2 variables respectively, then after executing MOVS the content of VAR1 is copied onto VAR2. The MOVSB and MOVSW are used in the same way as MOVS, the first one moves one byte and the second one moves a word. Loading instructions They are specific register instructions. They are used to load bytes or chains of bytes onto a register. LODS (LODSB) (LODSW) INSTRUCTION Purpose: To load chains of a byte or a word into the accumulator. Syntax: LODS This instruction takes the chain found on the address specified by SI, loads it to the AL (or AX) register and adds or subtracts , depending on the state of DF, to SI if it is a bytes transfer or if it is a words transfer. MOV SI, OFFSET VAR1 LODS The first line loads the VAR1 address on SI and the second line takes the content of that locality to the AL register. The LODSB and LODSW commands are used in the same way, the first one loads a byte and the second one a word (it uses the complete AX register). LAHF INSTRUCTION Purpose: It transfers the content of the flags to the AH register. Syntax: LAHF This instruction is useful to verify the state of the flags during the execution of our program. The flags are left in the following order inside the register: SF ZF ?? AF ?? PF ?? CF LDS INSTRUCTION Purpose: To load the register of the data segment Syntax: LDS destiny, source The source operator must be a double word in memory. The word associated with the largest address is transferred to DS, in other words it is taken as the segment address. The word associated with the smaller address is the displacement address and it is deposited in the register indicated as destiny. LEA INSTRUCTION Purpose: To load the address of the source operator Syntax: LEA destiny, source The source operator must be located in memory, and its displacement is placed on the index register or specified pointer in destiny. To illustrate one of the facilities we have with this command let us write an *****alence: MOV SI,OFFSET VAR1 Is *****alent to: LEA SI,VAR1 It is very probable that for the programmer it is much easier to create extensive programs by using this last format. LES INSTRUCTION Purpose: To load the register of the extra segment Syntax: LES destiny, source The source operator must be a double word operator in memory. The content of the word with the larger address is interpreted as the segment address and it is placed in ES. The word with the smaller address is the displacement address and it is placed in the specified register on the destiny parameter. Stack instructions These instructions allow the use of the stack to store or retrieve data. POP INSTRUCTION Purpose: It recovers a piece of information from the stack Syntax: POP destiny This instruction transfers the last value stored on the stack to the destiny operator, it then increases by 2 the SP register. This increase is due to the fact that the stack grows from the highest memory segment address to the lowest, and the stack only works with words, 2 bytes, so then by increasing by two the SP register, in reality two are being subtracted from the real size of the stack. POPF INSTRUCTION Purpose: It extracts the flags stored on the stack Syntax: POPF This command transfers bits of the word stored on the higher part of the stack to the flag register. The way of transference is as follows: BIT FLAG 0 CF 2 PF 4 AF 6 ZF 7 SF 8 TF 9 IF 10 DF 11 OF These localities are the same for the PUSHF command. Once the transference is done the SP register is increased by 2, diminishing the size of the stack. PUSH INSTRUCTION Purpose: It places a word on the stack. Syntax: PUSH source The PUSH instruction decreases by two the value of SP and then transfers the content of the source operator to the new resulting address on the recently modified register. The decrease on the address is due to the fact that when adding values to the stack, this one grows from the greater to the smaller segment address, therefore by subtracting 2 from the SP register what we do is to increase the size of the stack by two bytes, which is the only quantity of |
PUSHF INSTRUCTION Purpose: It places the value of the flags on the stack. Syntax: PUSHF This command decreases by 2 the value of the SP register and then the content of the flag register is transferred to the stack, on the address indicated by SP. The flags are left stored in memory on the same bits indicated on the POPF command. Logic instructions They are used to perform logic operations on the operators. AND INSTRUCTION Purpose: It performs the conjunction of the operators bit by bit. Syntax: AND destiny, source With this instruction the "y" logic operation for both operators is carried out: Source Destiny | Destiny ------------------------- 1 1 | 1 1 0 | 0 0 1 | 0 0 0 | 0 The result of this operation is stored on the destiny operator. NEG INSTRUCTION Purpose: It generates the complement to 2. Syntax: NEG destiny This instruction generates the complement to 2 of the destiny operator and stores it on the same operator. For example, if AX stores the value of 1234H, then: NEG AX This would leave the EDCCH value stored on the AX register. NOT INSTRUCTION Purpose: It carries out the negation of the destiny operator bit by bit. Syntax: NOT destiny The result is stored on the same destiny operator. OR INSTRUCTION Purpose: Logic inclusive OR Syntax: OR destiny, source The OR instruction carries out, bit by bit, the logic inclusive disjunction of the two operators: Source Destiny | Destiny ------------------------- 1 1 | 1 1 0 | 1 0 1 | 1 0 0 | 0 TEST INSTRUCTION Purpose: It logically compares the operators Syntax: TEST destiny, source It performs a conjunction, bit by bit, of the operators, but differing from AND, this instruction does not place the result on the destiny operator, it only has effect on the state of the flags. XOR INSTRUCTION Purpose: OR exclusive Syntax: XOR destiny, source Its function is to perform the logic exclusive disjunction of the two operators bit by bit. Source Destiny | Destiny ------------------------- 1 1 | 0 0 0 | 1 0 1 | 1 0 0 | 0 Arithmetic instructions They are used to perform arithmetic operations on the operators. ADC INSTRUCTION Purpose: Cartage addition Syntax: ADC destiny, source It carries out the addition of two operators and adds one to the result in case the CF flag is activated, this is in case there is carried. The result is stored on the destiny operator. ADD INSTRUCTION Purpose: Addition of the operators. Syntax: ADD destiny, source It adds the two operators and stores the result on the destiny operator. DIV INSTRUCTION Purpose: Division without sign. Syntax: DIV source The divider can be a byte or a word and it is the operator which is given the instruction. If the divider is 8 bits, the 16 bits AX register is taken as dividend and if the divider is 16 bits the even DX:AX register will be taken as dividend, taking the DX high word and AX as the low. If the divider was a byte then the quotient will be stored on the AL register and the residue on AH, if it was a word then the quotient is stored on AX and the residue on DX. IDIV INSTRUCTION Purpose: Division with sign. Syntax: IDIV source It basically consists on the same as the DIV instruction, and the only difference is that this one performs the operation with sign. For its results it used the same registers as the DIV instruction. MUL INSTRUCTION Purpose: Multiplication with sign. Syntax: MUL source The assembler assumes that the multiplicand will be of the same size as the multiplier, therefore it multiplies the value stored on the register given as operator by the one found to be contained in AH if the multiplier is 8 bits or by AX if the multiplier is 16 bits. When a multiplication is done with 8 bit values, the result is stored on the AX register and when the multiplication is with 16 bit values the result is stored on the even DX:AX register. IMUL INSTRUCTION Purpose: Multiplication of two whole numbers with sign. Syntax: IMUL source This command does the same as the one before, only that this one does take into account the signs of the numbers being multiplied. The results are kept in the same registers that the MOV instruction uses. SBB INSTRUCTION Purpose: Subtraction with cartage. Syntax: SBB destiny, source This instruction subtracts the operators and subtracts one to the result if CF is activated. The source operator is always subtracted from the destiny. This kind of subtraction is used when one is working with 32 bits quantities. SUB INSTRUCTION Purpose: Subtraction. Syntax: SUB destiny, source It subtracts the source operator from the destiny. Jump instructions They are used to transfer the flow of the process to the indicated operator. JMP INSTRUCTION Purpose: Unconditional jump. Syntax: JMP destiny This instruction is used to deviate the flow of a program without taking into account the actual conditions of the flags or of the data. JA (JNBE) INSTRUCTION Purpose: Conditional jump. Syntax: JA Label After a comparison this command jumps if it is or jumps if it is not down or if not it is the equal. This means that the jump is only done if the CF flag is deactivated or if the ZF flag is deactivated, that is that one of the two be equal to zero. JAE (JNB) INSTRUCTION Purpose: Conditional jump. Syntax: JAE label It jumps if it is or it is the equal or if it is not down. The jump is done if CF is deactivated. JB (JNAE) INSTRUCTION Purpose: Conditional jump. Syntax: JB label It jumps if it is down, if it is not , or if it is the equal. The jump is done if CF is activated. JBE (JNA) INSTRUCTION Purpose: Conditional jump. Syntax: JBE label It jumps if it is down, the equal, or if it is not . The jump is done if CF is activated or if ZF is activated, that any of them be equal to 1. JE (JZ) INSTRUCTION Purpose: Conditional jump. Syntax: JE label It jumps if it is the equal or if it is zero. The jump is done if ZF is activated. JNE (JNZ) INSTRUCTION Purpose: Conditional jump. Syntax: JNE label It jumps if it is not equal or zero. The jump will be done if ZF is deactivated. JG (JNLE) INSTRUCTION Purpose: Conditional jump, and the sign is taken into account. Syntax: JG label It jumps if it is larger, if it is not larger or equal. The jump occurs if ZF = 0 or if OF = SF. JGE (JNL) INSTRUCTION Purpose: Conditional jump, and the sign is taken into account. Syntax: JGE label It jumps if it is larger or less than, or equal to. The jump is done if SF = OF |
JL (JNGE) INSTRUCTION Purpose: Conditional jump, and the sign is taken into account. Syntax: JL label It jumps if it is less than or if it is not larger than or equal to. The jump is done if SF is different than OF. JLE (JNG) INSTRUCTION Purpose: Conditional jump, and the sign is taken into account. Syntax: JLE label It jumps if it is less than or equal to, or if it is not larger. The jump is done if ZF = 1 or if SF is defferent than OF. JC INSTRUCTION Purpose: Conditional jump, and the flags are taken into account. Syntax: JC label It jumps if there is cartage. The jump is done if CF = 1 JNC INSTRUCTION Purpose: Conditional jump, and the state of the flags is taken into account. Syntax: JNC label It jumps if there is no cartage. The jump is done if CF = 0. aysegul 09-22-2006, 12:18 AM JNO INSTRUCTION Purpose: Conditional jump, and the state of the flags is taken into account. Syntax: JNO label It jumps if there is no overflow. The jump is done if OF = 0. JNP (JPO) INSTRUCTION Purpose: Conditional jump, and the state of the flags is taken into account. Syntax: JNP label It jumps if there is no parity or if the parity is uneven. The jump is done if PF = 0. JNS INSTRUCTION Purpose: Conditional jump, and the state of the flags is taken into account. Syntax: JNP label It jumps if the sign is deactivated. The jump is done if SF = 0. JO INSTRUCTION Purpose: Conditional jump, and the state of the flags is taken into account. Syntax: JO label It jumps if there is overflow. The jump is done if OF = 1. JP (JPE) INSTRUCTION Purpose: Conditional jump, the state of the flags is taken into account. Syntax: JP label It jumps if there is parity or if the parity is even. The jump is done if PF = 1. JS INSTRUCTION Purpose: Conditional jump, and the state of the flags is taken into account. Syntax: JS label It jumps if the sign is on. The jump is done if SF = 1. Instructions for cycles ( loops ) They transfer the process flow, conditionally or unconditionally, to a destiny, repeating this action until the counter is zero. LOOP INSTRUCTION Purpose: To generate a cycle in the program. Syntax: LOOP label The loop instruction decreases CX on 1, and transfers the flow of the program to the label given as operator if CX is different than 1. LOOPE INSTRUCTION Purpose: To generate a cycle in the program considering the state of ZF. Syntax: LOOPE label This instruction decreases CX by 1. If CX is different to zero and ZF is equal to 1, then the flow of the program is transferred to the label indicated as operator. LOOPNE INSTRUCTION Purpose: To generate a cycle in the program, considering the state of ZF. Syntax: LOOPNE label This instruction decreases one from CX and transfers the flow of the program only if ZF is different to 0. Counting instructions They are used to decrease or increase the content of the counters. DEC INSTRUCTION Purpose: To decrease the operator. Syntax: DEC destiny This operation subtracts 1 from the destiny operator and stores the new value in the same operator. INC INSTRUCTION Purpose: To increase the operator. Syntax: INC destiny The instruction adds 1 to the destiny operator and keeps the result in the same destiny operator. Comparison instructions They are used to compare operators, and they affect the content of the flags. CMP INSTRUCTION Purpose: To compare the operators. Syntax: CMP destiny, source This instruction subtracts the source operator from the destiny operator but without this one storing the result of the operation, and it only affects the state of the flags. CMPS (CMPSB) (CMPSW) INSTRUCTION Purpose: To compare chains of a byte or a word. Syntax: CMP destiny, source With this instruction the chain of source characters is subtracted from the destiny chain. DI is used as an index for the extra segment of the source chain, and SI as an index of the destiny chain. It only affects the content of the flags and DI as well as SI are incremented. Flag instructions They directly affect the content of the flags. CLC INSTRUCTION Purpose: To clean the cartage flag. Syntax: CLC This instruction turns off the bit corresponding to the cartage flag, or in other words it puts it on zero. CLD INSTRUCTION Purpose: To clean the address flag. Syntax: CLD This instruction turns off the corresponding bit to the address flag. CLI INSTRUCTION Purpose: To clean the interruption flag. Syntax: CLI This instruction turns off the interruptions flag, disabling this way those maskarable interruptions. A maskarable interruptions is that one whose functions are deactivated when IF=0. CMC INSTRUCTION Purpose: To complement the cartage flag. Syntax: CMC This instruction complements the state of the CF flag, if CF = 0 the instructions equals it to 1, and if the instruction is 1 it equals it to 0. We could say that it only "inverts" the value of the flag. STC INSTRUCTION Purpose: To activate the cartage flag. Syntax: STC This instruction puts the CF flag in 1. STD INSTRUCTION Purpose: To activate the address flag. Syntax: STD The STD instruction puts the DF flag in 1. STI INSTRUCTION Purpose: To activate the interruption flag. Syntax: STI The instruction activates the IF flag, and this enables the maskarable external interruptions ( the ones which only function when IF = 1). Interruptions and file managing • Internal hardware interruptions • External hardware interruptions • Software interruptions • Most Common interruptions o Int 21H (DOS interruption) Multiple calls to DOS functions. o Int 10H (BIOS interruption) Video input/output. o Int 16H (BIOS interruption) Keyboard input/output. o Int 17H (BIOS interruption) Printer input/output. • Ways of working with Files • FCB method o Introduction o Open files o Create a new file o Sequential writing o Sequential reading o Random reading and writing o Close a file • Channels of communication o Working with handles o Functions to use handles _______________________________________ |
Internal hardware interruptions Internal interruptions are generated by certain events which come during the execution of a program. This type of interruptions are managed on their totality by the hardware and it is not possible to modify them. A clear example of this type of interruptions is the one which actualizes the counter of the computer internal clock, the hardware makes the call to this interruption several times during a second in order to maintain the time to date. Even though we cannot directly manage this interruption, since we cannot control the time dating by means of software, it is possible to use its effects on the computer to our benefit, for example to create a "virtual clock" dated continuously thanks to the clock's internal counter. We only have to write a program which reads the actual value of the counter and to translates it into an understandable format for the user. External hardware interruptions External interruptions are generated by peripheral devices, such as keyboards, printers, communication cards, etc. They are also generated by coprocessors. It is not possible to deactivate external interruptions. These interruptions are not sent directly to the CPU, but rather they are sent to an integrated circuit whose function is to exclusively handle this type of interruptions. The circuit, called PIC8259A, is controlled by the CPU using for this control a series of communication ways called paths. aysegul 09-22-2006, 12:19 AM Software interruptions Software interruptions can be directly activated by the assembler invoking the number of the desired interruption with the INT instruction. The use of interruptions helps us in the creation of programs, and by using them our programs are shorter, it is easier to understand them and they usually have a better performance mostly due to their smaller size. This type of interruptions can be separated in two categories: the operative system DOS interruptions and the BIOS interruptions. The difference between the two is that the operative system interruptions are easier to use but they are also slower since these interruptions make use of the BIOS to achieve their goal, on the other hand the BIOS interruptions are much faster but they have the disadvantage that since they are part of the hardware, they are very specific and can vary depending even on the brand of the maker of the circuit. The election of the type of interruption to use will depend solely on the characteristics you want to give your program: speed, using the BIOS ones, or portability, using the ones from the DOS. Most common interruptions 21H Interruption Purpose: To call on diverse DOS functions. Syntax: int 21H Note: When we work in TASM program is necessary to specify that the value we are using is hexadecimal. This interruption has several functions, to access each one of them it is necessary that the function number which is required at the moment of calling the interruption is in the AH register. Functions to display information to the video. 02H Exhibits output 09H Chain Impression (video) 40H Writing in device/file Functions to read information from the keyboard. 01H Input from the keyboard 0AH Input from the keyboard using buffer 3FH Reading from device/file Functions to work with files. In this section only the specific task of each function is exposed, for a reference about the concepts used, refer to unit 7, titled : "Introduction to file handling". FCB Method 0FH Open file 14H Sequential reading 15H Sequential writing 16H Create file 21H Random reading 22H Random writing Handles 3CH Create file 3DH Open file 3EH Close file driver 3FH Reading from file/device 40H Writing in file/device 42H Move pointer of reading/writing in file 02H FUNCTION Use: It displays one character to the screen. Calling registers: AH = 02H DL = Value of the character to display. Return registers: None. This function displays the character whose hexadecimal code corresponds to the value stored in the DL register, and no register is modified by using this command. The use of the 40H function is recommended instead of this function. 09H FUNCTION Use: It displays a chain of characters on the screen. Call registers: AH = 09H DShttp://www.supermp3.org/images/smilies/biggrin.gifX = Address of the beginning of a chain of characters. Return registers: None. This function displays the characters, one by one, from the indicated address in the DShttp://www.supermp3.org/images/smilies/biggrin.gifX register until finding a $ character, which is interpreted as the end of the chain. It is recommended to use the 40H function instead of this one. 40H FUNCTION Use: To write to a device or a file. Call registers: AH = 40H BX = Path of communication CX = Quantity of bytes to write DShttp://www.supermp3.org/images/smilies/biggrin.gifX = Address of the beginning of the data to write Return registers: CF = 0 if there was no mistake AX = Number of bytes written CF = 1 if there was a mistake AX = Error code The use of this function to display information on the screen is done by giving the BX register the value of 1 which is the preassigned value to the video by the operative system MS-DOS. 01H FUNCTION Use: To read a keyboard character and to display it. Call registers AH = 01H Return registers: AL = Read character It is very easy to read a character from the keyboard with this function, the hexadecimal code of the read character is stored in the AL register. In case it is an extended register the AL register will contain the value of 0 and it will be necessary to call on the function again to obtain the code of that character. 0AH FUNCTION Use: To read keyboard characters and store them on the buffer. Call registers: AH = 0AH DShttp://www.supermp3.org/images/smilies/biggrin.gifX = Area of storage address BYTE 0 = Quantity of bytes in the area BYTE 1 = Quantity of bytes read from BYTE 2 till BYTE 0 + 2 = read characters Return characters: None. The characters are read and stored in a predefined space on memory. The structure of this space indicate that in the first byte are indicated how many characters will be read. On the second byte the number of characters already read are stored, and from the third byte on the read characters are written. When all the indicated characters have been stored the speaker sounds and any additional character is ignored. To end the capture of the chain it is necessary to hit [ENTER]. 3FH FUNCTION Use: To read information from a device or file. Call registers: AH = 3FH BX = Number assigned to the device CX = Number of bytes to process DShttp://www.supermp3.org/images/smilies/biggrin.gifX = Address of the storage area Return registers: CF = 0 if there is no error and AX = number of read bytes. CF = 1 if there is an error and AX will contain the error code. FILE WORKING FUNCTIONS 0FH FUNCTION Use: To open an FCB file Call registers: AH = 0FH DShttp://www.supermp3.org/images/smilies/biggrin.gifX = Pointer to an FCB Return registers: AL = 00H if there was no problem, otherwise it returns to 0FFH 14H FUNCTION Use: To sequentially read an FCB file. Call registers: AH = 14H DShttp://www.supermp3.org/images/smilies/biggrin.gifX = Pointer to an FCB already opened. Return registers: AL = 0 if there were no errors, otherwise the corresponding error code will be returned: 1 error at the end of the file, 2 error on the FCB structure and 3 pa What this function does is that it reads the next block of information from the address given by DSX, and dates this register. 15H FUNCTION Use: To sequentially write and FCB file. Call registers: AH = 15H DSX = Pointer to an FCB already opened. Return registers: AL = 00H if there were no errors, otherwise it will contain the error code: 1 full disk or read-only file, 2 error on the formation or on the specification of The 15H function dates the FCB after writing the register to the present block. 16H FUNCTION Use: To create an FCB file. Call registers: AH = 16H DSX = Pointer to an already opened FCB. Return registers: AL = 00H if there were no errors, otherwise it will contain the 0FFH value. It is based on the information which comes on an FCB to create a file on a disk. 21H FUNCTION Use: To read in an random manner an FCB file. Call registers: AH = 21H DSX = Pointer to and opened FCB. Return registers: A = 00H if there was no error, otherwise AH will contain the code of the error: 1 if it is the end of file, 2 if there is an FCB specification error and 3 if This function reads the specified register by the fields of the actual block and register of an opened FCB and places the information on the DTA, Disk Transfer Area. 22H FUNCTION Use: To write in an random manner an FCB file. Call registers: AH = 22H DSX = Pointer to an opened FCB. Return registers: AL = 00H if there was no error, otherwise it will contain the error code: 1 if the disk is full or the file is an only read and 2 if there is an error on the It writes the register specified by the fields of the actual block and register of an opened FCB. It writes this information from the content of the DTA. 3CH FUNCTION Use: To create a file if it does not exist or leave it on 0 length if it exists, Handle. Call registers: AH = 3CH CH = File attribute DSX = Pointer to an ASCII specification. Return registers: CF = 0 and AX the assigned number to handle if there is no error, in case there is, CF ill be 1 and AX will contain the error code: 3 path not found, 4 there This function substitutes the 16H function. The name of the file is specified on an ASCII chain, which has as a characteristic being a conventional chain of bytes ended with a 0 character. The file created will contain the attributes defined on the CX register in the following manner: Value Attributes 00H Normal 02H Hidden 04H System 06H Hidden and of system The file is created with the reading and writing permissions. It is not possible to create directories using this function. 3DH FUNCTION Use: It opens a file and returns a handle. Call registers: AH = 3DH AL = manner of access DSX = Pointer to an ASCII specification Return registers: CF = 0 and AX = handle number if there are no errors, otherwise CF = 1 and AX = error code: 01H if the function is not valid, 02H if the file was not found, 03 The returned handled is 16 bits. The access code is specified in the following way: BITS 7 6 5 4 3 2 1 . . . . 0 0 0 Only reading . . . . 0 0 1 Only writing . . . . 0 1 0 Reading/Writing . . . x . . . RESERVED aysegul 09-22-2006, 12:19 AM 3EH FUNCTION Use: Close file (handle). Call registers: AH = 3EH BX = Assigned handle Return registers: CF = 0 if there were no mistakes, otherwise CF will be 1 and AX will contain the error code: 06H if the handle is invalid. This function dates the file and frees the handle it was using. 3FH FUNCTION Use: To read a specific quantity of bytes from an open file and store them on a specific buffer. 10h Interruption |
rpose: To call on diverse BIOS video function Syntax: int 10H This interruption has several functions, all of them control the video input/output, to access each one of them it is necessary that the function number which is required at the moment of calling the interruption is in the Ah register. In this tutorial we will see some functions of the 10h interruption. Common functions of the 10h interruption 02H Function, select the cursor position 09H Function, write attribute and character of the cursor 0AH Function, write a character in the cursor position 0EH Function, Alphanumeric model of the writing characters 02h Function Use: Moves the cursor on the computer screen using text model. Call registers: AH = 02H BH = Video page where the cursor is positioned. DH = row DL = Column Return Registers: None. The cursor position is defined by its coordinates, starting from the position 0,0 to position 79,24. This means from the left per computer screen corner to right lower computer screen. Therefore the numeric values that the DH and DL registers get in text model are: from 0 to 24 for rows and from 0 to 79 for columns. 09h Function Use: Shows a defined character several times on the computer screen with a defined attribute, starting with the actual cursor position. Call registers: AH = 09H AL = Character to display BH = Video page, where the character will display it; BL = Attribute to use number of repetition. Return registers: None This function displays a character on the computer screen several times, using a specified number in the CX register but without changing the cursor position on the computer screen. 0Ah Function Use: Displays a character in the actual cursor position. Call registers: AH = 0AH AL = Character to display BH = Video page where the character will display it BL = Color to use (graphic mode only). CX = number of repetitions Return registers: None. The main difference between this function and the last one is that this one doesn't allow modifications on the attributes neither does it change the cursor position. 0EH Function Use: Displays a character on the computer screen dates the cursor position. Call registers: AH = 0EH AL = Character to display BH = Video page where the character will display it BL = Color to use (graphic mode only). Return registers: None 16H interruption We will see two functions of the 16 h interruption, these functions are called by using the AH register. Functions of the 16h interruption 00H Function, reads a character from the keyboard. 01H Function, reads the keyboard state. 00H Function Use: Reads a character from the keyboard. Call registers: AH = 00H Return registers: AH = Scan code of the keyboard AL = ASCII value of the character When we use this interruption, the program executing is halted until a character is typed, if this is an ASCII value; it is stored in the Ah register, Else the scan code is stored in the AL register and the AH register contents the value 00h. The proposal of the scan code is to use it with the keys without ASCII representation as [ALT][CONTROL], the function keys and so on. 01h function Use: Reads the keyboard state Call registers: AH = 01H Return registers: If the flag register is zero, this means, there is information on the buffer memory, else, there is no information in the buffer memory. Therefore the value of the Ah register will be the value key stored in the buffer memory. 17H Interruption Purpose: Handles the printer input/output. Syntax: Int 17H This interruption is used to write characters on the printer, sets printer and reads the printer state. Functions of the 16h interruptions 00H Function, prints value ASCII out 01H Function, sets printer 02H Function, the printer state 00H Function Use: Writes a character on the printer. Call registers: AH = 00H AL = Character to print. DX = Port to use. Return registers: AH = Printer device state. The port to use is in the DX register, the different values are: LPT1 = 0, LPT2 = 1, LPT3 = 2 ... The printer device state is coded bit by bit as follows: BIT 1/0 MEANING --------------- 0 1 The waited time is over 1 - 2 - 3 1 input/output error 4 1 Chosen printer 5 1 out-of-paper 6 1 communication recognized 7 1 The printer is ready to use 1 and 2 bits are not relevant Most BIOS sport 3 parallel ports, although there are BIOS which sport 4 parallel ports. 01h Function Use: Sets parallel port. Call registers: AH = 01H DX = Port to use Return registers: AH = Printer status Port to use is defined in the DX register, for example: LPT=0, LPT2=1, and so on. The state of the printer is coded bit by bit as follows: BIT 1/0 MEANING --------------- 0 1 The waited time is over 1 - 2 - 3 1 input/output error 4 1 Chosen printer 5 1 out-of-paper 6 1 communication recognized 7 1 The printer is ready to use 1 and 2 bits are not relevant Most BIOS sport 3 parallel ports, although there are BIOS which sport 4 parallel ports. 02h Function Uses: Gets the printer status. Call registers: AH = 01H DX = Port to use Return registers AH = Printer status. Port to use is defined in the DX register, for example: LPT=0, LPT2=1, and so on The state of the printer is coded bit by bit as follows: BIT 1/0 MEANING --------------- 0 1 The waited time is over 1 - 2 - 3 1 input/output error 4 1 Chosen printer 5 1 out-of-paper 6 1 communication recognized 7 1 The printer is ready to use 1 and 2 bits are not relevant Most BIOS sport 3 parallel ports, although there are BIOS which sport 4 parallel ports. Ways of working with files There are two ways to work with files, the first one is by means of file control blocks or "FCB" and the second one is by means of communication channels, also known as "handles". The first way of file handling has been used since the CPM operative system, predecessor of DOS, thus it assures certain compatibility with very old files from the CPM as well as from the 1.0 version of the DOS, besides this method allows us to have an unlimited number of open files at the same time. If you want to create a volume for the disk the only way to achieve this is by using this method. Even after considering the advantages of the FCB, the use of the communication channels it is much simpler and it allows us a better handling of errors, besides, since it is much newer it is very probable that the files created this way maintain themselves compatible through later versions of the operative system. For a greater facility on later explanations I will refer to the file control blocks as FCBs and to the communication channels as handles. |
FCB method Introduction There are two types of FCB, the normal, whose length is 37 bytes and the extended one of 44 bytes.On this tutorial we will only deal with the first type, so from now on whenI refer to an FCB, I am really talking about a 37 bytes FCB. The FCB is composed of information given by the programmer and by information which it takes directly from the operative system. When thesetypes of files are used it is only possible to work on the current directory since the FCBs do not provide sport for the use of the organization by directories of DOS. The FCB is formed by the following fields: POSITION LENGTH MEANING 00H 1 Byte Drive 01H 8 Bytes File name 09H 3 Bytes Extension 0CH 2 Bytes Block number 0EH 2 Bytes Register size 10H 4 Bytes File size 14H 2 Bytes Creation date 16H 2 Bytes Creation hour 18H 8 Bytes Reserved 20H 1 Bytes Current register 21H 4 Bytes Random register To select the work drive the next format is followed: drive A = 1; drive B = 2; etc. If 0 is used the drive being used at that moment will be taken as option. The name of the file must be justified to the left and in case it is necessary the remaining bytes will have to be filled with spaces, and the extension of the file is placed the same way. The current block and the current register tell the computer which register will be accessed on reading or writing operations. A block is a gro of 128 registers. The first block of the file is the block 0. The first register is the register 0, therefore the last register of the first block would be the 127, since the numbering started with 0 and the block can contain 128 registers in total. Opening files To open an FCB file the 21H interruption, 0FH function is used. The unit, the name and extension of the file must be initialized before opening it. The DX register must point to the block. If the value of FFH is returned on the AH register when calling on the interruption then the file was not found, if everything came out well a value of 0 will be returned. If the file is opened then DOS initializes the current block to 0, the size of the register to 128 bytes and the size of the same and its date are filled with the information found in the directory. Creating a new file For the creation of files the 21H interruption 16H function is used. DX must point to a control structure whose requirements are that at least the logic unit, the name and the extension of the file be defined. In case there is a problem the FFH value will be returned on AL, otherwise this register will contain a value of 0. Sequential writing Before we can perform writing to the disk it is necessary to define the data transfer area using for this end the 1AH function of the 21H interruption. The 1AH function does not return any state of the disk nor or the operation, but the 15H function, which is the one we will use to write to the disk, does it on the AL register, if this one is equal to zero there was no error and the fields of the current register and block are dated. Sequential reading Before anything we must define the file transfer area or DTA. In order to sequentially read we use the 14H function of the 21H interruption. The register to be read is the one which is defined by the current block and register. The AL register returns to the state of the operation, if AL contains a value of 1 or 3 it means we have reached the end of the file. A value of 2 means that the FCB is wrongly structured. In case there is no error, AL will contain the value of 0 and the fields of the current block and register are dated. Random reading and writing The 21H function and the 22H function of the 21H interruption are the ones in charge of realizing the random readings and writings respectively. The random register number and the current block are used to calculate the relative position of the register to read or write. The AL register returns the same information for the sequential reading of writing. The information to be read will be returned on the transfer area of the disk, likewise the information to be written resides on the DTA. Closing a file To close a file we use the 10H function of the 21H interruption. If after invoking this function, the AL register contains the FFH value, this means that the file has changed position, the disk was changed or there is error of disk access. Channels of communication Working with handles The use of handles to manage files greatly facilitates the creation of files and programmer can concentrate on other aspects of the programming without worrying on details which can be handled by the operative system. The easy use of the handles consists in that to operate o a file, it is only necessary to define the name of the same and the number of the handle to use, all the rest of the information is internally handled by the DOS. When we use this method to work with files, there is no distinction between sequential or random accesses, the file is simply taken as a chain of bytes. Functions to use handles The functions used for the handling of files through handles are described in unit 6: Interruptions, in the section dedicated to the 21H interruption. Macros and procedures • Procedures • Macros o Definition of a macro o Syntax of a macro o Macro libraries ________________________________________ Procedure Definition of procedure A procedure is a collection of instructions to which we can direct the flow of our program, and once the execution of these instructions is over control is given back to the next line to process of the code which called on the procedure. Procedures help us to create legible and easy to modify programs. At the time of invoking a procedure the address of the next instruction of the program is kept on the stack so that, once the flow of the program has been transferred and the procedure is done, one can return to the next line of the original program, the one which called the procedure. Syntax of a Procedure There are two types of procedures, the intrasegments, which are found on the same segment of instructions, and the inter-segments which can be stored on different memory segments. When the intrasegment procedures are used, the value of IP is stored on the stack and when the intrasegments are used the value of CS:IP is stored. To divert the flow of a procedure (calling it), the following directive is used: CALL NameOfTheProcedure The part which make a procedure are: Declaration of the procedure Code of the procedure Return directive Termination of the procedure For example, if we want a routine which adds two bytes stored in AH and AL each one, and keep the addition in the BX register: Adding Proc Near ; Declaration of the procedure Mov Bx, 0 ; Content of the procedure Mov B1, Ah Mov Ah, 00 Add Bx, Ax Ret ; Return directive Add Endp ; End of procedure declaration On the declaration the first word, Adding, corresponds to the name of out procedure, Proc declares it as such and the word Near indicates to the MASM that the procedure is intrasegment. The Ret directive loads the IP address stored on the stack to return to the original program, lastly, the Add Endp directive indicates the end of the procedure. To declare an inter segment procedure we substitute the word Near for the word FAR. The calling of this procedure is done the following way: Call Adding Macros offer a greater flexibility in programming compared to the procedures, nonetheless, these last ones will still be used. Macros Definition of the macro A macro is a gro of repetitive instructions in a program which are codified only once and can be used as many times as necessary. The main difference between a macro and a procedure is that in the macro the passage of parameters is possible and in the procedure it is not, this is only applicable for the TASM - there are other programming languages which do allow it. At the moment the macro is executed each parameter is substituted by the name or value specified at the time of the call. We can say then that a procedure is an extension of a determined program, while the macro is a module with specific functions which can be used by different programs. Another difference between a macro and a procedure is the way of calling each one, to call a procedure the use of a directive is required, on the other hand the call of macros is done as if it were an assembler instruction. Syntax of a Macro The parts which make a macro are: Declaration of the macro Code of the macro Macro termination directive The declaration of the macro is done the following way: NameMacro MACRO [parameter1, parameter2...] Even though we have the functionality of the parameters it is possible to create a macro which does not need them. The directive for the termination of the macro is: ENDM An example of a macro, to place the cursor on a determined position on the screen is: Position MACRO Row, Column PUSH AX PUSH BX PUSH DX MOV AH, 02H MOV DH, Row MOV DL, Column MOV BH, 0 INT 10H POP DX POP BX POP AX ENDM To use a macro it is only necessary to call it by its name, as if it were another assembler instruction, since directives are no longer necessary as in the case of the procedures. Example: Position 8, 6 Macro Libraries |
One of the facilities that the use of macros offers is the creation of libraries, which are groups of macros which can be included in a program from a different file. The creation of these libraries is very simple, we only have to write a file with all the macros which will be needed and save it as a text file. To call these macros it is only necessary to use the following instruction Include NameOfTheFile, on the part of our program where we would normally write the macros, this is, at the beginning of our program, before the declaration of the memory model. The macros file was saved with the name of MACROS.TXT, the instruction Include would be used the following way: ;Beginning of the program Include MACROS.TXT .MODEL SMALL .DATA ;The data goes here .CODE Beginning: ;The code of the program is inserted here .STACK ;The stack is defined End beginning ;Our program ends ________________________________________ Program Examples In this section we provide you several assembler programs to run in the debug program. You can execute each assembler program using the "t" (trace) command, to see what each instruction does. Also you will find some examples using Assembler Program (TASM) • Debug Program Examples o Example 1 o Example 2 o Example 3 o Example 4 o Example 5 o Example 6 o Example 7 o Example 8 o Example 9 o Example 10 o Example 11 • Assembler Program Examples o Example 1 o Example 2 o Example 3 o Example 4 o Example 5 o Example 6 ________________________________________ Debug Program Examples First example The only thing that this program does is to save two values in two registers and add the value of one to the other. -a0100 297D:0100 MOV AX,0006 ; Puts value 0006 at register AX 297D:0103 MOV BX,0004 ;Puts value 0004 at register BX 297D:0106 ADD AX,BX ;Adds BX to AX contents 297D:0108 INT 20 ;Causes end of the Program Second example This program displays on the screen 15 times a character string. - a100 0C1B:0100 jmp 125 ; Jumps to direction 125H 0C1B:0102 [Enter] - e 102 'Hello, How are you ?' 0d 0a '$' - a125 0C1B:0125 MOV DX,0102 ; Copies string to DX register 0C1B:0128 MOV CX,000F ; Times the string will be displayed 0C1B:012B MOV AH,09 ; Copies 09 value to AH register 0C1B:012D INT 21 ; Displays string 0C1B:012F DEC CX ; Reduces in 1 CX 0C1B:0130 JCXZ 0134 ; If CX is equal to 0 jumps to 0134 0C1B:0132 JMP 012D ; Jumps to direction 012D 0C1B:0134 INT 20 ; Ends the program Third example This program is good for changing the form of the cursor. -a100 297D:0100 MOV AH,01 ;Function to change the cursor 297D:0102 MOV CX,0007 ;Forms the cursor 297D:0105 INT 10 ;Calls for BIOS 297D:0107 INT 20 ;Ends the program Fourth example This program uses DOS 21H interruption. It uses two functions of the same: the first one reads the keyboard (function 1) and the second one writes on the screen. It reads the keyboard characters until it finds a carriage return. -a100 297D:0100 MOV AH,01 ; Funtion 1 (reads keyboard) 297D:0102 INT 21 ; Calls for DOS 297D:0104 CMP AL,0D ; Compares if what is read is a carriage return 297D:0106 JNZ 0100 ; If it is not, reads another character 297D:0108 MOV AH,02 ; Funtion 2 (writes on the screen) 297D:010A MOV DL,AL ; Character to write on AL 297D:010C INT 21 ; Calls for DOS 297D:010E INT 20 ; Ends the program Fifth example This program displays on the screen a binary number through a conditional cycle (LOOP) using byte rotation. -a100 297D:0100 MOV AH,02 ; Function 2 (writes on the screen) 297D:0102 MOV CX,0008 ; Puts value 0008 on register CX 297D:0105 MOV DL,00 ; Puts value 00 on register DL 297D:0107 RCL BL,1 ; Rotates the byte in BL to the left by one bit through the ;carry flag 297D:0109 ADC DL,30 ; Converts flag register to1 297D:010C INT 21 ; Calls for DOS 297D:010E LOOP 0105 ; Jumps if CX > 0 to direction 0105 297D:0110 INT 20 ; Ends the program Sixth example This program prints a zero value on hex digits -a100 297D:0100 MOV AH,02 ; Function 2 (writes on the screen) 297D:0102 MOV DL,BL ; Puts BL's value on DL 297D:0104 ADD DL,30 ; Adds value 30 to DL 297D:0107 CMP DL,3A ; Compares 3A value with DL's contents without affecting ; its value only modifying the state of the car 297D:010A JL 010F ; jumps if 297D:010C ADD DL,07 ; Adds 07 value on DL 297D:010F INT 21 ; Calls for Dos 297D:0111 INT 20 ; Ends the Program Seventh example This program is used to print two digit hex numbers. -a100 297D:0100 MOV AH,02 ; Function 2 (writes on the screen) 297D:0102 MOV DL,BL ; Puts BL value on DL 297D:0104 AND DL,0F ; Carries ANDing numbers bit by bit 297D:0107 ADD DL,30 ; Adds 30 to Dl 297D:010A CMP DL,3A ; Compares Dl with 3A 297D:010D JL 0112 ; Jumps if <0112 direction 297D:010F ADD DL, 07 ; Adds 07 to DL 297D:0112 INT 21 ; Calls for Dos 297D:0114 INT 20 ;Ends the program Eight example This program works for printing the first of two digit hex numbers -a100 297D:0100 MOV AH,02 ; Function 2 (writes on the screen) 297D:0102 MOV DL,BL ; Puts BL value on DL 297D:0104 MOV CL,04 ; Puts 04 value on CL 297D:0106 SHR DL,CL ; Moves per four bits of your number to the rightmost ;nibble 297D:0108 ADD DL,30 ; Adds 30 to DL 297D:010B CMP DL,3A ; Compares Dl with 3A 297D:010E JL 0113 ; Jumps if <0113 direction 297D:0110 ADD DL,07 ; Adds 07 to DL 297D:0113 INT 21 ; Calls for Dos 297D:0115 INT 20 ; Ends the program Ninth example This program works for printing the second of two digit hex numbers -a100 297D:0100 MOV AH,02 ; Function 2 (writes on the screen) 297D:0102 MOV DL,BL ; Puts BL value on DL 297D:0104 MOV CL,04 ; Puts 04 value on CL 297D:0106 SHR DL,CL ; Moves per four bits of your number to the rightmost ;nibble 297D:0108 ADD DL,30 ; Adds 30 to DL 297D:010B CMP DL,3A ; Compares Dl with 3A 297D:010E JL 0113 ; Jumps if <0113 direction 297D:0110 ADD DL,07 ; Adds 07 to DL 297D:0113 INT 21 ; Calls for Dos 297D:0115 MOV DL,BL ; Puts Bl value on DL 297D:0117 AND DL,0F ; Carries ANDing numbers bit by bit 297D:011A ADD DL,30 ; Adds 30 to DL 297D:011D CMP DL,3A ; Compares Dl with 3A 297D:0120 JL 0125 ; Jumps if <125 direction 297D:0122 ADD DL,07 ; Adds 07 to DL 297D:0125 INT 21 ; Calls for Dos 297D:0127 INT 20 ; Ends the Program Tenth example This program can read two digit hex numbers -a100 297D:0100 MOV AH,01 ; Function 1 (reads keyboard) 297D:0102 INT 21 ; Calls for Dos 297D:0104 MOV DL,AL ; Puts Al value on DL 297D:0106 SUB DL,30 ; Subtracts 30 from DL 297D:0109 CMP DL,09 ; Compares DL with 09 297D:010C JLE 0111; Jumps if <= 0111 direction 297D:010E SUB DL,07 ; Subtracts 07 from DL 297D:0111 MOV CL,04 ; Puts 04 value on CL register 297D:0113 SHL DL,CL ; It inserts zeros to the right 297D:0115 INT 21 ; Calls for Dos 297D:0117 SUB AL,30 ; Subtracts 30 from AL 297D:0119 CMP AL,09 ; Compares AL with 09 297D:011B JLE 011F ; Jumps if <= 011f direction 297D:011D SUB AL,07 ; Subtracts 07 from AL 297D:011F ADD DL,AL ; Adds Al to DL 297D:0121 INT 20 ; Ends the Program Eleventh example This program keeps reading characters until it receives one that can be converted to a hex number -a100 297D:0100 CALL 0200 ; Calls for a procedure 297D:0103 INT 20 ;Ends the program -a200 297D:0200 PUSH DX ; Puts DX value on the stack 297D:0201 MOV AH,08 ; Function 8 297D:0203 INT 21 ; Calls for Dos 297D:0205 CMP AL,30 ; Compares AL with 30 297D:0207 JB 0203 ; Jumps if CF is activated towards 0203 direction 297D:0209 CMP AL,46 ; Compares AL with 46 297D:020B JA 0203 ; jumps if 0203 direction 297D:020D CMP AL,39 ; Compares AL with 39 297D:020F JA 021B ; Jumps if 021B direction 297D:0211 MOV AH,02 ; Function 2 (writes on the screen) 297D:0213 MOV DL,AL ; Puts Al value on DL 297D:0215 INT 21 ; Calls for Dos 297D:0217 SUB AL,30 ; Subtracts 30 from AL 297D:0219 POP DX ; Takes DX value out of the stack 297D:021A RET ; Returns control to the main program 297D:021B CMP AL,41 ; Compares AL with 41 297D:021D JB 0203 ; Jumps if CF is activated towards 0203 direction 297D:021F MOV AH,02 ; Function 2 (writes on the screen) 297D:022 MOV DL,AL ; Puts AL value on DL 297D:0223 INT 21 ; Calls for Dos 297D:0225 SUB AL,37 ; Subtracts 37 from AL 297D:0227 POP DX ; Takes DX value out of the stack 297D:0228 RET ; Returns control to the main program aysegul 09-22-2006, 12:20 AM Assembler programs Examples( using TASM program) Example 1 This program reads two characters from the keyboard and prints them on the screen. ;name of the program: one.asm ; .model small .stack .code mov AH,1h ;Selects the 1 DOS. function Int 21h ;reads character and return ASCII code to register AL mov DL,AL ;moves the ASCII code to register DL sub DL,30h ;makes the operation minus 30h to convert 0-9 digit number cmp DL,9h ;compares if digit number it was between 0-9 jle digit1 ;If it true gets the first number digit (4 bits long) sub DL,7h ;If it false, makes operation minus 7h to convert letter A-F digit1: mov CL,4h ;prepares to multiply by 16 shl DL,CL ; multiplies to convert into four bits upper int 21h ;gets the next character sub AL,30h ;repeats the conversion operation cmp AL,9h ;compares the value 9h with the content of register AL jle digit2 ;If true, gets the second digit number sub AL,7h ;If no, makes the minus operation 7h digit2: add DL,AL ;adds the second number digit mov AH,4CH Int 21h ;21h interruption End ;finishes the program code Example 2 This program prints the a character through j character on the screen ;name the program: two.asm .model small .stack .code PRINT_A_J PROC MOV DL,'A' ;moves the A character to register DL MOV CX,10 ;moves the decimal value 10 to register cx ;This number value its the time to print out after the A ;character PRINT_LOOP: CALL WRITE_CHAR ;Prints A character out INC DL ;Increases the value of register DL LOOP PRINT_LOOP ;Loop to print out ten characters MOV AH,4Ch ;4Ch function of the 21h interruption INT 21h ;21h interruption PRINT_A_J ENDP ;Finishes the procedure WRITE_CHAR PROC MOV AH,2h ;2h function of the 21 interruption INT 21h ;Prints character out from the register DL RET ;Returns the control to procedure called WRITE_CHAR ENDP ;Finishes the procedure END PRINT_A_J ;Finishes the program code Example 3 This program prints a predefined value on the screen ;name of the program: three.asm .model small .STACK .code TEST_WRITE_HEX PROC MOV DL,3Fh ;moves the value 3Fh to the register DL CALL WRITE_HEX ;Calls the procedure MOV AH,4CH ;4Ch function INT 21h ;Returns the control to operating system TEST_WRITE_HEX ENDP ;Finishes the procedure PUBLIC WRITE_HEX ;................................................. .......; ; This procedure converts into hexadecimal number the byte ; is in the register DL and show the digit number; ; Use:WRITE_HEX_DIGIT ; ;................................................. .......; WRITE_HEX PROC PUSH CX ;pushes the value of the register CX to the stack memory PUSH DX ;pushes the value of the register DX to the stack memory MOV DH,DL ;moves the value of the register DL to register DH MOV CX,4 ;moves the value numeric 4 to register CX SHR DL,CL CALL WRITE_HEX_DIGIT ;shows on the computer screen, the first ;hexadecimal number MOV DL,DH ;moves the value of the register DH to the register DL AND DL,0Fh ;ANDing the upper bit CALL WRITE_HEX_DIGIT ; shows on the computer screen, the second ;hexadecimal number POP DX ;pops the value of the register DX to register DX POP CX ; pops the value of the register DX to register DX RET ;Returns the control of the procedure called WRITE_HEX ENDP PUBLIC WRITE_HEX_DIGIT ;................................................. ...............; ; This procedure converts the lower 4 bits of the register ; DL into hexadecimal ; number and show them in the computer screen ; ; Use: WRITE_CHAR ; ;................................................. ...............; WRITE_HEX_DIGIT PROC PUSH DX ;Pushes the value of the register DX in the stack memory CMP DL,10 ;compares if the bit number is minus than number ten JAE HEX_LETTER ;No , jumps HEX_LETER ADD DL,"0" ;yes, it converts into digit number JMP Short WRITE_DIGIT ;writes the character HEX_LETTER: ADD DL,"A"-10 ;converts a character into hexadecimal number WRITE_DIGIT: CALL WRITE_CHAR ;shows the character in the computer screen POP DX ;Returns the initial value of the register DX to register DL RET ;Returns the control of the procedure called WRITE_HEX_DIGIT ENDP |
PUBLIC WRITE_CHAR ;................................................. ...............; ;This procedure shows the character in the computer screen using the DOS. ;................................................. ...............; WRITE_CHAR PROC PUSH AX ;pushes the value of the register AX in the stack memory MOV AH,2 ;2h Function INT 21h ;21h Interruption POP AX ;Pops the initial value of the register AX to the register AX RET ;Returns the control of the procedure called WRITE_CHAR ENDP END TEST_WRITE_HEX ;finishes the program code Example 4 This program prints the 256 ASCII code on the screen ;name of the program: four.asm .model small .stack .code PRINT_ASCII PROC MOV DL,00h ;moves the value 00h to register DL MOV CX,255 ;moves the value decimal number 255. this decimal number will be 255 times to print out after the character A PRINT_LOOP: CALL WRITE_CHAR ;Prints the characters out INC DL ;Increases the value of the register DL content LOOP PRINT_LOOP ;Loop to print out ten characters MOV AH,4Ch ;4Ch function INT 21h ;21h Interruption PRINT_ASCII ENDP ;Finishes the procedure WRITE_CHAR PROC MOV AH,2h ;2h function to print character out INT 21h ;Prints out the character in the register DL RET ;Returns the control to the procedure called WRITE_CHAR ENDP ;Finishes the procedure END PRINT_ASCII ;Finishes the program code Example 5 This program prints a defined character using an ASCII code on the screen. dosseg .model small ; the name of the program is five.asm .stack .code write proc mov ah,2h; mov dl,2ah; int 21h mov ah,4ch int 21h write endp end write Example 6 This program reads characters form the keyboard and prints them on the screen until find the return character. .model small; the name of the program is six.asm .stack; .code; EEL: MOV AH,01 ; 1 function (reads one character from the keyboard) INT 21h ; 21h interruption CMP AL,0Dh ; compares the value with 0dh JNZ EEL ;jumps if no equal of the label eel MOV AH,2h ; 2 function (prints the character out on the screen) MOV DL,AL ;moves the value of the register AL to the register DL INT 21h ;21 interruption MOV AH,4CH ;4C function (returns the control to the DOS. operating system) INT 21h ;21 interruption END ;finishes the program |
VERİ İŞLEME KOMUTLARI Veri işleme komutları iki bölüme ayrılır: Aritmetik ve lojik komutlardır. Bu komutlar bayrakları etkiler. Aşağıda bu komutlar örneklerle anlatılmaktadır. Aritmetik Komutlar Tablosu Aşağıdaki tabloda 8051 ailesinin aritmetik komutlarını özetlemektedir. Bu tablodaki bir çok komut, Saklayıcı-Özel adresleme modunu kullanmaktadır. Gösterim İşlem Adresleme Modları Dir Ind Reg Imm ADD A,<byte> A=A+<byte> X X X X ADDC A,<byte> A=A+<byte>+C X X X X SUBB A,<byte> A=A-<byte>-C X X X X INC A A=A+1 Sak.Özel(Sadece ACC) INC <byte> <byte>=<byte>+1 X X X INC DPTR DPTR=DPTR+1 Sak.Özel(Sadece DPTR) DEC A A=A-1 Sak.Özel(Sadece ACC) DEC <byte> <byte>=<byte>-1 X X X MUL AB B:A=B*A Sak.Özel(Sadece ACC ve B) DIV AB A=Int (A/B) B=Mod(A/B) Sak.Özel(Sadece ACC ve B) DA A Ondalık Ayar Sak.Özel(Sadece ACC) Toplama ve Çıkarma Komutları İki tane toplama komutu vardır. ADD ve ADDC (C-elde ile topla). Her iki komut 2 byte değişkenin toplama işlemini gerçekleştirmektedir. Birinci operand her zaman ACC'dedir. İkinci operand, doğrudan, dolaylı, saklayıcı veya ivedi adresleme modları ile belirtilir. Bir ADD ve ADDC işlemlerinden sonra, bayraklardan üçü (C,AC ve OV) sonuca göre 1'lenir Veya 0'lanır. ADDC komutu, C bayrağının sonuna eklenmesi farkının dışında, ADD komutu gibidir. ADDC komutu, özellikle uzun tamsayı toplamalarında kullanılır. Yukarıdaki tabloda ve aşağıda verilen program örneğinde, iki 16-bit X ve Y tamsayılarının toplama işleminde (X=X+Y), ADD ve ADDC komutlarının kullanımı gösterilmektedir. Her iki sayı, 8-bit düşük (XL ve YL) ve yüksek değeri (XH ve YH) byte'lar olarak işleme alınmaktadır. C ADDC ADD X Y + İki 16- Bitlik X ve Y tamsayılarının toplama işlemi (X=X+Y). Bu byte’ların saklayıcılarda aşağıda verildiği gibi saklandığını düşünelim. -------------------------------------------- Byte Saklayıcı -------------------------------------------- XL 78H XH 79H YL 7AH YH 7BH -------------------------------------------- X=1234h ve Y=12EFh tamsayılarını bu hafıza hücrelerine yükleyen program parçası: MOV 78h, 34h ; XL MOV 79h, 12h ; XH MOV 7Ah, 0Efh ; YL MOV 7Bh, 12h ; YH XL=XL+YL Toplamını gerçekleştiren program kodu: MOV A, 78h ; A=XL ADD A, 7Ah ; A=XL+YL MOV 78H, A ; XL=A Yapılan işlemin bu noktasında , 78h adresli hücre 23h değerini içermektedir ve C bayrağı 1’lenmiştir. Şimdi XH=XH+YH+C işlemini gerçekleştiren program parçasına bakalım: MOV A, 79h ; A=XH ADDC A, 7BH ; A=XH+YH+C MOV 79H, A ; XH=A Bu programın çalıştırılması sonucu,dahili saklayıcı hücreleri 78h ve 79h’ta 2523h değeri doğru olarak saklanır. Çıkarma işlemi SUBB de ,ACC’yi ilk operand olarak kullanılır.Doğrudan, dolaylı,saklayıcı veya ivedi adresleme modları ile belirtilen ikinci operand, ACC’den çıkartılır ve sonuç yine ACC’ye yerleştirilir. C bayrağı,uzun tamsayı çıkarma işlemlerinde, toplama işlemine benzer şekilde kullanılır. Çıkarma işlemi,bir ödünç almaya ihtiyaç duyar ise, C bayrağı 1’lenir. Eğer bir çıkarma işleminden önce, C 1’lenmiş ise,yapılan çıkarma sonucunda bir eksiltilir. Bu sayede, birden fazla byte uzunluğunda olan tamsayıların çıkarma işlemi, en düşük değerli byte’lardan başlayıp yüksek değerli byte’lara doğru, peş peşe byte çıkartma işlemi şeklinde yapılır. Bu durumda , ilk çıkarma işleminden önce C bayrağının sıfırlanması gerekmektedir. Aşağıda verilen program örneği, iki 16-bit X ve Y tamsayılarının çıkarma işlemini (X=X-Y) göstermektedir. Her iki sayı , 8-bit düşük(XL ve YL) ve yüksek değerlikli (XH ve YH) byte’lar olarak işleme alınmaktadır. |
İki 16- Bitlik X ve Y tamsayılarının toplama işlemi (X=X+Y). Bu byte’ların saklayıcılarda aşağıda verildiği gibi saklandığını düşünelim. -------------------------------------------- Byte Saklayıcı -------------------------------------------- XL 78H XH 79H YL 7AH YH 7BH -------------------------------------------- X=1234h ve Y=12EFh tamsayılarını bu hafıza hücrelerine yükleyen program parçası: MOV 78h, 34h ; XL MOV 79h, 12h ; XH MOV 7Ah, 0Efh ; YL MOV 7Bh, 12h ; YH XL=XL+YL Toplamını gerçekleştiren program kodu: MOV A, 78h ; A=XL ADD A, 7Ah ; A=XL+YL MOV 78H, A ; XL=A Yapılan işlemin bu noktasında , 78h adresli hücre 23h değerini içermektedir ve C bayrağı 1’lenmiştir. Şimdi XH=XH+YH+C işlemini gerçekleştiren program parçasına bakalım: MOV A, 79h ; A=XH ADDC A, 7BH ; A=XH+YH+C MOV 79H, A ; XH=A Bu programın çalıştırılması sonucu,dahili saklayıcı hücreleri 78h ve 79h’ta 2523h değeri doğru olarak saklanır. Çıkarma işlemi SUBB de ,ACC’yi ilk operand olarak kullanılır.Doğrudan, dolaylı,saklayıcı veya ivedi adresleme modları ile belirtilen ikinci operand, ACC’den çıkartılır ve sonuç yine ACC’ye yerleştirilir. C bayrağı,uzun tamsayı çıkarma işlemlerinde, toplama işlemine benzer şekilde kullanılır. Çıkarma işlemi,bir ödünç almaya ihtiyaç duyar ise, C bayrağı 1’lenir. Eğer bir çıkarma işleminden önce, C 1’lenmiş ise,yapılan çıkarma sonucunda bir eksiltilir. Bu sayede, birden fazla byte uzunluğunda olan tamsayıların çıkarma işlemi, en düşük değerli byte’lardan başlayıp yüksek değerli byte’lara doğru, peş peşe byte çıkartma işlemi şeklinde yapılır. Bu durumda , ilk çıkarma işleminden önce C bayrağının sıfırlanması gerekmektedir. Aşağıda verilen program örneği, iki 16-bit X ve Y tamsayılarının çıkarma işlemini (X=X-Y) göstermektedir. Her iki sayı , 8-bit düşük(XL ve YL) ve yüksek değerlikli (XH ve YH) byte’lar olarak işleme alınmaktadır. C _ İki 16- Bitlik X ve Y tamsayılarının çıkarma işlemi (X=X-Y). X=1234h ve Y=1135h tamsayılarını hafızaya yükleyen program parçası: MOV 78h, 34h ; XL MOV 79h, 12h ; XH MOV 7Ah, 35h ; YL MOV 7Bh, 11h ; YH CLR C ; C bayrağını temizle XL=XL-YL çıkarma işlemini gerçekleyen program parçası: MOV A, 78h ; A=XL SUBB A, 7Ah ; A=XL-YL-0 MOV 78H, A ; XL=A Bu noktada 78h adresli hücre FFh değerini içermektedir ve C bayrağı 1’lenir. Şimdi XH=XH-YH-C işlemini gerçekleştiren program parçasına bakalım: MOV A, 79h ; A=XH SUBB A, 7BH ; A=XH-YH-C MOV 79h, A ; XH=A Bu programın çalıştırılması sonucu , dahili saklayıcı hücreleri 78h ve 79h’ta 00FFh değeri doğru olarak saklanır. Arttırma ve azaltma komutları Bu komutlar,çevirim sayaçlarını veya veri işaretçilerini arttırma veya azaltma işlemlerinde faydalıdırlar. Aşağıda verilen bu komutların kullanıldığı bu örnekte,dahili veri hafızada bulunan X veya Y vektörleri (veri blokları) toplanmaktadır.(X=X+Y).Bu programda X ve Y vektörlerinin uzunlukları R3 saklayıcısında olduğu ve ayrıca, X vektörüne R0 Y vektörüne R1 saklayıcılarının işaret ettikleri varsayılmaktadır. LOOP: MOV A, @R0 :X ten bir byte oku. ADD A, @R1 :Y byte'ı topla. MOV @R0,A :sonucu X e yerleştir. INC R0 :bir sonraki X byte'ına işaret et. INC R1 :Bir sonraki Y byte'ına işaret et. DJNZ R3 , LOOP http://www.supermp3.org/images/smilies/biggrin.giföngü sayacını azalt.sayaç sıfır :değil ise,LOOP etiketine dallan. Çarpma bölme komutları 8051 ailesinin üyeleri donanım çarpma ve bölme birimlerine sahiptir.Bu komutlar,4 makine çevrimi ile en uzun zamanı alır.Çarpma ve bölme komutları,saklayıcı-özel komutlar olup ACC ve B saklayıcılarını kullanır. MUL AB Komutu,ACC ve B saklayıcılarındaki iki işaretsiz tamsayıyı çarpar.16-bit çarpma sonucunun düşük byte 'ı ACC de ve yüksek byte'ı B saklayıcısında bulunur.Sonuç FFFFh'tan büyük olamaz.Yani C bayrağı hiçbir zaman 1'lenmez.eğer sonuç FFh'tan büyük ise,taşma bayrağı 0V 1'lenir.0V bayrağının sıfırlanması,B saklayıcısının 0 olduğu anlamına gelir. |
DIV AB Komutu ACC'deki 8-bit işaretsiz tamsayıyı B saklayıcısındaki 8-bitlik işaretsiz tamsayıya böler.Sonucun tamsayı kısmı ACC'de,kalan kısmı ise B saklayıcısında tutulur.C bayrağı herzaman temizlenir.Taşma bayrağı 0V, sıfıra bölme durumunu belirtir.Eğer B saklayıcısında bu komuttan önce sıfır bulunursa,sonuç belirsiz olur ve taşma bayrağı 0V 1'lenir. Ondalık ayarlama(decimal adjust ) Komutu DA komutu,ikili kodlanmış ondalık (BCD-binary coded decimal) sayılrın toplama işleminden sonra kullanılır.Bir BCD sayının her 4-bit'i (nibble) bir ondalık sayıyı belirtir.Yani,her bir 4-bit'in değeri 0(0000)ile 9(1001) sayıları arasında olabilir.DA komutu ile yapılan işle,ACC ve PSW içeriklerine göre,ACC'ye 0,6,60h veya 66h ekleme işlemi olarak görülebilir.Aşağıdaki örneklerde ,DA komutunun bu özelliği gösterilmektedir. MOV A,#12h :A=12h (BCD) MOV B, #29h :B=29h (BCD) ADD A,B :12h + 29h =3Bh, BCD değil! DA A http://www.supermp3.org/images/smili...face.gifndalık ayarlama ,burada sonuca 6 eklenir, :3Bh + 6 = 41h doğru BCD sonuç(12 +29) bulunur. MOV A,#55h :A=55h (BCD) MOV B, #66h :B=66h (BCD) ADD A,B :55h + 66h =BBh, BCD değil! DA A http://www.supermp3.org/images/smili...face.gifndalık ayarlama ,burada sonuca 66 eklenir, :BBh + 66 = 121h :doğru BCD sonuç(55 +66) bulunur. :ACC,21h (BCD) içermektedir ve :C bayrağıda 1'lenmiştir. Gösterim İşlem Adresleme Modları Dir Ind Reg Imm ANL A<byte> A=A AND <byte> X X X X ANL<byte>,A <byte>=<byte> And A X ANL<byte>,#data <byte>=<byte> And #data X ORL A,<byte> A=A OR <byte> X X X X ORL <byte>,A <byte>=<byte> OR A X ORL <byte>,#data <byte>=<byte> OR #data X XRL A,<byte> A=A XOR <byte> X X X X XRL <byte>,A <byte>=<byte> XOR A X XRL <byte> #data <byte>=<byte> XOR A #data X CRL A A=00H Sak.özel(ACC) CPL A A=NOT A Sak.özel(ACC) RL A ACC’yi bir-bit sola döndür Sak.özel(ACC) RLC A Sola CY üzerinden döndür Sak.özel(ACC) RR A ACC’yi bir-bit sağa döndür Sak.özel(ACC) RRC A Sağa CY üzerinden döndür Sak.özel(ACC) SWAP A ACC’deki iki 4-bit’i değiştir Sak.özel(ACC) AND,OR VE XOR Komutları AND,OR VE XOR Komutlarının hepsi aynı adresleme modunu kullanır.Byte-tabanlı lojik işlemlerinde ,8-bit operand'ların karşılıklı bit'leri üzerinde işlem gerçekleştirilir.Operand'lardan biri,çoğu zaman ,ACC'dir ve aynı zamanda,ACC sonucunsaklandığı hedef saklayıcıdır.İşlem sonucunda hiçbir bayrak etkilemez. AND ve OR komutları,bir kontrol saklayıcısındaki belirli bitlerin maskelenmesinde (masking) faydalıdırlar.Örneğin PSW'deki diğer bitleri etkilemedensaklayıcı kümesi 3'ün seçilmesini düşünelim.aşağıdaki komutlar PSW'nin 3 ve 4'üncü bitlerinin 1'lenmesini sağlar. MOV A,#18h :bit 3 ve 4 (00011000b) 1'lenir ORL PSW,A :saklayıcı kümesi 3 seçilir. Şimdide saklayıcı kümesi 0 ın seçilmesini sağlayalım.Bu kez,bit 3 ve 4 sıfırlanır. MOV A,#0E7h :Bit 3ve 4 (11100111b) 0'lanır. ANL PSW,A :Saklayıcı kümesi 0 seçilir. Temizle (clear)ve tersle(complement)komutları Bu komutlar ACC üzerinde işlem yapan saklayıcı-özel komutlardır. CLR A komutu,ACC'nin bütün bitlerini temizler.CPL A komutu ise,ACC'nin her bir bit'inintersini alır. Döndürme(rotate)komutları Bu komutlar ACC üzerinde işlem yapan saklayıcı-özel komutlardır.Şekil 6.6'da görülen 4 tane döndürme komutu vardır.Bu komutlar ACC'deki 8-bit sayı veya ACC ve C bayrağındaki 9-bit sayı,sağa veya sola birer bit döndürülür. Döndürme komutları,maskeleme byte'ları oluşturmada 22nin katları ile çarpma veya bölme işlemlerinde kullanılır.Bit 0'ın sıfır olması sağlanarak ,ACC'yi bir bit sola kaydırma işlemi,ACC'yi 2 ile çarpma işlemine eşittir.Benzeri şekilde peş peşe iki kere sola kaydırma ,ACC'yi 4 ile çapma demektir.Sağa döndürme ise ,2 ile bölme işlemine eşit olur.ikinin katları ile çarpma ve bölme işlemlerinde,MUL ve DIV komutları yerine ,döndürme komutlarının kullanılması işlem hızı açısından önemli kazanç sağlar. A7 A0 RL A7 A0 RLC A7 A0 RR A7 A0 RRC Döndürme Komutlarının gösterimi Karşılıklı Değiştirme (Swap) Komutu Karşılıklı değiştirme komutu SWAP A ACC’ nin 4-bit içeriğinin yerlerini değiştirir. Bu komutla yapılan işlem ACC’ yi 4 kez (her iki yönden birinde) döndürme işlemi olarak ta görülebilir. Bit-Tabanlı Lojik Komutlar 8051 ailesinin ürünleri, yoğun bit-tabanlı özelliklere sahiptir. Daha önceki bölümlerde bu özelliklerin bir kısmı anlatılmıştı. Tablo 6.6 bit-tabanlı komutların bir özetini vermektedir. Gösterim işlem ANL C, bit C bayrağını adreslenen bit ile AND’le ANL C, /bit C bayrağını adreslenen bitin tersi ile AND’le ORL C, /bit C bayrağını adreslenen bit ile OR’la ORL C, /bit C bayrağını adreslenen bitin tersi ile OR’la CLR C C bayrağını temizle CLR bit Adreslenen bit’i temizle CPL C C bayrağını tersle (Complement) CPL bit Adreslenen bit’i tersle (Complement) SETB C C bayrağını l’le SETB bit Adreslenen bit’i l’le Bit-tabanlı işlemlerde elde bayrağı C, l-bit ACC olarak kullanılır. Örneğin, Tablo 6.6’ dan görüldüğü gibi, birçok bit-tabanlı lojik işlemlerde, C bayrağı, operand’ lardan biri ve sonuç için, hedef l-bit saklayıcı olarak kullanılır. Bit-tabanlı lojik işlemlerde, kaynak bit’in tersi kullanılmak istenmiyorsa, ‘/’ sembolü kaynak bit’in önüne konur. Bu sembol, kaynat bit’in gerçek değerinin değişmesine neden olmayıp sadece, yapılan işleme, değerinin tersini alınarak girmesine neden olur. 6.5.3 Program Akışı Kontrol Komutları Dallanma komutları, mikro denetleyicinin yürütme sırasında farklı işlemler yapmasını yönlendiren komutlardır. Örneğin, bir tuşun durumuna veya bir kontrol sinyaline göre, bir motorun durdurulmasını veya çalıştırılmasının devamına karar verme gibi. Bir dallanma komutu ile, PC’nin içeriği değişip program akışı da değişir. Her komut okuma çevriminde, PC, bir sonraki komuta işaret edecek şekilde yenilenmektedir. Normalde bir sonra yürütülecek komut, hafızada o anki komuttan sonra gelen komut olmaktadır. PC’ nin değişmesi durumunda ise, PC’ deki adresten itibaren program akışı devam eder. Yani hafızada başka bir program alanına dallanma gerçekleştirilmiş olur. Dallanma komutları, JMP (jump), CALL ve RET (RETurn) komutlarıdır. Bir JMP komutu sadece PC’yi değiştirmektedir. Dallanma komutları, Durumdan Bağımsız (unconditional) ve Duruma Bağımlı (conditional) olmak üzere ikiye ayrılır. 8051 ailesinin mikro denetleyicileri, 3 tane durumdan bağımsız dallanma komutuna sahiptir: SJMP, AJMP ve LJMP. Durumdan Bağımsız Dallanma Komutları Aşağıdaki Tablo 3.7’de Durumdan Bağımsız Dallanma komutlarının bir özeti verilmektedir. Bu komutların her biri ile gerçekleşen program akışındaki dallanma, PC içeriğinin değişmesiyle olur. Tabloda verilen ilk 3 dallanma komutu birbirine benzemektedir. Verilen en son indisli dallanma komutu ise, ACC ile DPTR’ ın içeriklerini toplayıp bir sonra okunacak ve yürütülecek komutun adresini hesaplayan güçlü bir komuttur. Gösterim Açıklama SJMP <rel add> (Short Jump- Kısa Dallanma) Operand, 2-nin tümleyeni tek bir byte olup değeri PC’ ya ekle- nir. Bir sonraki komut, 127 byte ileri veya 128 byte gerideki bir komut olacaktır. AJMP<Address ll> (Absolute Jump-Mutlak Dallanma) Operand, ll-bit bir adres olup Program Hafızanın o anki 2 Kbyte’lık alanı içine karşı gelir. LJMP<Address 16> (Long jump-Uzun Dallanma) Operand, l6-bit bir adres olup Program Hafızasının 64 Kbyte’lık alanı içinde bir yere karşı gelir. LJMP A+DPTR **eksik**var (Long jump-Uzun Dallanma) Yürütülecek bir sonraki komutun adresi, ACC ile DPTR’ ın toplamıdır. |
Kısa ve Uzun Dallanmalar Kısa dallanma komutları, genelde bir altprogramın içinde kullanılır. Bu komutlarda dallanacak alan, dallanma komutunu takip eden 127 byte ilerisi ile 128 byte gerisi, arasında sınırlıdır. Dallanma adresi, bir sonraki komuta göre göreceli (relative) ofset olarak tanımlı olduğu için, program kodu başka bir adrese tekrar taşınabilir durumdadır (relocatabla code). Bir program veya bir blok kod, program hafızada yerleştirildiği yerden bağımsız olarak doğru çalışıyorsa, tekrar yerleştirilebilir (relocatable) diye adlandırılır. Kodun tekrar yerleştirilebilir olmaözelliği, dallanma komutları kullanıldığında önemli olur. Eğer bir dallanma komutu, program akışını Program Hafızada belli bir adrese yönlendirirse dallanma adresinde geçerli bir kodun olması programcının sorumluluğundadır. Kısa dallanma komutları kullanılan bir kod bloğunun, hafızada bir başka adrese taşınması durumunda, program, yerleştirildiği yerden bağımsız olarak düzgün çalışacaktır. Çünkü, bir dallanma adresi sonraki komuta göre, göreceli ofset olarak hesaplanır. Aşağıda verilen program parçasını düşünelim: ORG 8000h MOV C, P0.0 MOV Pl.0, C LJMP 8000h ; tekrar Bu program 8000h adresinden itibaren yerleştirilmelidir. Çünkü , son komut 8000h adresine bir dallanma yapar. Eğer program başka bir adrese yerleştirildiyse, doğru çalışmayacaktır. Şimdide aşağıdaki değişiklikle programa bakalım: ORG 8000h START: MOV C,P0.0 MOV P1.0, C SJMP START ;TEKRAR Bu durumda başlangıç (ORG-origin) adresi değiştirilse de program doğru olarak çalışacaktır. Yukarıda verilen üç komutun her biri 2 byte uzunluğundadır. Program başlarken PC 8000h değerindedir ve sırasıyla 8002h ve son komut yürütülmeden 8004h değerini alır. Son komut ta 2 byte uzunluğunda olduğu için , PC artırılarak 8006h olur. Bununla beraber ,son komut bir dallanma komutu olduğu için , PC değerinin göreceli 6 byte gerisindeki adres olan 8000h değeri PC’nin değeri olur. Böylece, işlemci sonsuz bir çevirim içinde çalışmasına devam eder. Eğer program başlangıç adresi değiştirilse , örneğin , 9000h yapılsa; program yine doğru çalışacaktır. Komutlar 9000h , 9002h ve 9004h adreslerinden başlar ve son komut yürütüldüğünde, PC 9000h adresinden başlayarak çevirim tekrar eder.programın kısa dallanmalı ikinci şekli, Program Hafızada tekrar yerleştirilebilir olup birinci verilen örnek , hafıza –özeldir. Yukarıdaki örnekleri genelleştirecek olursak,uzun dallanmalar kullanan programlar hafıza-özeldir.Buna karşın, kısa dallanmalar kullananlar ise, tekrar yerleştirilebilir programlardır.Uzun dallanmalara,bilhassa,kod boyunun kısa dallanmaların alanı dışına taşması durumlarında ihtiyaç vardır.Program geliştirmede genel bir yaklaşım, kod üretimindeki derleme(assembly) ve kod bağlama(link) işlemlerinin ayrılmasıdır. Derlemede, uzun dallanmaları takip eden adresler gibi , bazı özel adresler haricindeki assembly kodu büyük bir kısmı makine diline çevrilir. Derlenen kod segmentleri ve alt programlar , daha sonra bir linker programı ile bağlanarak en son yürütülecek program elde edilir. Bu bağlama aşama ,dallanma adreslerine harici referansların değerleri ve değişkenlerin değerleri belirlenir. Mutlak (absolute) Dallanma 8051’in mutlak (absolute) dallanma komutu (AJMP) , derleme ve bağlama işlemlerini ayırmaya bir alternatif sunarak , kod için bir çeşit tekrar yerleştirilebilirlik sunmaktadır. Mutlak dallanmalar, dallanma adresinin en düşük değerli 11-bit’ini tanımlar. Iste internette bircok sitede, formda gördügüm bu cümle. HAYIR Assembler ölmedi ve ölemezde! Assembler bugünde tipki yillar öncesindeki gibi önemli bir dil. Makine yakini hizli, kücük programlar üretmek icin en iyi dil. >> Neden Assembler? C/C++ da makine yakini, kücük ve gercekten hizli programlar üretebiliyor. << diyorsaniz ve eger yeni bir isletim sistemi veya sürücü yazmak istemiyorsaniz, hakli oldugunuzu itiraf etmeliyim. Ama bugun bile bazi yerlerde derleyicilerden daha iyi programlari optime etmek mümkün. Bunun disinda Assembler ile programlamak size bilgisayarla tam bir iletisim kurma imkani veriyor. Yani yazdiginiz her komut, bilgisayarin CPU(FPU komutlari haric) tarafindan direkt olarak calistiriliyor. Ilk bölümde daha önce Bilgisayar donanimi hakkinda yada CPU ve FPU hakkinda fazla bilgi sayibi olmayan insan lara bu donanim parcalari hakinda bilgi verecegim. Her bilgisayar bir CPU ya sahiptir. CPU lar farkli bicimlerde olabilirler. Su an kullanilan CPU lar genelde iki bicimdelerdir. RISC ve CISC CPU lar. CISC 8086 tabanli islemcilerin kullandiklari komut modelidir. RISC komut destekli CPU lar ise genelde Server ve Workstation larda kullanilirlar. RISC az bir komut kapestesine ve az sapida adresleme modellerine sahiptir. Genelde her komut bir Takt da yapilir. Hatta bazi durumlarda bir Takt icinde bir kac islem yapmakta mümkündür. CISC CPU lar ise bir CPU ne kadar komut taniyorsa o kadar iyidir, felsefesi üzerine yapilirlar. Bazi komutlar 10 Takt bile gerektrebilirler. Ama yeni CISC CPU lari ile CISC ile RISC arasinda fazla bir fark kalmamistir. Cogu CISC CPU usu günümüzde CISC komutlarini kücük RISC komutlari haline getirip calistirabilme özelliginin yani sira 1 Takt da bir kac islem yapma özzelliginede sahiplerdir. Bunun disinda yeni bir islemci modeli olan EPIC (CISC ile RISC in karisimi) de intel tarafindan IA64 ile su anda pazara yerlestirilmeye calisiliyor. Ama genel bir CPU her sekilde registerlere, ve bir adresleme bicimine sahiptir. CPU: Datenbus ---------------------------------- ^....-REGISTERS-.-............. |...............|..........-................. |...............|.........-.................. |...............|........-................... |...............|.......-.................... |...............|......-..................... |...............|...- . . OP-Code. ---------ALU-------BR .. BZ Flags...... |........................... ---------------------------------- Adressbus ALU bir islemcinin kalbidir denebilir. Islemler ALU icinde gerceklesir. Adressbus bize herhangibi bir alani adresleme olanagi verir. Datenbus üzerinden veri degis tokusu olur. Registerler bir islemcinin en önemli parcalaridirlar.Islemlerin yapilabilmesi icin ihtiyac duyulurlar, ve her hangibibir veri den cok daha hizli erisilebilirler. FPU ya gelince. FPU da CPU gibi kendi register lerini icerir ve kendi komut satiri vardir. Yüksek, komali vs. sayilarin hesaplanmasinda CPU dan cok daha hizlidir. 8486 dan beri FPU CPU un bir parcasi olarak bulunuyor. FPU ile programlamayi bu dökümanda ögrenmeyeceksiniz. Ama talep gelirse bu konu hakkindada bir döküman hazirlayabilirim. Merhaba Dünya! -------------------------------------------------------------------------------- Bircok kitaptaki gibi bizde önce bir “Merhaba Dünya!” programiyla Assembler diline girelim. Derliyici olarak aksi söylenmedigi sürece TASM kullanilacaktir.(Zaten MASM ile TASM arasinda bir fark oldugu söylenemez) .model small .data merhaba db ‘Merhaba Dunya!$’ .code start: mov ax, @data mov ds, ax mov ah, 0x09 lea dx, merhaba int 0x021 mov ah, 0x04c int 0x021 end start ends Aslinda ilk bakista fazla cana yakin bir dile benzemiyor Assembler, ama anlayinca gercektende kolay oldugunu anlayacaksiniz. Anlatmaya basliyorum; Öncelikle “.model small” komutu ile programin programin bir CS(Code Segment) ve bir DS(Data Segment) e sahip olacagini söylüyoruz.SS(Stack Segment) ile DS ne yazikki ayni yeri paylasiyorlar. Daha sonra “.data” ile degiskenlerin saklanacaklari yeri belirliyoruz. DB(Define Byte) ile satirimizin Byte lar halinde saklanan bir degisken olmasini istedigimizi belirtiyoruz. “.code” ile CS e girdigimizi söylüyoruz. “mov ax, @data” ve “mov ds, ax” ile önce AX e DS nin baslangic adresini yükleyip sonrada DS in baslangic adresini AX den DS e yüklüyoruz. Bu cok önemli cünkü 8086 Segment ve Offset lerle adreslemeye izin veriyor. “mov ah, 0x09” ilea ax registerinin üst 8 Bittine 9 degerini yüklüyoruz. “int 0x21” ile bu DOS icin ds:dx adresindeki satiri yaz anlamina geliyor. Tabi adresin offset kismini dx e “lea” ile yüklüyoruz. Sonrada yine ah ye 0x04c yükleyerek int 0x21 i cagiriyoruz, buda DOS icin “Program bitti CIK!” demek oluyor. Simdi gelelim NE DEMEK Segment NE DEMEK Offset isine. 8086 islemcisi 20 Bitlik bir Adressbus a sayipti. Yani 1MB lik adresleme olanagina. Ama sadece 16 Bitlik registerleri vardi, bu yüzden INTEL aklina gelen süper(Ne kadar süper oldugu tartisilamaz tabi) bir fikri hayata sundu. Buna göre adresler söyle hesaplaniyordu: Adres= 16*Segment+Offset Mesela havisada F6000 adresine ulasilmak istendiginde bu ister bu adresi F600:0000 olarak ister F000:6000 seklinde yazibilisiniz. Birinci kisimda Segment ikinci kisimda ise Offset in bulunmasi gerekiyor. Iste size 8086 nin registerleri: 8086: ax ah al bx bh bl cx ch cl dx dh dl cs: ip ds: di es: si fs gs ss: bp, sp Flags Aslinda 8086 nin gercektende az registere sahip oldugunu söyleyebiliriz. Ax, bx, cx, dx genel amacli registerlerdir. Cs, ds, es, fs, gs, ss adreslemede Segment kisminda kullanilabilir ip, di, si, bp ve sp ise offset kisminda kullanilabilirler. Bunun disinda her register 16- Bit boyutunda ve ax, bx, cx, dx registerleri üst ve alt kisimlari seklindede kullanmak bümkün. H üst 8 Bit L ise alt 8Bit icindir. Bu sekilde mesela ax registerine hem 6 hemde 4 degerini tutacak sekilde verebiliriz. Örnek: mov ah, 6 mov al, 4 ; iki degerde ax registerinin icinde bulunuyor. Programcilar icin bir diger önemli gelisme ise 8386 ile gerceklesti. Bu islemci ilk IA32 destekli islemci olmakla beraber, kendi 32-Bitlik registerlerini sunuyordu. Hemde bu islemci üzerinde her registeri her islem icin kullanmak mümkün. Tabi CS ile EIP disinda. Cünkü CS:EIP programin o anda bulundugu durumu, yani bir sonraki komutun adresini tutar. Iste 8386 nin registerleri: 8386: eax ax ah al ebx bx bh bl ecx cx ch cl edx dx dh dl cs ds es fs gs ss eip ip edi di esi si ebp bp esp sp eflags Önünde e harfi olan registerler 32 Bitlikler. Ve 8386 sayesinde artik adreslemek icin Segment lere ihtiyacimiz yok, 20 Bitlik adres kapestesi yerine 32- Bitlik bir adres kapestesi var 8386 nin, ve bu adresler tam bir registere sigiyorlar, yani 1MB lik adres kapestesi 4GB seviyesinde artik! Eski(8086): Merhaba db ‚Merhaba Dunya!’ lds di, merhaba ; merhaba nin adresi= ds:di Simdi(8386) Merhaba db ‘Merhaba Dunya!’ lea edi, merhaba ; merhabanin adresi= edi Simdilik öncelikle en önemli Assembler komutlarini burda kisaca bir aciklayayim: “mov register/segment/degisken, register/segment/degisken” virgülden önceki kisma, virgülden sonraki kismi yükler. Önemli olan ve dikkat edilmesi gereken en az bir tane registerin verilmis olmasi. Daha sonraki en önemli komutlar ise Matamatik komutlari. “add” toplama, “sub” cikarma “mul” carpma ve “div” bölme icindir. Mesela deger1= deger2*16; Assembler: mov ax, deger2 shl ax, 4 mov deger1, ax Burada dikkatinizi ceken komut “shl” olabilir. Shl belirtelen sekilde bitlerin sola kaydirir, fakat capma islemlerindede kullanilabilirler, üstelik mul dan 4-5 kat daha hizli calisirlar. 1 degerinde kaydirmak 2 ile capmak, 2 degerinde kaydirmak 4 ile carpmak , vs seklinde devam eder. Tabi matamatik komutlarini “lea” ile gerceklestirmekte mümkün, tabi 8386 dan itibaren, nasilmi? 8386 da her registerle adresleyebildigimizi söylemistim, artik cs, sp gibi registerleri kullanmak zorunda degiliz. Bu yüzden, simdik su komutun ne yaptigina bir bakalim: lea eax, [eax+eax*4] Bu komut eax e eax+eax*4 ün icerigini yüklüyor. Ama bu eax ile 5 in carpimindan baska bir sey degil! mov ecx, eax shl eax, 2 add eax, ecx Burda “lea” ile sadece 3 satiri 1 satir haline getirmekle kalmiyoruz ayni zamanda bir registerin kullaniminida engellemis oluyoruz. Bu kadar derinlere girdikten sonra simdik kaldigimiz yerden devam edelim. Ilk programda “merhaba db ‘Merhaba Dunya!$” satirinda dikkatinizi ‘$’ cekmisdir herhalde. Bu isaret Dos icin cok önemli, satirin sonunu belirtiyor. Windows da 0 ile satir sonu belli edilebiliyor. Simdik en basta yazdigimiz “Merhaba Dünya!” programini birde Windows icin yazalim; |
Includelib import32.lib ; Windows fonksiyonlari icin .386 ; 8386 nin registerlerine ve ;komutlarina ihtiyacimiz var! .model flat, stdcall ; 32- Bit adresleme(4GB!) extrn MessageBoxA : Proc extrn ExitProcess : Proc .data Caption db „Merhaba Dunya!“,0 Text db “MERHABA!”, 0 .code start: push 64 push Caption push Text push 0 call MessageBoxA ; MsgBox göster call ExitProcess ; cik end start ends Yukaridaki programda push ile fonksiyonlara verileri gönderdik. Normalde push ladiginiz herseyi pop lamalisinizda, ama bu örnekte ExitProcess zaten bir degisken beklemedigi icin bu bir sorun yaratmiyor, neyse bu tek Windows programiydi bu kitap icerisindeki, daha fazlasi icin Windows API isini ögrenmeniz gerekiyor. Bunun disinda diger DOS programlarinda kullandigimiz “mov ax, @data”, “mov ds, ax” satirlarinida kullanmamiz gerekmiyor, cünkü adresle tek bir registere sigdiklari icin Segment lere ihtiyacimiz olmuyor. Programlamaya kaldigimiz yerden devam edelim, Size bir kac Tipp vereyim; Carpma ve bölme islemleri icin shl ve shr yi kullanin. Bir sayi 0 a esit olup olmadigini kontrol ederken cmp ax, 0 yerine test ax, ax i kullanin. CMOVcc ve SETcc yi programlarinizda kullanin. Bir sayiya 0 yüklemek isterken mov ax, 0 yerine xor ax, ax i kullanin. Bir sayiya bir eklerken inc bir cikarirken dec i kullanin. Bir kac altin tipten sonra simdikte iki sayiyi toplayan, basit bir program yazalim; sayi_bir equ 0x18 ; 24 sayi_iki equ 0x5 ; 5 sonuc equ ax .model small .stack 0x100 ; 256 Bytes yeter .code start: mov ax, sayi_bir add ax, sayi_iki mov ah, 0x9 int 0x21 end start ends Bu programda sayi_bir, sayi_iki ve sonuc birer degisken degil sadece equ ile isimlendirilmislerdir. Daha önce C ile programladiysaniz EQU nun #define ile ayni oldugunu size söyleyebilirim. Bir diger önemli komut ise CMP komutudur. Degerleri karsilastirir ama kaydetmez bunun yerine Flag lari degistirir. Cmp nin kullanim sekli söyledir; Örnek: cmp ax, 2 Bu komuttan sonra cmp önce ax 2 ye essitmi diye bakar., esitse zero-flag (zf) doldurur, sonra da kücük büyük denemesi yapar. Kücük ise SF=OF büyük ise SF!=OF degerlerini gönderir. Örnek: .model small .code start: cmp ax, 4 jge kucuk jl buyuk je esit jmp son kucuk: inc ax jmp son buyuk: dec ax jmp son esit: add ax, ax son: mov ah, 0x09 int 0x21 end start ends Böylece degerleri karsilastirabiliriz. Üstekki program 8086 icin yazildi. Pentium Pro icin optime edildiginde söyle bir kod cikacaktir: .686 .model small .code start: cmp ax, 4 cmovge cx, 1 cmovl cx, -1 cmove cx, ax add ax, cx mov ah, 0x09 int 0x21 end start ends seklinde cok daha kisa, ve performans bakimindan cok daha yüksek bir program elde edecegiz, iste bu tip Optime olaylari bize Assembler ile gerceklestirilirken bütün diger dillerden daha cok kolaylik sagliyor bize. VC++ 6.0 hayla cmove, csete gibi komutlari desteklemiyor, yukaridaki kodu bir VC++ 7.0(.Net) derliyicisiyle elde etmeniz mümkün. Kaldigimiz yerden devam edelim yukaridaki kod ne anlama geliyor; iste C/C++ veya Java bilenler icin: if(ax<4) ax++; else if(ax>4) ax--; else if(ax==4) ax = ax*2; Yada herkesin anliyacagi bir bicimde: Eger(ax 4den kücükse) ax i bir degerinde arttir. Eger(ax 4den büyükse) ax i bir degerinde azalt. Eger(ax 4 e esitse) ax i 2 ile carp. Bunun disinda ziplama komutlari dilin en önemli yapi taslarini olusturmaktadirlar. Hicbir Flag a bakmazsizin ziplama JMP komutu ile yapilir. Daha sonra Jcc(cc yerine herhangibi harfler gelebilirler) seklinde belli flaglar doldurulduklarinda yada silindiklerinde sadece ziplama yapan komutlar vardir. Bir ziplama komutunu ister bir label in adini ister bir adresi yazarak kullanabilirsiniz. Simdi buraya kadar gördügümüz ziplama komutlarina bakalim: JE = Eger ZF dolu ise ziplar. JLE= Eger SF OF den farkli ise ziplar. JGE= Eger SF OF ye esitse ziplar. Bunun disinda simdi yeni baslayanlara birkac Tipp daha vereyim: Mümkün oldugunca az ziplama komutlarini kullanin. Mümkün oldugunca az sekilde registerlerin alt, ve üst kisimlariyla ayri seklide calisin. Mesela ah ye 2 ve al ye 4 degerini yüklemek istediginizde: mov ah, 2 mov al, 4 Yerine; mov ax, 0x0204 yazarak programinizin icindeki bir islemin hizini 2 Kat daha hizli halledebilirsiniz. Eger 8086 icin programlamak zorunda degilseniz CMOVcc, SETcc ve MMX i kullanmaktan kacinmayin.Degerleri DX:AX icine saklamak yerine 32- Bitlik registerleri kullanin. FPU yu kullandiktan(dagittiktan) sonra tekrar toplamayi unutmayin. Bu size ve diger programcilara yardim eder. Eger 32- Bit programliyorsaniz her registeri her is icin kullanmaktan kacinmayin. Ama Windows icin programliyorsaniz EBX, EDI, ESI ve EBP nin degerlerini degistirmeden önce yedeklemeniz gerekmekte. Bunu su sekilde yapabilirsiniz: push ebp push edi push esi push ebx ; Burada registerleri kullanabilirsiniz. ; …. pop ebx pop esi pop edi pop ebp Burda gördügünüz gibi PUSH stack’a(Yada havisaya) deger itmek icin kullanilirken, POP da deger cekmek icin kullanilir. Neden ilk ebp nin itilipte en son cekildigine gelince: Biz dokunmadan önce bos bir havisa rutini (Stack): BP SP Simdi önce iki degeri push liyalim. push 3 push ds Su anda Stack söyle gözüküyor: BP 3 DS SP Eger bir degeri pop larsak stack in en basindaki elemani cekiyoruz demektir. Yani: pop ax ; ax= 3 pop es ; es=ds Ve bu komuttan sonra Stack yine su sekilde gözüküyor: BP SP Unutmayin SP herzaman Stackin sonunu BP ise basini tutar. Ayni zamanda BP fonksiyonlarda elemanlara erismek icinde kullanilir. Aslinda fonksiyonlar bir cok sekilde yaratilma imkani sunarlar ki bunlardan bazilari su sekildedirler: topla proc near push ebp mov ebp, esp mov eax, [ebp+4] add eax, [ebp+8] leave ret endp yada; topla: push ebp mov ebp, esp mov eax, [ebp+4] add eax, [ebp+8] pop bp ret yada; topla: mov eax, [esp+4] add eax, [esp+8] ret En alttaki sekil size biraz yabanci gelebilir, cünkü derliyiciler tarafindan fazla kullanilmaz. Bunun disinda ebp+4 ün ikinci ebp+8 ise birinci deger oldugunu unutmayin. Bunun sebebi Stackin yukaridan asagi dogru gitmasidir.Yani esp+8, esp+4 den daha önce push ile itilmistir. Bu yüzden birinci degerdir. Ama C/C++ da ikinci deger! Cünkü C/C++ Stack a biraz baska bir acidan bakar ve ilk push ile itilen degeri en son, en sonda push lanan degeri ise ilk deger olarak görür. Bunun disinda söyle bir fonksiyonun yapisina bakildiginda: topla proc near push ebp mov ebp, esp mov eax, [ebp+8] add eax, [ebp+12] pop ebp ret Bu yukardaki fonksiyon C/C++ de su sekilde yazilabilir: int topla(int sayi1, int sayi2) { return sayi1+sayi2; } Ama eger size gelen verinin icerigini degistirmek istiyorsaniz, Java da; public static void topla(int sayi1, int sayi2) { sayi1+=sayi2; } Ilk bakista bu koddan yola cikarak asagidaki kodu yazarsak gercekten bir yanlis yapmis oluruz; void topla(int sayi1, int sayi2) { sayi1+=sayi2; } C/C++ ile programlayanlar yukardaki kodun, size hicbirsey kazandirmadigini bilirler, bu ayni sekilde Assembler dilindede böyledir, eger toplama islemini bu sekilde yapmak istiyorsaniz, iki yolunuz var: void topla(int *sayi1, int sayi2) { *sayi1+= sayi2; } yada C++ da; void topla(int &sayi1, int sayi2) { sayi1+=sayi2; } ikiside ayni Assembler Kodunu yaratirlar; topla proc near push ebp mov ebp, esp mov eax, [ebp+8] mov edx, [ebp+12] add [eax], edx pop ebp ret |
Burada ilk dikkatinizi ceken “add [eax], ecx” kod parcasi olmali, bu kod C/C++ da “*eax+=ecx” ile aynidir. Yani size gelen degeri degistirmek yerine, size gelen degeri tasiyan degiskeni degistiriyoruz burda. Yani eger bir deger, yada register parantez icinde ise, o registerin icindeki deger degil, gösterdigi adresdeki deger önemli demektir. Dikkat edin yukardaki fonksiyonu su sekilde cagiramazsiniz; push 12 push 6 call topla Böyle bir kodda siz eax in icine 0x06 adresini yüklersiniz, ve programiniz bu yüzden hata cikartir. Cünkü “topla” fonksiyonu 0x06 adresindeki veriyi degistirmeye calisir. Böyle bir fonksiyon su sekilde kullanilir; lea eax, degisken push 12 push eax call topla Bu durumda fonksiyona degiskenin adresi gönderilir(°isken) ve fonksiyonda bu degeri degistirmesi beklenir.Degisken icin tanimladigimiz bir degisken, yada Stack dan bir degisken koyabiliriz. Bunun disinda Assembler dilinde bir döngü yapmak icinde bir kac yöntem bulunmakta, iste iki temel döngü sekli: dongu: cmp ax, cx je devam_et dec cx jne dongu devam_et : ;... Yukaridaki kod C/C+ da; while(cx!=ax) cx--; Seklinde yazilabilir. Bu cx, ax e esit olmadigi sürece cx den bir cikar anlamina geliyor. Ama bir dongunun cx sifir olana kadar devam etmesini isterseniz; while(cx!=0) cx--; Seklinde bir kod parcasina derleyici size baska bir kod parcasi gösterecektir; dongu: loop dongu ; … Seklinde olacaktir kodunuz. „loop“ komuttu cx sifir oalana kadar donguyu devam ettirir, her seferinde cx den bir cikarir. Mesela; while(cx!=0) { ax++; cx-- } su sekilde derlenir; dongu: inc ax loop dongu ; … Tabikki derliyicinizin yukaridaki koddan daha degisik bir kod da vermesi dogal olacaktir, nede olsa C/C++ da registerlerle degil, degiskenlerle ugrasir programci, eger derleyici yeterli bir optime islemi yapmayi basarirsa elinize yukardaki kod gecer. Son olarakta SETcc hakkinda kücük bir kod örnegi yazayim ; mov ax, 0x00FF mov dx, 0xFF00 ; dx :ax= 0xFF0000FF add ax, 0xFF00 setc dl Yukaridaki kod ne yapar? DX:AX in icine 32- Bitlik bir sayi yazar, daha sonra bu sayinin alt 16- Bittini 0xFF00 ile toplar. Eger sonuc sigmazsa dl nin icine 0x01 degerini yükler, böylece toplama islemi sorunsuzca gerceklesmis olur. Not: Yukaridaki kod sonuc bilindigi icin yazildi, eger böyle bir koda programinizda ihtiyac duyuyorsaniz, asadaki sekilde yazin: add ax, 0xFF00 adc dx, 0 Böylelikle isinizi riske atmamis olursunuz |
Tabikki Setcc nin gücünü gösteren Örnek bir kodda yazmak mümkün, mesela asadakki gibi cok fazla kosulun oldugu program parcasinda, C++: if(r1==r2) r1++; else if(r2==r1) r2++; else r1=r2; if(r1==r2) r1--; if(r2==r1) r2--; else if(r2==(r1-1)) r3=r2; else r2=r3; Assembler x86: if0: Cmp ax, bx Jne else_if0 Inc ax Jmp if1 else_if0: Cmp bx, ax Jne else0 Inc bx Jmp if1 else0: Mov ax, bx if1: Cmp r1, r2 Jne if2 Dec ax if2: Cmp bx, ax Jne else_if1 Dec bx else_if1: Mov cx, bx Dec cx Cmp ax, cx Jne else1 Mov cx, bx Jmp cnt else1: Mov bx, cx cnt: ;... Burda Cmov ve Set komutlarini kullanarak yüksek bir seviyede performans elde ediyoruz, cünkü sadece 4 kere zipliyoruz. Yukarida ise 8 kere. xor ecx, ecx cmp eax, edx jne else_if1 inc eax jmp if_1 else_if1: cmp edx, eax sete cl cmovne eax, edx add eax, ecx if_1: cmp eax, edx sete cl sub eax, ecx cmp edx, eax jne else_if2 dec edx jmp end_if else_if2: mov ecx, eax dec ecx cmp edx, ecx xor ecx, ecx cmove ecx, edx cmovne edx, ecx end_if: Yukaridaki Cmov ve Set ile yazilmis olan kod x86 icin yazilmis koddan cok daha hizli(Tabikki Pentium Pro icin), ziplama komutlari kullanilmadigi icin, islemcinin bir sonraki komutu tespit etme imkani daha yüksek. Bunun disinda ziplama olmadigi icin koddaki CS:EIP register ciftlerinin icerigide degistirilmiyor. Unutmayin Set komutu 8386 dan Cmov komutu ise Pentium Pro dan itibaren gecirlidir. Eger Assembler i ögrenmek istiyorsaniz, BIOS int. lerini ögrenmelisiniz. Ama eger Dos icin program yapmak(yazmak) istiyorsaniz Dos cagrilarini, Windows icin program yapmak(yazmak) istiyorsaniz Windows API isini ögrenmelisiniz. Ama BIOS int. lerini kesinlikle ögrenmeniz gerekmekte, bunlar size er yada gec lazim olacaktirlar.(Meselaa bir isletim sistemi yazmak istediginizde!) Yüksek sayilarla calismak -------------------------------------------------------------------------------- Bir cok dilde 64-Bitlik veri tiplerine raslamak dogal, oysa x86 islemcilerinin 64 Bitlik registerleri bulunmuyor, peki nasil oluyor bu? Öncelikle ilk akla gelen cevap 64-Bit lik bir sayinin 32 Bitinin bir resistere, diger 32 Bittin baska baska bir resistere yüklenmesi. Bu VC++ deki __int64 ile tanimlanabilen veri türü ile ayni islemin yapilmasi anlamina geliyor. Mesela: mov eax, 0x00ffff00 mov edx, 0x000000ff Seklinde 0x000000ff00ffff00 (1095233437440) sayisini eax:edx in icine kaydediyoruz. Mesela basit bir toplama islemini su sekilde yapiyoruz, add eax, eax adc edx, edx Burda 1095233437440 sayisini kendisi ile topladik(yada iki ile carptik). Adc komutu add dan farkli olarak önce sayiyi topluyor sonrada üstüne CF in degerini ekliyor. Akla gelen ikinci yöntem ise FPU, bu sayede C/C++ da double adi verilen sayilarla carisma olanagimiz oluyor. 3 üncü ve en iyi tekniklerden biride MMX. MMX 8 tane 64-Bitlik register le geliyor.(MM0…MM7) Ama bu registerler yeni degiller, aksine eski 80-Bitlik FPU registerlerini(ST0…ST7) kullaniyorlar. Ama yaninda bu sayilari islemek icin bircok yeni komutla beraber geliyor MMX, ve bu sekilde sadece bir register icinde bir sayi ile calismak zorunda degiliz. Herhangibir registerin icine 8 tane sayi koyup, 8 ile ayni anda calismamiz bile mümkün. Ama yinede MMX inde eksikleri var, ama bunlar 3Dnow! SSE ve SSE2 ile ortadan kalkmis durumdalar. Yinede size su anda MMX ile calismanizi tavsiye ederim, cünkü hem 3DNow, hem SSE hemde SSE2 MMX i destekliyorlar. Ama su anda SSE2 sadece Pentium 4 tarafindan destekleniyor. TIP: Sayilarin hesaplanmasinda Windows un hesap makinesi, gelismis bölümünü kullanabilirsiniz. Gercektende cok faydali, hem hex, hem binary hemde normal sayilarin hesaplanmasinda. DOS ve Windows Ilk programlamaya basliyanlar icin kusursuz bir ögrenim ortami olusturan DOS ayni zamanda bazi isleri gercektende zorlastiriyor. Mesela dosda sayilari ekrana yazmak icin ASCII formatina cevirmeniz gerekiyor ki, bu bir sayinin her basamaginin tek tek cevrilmesi anlamina geliyor. DOS icat edildigi siralarda 8086 bulundugundan dolayi sadece 1MB lik adresleme kapastesine sahip DOS, ve bu DOS un en son sürümü 6.0 ile bile bugün öyle. Bunun disinda Windows 3.x de 16-Bitlik bir isletim sistemi ama 16MB lik adresleme destegi var. Yani Windows 3.x de adresler 8286 ya göre hesaplaniyorlar: DOS(8086) adreslemesi=16*Segment+Offset Windows 3x(8286) adreslemesi=256*Segment+Offset Bunun disinda Windows 3.x su anki Windows versiyonlarina göre cok daha farkli bir coklu-kanal programlama teknigi kullaniyor. Buna göre sadece o an secili olan program calisiyor, diger kanallar arkada beklemede kaliyorlar. TSS 16-Bitlik ve cok kanalli programlama mantigi cok basit bir sekilde calisiyor Windows 3.x de. Buna göre TSS 44 Bytes büyüklügünde. Windows 95 ile gelen coklu kanal sisteminde ise her program belli bir aralikla calistiriliyor. Kanallar degistirilirken(Yani sira diger programa geldiginde) TSS(Task Switch Segment) ye programin her registeri ve Flaglari yüklüyor. 32-Bit TSS 104 Bytes büyüklügünde. Windows EDI, ESI, EBX ve EBP registerlerini kullaniyor ve bu degerleri degistirmemenizi bekliyor. Bu yüzden bu registerler kullanilmadan önce yedeklemeniz gerekiyor, aksi halde sistemi cöktürebilirsiniz. Hernekadar 8386 da 4GB gibi bir bellek alani gösterilebilsede, Windows altinda bu sadece 2GB büyüklügünde. Geri kalan 2GB Windows tarafindan ayrilmis, ve kullanimi yasak olarak duruyor. Coklu kanallilik olunca her programin adresleme kismida Windows a yükleniyor. Yani programlarin biribirlerinin degiskenlerini göstermemeleri, vs. Kisimlarida Windows hallediyor. Windows XP ise gercek bir 32-Bit isletim sistemi olma özelligi ile geliyor. Bundan önceki Windows serisi Dos üzerinde aciliyordu, ve daha sonra 32-Bit moda geciyorlardi. Bu yüzden aslinda Windows 9x serisininde 16/32-Bit bir isletim sistemi oldugu söylenebilir. 32-Bit Moda sizde programlariniz icinde DOS dan gecebilirsiniz, bunun icin programiniza su kücük satiri eklemeniz yeterli: push cr0 ; Daha sonra Real-Mode geri dönmek icin. smsw ax or ax,0x01 ; Protected –Mode lmsw ax ; ... pop cr0 ; Geri Real-Mode dayiz simdik Her ne kadar bir programin icinde Mode degistirmek fazla gerekli bir durum olmasada, burda kisa bir aciklamada bulunayim dedim. SMSW ile CR0 registerinin ilk 16-Bit tini ax e kaydedip, 1 inci biti degistererek Protected mode girmek icin gerekli degeri ax e yüklüyoruz. Daha sonrada LMSW ile ax i CR0 registerine yazarak Protected Mode geciyoruz. Protected Mode: Windows 9x ve yeni sürümlerinin kullandigi, isletim sistemi Mode u. Bu mod un özelligi degisik programlarin birbirilerine zarar vermelerini engelleyebilmesi. Real- Mode: 8086 ile beraber gelen isletim sistemi Mode u. Pogramlamayi ögrenmek icin kusursuz bir ortam bence. Virtual 8086 Mode: Protected Mode altinda baslatilan fakat 8086 icin yazilmis programlarin calistiklari Mode. CPUID Pentium ile birlikte, programinizin üstünde calistigi islemci hakkinda bilgi alabilecegi bir komut geldi, CPUID. CPUID eax registerinin icinde bir fonksiyon numarasi bekler, böylelikle hangi bilgileri göndermesi gerektigini anlar. Bu bilgiler EDX icinde geri dönerler. Daha sonra TEST komutu ile geri dönen bilgilerde istenilen özelligin olup olmadigi anlasilabilir. Mesela: mov eax, 0x01 cpuid eax test edx, 0x0800000 ;(23 uncu bit dolu ise MMX vardir.) jnz mmx_var EKLER ADC ---------------------------------------- add with carry ADC O1, O2 ADC iki elemani(O1 ve O2) toplar ve bu sonuca Carry Flags sida ekler. Örnek: stc mov al, 3 mov ah, 2 adc al, ah ; al= ah+al+cf=6 ADD -------------------------------------- ADD O1, O2 ADD O1 ile O2 yi toplayip O1 in icine yazar. Tip: Eger bir registere 1 eklemek istiyorsaniz INC i kullanin. DIV ---------------------------------------- division DIV O1 Bu komut bölme icindir. Eger O1 8 Bit ise AX deki sayi bölünür, kalan AH nin icine ve sonuc AL nin icine yazilir. Eger O1 16 Bit ise DX:AX icindeki sayi bölünür, kalan DX in icne sonuc AX in icine yazilir. Eger O1 32- Bit ise EDX:EAX deki sayi bölünür, kalan EDX e sonuc EAX e yazilir. Tip: Eger bir sayiyi 2 nin katlarina bölmek istiyorsaniz; SHR komutunu kullanabilirsiniz. mov ax, 24 mov bl, 8 div bl yerine; mov ax, 24 shr ax, 3 (2 üstü 3) yazarsaniz kodun boyu ve hizi degisecektir. IDIV --------------------------------------- interger division IDIV O1 Bo komut DIV ile hemen hemen aynidir, fark olarak isaretli sayilarlada islem yapabilir. IMUL --------------------------------------- interger multiply IMUL O1, [O2, [O3]] IMUL iki virgüllü sayiyi carpar. Ilk olarak eger iki tane adress yada register le kullanirsaniz; Örnek: IMUL ax, dx sonuc ax= ax*dx Eger ama 3 tane adress yada register kullanirsaniz; Örnek: IMUL ax, dx, cx O zaman ax= dx*cx seklindedir. MUL --------------------------------------- multiply MUL O1 MUL O1 i Akkumulator(AH, AL, AX, EAX) ile carpar. Tip: Eger bir sayiyi 2 nin katlariyla carpacaksaniz: mov al, 5 mov bl, 4 mul bl yerine; mov al, 5 shl al, 2 seklinde yazarsaniz programinizin boyutunu ve hizini degistirmis olursunuz. SBB --------------------------------------- subtraction with borrow SBB O1, O2 SBB O2 ile Carry- Flag i toplayip sonuctan O1 i cikarir. SUB --------------------------------------- subtract SUB O1, O2 O2 yi O1 den cikarir ve sonucu O1 e yazar. Tip: Bir sayidan 1 cikarmak istiyorsaniz, Örnek: sub ax, 1 yerine: dec ax yazmaniz kodunuzun boyunu ve hizini degisterecektir. XADD --------------------------------------- exchange and add XADD O1, O2 XADD iki elemanin önce iceriklerini degistirir sonrada ADD komutunun yaptigini yapar. Örnek: mov al, 3 mob bl, 5 xadd al, bl ; Al= 8, Bl=3 KARSILASTIRMA KOMUTLARI CMP Compare CMP birinci ile ikinci girilen degerleri karsilastirir ve sonucu FLAG lara yazar. Örnek: mov ax, 2 cmp ax, 2 ; ZF=1 CMPXCHG Compare and exchange Cmpxchg komutu kendisine gelen ilk degeri al, ax veya eax ile(Kendisine gelen ilk degeri boyutuna göre) karsilastirir. Eger degerler esitseler kendisine gelen ilk degere ikinci degeri yükler ve ZF ki doldurur. Örnek: mov eax, 3 mov edx, 3 lea ecx, [eax+edx*8] cmpxchg edx, ecx ; edx= ecx Bunun disinda cmpxchg8b ile 64-Bit lik sayilar üstündede bu islemi yapabilirsiniz. Yalniz cmpxchg8b biraz daha degisik calisiyor, sadece bir tane adres gelmesini bekliyor kendisine, daha sonrada bu adresteki degeri EDX:EAX icindeki deger ile karsilastiriyor. Eger esitlerse ECX:EBX icindeki degeri bu adrese yaziyor. Örnek: Cmpxchg8b qword ptr[ebp] TEST Test Test kendisine gelen degeri, ile kendisine gelen ikinci deger arasinda bir “and” islemi yapar. Ama sonucu and komuttundaki gibi kaydetmek yerine sadece FLAG lari degistirir. FONKSIYON KOMUTLARI: CALL Call bir fonksiyonu cagirmak icin kullanilir. Eger bir near-call yapilirsa sadece o anki programin eip(ip) registeri yedeklenir, böylece fonksiyon bittikten sonra programda kalinan yerden devam edilebilir. Eger bir far call yapilirsa hem cs hemde eip(ip) yedeklenir. INT Interrupt Int kendisine gelen 8-Bitlik(0 ile 255 arasinda sayilar) adresdeki aliciyi cagirir. Örnek: int 0x21 ; Dos interrupt unu cagirma. Bunun disinda birde into vardir. Bu komut ise eger OF=1 ise bir int islemi gerceklestirir. Ama bir deger göndermeniz gerekmemektedir, otomatik olarak interrupt 0x04 ü cagirir. RET Ret Call ile cagrilan bir fonksiyondan tekrar dönmek icin kullanilir. Eger bir near call yapilmissa eip yi tekrar eski haline getirir. Eger bir far call yapilmissa hem cs yi hemde eip yi eski haline getirir. MANTIKSAL OPERATORLER Assembler C/C++/Java And && Not ! Or || Xor ^ Shl << Shr >> |
REGISTER KOMUTLARI BSWAP --------------------------------------- byte swap BSWAP O1 BSWAP O1 yerinde 32 Bit lik bir register bekler. 0 .ile 4. üncü byte'i ve 2. ile 3. yü degistirir. Örnek: mov eax, 11223344h BSWAP EAX ; EAX= 44332211h CBW --------------------------------------- convert byte to word CBW AL- registeri icinde bulunan seyi, bir Word seklinde AX e yazar. CDQ --------------------------------------- convert word to quadword CDQ EAX icindeki doubleword 'u EDX:EAX icine quadword olarak yazar. CWD --------------------------------------- convert word to doubleword CWD AX icinde bulunan word' u DX:AX e doubleword olarak yazar. CWDE --------------------------------------- convert word to doubleword extended CWDE AX icindeki word'u EAX 'E doubleword olarak yazar. LEA --------------------------------------- load effective address LEA O1, O2 LEA O2 nin adresini O1 e yazar. O1 16 yada 32 Bit lik bir register olabilir. Örnek: lea dx, deger mov dx, offset deger ; Bu ikisi ayni isi yapar LMSW --------------------------------------- load machine status word LMSW O1 O1 e CR0 registerinin ilk 16 bitini yazar(32 Protected Mode gecmeye yariyon kisimda ordadir) Ne yazikki real mode da bu gecirli degil, o yüzden mov O1, cr0 yazmaniz gerekebilir. Bu komut aslinda isletim sistemi icindir, ve normal bir programda kullanilmasi gerekli degildir. MOV --------------------------------------- move MOV O1, O2 Assembler dilinin en önemli komutudur. O1 e O2 yi tasir, önemli olan her iki Ox nun esit olmasidir. Ikinci kural ise ikisininde Segmentregister olmamasidir. 16 bitlik bir registeri 32 bit lik bir registerin icine kopyaladiginiz zaman Pentium Pro dan itibaren 0 ile diger bitler doldurulur. Önceki islemcilerde karisik bitlerle dolduruluyorlardi. Tip: xor ax, ax ; mov ax, 0 push ds ; mov ax, ds pop es ; mov es, ax MOVSX --------------------------------------- move with sign- extension MOVSX O1, O2 MOVSX o1 in icine o2 yi kopyalar, burdaki fark ise o1 in 16 yada 32 bit olup o2 nin 8 veya 16 bit olabilmesidir. Örnek: mov ax, 0 mov bl, -5 movsx ax, bl MOVZX --------------------------------------- move with zero- extend MOVZX O1, O2 POP --------------------------------------- POP O1 Stak(daha önce PUSH lanmis seyler) tan O1 icine cekmeye yarar. Stak n son karakterini ceker. Eger O1 16-Bit ise SP = SP+ 2 eger O1 32-Bit ise SP= SP+4 olur. POPA --------------------------------------- pop all POPA bütün registerleri kullanmak icindir. Registerler siradaki gibi kullanilmis olurlar; DI, SI, BP, BX, DX, CX, AX POPAD ------------------------------------- pop all doubleword Baknz: POPA POPAW ------------------------------------- pop all word Baknz: POPA PUSH -------------------------------------- PUSH O1 Stak 'a eleman göndermeye yarar, ama o1 8- Bitlik bir eleman olamaz. Eger O1 16-Bit ise SP = SP- 2 eger O1 32-Bit ise SP= SP- 4 olur. PUSHA -------------------------------------- push all 16 bitlik bütün registerleri su sirada pushlar; AX, CX, DX, BX, SP, BP, SI, DI. PUSHAD ------------------------------------ push all doubleword baknz: PUSA PUSHAW -------------------------------------- push all word baknz: PUSHA SMSW --------------------------------------- store machine status word SMSW O1 SMSW CR0 in ilk 16 bitini O1 e kaydeder. Aslinda isletim sisteminin ihtiyac duydugu, bir komuttur ve bir uygulamada kullanilmasi gerekli degildir. MSRs -------------------------------------- 80 nin üzerinde MSR vardir, ama her islemcide degisik olabilirler. Bu yüzden Pogramlamada fazla kullanilmamaktadirlar, WRMSR ile EDX: EAX icindeki eleman yazilir, RDMSR ile okunurlar. Tip: Hayla merak ediyorsaniz Döküman Nr. 245472 de Pentium4 ün MSRs hakkinda bilgi bulabilirsiniz, developer.intel.com da. XCHG -------------------------------------- exchange XCHG O1, O2 Iki elemanin iceriklerini degistirir. XLAT --------------------------------------- translate XLAT [O1] XLAT DShttp://www.supermp3.org/images/smilies/frown.gifE)BX adresindeki degeri AL ye kopyalar. Önceden AL de hangi Byte istendigi yazilmalidir. Örnek: var db "ABCDE" ... lea bx, var mov al, 3 ;Dördüncü eleman XLAT ; AL=D ... XLAT ES: O1 EK B: NASILSINIZ? ; 2003 Anil Öner .model small .data msg db "Iyimisiniz?([E]vet/[H]ayir)$" msg2 db 0Ah, "Iyi. http://www.supermp3.org/images/smilies/smile.gif$" msg3 db 0Ah, "Kotu. http://www.supermp3.org/images/smilies/frown.gif$" .code start: mov ax, @data ; ds = data mov ds, ax mov ah, 09h lea dx, msg ; Ekrana msg yi yaz. int 21h mov ah, 07h int 21h cmp al, 'e' je sec_1 cmp al, 'E' je sec_1 ; e yada E ise sec_1 e git. mov ah, 09h lea dx, msg3 ; degilse msg3 u ekrana yaz int 21h sec_1: ; iyi ise mov ah, 09h lea dx, msg2 int 21h son: mov ah, 04ch ; cikis int 21h end start ends EK C: AMD vs Intel(I64 vs X86-64) Bu yazimda size bir kac yeni teknolojiden söz edecegim. Eminim ki aranizda Ia64 ve x86-64 ü duymus olanlar vardir. Bu iki teknolojide 64- Bitlik sistemler. Ia64 ---------------------------------------------------------------------------- Intelin CISC tabanli islemcileriyle Hp nin RISC tabanli islemcilerinin komutlarinin birlestirilmesiyle olusmus EPIC teknolojisine dayaniyor. Ilk EPIC islemci Itanium' du. Itanium Server ler icin gelistirilmis bir islemciydi, bu yüzden pahali. IA64 gercekten cok fazla registere sahip. Bu yüzden ziplama orani düsürülebiliyor. Buda gercekten cok iyi bir performans demek oluyor. Tabiki EPIC in gercek ten zor oldugunu söylemem gerek. Bunun disinda derleyicilerde EPIC icin cok optimize edilmis kod yaratamiyorlar. Iste örnek bir kod: Mantik Eger p1=p2 r2=r3+r4 Yoksa r7=r6-r5 EPIC: cmp.eq p1, p2 = r1, r0 (p2) br.cond else_clause add r2 = r3, r4 br.endif else_clause: sub r7 = r6, r5 endif: .... Tabiki yukaridaki kod daha optimize edilmeden x86 gözüyle bakilarak yazildi, yani ziplama komutlariyla. Ayni Kodun optimize edilmis hali: EPIC: cmp.eq p1, p2 = r1, r0 (p1) add r2 = r3, r4 (p2) sub r7 = r6, r5 ... x86-64 |
Simdide x86-64 sistemine bakalim. Ia64 ün aksine x86-64 Ia32 programlarini da 64- Bitlik programlarla ayni hizda calistirabiliyor. Eski x86 komut satirini kullaniyor, ama tabiki bircok yeni gelismeyle, bulardan en önemlileri: -Eski registerlerin 64- Bitlik leri ve 8 yeni 64- Bit register. -Daha temiz ve kullanisli bir FPU -Gercek 64 Bitli adresleme x86-64 de Intelin 16- Bit den 32- Bit e gecerken yaptigi straji kullaniliyor. Ilk x86-64 islemci AMD denin Hammer adli islemcisi. Gcc de derlenmis örnek bir kod su sekilde gözüküyor: Hammer: gcc ------------------------------------------------------------------------------- C: int bar(int a,int b,int c) { return foo(a,b,c,0); } bar_x86: bar_hammer: pushl %ebp xorl %ecx, %ecx movl %esp, %ebp jmp foo pushl $0 pushl 16(%ebp) pushl 12(%ebp) pushl 8(%ebp) call foo addl $16, %esp leave ret ... Ve Gelecek ---------------------------------------------------------------------------- Peki ya gelecek, acaba Intel IA64 üylemi yeni nesil islemci modelini belirleyecek, yada AMD x86-64 üylemi. Nasil olursa olsun 64- Bit lik islemcilerin kapida oldugunu görmemek olagan degil. Intel Serverler icin 64- Bitlik islemci yaratmaya calisirken, AMD Desktop Pc ler icin bunun aynisi yapmaya calisiyor. Peki ya gercektende Desktop Pclerin buna ihtiyaclari varmi? Gercektende gelecekte 16TByte lik Ram lar kullanmamiz gerekecekmi? Iste bu tip sorularin cevabini vu yilin sonuna dogru Amd nin Hammer islemcisi cikinca alacagimizi düsünüyorum. Eger AMD Hammer tutarsa büyük ihtimalle Intel 32- Bitlik Pentium 5 in tasarimini 64- Bitlik EPIC tasarimiyla zenginlestirip, masaüstüne sunmaya calisacaktir. Ama su anda x86-64 daha parlak bir gelecege sahip benziyor, cünkü 32Bitlik programlar cok fazla. Ve Intelin EPIC seti 32 Bitlik islemcileri gercekten yavas calistiriyor. Yani su birkac yil bilgisayarlar icin cok önemli, Iyi calismalar... Kaynaklar: ----------------------------------- Welcome to Intel (Welcome to Intel) Advanced Micro Devices, AMD ? Global Provider of Innovative Microprocessor, Graphics and Media Solutions (Advanced Micro Devices, AMD ? Global Provider of Innovative Microprocessor, Graphics and Media Solutions) AMD Athon 64 IA64 Assembler IA64 vs X86-64 was soll ein Hacker darüber wissen? Itanium Sowftware Developer's Manual Volume 1,2,3 EK C: Küyük bir isletim sistemi YAZMAK! Hangi Dil? ---------------------------------------------------------------------------- Isletim sistemini aslinda C/C++ da yapmak isterim, ama mesela ekrana girdi vermek istedigimde bunun icin gerekli olan "printf" komutunu cagirmam gerektigini varsayalim. O zaman adindaki baslik dosyasini kullanmam gerekmekte.Ama sorun her basligin C/C++ derliyicileri tarafindan belli isletim sistemler(yada belli sistemler) icin tasarlandigi icin ne yazikki C/C++ dillerini cekirdegi yazarken kullanmayacagim fakat sonradan isletim sisteminin devamini C/C++ ile yazabilirsiniz. Söyle düsük seviyede Assembler bilginiz olmasi sizin cekirdegi daha iyi anlamanizi saglayacaktir... Gerekenler --------------------------------------------------------------------------- 1.Netwide Assembler (NASM) 2.RaWrite yada Diskete Imageleri yazacak baska bir program. 3.Bos bir disket. Buraya Dikkat! ---------------------------------------------------------------------------- Size söylemem gerekirki Assembler ile cok sey yapilabilir(yada cok sey yanlis yapilabilir).Bu bilgisayariniza gelebilecek herhangibir zarar benim degil, sizin sucunuzdur! Basliyoruz ---------------------------------------------------------------------------- Bir isletim sisteminin nasil calistigini anlamak icin, önce bir bilgisayarin nasil calistigini iyi anlamak gerekir. Burada kisaca söylüyorum ki, önce bilgisayar acilir, hemen BIOS devreye girer ve denetimler yaptiktan sonra isletim sistemini cagirir. BIOS hangi sürücünün önce "BOOT" lanacagini belirler. Isletim sistemini önce yerel sürücüde arar. Biz isletim sistemimizi diskete yazacagiz. Simdik kodlari yazmaya basliyalim; ---------------------------------------------------------------------------- Ilk Kernel: Tabiki bir Kernel sadece bir mesaj ekrana yazip sistemi yeniden baslatmak la kalmaz ama böyle bir kod yapiyi anlamak icin kolaydir: -------------------------------------------------------- mov ax, 1000h mov ds, ax mov es, ax start: ; Burda gercek anlamda isletim ; sistemimize basliyoruz. mov si, msg ; hemen bir string gösteriyoruz call put call read ; "oku" bir tusa basilana kadar bekler jmp reset msg db "Yeniden baslatmak icin bir tusa" db "basin!",13,10,0 put: lodsb or al, al jz short put_d mov ah, 0x0E mov bx, 0x0007 int 0x10 jmp put put_d: retn read: mov ah, 0 int 016h ret reset: db 0Eah dw 0000h dw 0FFFFh --------------------------------------------------------- Dosyayi kernel.asm diye kaydettikten sonra; nasm –f bin –o kernel.bin kernel.asm seklinde derlenmelidir. Bir BOOTMANAGER ---------------------------------------------------------------------------- BIOS ilk acildiginda 512Bytes boyutunda bir OP-Code arar ve BIOS bu dosyayi 0x7C00 adresine yükler. -----------------------BOOT.ASM-------------------------- org 0x7C00 ; Öncelikle dosyanin adresini ayaliyoruz. start: cli ; Interrupts kullanma! mov ax, 0x9000 ; Stack adresini kayit etme mov ss, ax mov sp, 0 ; Stackpointer' 0 lamak sti mov [bootdriv], dl call load ; Kernel i yükleme mov ax, 0x1000 ; 0x1000 Shell' in adresi mov es, ax mov ds, ax push ax mov ax, 0 push ax retf bootdriv db 0 loadmsg db "Sistem Yükleniyor...",13,10,0 putstr: lodsb or al,al jz short putstrd mov ah,0x0E mov bx,0x0007 int 0x10 jmp putstr putstrd: retn load: push ds mov ax, 0 mov dl, [bootdriv] int 13h pop ds jc load load1: mov ax,0x1000 mov es,ax mov bx, 0 mov ah, 2 mov al, 5 mov cx, 2 mov dx, 0 int 13h jc load1 mov si,loadmsg call putstr retn ;Programin 512 Bytes dan büyük olmamasi icin... times 512-($-$$)-2 db 0 dw 0AA55h ; Bu da BIOS sa bitis talimatini verir ---------------------------------------------------- nasm –f bin –o boot.bin boot.asm seklinde de dosya derlenmelidir. Simdide isletim sistemimizi Diskete yükleyip calistirmak icin; copy boot.bin+kernel.bin vitaxia.img Seklinde iki dosyayi birlestiriyoruz. Son olarak da RaWrite programi ile bu img dosyasini diske yaziyoruz. Disketi sokup bilgisayari yeniden baslattigimizda isletim sistemimiz calisacaktir. Son olarak tabi ki bunu hepsi sadece bir örnek, nasil bir isletim sistemi yapabilecegimize dahil. |
Z80 ASSEMBLY LANGUAGE PROGRAMMING EXERCISES 1. k is the contents of memory location FC00H representing an unsigned 8-bit number. Write a Z-80 Assembly language program that computes the following equations depending on the initial value of k. Store the result in memory location FC00H. 2. Write a Z-80 Assembly language program that adds the two digits of a BCD number in memory location FC00H. Place the BCD result in memory location FC01H. example: Address Contents of Memory Loc. FC00 39H FC01 12H ; <== 3+9=12 (BCD result) 3. Write a Z-80 Assembly language program that computes the 2’s complement of a 16-bit number stored in memory locations FC01H (LObyte) and FC02H (HIbyte). Store the result in in memory locations FC03H (LObyte) and FC04H (HIbyte). See the example given on the right hand side. example: Address Contents of Memory Loc. FC01 FFH FC02 C6H FC03 01H Result: LObyte FC04 39H Result: HIbyte C6FFH= 1100011011111111B 2’s complement= 0011100100000001B 4. Write a Z-80 Assembly language program that merges the least significant digits of two bytes in memory locations FC00H and FC01H. The most significant digits of the bytes will be discarded. (see the example). Place the resulting byte into memory location FC02H. example: Address Contents of Mem. Loc. FC00 2AH FC01 C3H FC02 A3H result 5. Write a Z-80 Assembly language program that adds ten numbers (8-bit each) stored in memory locations F000H-F009H with ten numbers (8-bit each) stored in memory locations D000H-D009H. Assume that the results of additions are also 8-bit and store the results in memory locations F000H-F009H. contents of memory location F000H + contents of memory location D000H will be stored in memory location F000H contents of memory location F001H + contents of memory location D001H will be stored in memory location F001H and so on (ten additions in total). In your program, use a program loop and index registers as address pointers. 6. Write a Z-80 Assembly language program that adds two 32-bit numbers in memory locations FC00H-FC03H and FC04H-FC07H, respectively (use a program loop). The least significant bytes of both numbers are in memory locations FC00H and FC04H respectively. Store the result in memory locations FC08H-FC0BH. |
Türkiye`de Saat: 17:15 . |
Powered by: vBulletin Version 3.8.1
Copyright ©2000 - 2024, Jelsoft Enterprises Ltd.
SEO by vBSEO 3.3.2