How does an assembler work?
Posted: (EET/GMT+2)
In an earlier article I discussed why it can be useful for a programmer to understand how the computer's processor works. If you want to try programming the processor directly, you will need a tool called an assembler.
An assembler is a program which converts assembly language instructions into machine code. Machine code is the binary instructions which the processor can execute directly.
For example, the Intel processors used in most PCs understand instructions for moving data, doing calculations and jumping to different parts of a program. In assembly language, these instructions have names such as MOV, ADD and JMP.
Consider the following two instructions:
MOV EAX, 10 ADD EAX, 20
The first instruction places the value 10 into the EAX register. The second adds 20 to it, so the register will contain 30.
The processor doesn't understand the text commands MOV or ADD. The assembler converts these instructions into the correct bytes for the processor.
For example, the two instructions above can be represented using these hexadecimal bytes:
B8 0A 00 00 00 83 C0 14
When the processor sees these bytes as executable code, it executes the instructions one at a time.
The assembler also handles labels. Instead of calculating the addresses of jumps yourself, you can give a location a name and refer to that name in your instructions.
MOV ECX, 5
Again: DEC ECX
JNZ Again
The assembler calculates the address of the label and creates the necessary jump instruction. In this example, the loop executes until ECX becomes zero.
One assembler available for Intel processors is Microsoft Macro Assembler (MASM). It uses source files with the .ASM extension and can produce object files which are then processed by a linker.
Source file (.ASM) > Assembler > Object file (.OBJ) > Linker Executable file (.EXE)
The assembler and linker have different jobs. The assembler converts your instructions into machine code and creates information about the symbols used in the program. The linker combines object files and libraries, resolves references and produces the executable program.
Writing a complete Windows application in assembly language requires some additional work, because you must also use the Windows API and follow the rules for calling its functions.
However, you don't need to start with a complete application. Studying a few simple instructions is already a good way to learn how the processor works. For more information, see the Microsoft Macro Assembler documentation and the Intel Architecture programmer's manuals.
Happy assembling!