Microprocessors · Lecture Notes
Chapter 3.1: Programming Languages
A processor recognizes only bits. Every byte it reads from memory is either part of an instruction or a piece of data, and the flow of the program decides which. A person, on the other hand, thinks “add a and b and store the result in x.” Programming languages were invented to close the gap between these two worlds. These notes climb that gap layer by layer. At the bottom is machine language, which the processor executes directly; we follow, step by step, how a few bytes of 8086 code are fetched and executed from memory. On a small, made-up instruction format we encode and decode instructions by hand. Next come assembly language, the two passes of the assembler, the linker, and the loader. Writing the same “Welcome” program in six different environments shows how strongly assembly code depends on both the processor and the operating system. The last sections divide high-level languages into compiled, interpreted, and hybrid ones. A program that decides whether a number is odd or even is read in fourteen languages and, finally, in 8086 assembly.
Learning outcomes
- Distinguish the language levels
- Explain the difference between machine language, assembly language, and high-level languages in terms of abstraction, portability, and control over the hardware.
- Read and write machine code
- Encode and decode binary instructions for a given instruction format; trace how 8086 bytes such as
A1 00 02are fetched from memory and executed. - Describe the toolchain
- Explain the two passes of the assembler, the symbol table, the linker, and the loader; read a listing file.
- Show platform dependence
- Explain, through system calls and calling conventions, why the same program is written differently for x86, 68000, ARM, PowerPC, and different operating systems.
- Compare compilation and interpretation
- Compare compilers, linkers, interpreters, intermediate code, and JIT compilation in terms of speed, portability, and error detection.
- Read across languages
- Trace the same algorithm in several languages and in 8086 assembly; show how
forandifconstructs turn into comparisons and conditional jumps.
3.1.1Software and language levels
3.1.1.1The role of software and its layers
The hardware of a computer does nothing on its own. The processor, memory, and input/output units are ready to work the moment power is applied, but they do not know what to do or in what order. Software supplies that knowledge. Software is the body of instructions and data that makes the hardware work correctly, in coordination, and in the desired way. In an electronic circuit a control unit determines the sequence of signals; in a computer, the program in memory determines that sequence.
The most fundamental piece of software is the operating system. The operating system manages the hardware: it shares memory among programs, arbitrates access to the disk and the screen, and keeps concurrently running programs from corrupting one another. Application programs do not touch the hardware directly; when they want to open a file or write text to the screen, they ask the operating system for a service. Such a request is called a system call, and we will see its details in the “Welcome” programs. The operating system in turn reaches the hardware through drivers, which know the device-specific details.
Figure 3.1.1 shows this arrangement as four layers. The user is at the top and the hardware at the bottom. Each layer uses only the services offered by the layer immediately below it. Applications such as a browser, a compiler, or a game use the operating system, and the operating system uses the processor, memory, and input/output units.
Programming languages are used to write applications, operating systems, and drivers. A programming language is an artificial language, with precisely defined rules, for describing a task step by step. Today there are hundreds of them. Some target operating systems, some numerical computation, some web pages. The history of languages also mirrors the history of computer technology. The first computers were programmed with wires and switches. As memories grew and processors got faster, languages appeared that shifted the programmer's burden onto the machine.
3.1.1.2Three language levels
Programming languages fall into three levels according to how close they are to the hardware. Figure 3.1.2 stacks these levels; as we move up, abstraction increases, that is, the programmer sees fewer of the hardware's details.
Machine language consists of the binary instructions that the processor executes directly, with no translation. Assembly language writes each machine instruction with a memorable name such as MOV or ADD, that is, a mnemonic. An assembly line usually corresponds to a single machine instruction. A high-level language is written with variables, expressions, loops, and functions, independently of the processor's instructions; one line usually turns into several machine instructions.
High-level languages split further into two groups. In compiled languages (C, Rust, Go) the source code is translated entirely into machine language before the program runs. The resulting file runs directly on the processor. In interpreted languages (Python, Ruby) the source code is read and processed at run time by a program called an interpreter. The examples in the figure show the distinction: the line MOV AL, 5 is assembly language, and its equivalent, the bits 1011 0000 0000 0101, is machine language.
As the level rises, three things change together. The first is readability. Anyone who reads the line x = a + b understands what is being done; decoding the machine code for the same job requires an instruction table. The second is portability. A program written in C can be compiled for x86 as well as for ARM, whereas 8086 machine code runs only on the 8086 family. The third is direct control, and it moves the opposite way. In a high-level language the compiler decides which register holds a variable and which jump instruction builds a loop. The assembly programmer chooses every register, every flag, and every memory access personally. For hardware-near work such as device drivers, interrupt handlers, or bootloaders, this control is necessary.
For an electrical and electronics engineer, these levels can be thought of through a familiar analogy. Machine language is the bit patterns applied to the control inputs of a digital circuit. Assembly language is a symbol list that gives those patterns names. A high-level language resembles describing behavior in a hardware description language and leaving the details to the synthesis tool. The job is the same at every level; what changes is who fills in the details.
3.1.1.3The same operation at three levels
The best way to see the difference between the levels is to write the same job at all three. The job is simple: add the variables a and b and store the result in the variable x. All three variables are 16-bit integers.
In C this job is a single line:
x = a + b;This line does not say where the variables live in memory or in which register the addition is performed. Those decisions are left to the compiler. In 8086 assembly language the same job takes three lines:
MOV AX, [a] ; load a into AX
ADD AX, [b] ; AX = AX + b
MOV [x], AX ; store the result in xHere everything is explicit. The addition is done in the AX register. The square brackets mean the contents of the memory cell at the variable's address. On the 8086, two memory operands cannot be used together in one instruction. For that reason a is first brought into a register, then b is added, and finally the result is written back to memory. Each line is a single machine instruction.
In machine language only bytes remain. Let the variables' addresses be a = 0200h, b = 0202h, and x = 0204h. The suffix “h” indicates that the number is written in hexadecimal. The assembler translates these three lines into the following bytes:
A1 00 02 ; MOV AX, [0200h]
03 06 02 02 ; ADD AX, [0202h]
A3 04 02 ; MOV [0204h], AXThe first byte of each instruction is the opcode: it tells the processor which operation to perform. A1 means “load the memory word into AX,” and the address follows immediately. A3 is its opposite: “store AX to memory.” These two are short forms specific to AX. 03, by contrast, is a general addition instruction: “add a register or a memory word to a 16-bit register.” Which register and which memory cell is determined by the second byte, called the ModR/M byte. 06 = 00 000 110b; the middle 000 encodes AX, while the outer 00 and 110 encode the case “the address is given directly inside the instruction.”
The order of the address bytes looks reversed at first glance: the address 0200h is written as 00 02. The 8086 stores multi-byte numbers in memory low byte first (little-endian). The low byte of 0200h is 00h and the high byte is 02h; 00h comes first, then 02h. The same rule applies to data: if a = 0015h, then address 0200h holds 15h and address 0201h holds 00h.
A common mistake is to read the address bytes in machine code in the order they are written. The address in the instruction A1 00 02 is 0200h, not 0002h. On the 8086, every 16-bit number inside an instruction, whether an address or a constant, is written low byte first. When you read a word in a memory dump, the second byte is likewise the high byte.
3.1.1.4Code trace: x = a + b in memory
To trace how these three instructions run in memory, let us put them into a small COM program. A COM program is the simplest executable file type, used by emu8086 and DOS. Code, data, and stack live in the same 64 KB segment; the program starts at offset 0100h of the segment.
org 100h
mov ax, [0200h] ; A1 00 02
add ax, [0202h] ; 03 06 02 02
mov [0204h], ax ; A3 04 02
ret ; C3org 100h is a directive: it generates no machine code and only tells the assembler that the first byte will be placed at address 0100h. The code is the 11 bytes in the range 0100h–010Ah: the three instructions take 3 + 4 + 3 = 10 bytes, and ret takes 1 byte. Let a = 0015h (21) and b = 0027h (39) initially; the value of x is unknown.
The processor handles each instruction in two phases. In the fetch phase the instruction bytes are read from the address IP points to, and IP advances by the instruction length. In the execute phase the opcode is decoded and the work is done. On the 8086 these two phases are divided between two separate units. The bus interface unit (BIU) reads instruction bytes from memory and fills a six-byte instruction queue. The execution unit (EU) takes bytes from this queue, decodes them, and executes them. If the bus is idle while the execution unit is working, the BIU prefetches the next bytes. The trace table shows the two phases on separate rows, but in a real processor the execution of one instruction and the fetching of the next can overlap in time.
| Step | Phase | Instruction bytes | IP | AX | 0204h–0205h (x) |
|---|---|---|---|---|---|
| 1 | fetch | A1 00 02 | 0100h → 0103h | ???? | ?? ?? |
| 2 | execute | read a word from 0200h: 15 00 | 0103h | 0015h | ?? ?? |
| 3 | fetch | 03 06 02 02 | 0103h → 0107h | 0015h | ?? ?? |
| 4 | execute | 27 00 from 0202h; 15h + 27h | 0107h | 003Ch | ?? ?? |
| 5 | fetch | A3 04 02 | 0107h → 010Ah | 003Ch | ?? ?? |
| 6 | execute | write AX to 0204h | 010Ah | 003Ch | 3C 00 |
| 7 | fetch, execute | C3 (RET) | 010Ah → return | 003Ch | 3C 00 |
In step 1, IP = 0100h. When the processor reads the byte A1, it learns that the instruction is three bytes long; the following bytes 00 02 form the address. The address is read little-endian: 0200h. IP advances to 0103h. In step 2 the execution unit asks for a word at address 0200h of the data segment. The BIU reads the 15h at 0200h and the 00h at 0201h; AX becomes 0015h. This read is a real bus cycle. The 8086's data bus is 16 bits wide and 0200h is an even address. The two bytes of the word therefore arrive in a single bus cycle, that is, in at least four clock periods. Had the word been at an odd address, two separate cycles would have been needed.
In step 3 the four-byte 03 06 02 02 is fetched. 03 carries the addition operation, 06 the information “destination AX, source direct address,” and 02 02 the address 0202h. In step 4, 0027h is read from 0202h and added to AX in the arithmetic logic unit: 0015h + 0027h = 003Ch, which is 21 + 39 = 60 in decimal. The addition also updates the flags: since the result is nonzero, ZF = 0; since the most significant bit is 0, SF = 0; and since there is no carry out, CF stays 0.
In step 5, A3 04 02 is fetched, and in step 6 AX is written to memory. The write is also done low byte first: 3Ch goes to address 0204h and 00h to address 0205h. Now x = 003Ch = 60. The byte C3 in step 7 is the RET instruction; the COM program hands control back to the system that ran it. Figure 3.1.3 shows three moments of this trace.
x = a + b machine code. At the top, the first instruction has executed and AX = 0015h; in the middle, the addition is done and AX = 003Ch; at the bottom, AX has been written to addresses 0204h and 0205h as 3C 00. Highlighted boxes are the bytes used in that step.This trace shows what a single line of C turns into in hardware. The line has become three instructions and ten bytes of machine code. To these are added three data accesses and the bus cycles that fetch the instruction bytes. The timing table in the 8086 user's manual also gives the durations of these instructions. Loading memory into AX takes 10 clock periods. Adding a memory word to a register with direct addressing takes 9 + 6 = 15, and writing AX to memory again takes 10. Since one clock period is 200 ns on a 5 MHz 8086, these three instructions take about 35 × 200 ns = 7 µs. Periods spent waiting for fetches when the instruction queue runs empty may be added to these times.
What happens to x and the flags if the same program is run with a = 7FFFh and b = 0001h?
The addition gives 7FFFh + 0001h = 8000h. Memory receives 0204h ← 00h and 0205h ← 80h. The result is not zero (ZF = 0). Because the most significant bit is 1, SF = 1. In unsigned addition there is no carry out of 16 bits (CF = 0). Viewed as signed numbers, however, the sum of two positives appears negative: +32767 + 1 yields −32768. This is a signed overflow and OF = 1. The processor merely records the overflow in the OF flag and carries on. C does not report signed overflow by itself either; the language standard treats this case as undefined behavior. Checking for overflow is the programmer's job.
3.1.2Machine language
3.1.2.1The only language the processor understands
Machine language is the lowest-level language, made of 0s and 1s. The processor's control unit decodes the bit pattern it reads from memory and drives the registers, the arithmetic logic unit, and the data bus accordingly. This decoding is done by decoder circuits: a given opcode activates given control lines. Machine language is therefore entirely dependent on the processor and the hardware. Machine code written for one processor family is meaningless to the decoder of another family, or does something completely different.
ENIAC (1945), one of the first general-purpose electronic computers, did not work with a program loaded into memory. The program was set up on the hardware by plugging cables between units and setting switches. Rewiring for a new problem could take days. The idea of placing the program in memory like data solved this problem. The instructions in memory were now numbers, and the language of those numbers was machine language.
Today every processor family has its own machine language, in other words its own instruction set. Machine language is impractical to read and write, so programmers do not use it directly. Even so, a microprocessor engineer must be able to decode machine code. Reading a memory dump, making sense of the bytes on a bus with a logic analyzer, or checking what a compiler produced all rest on this skill.
Figure 3.1.4 shows how the job “load 5 into register AL” is encoded in two different machine languages. On the 8086 the job takes two bytes: B0 05. The upper four bits of the first byte, 1011, specify the “load a constant into a register” instruction. The next bit, w = 0, says that the operation is 8 bits wide. The last three bits, 000, select the destination register; among the 8-bit registers, 000 is AL. The second byte is the constant itself: 00000101 = 5. Had the same instruction been written for the 16-bit AX, w would be 1 and the constant would take two bytes: MOV AX, 5 = B8 05 00.
MOV AL, 5 is the two-byte B0 05: opcode 1011, the w bit, the register field, and the constant. On ARM, MOV r0, #5 is a single 32-bit word: E3A00005.On ARM processors, by contrast, every instruction is 32 bits long. The instruction MOV r0, #5 is translated into the word E3A00005. The top four bits of this word, 1110, are the “always execute” condition. The following fields encode that the instruction is a data-processing instruction, that the operation is MOV, that the destination register is r0, and the lowest eight bits hold the constant 5. For the same job the 8086 uses two bytes and ARM four. The position and meaning of the fields are completely different as well. This difference explains with a single example why 8086 code does not run on an ARM processor.
This dependence of machine language is softened by assembly languages. Assembly language is also tied to the processor, but it spares the programmer from fiddling with bit fields and makes programming friendlier.
3.1.2.2A sample instruction format
The instruction set of a real processor contains hundreds of instructions and dozens of formats. To see the main idea of machine language, it suffices to design a much smaller, made-up processor. Let this processor have four registers (R0–R3) and let every instruction be 8 bits. Figure 3.1.5 shows the fields of the instruction.
The instruction format is the layout that specifies into which fields the bits of a machine instruction are divided and what each field encodes. The opcode field specifies the operation to perform, and the operand fields specify which register, memory cell, or constant the operation acts on.
In the sample processor the meaning of an instruction always follows one pattern: destination ← destination operation source. The result is written to the destination register; the source register does not change. Registers are encoded with two bits: R0 = 00, R1 = 01, R2 = 10, R3 = 11. Two bits are exactly enough to tell four registers apart. The opcodes are given in Table 3.1.2.
| Opcode | Mnemonic | Meaning |
|---|---|---|
0000 | HALT | halt the program |
0001 | ADD | dest ← dest + src |
0010 | SUB | dest ← dest − src |
0011 | AND | dest ← dest AND src (bitwise) |
0100 | OR | dest ← dest OR src (bitwise) |
Because the opcode field is 4 bits, at most 24 = 16 different operations can be defined. This design uses only five; the remaining eleven codes are free for instructions added later. The width of a field determines how many things it can select: a field of k bits selects one of 2k things. Conversely, selecting one of n things takes at least ⌈log2 n⌉ bits.
An example instruction: 0001 10 11. The first four bits 0001 = ADD, the next two bits 10 = R2 (destination), and the last two bits 11 = R3 (source). The instruction is ADD R2, R3 and performs R2 ← R2 + R3. In hexadecimal this byte is 1Bh. The convenience of hexadecimal shows here: the first hex digit is directly the opcode, and the second digit carries the destination and source fields together.
3.1.2.3Encoding and decoding instructions
Translating an assembly line into machine code is called encoding, and recovering an assembly line from a byte is called decoding. The assembler does the first; the disassembler and the processor's decoder do the second. The way to decode is to split the bits into their fields. Table 3.1.3 splits a four-instruction program into its fields.
| Machine code | Hex | Operation | Destination | Source | Meaning |
|---|---|---|---|---|---|
0001 0001 | 11h | ADD | R0 | R1 | R0 ← R0 + R1 |
0011 1011 | 3Bh | AND | R2 | R3 | R2 ← R2 AND R3 |
0100 0110 | 46h | OR | R1 | R2 | R1 ← R1 OR R2 |
0000 0000 | 00h | HALT | — | — | halt the program |
The format defines the first two-bit register field as the destination. Hence the result of each instruction goes to the register written first: R0 in the first instruction, R2 in the second, R1 in the third. The register fields are unused in HALT and are left as zero.
Let us encode SUB R2, R0 and decode the byte 4Dh.
The opcode of SUB is 0010, R2 = 10, R0 = 00. Written side by side, the fields give 0010 1000, which is 28h in hexadecimal. If R2 = 12 and R0 = 5, the instruction performs R2 ← 12 − 5 = 7, and R0 is unchanged.
4Dh = 0100 1101. The opcode 0100 = OR. The remaining four bits are 11 01: destination R3, source R1. The byte is the instruction OR R3, R1 and performs R3 ← R3 OR R1. If R3 = 1010 and R1 = 0011, the result is 1011 = 11.
3.1.2.4Code trace: the sample machine program
The program in Table 3.1.3 sits at addresses 0, 1, 2, and 3 in memory. The processor's program counter (PC) holds the address of the next instruction. On the 8086 this register is called IP. Each time an instruction is fetched, PC increases by one, because every instruction is a single byte.
0001 0001 ; ADD R0, R1 → R0 ← R0 + R1
0011 1011 ; AND R2, R3 → R2 ← R2 AND R3
0100 0110 ; OR R1, R2 → R1 ← R1 OR R2
0000 0000 ; HALTLet the initial values be R0 = 5, R1 = 3, R2 = 12, R3 = 10. To follow the logical operations, the values must also be written in binary. Table 3.1.4 gives the state after each instruction; the register that changed is shown in bold.
| Step | Instruction | PC | R0 | R1 | R2 | R3 |
|---|---|---|---|---|---|---|
| initial | — | 0 | 0000 0101 (5) | 0000 0011 (3) | 0000 1100 (12) | 0000 1010 (10) |
| 1 | ADD R0, R1 | 1 | 0000 1000 (8) | 0000 0011 (3) | 0000 1100 (12) | 0000 1010 (10) |
| 2 | AND R2, R3 | 2 | 0000 1000 (8) | 0000 0011 (3) | 0000 1000 (8) | 0000 1010 (10) |
| 3 | OR R1, R2 | 3 | 0000 1000 (8) | 0000 1011 (11) | 0000 1000 (8) | 0000 1010 (10) |
| 4 | HALT | 3 | 0000 1000 (8) | 0000 1011 (11) | 0000 1000 (8) | 0000 1010 (10) |
The first instruction is ADD R0, R1: 5 + 3 = 8, and the result is written to R0. The source R1 is unchanged. The second instruction is AND R2, R3. In a bitwise AND, only the bit that is 1 on both sides stays 1: 1100 AND 1010 = 1000, so R2 = 8. The third instruction is OR R1, R2. In OR, a bit that is 1 on either side becomes 1: 0011 OR 1000 = 1011, so R1 = 11. This instruction uses the value of R2 changed in the previous step. Since the instructions execute in order, each instruction sees the state left by the earlier ones. The fourth instruction is HALT and the processor stops. In this design PC is not incremented after HALT is fetched and stays at 3; in real processors this detail varies with the design. Result: R0 = 8, R1 = 11, R2 = 8, R3 = 10.
This small processor also carries the basic working cycle of the 8086: fetch, advance PC, decode, execute, write the result.
3.1.2.5Pros and cons of machine language
The pros of machine language come from its closeness to the hardware. No translation is needed; the processor runs the code as it is. The programmer has full control over the hardware: which byte is written where and which instruction comes in what order are all their decisions. Written well, this is also how the smallest and fastest code is obtained.
The cons are heavy. Machine code is unreadable, and it is very hard to write and debug. A single wrong bit turns an instruction into another one; if 0011 0001 is written instead of 0001 0001 (ADD R0, R1), the addition becomes an AND. The code is not portable either. The program has to be rewritten from scratch for every processor.
Perhaps the most annoying problem is computing addresses by hand. Jump instructions carry the address of the target. When an instruction is inserted in the middle of the program, the addresses of all the following instructions shift, but the addresses inside the jump instructions stay as they were. Figure 3.1.6 shows this situation.
JMP 0105h reaches the right target. At the bottom, a two-byte instruction has been inserted; the target has moved to 0107h, but the jump still goes to 0105h.The programmer must then find and fix all the jump addresses again. In a large program this takes a long time and is error-prone. To solve these problems, assembly languages (1950s) were developed first, followed by high-level languages such as FORTRAN (1957). In assembly language a jump target is written as a label; the assembler recomputes its address every time.
A common mistake is to mix up the order of the fields in the instruction format. In the sample processor the destination field comes before the source: 0010 11 00 is SUB R3, R0 and performs R3 ← R3 − R0. If the fields are read in reverse, SUB R0, R3 results; because subtraction is not commutative, the result is written to a different register with a different value.
3.1.3Assembly languages and the assembler
3.1.3.1Mnemonics
The first gain of assembly language is names. The programmer writes MOV AL, 5 instead of 10110000 00000101. MOV is a mnemonic: as an abbreviation of the word “move,” it reminds you what the instruction does. AL is the name of a register, and 5 is a constant written in decimal. The program that translates this line into machine code is called an assembler. Figure 3.1.7 shows what the translation does for a single line.
MOV AL, 5 into the machine code B0 05, that is, the bits 10110000 00000101.Assembly language is designed separately for each processor architecture and instruction set. Intel x86, Motorola 68000, ARM, PIC, and AVR processors each have their own assembly language. The register names and instructions valid in one are absent in another. Within a processor family, however, compatibility is preserved. An assembly program written for the 8086 can, with small differences, also be assembled and run on the 80286, 80386, and today's x86 processors. Assembly languages specific to microcontrollers are still widely used in embedded systems and electronics applications.
Assembly language remains important today, when high-level languages are widespread, for three reasons. First, some code can be written only in assembly. The bootloader that runs first when a computer powers on, interrupt handlers, the hardware-touching parts of device drivers, and the context-switching parts of an operating system kernel are of this kind. Second, the way to understand how a processor really works runs through assembly. Why a program crashed, what the code shown by a debugger does, or examining software by reverse engineering all require reading assembly. Third, performance. Special instructions that the compiler cannot generate by itself, such as SIMD or cryptographic instructions, and time-critical loops are still written by hand.
3.1.3.2From source code to a running program
The text file the programmer writes is called source code. Three tools take part on the way from source code to a running program. Figure 3.1.8 shows this toolchain.
- Assembler
- Reads the source file (
prog.asm) and translates each line into machine code. Its output is an object file (prog.objorprog.o). The object file contains machine code but is not yet complete. The addresses of functions defined in other files are left blank, and these blanks are recorded in a list. MASM, NASM, TASM, and GNU as are tools that do this job. - Linker
- The linker combines one or more object files and libraries (
.lib,.obj). It fills in the blank addresses and produces an executable file (prog.exe) in a form the operating system understands. Microsoft's LINK and GNU's ld are common linkers. - Loader
- The loader is a part of the operating system. It copies the executable file from disk into memory, sets up the segment registers and the stack, adjusts addresses to where the program was loaded if necessary, and hands control to the program's first instruction.
The assembler has one more output: the listing. The listing writes, next to each source line, that line's address and the machine code it produced. The listing of a small DOS program that prints “Welcome!” on the screen is as follows:
Address Machine code Source
0100 B4 09 mov ah, 09h
0102 BA 0C 01 mov dx, offset msg
0105 CD 21 int 21h
0107 B8 00 4C mov ax, 4C00h
010A CD 21 int 21h
010C 57 65 6C ... msg db 'Welcome!$'The listing can be read line by line. mov ah, 09h is two bytes: B4 means “load a constant into AH,” and 09 is the constant. mov dx, offset msg is three bytes: BA means “load a 16-bit constant into DX,” and the constant is 010Ch, the address of the label msg, written little-endian as 0C 01. int 21h is two bytes: CD is the interrupt instruction and 21 is the interrupt number. mov ax, 4C00h loads 4C00h into AX, that is, AH = 4Ch and AL = 00h. The db (define byte) directive on the last line produces data, not an instruction: the ASCII codes of the characters “Welcome!$” sit one after another in memory. The listing is used both to check what the assembler produced and to match addresses with source lines in a debugger. emu8086 performs all of these steps with a single key and produces the COM or EXE file directly.
3.1.3.3The assembler's two passes
There is an interesting situation in the listing above. The line mov dx, offset msg is the second line, but the label msg is defined at the very end. When the assembler reaches this line, it does not yet know the address of msg. Referring to a label before its definition is called a forward reference. Assemblers solve this problem by reading the source code twice.
A two-pass assembler reads the source code from start to end twice. In the first pass it computes how many bytes each line takes and advances the location counter (LC). It also writes each label into the symbol table with the current LC value. In the second pass it produces the machine code using the addresses in the symbol table.
The location counter holds the address in memory where the next byte will be placed. In the source it can be read with the $ sign. There is an important condition for the first pass: the length of every instruction must be computable without knowing the value of the operand. That mov dx, offset msg is 3 bytes is known whatever the value of msg turns out to be. The program being traced is this:
org 100h
mov ah, 09h
mov dx, offset msg
int 21h
mov ax, 4C00h
int 21h
msg db 'Welcome!$'| Pass | Line | Length | LC (after the line) | Symbol table | Bytes produced |
|---|---|---|---|---|---|
| 1 | org 100h | 0 | 0100h | msg = ? | — |
| 1 | mov ah, 09h | 2 | 0102h | msg = ? | — |
| 1 | mov dx, offset msg | 3 | 0105h | msg = ? | — |
| 1 | int 21h, mov ax, 4C00h, int 21h | 2 + 3 + 2 | 010Ch | msg = ? | — |
| 1 | msg db 'Welcome!$' | 9 | 0115h | msg = 010Ch | — |
| 2 | mov ah, 09h | 2 | 0102h | msg = 010Ch | B4 09 |
| 2 | mov dx, offset msg | 3 | 0105h | msg = 010Ch | BA 0C 01 |
| 2 | three lines | 7 | 010Ch | msg = 010Ch | CD 21 B8 00 4C CD 21 |
| 2 | msg db … | 9 | 0115h | msg = 010Ch | 4D 65 72 68 61 62 61 21 24 |
The first pass only counts. org 100h sets LC to 0100h; being a directive, it produces no bytes. mov ah, 09h takes 2 bytes and LC becomes 0102h. On the third line msg is not yet defined, but the instruction is known to be 3 bytes and LC advances to 0105h. The next three instructions are 2, 3, and 2 bytes; LC reaches 010Ch. On the last line the label msg is seen and enters the symbol table with the current LC: msg = 010Ch. The string is 9 characters (“Welcome!” is eight characters plus the trailing $), and LC becomes 0115h.
The second pass restarts LC from 0100h and this time produces the bytes. For mov ah, 09h, B4 09 is written. offset msg is now read from the symbol table: 010Ch, little-endian 0C 01. The remaining instructions are CD 21, B8 00 4C, and CD 21. Finally the ASCII codes of the string are written: W = 57h, e = 65h, l = 6Ch, c = 63h, o = 6Fh, m = 6Dh, e = 65h, ! = 21h, $ = 24h. The output is a COM file of 0115h − 0100h = 15h = 21 bytes. When run, it prints “Welcome!” on the screen. Figure 3.1.9 shows the state at the end of the two passes.
The two-pass structure also solves the address-shifting problem of machine language by itself. If the programmer inserts an instruction, the assembler recomputes the addresses of all labels at the next assembly and writes the new addresses into the jump instructions.
A common mistake is to take directives for instructions. org, db, equ, and offset are not processor instructions; they are information given to the assembler. org 100h produces no bytes and only sets the location counter. db produces data, not an instruction. If the processor reaches the bytes of a db line as if they were instructions, it tries to decode them as instructions too; this is why data is placed after the code.
3.1.3.4Assemblers and their syntax
There is more than one assembler for the same x86 processor, and they do not all follow the same rules. The rules that govern how an assembly line is written are called syntax. Two main syntaxes are used for x86: Intel and AT&T. Table 3.1.6 summarizes the common assemblers.
| Assembler | Syntax | Use |
|---|---|---|
| MASM | Intel | Microsoft, Windows |
| TASM | Intel | Borland, DOS |
| NASM | Intel | open source, multi-platform |
| GAS (as) | AT&T | GNU/Linux; the assembler used by gcc |
| emu8086 | Intel (MASM-like) | an 8086 emulator; the tool of this course |
The most important difference between the two syntaxes is the order of the operands. In Intel syntax the destination is written first and then the source. In AT&T syntax the order is reversed: source first, then destination. The same two instructions look like this in the two syntaxes:
; Intel: destination, source
mov eax, 5
add eax, [ebx+4]
# AT&T: source, destination
movl $5, %eax
addl 4(%ebx), %eaxIn AT&T syntax, register names are prefixed with % and constants with $. The operand size is indicated by the letter at the end of the instruction: b means 8, w 16, and l 32 bits. A memory operand is written as offset(base) instead of with square brackets: 4(%ebx) is the same address as [ebx+4] in Intel syntax. The comment character differs too: assemblers with Intel syntax use ;, while GNU as uses # on x86. Both notations give the processor the same bytes. The difference is only in the text a human reads.
A common mistake is to read AT&T code produced by a compiler with Intel conventions. The instruction subl %ebx, %eax does not subtract EAX from EBX; it performs EAX ← EAX − EBX, that is, Intel's sub eax, ebx. By default gcc and clang produce AT&T syntax; the -masm=intel option switches the output to Intel syntax.
3.1.4“Welcome” in different environments
A program that prints a short text on the screen is the smallest complete example of a language or an environment. In this section the same job is done in six environments: 32-bit Linux, DOS, Windows, the Motorola 68000-based Amiga, ARM, and PowerPC. All the programs follow the same three steps: define the text in memory, ask the operating system for the service “write this many bytes at this address to the screen,” and terminate the program. The differences lie in how each environment expresses these three steps.
3.1.4.1Linux, x86 (32-bit)
The first program runs on a 32-bit x86 processor under the Linux operating system and is assembled with NASM. The 16-bit registers AX, BX, CX, and DX of the 8086 were widened to 32 bits starting with the 80386; their 32-bit names are EAX, EBX, ECX, and EDX. AX is the lower half of EAX.
section .data
hello db 'Welcome, Linux!', 10
len equ $ - hello ; = 16 bytes
section .text
global _start
_start:
mov eax, 4 ; sys_write
mov ebx, 1 ; stdout
mov ecx, hello ; string address
mov edx, len ; byte count
int 0x80 ; call the kernel
mov eax, 1 ; sys_exit
xor ebx, ebx ; exit code 0
int 0x80The program consists of two sections. section .data opens the section where data lives, and section .text the section where code lives. The label hello marks the start address of the text; db places the bytes of the text and, at the end, 10, the newline character. The line len equ $ - hello occupies no memory. equ gives a name a constant value; $ is the current location counter. Subtracting the start address of the text from the location counter gives the length of the text. “Welcome, Linux!” is 15 bytes; with the newline it is 16 bytes. Having the assembler compute the length instead of counting by hand prevents an error when the text changes.
global _start makes the label _start visible to the linker. On Linux the linker looks for the program's entry point under this name. The code itself is two system calls. Table 3.1.7 gives the registers after each line.
| Line | EAX | EBX | ECX | EDX | Screen |
|---|---|---|---|---|---|
mov eax, 4 | 00000004 | ???????? | ???????? | ???????? | |
mov ebx, 1 | 00000004 | 00000001 | ???????? | ???????? | |
mov ecx, hello | 00000004 | 00000001 | hello (address) | ???????? | |
mov edx, len | 00000004 | 00000001 | hello (address) | 00000010 | |
int 0x80 | 00000010 | 00000001 | hello (address) | 00000010 | Welcome, Linux! |
mov eax, 1 | 00000001 | 00000001 | hello (address) | 00000010 | Welcome, Linux! |
xor ebx, ebx | 00000001 | 00000000 | hello (address) | 00000010 | Welcome, Linux! |
int 0x80 | process ends with exit code 0; the call does not return | ||||
The parameters of the first call are placed in registers. EAX = 4 is the number of the sys_write service in Linux's 32-bit call table. EBX = 1 is the file descriptor to write to; descriptor 1 is standard output, that is, the screen. ECX receives the address of the text, not its contents. EDX is the number of bytes to write: 16, which is 10h in hexadecimal. The int 0x80 instruction hands control to the kernel. The kernel writes the text to the screen and on return places the number of bytes written in EAX; that is why EAX becomes 00000010h.
The second call terminates the program. EAX = 1 is sys_exit. EBX carries the exit code, and 0 means success. xor ebx, ebx combines a number with itself using exclusive OR. Since every bit equals itself, the result is zero. This way produces shorter machine code than mov ebx, 0 (2 bytes against 5). XOR also affects the flags: because the result is zero, ZF = 1, and because it is a logical operation, CF = 0 and OF = 0. The last int 0x80 terminates the process and does not return.
A common mistake is to write the length by hand and then change the text. Had len been written as 15, the newline would not be printed and the next output would be appended to the same line. Had the text been shortened and the length left at 16, the memory bytes after the text would also be printed to the screen. $ - hello prevents both errors. Non-ASCII characters need extra care: in UTF-8, letters such as “ü” take 2 bytes; “Dünya” is 5 characters but 6 bytes.
3.1.4.2The system call
The Linux program did not write to the screen itself; it asked the kernel to do so. In modern operating systems, application programs cannot access the hardware directly. The processor's protection mechanism defines two operating modes. A program running in user mode cannot use input/output instructions and some control instructions. Kernel mode is privileged and open only to the operating system. When an application needs a hardware service, it crosses into the kernel through a controlled gate.
A system call is the special call by which a program requests a service from the operating system. The program puts the service number and the parameters in specific registers, then hands control to the kernel with a software interrupt or a special instruction. The kernel performs the service, places the result in a register, and returns control to the program.
int 0x80. The kernel selects the service by the number in EAX, writes to the screen through the driver, and returns the result in EAX.Figure 3.1.10 shows this path. int 0x80 is a software interrupt. The processor saves the flags and the return address, jumps to the address stored in entry number 80h of the interrupt table, and switches to kernel mode at the same moment. The entry routine in the kernel looks at EAX and calls the corresponding function from the service table. When the service finishes, a special return instruction both returns to the saved address and switches back to user mode.
The 8086 has no protection mechanism and no user/kernel mode distinction; every program can access everything. The interrupt mechanism is nevertheless the same. When executing INT n, the 8086 pushes the flags register, CS, and IP onto the stack and clears the IF and TF flags. It reads the new CS:IP from the interrupt vector table at the very beginning of memory. Each entry is 4 bytes; for INT 21h the entry is at address 21h × 4 = 84h. DOS writes the address of its own service routine into this entry. Table 3.1.8 compares the call paths in different environments.
| Environment | Call | Service number | Parameters |
|---|---|---|---|
| Linux 32-bit | int 0x80 | EAX (4 = write, 1 = exit) | EBX, ECX, EDX |
| Linux 64-bit | syscall | RAX (1 = write, 60 = exit) | RDI, RSI, RDX |
| MS-DOS | int 21h | AH (09h = write, 4Ch = exit) | DX, AL … |
| BIOS | int 10h | AH (0Eh = write character) | AL, BH … |
The table clearly shows that the numbers are specific to the environment. The “write” service is 4 on 32-bit Linux and 1 on 64-bit Linux. Even two versions of the same operating system use different numbers and different registers. BIOS services sit even below the operating system. These routines, held in the computer's permanent memory, work even before the operating system is loaded.
3.1.4.3DOS, 8086 (COM program)
The third program is in the environment of this course: a COM program running under DOS, assembled with emu8086.
org 100h ; COM program
mov ah, 09h ; DOS 09h: print string
lea dx, msg ; DS:DX = address
int 21h ; call DOS
mov ax, 4C00h ; DOS 4Ch: exit
int 21h
msg db 'Welcome, DOS!$'org 100h declares that the COM program will be loaded at offset 100h of the segment. When loading the program, DOS places a structure called the program segment prefix (PSP) in the first 256 bytes of the segment (0000h–00FFh). The program starts right after this structure. In a COM program all four segment registers point to the same segment: CS = DS = ES = SS. Code, data, and stack are within the same 64 KB.
mov ah, 09h selects DOS service number 09h: “print the string starting at DS:DX and ending with $ to the screen.” lea dx, msg loads the relative position of the label msg into DX (load effective address). Since DS already points to the program's segment, DS:DX is the full address of the string. int 21h calls DOS. DOS prints characters to the screen until it sees $; the $ itself is not printed. mov ax, 4C00h loads 4Ch into AH, that is, the “terminate the program” service, and the exit code 00h into AL. The last int 21h hands control back to DOS.
| Line | Machine code | IP (after) | AH | AL | DX | Screen |
|---|---|---|---|---|---|---|
org 100h | — | 0100h | ?? | ?? | ???? | |
mov ah, 09h | B4 09 | 0102h | 09h | ?? | ???? | |
lea dx, msg | BA 0C 01 | 0105h | 09h | ?? | 010Ch | |
int 21h | CD 21 | 0107h | 09h | ?? | 010Ch | Welcome, DOS! |
mov ax, 4C00h | B8 00 4C | 010Ah | 4Ch | 00h | 010Ch | Welcome, DOS! |
int 21h | CD 21 | 010Ch | 4Ch | 00h | 010Ch | program ends |
The addresses in Table 3.1.9 come from the instruction lengths. lea dx, msg is three bytes: emu8086 encodes a direct-address LEA in the same form as mov dx, offset msg, that is, the opcode BA and the address 0C 01 (MASM encodes the same instruction as a real four-byte LEA beginning with 8D 16). The code takes 2 + 3 + 2 + 3 + 2 = 12 bytes in the range 0100h–010Bh; that is why msg is at 010Ch. “Welcome, DOS!” is 13 characters and, together with $, occupies 14 bytes.
It is noteworthy that IP shows 010Ch on the second int 21h line: this address is the start of msg. Because the program terminates, the processor never reaches this address. Because the data is placed after the code, the processor does not mistake the data for instructions and execute it. Had the data been placed before the code, the program starting at 0100h would have decoded 57h, the code of the letter “W”, as an instruction. On the 8086, 57h is the PUSH DI instruction. The letters that follow would also turn into random instructions, and the program would behave unpredictably.
A common mistake is to forget the $ at the end of the string in service 09h. DOS has no other way to know where the string ends. Without $, it prints whatever lies after the code and data in memory until it hits the first 24h byte. You will see meaningless characters, beeps, and cursor jumps on the screen.
3.1.4.4Windows, Win32 API
Windows programs do not make system calls directly. The operating system's services are offered as functions in DLL (dynamic-link library) files. The program calls these functions with the call instruction like an ordinary subroutine. The following program opens a message box on the screen and then terminates the process.
extern MessageBoxA ; user32.dll
extern ExitProcess ; kernel32.dll
section .data
msg db 'Welcome, Windows!', 0
section .text
global _start
_start:
push 0 ; uType = MB_OK
push msg ; lpCaption (title)
push msg ; lpText (text)
push 0 ; hWnd = NULL
call MessageBoxA
push 0 ; uExitCode = 0
call ExitProcessThe extern lines say that the names MessageBoxA and ExitProcess are defined elsewhere. The assembler does not know the addresses of these names; it leaves a note in the object file: “let the linker fill this in.” Using the import information of the libraries user32.dll and kernel32.dll, the linker directs the calls to these functions. This time the string ends not with $ but with 0. The Windows API was designed with the C language in mind, and C strings end with a zero byte.
Parameters are passed not in registers but on the stack. In C the call has the form MessageBoxA(hWnd, lpText, lpCaption, uType). In assembly the parameters are pushed from right to left: uType first, hWnd last. That way the first parameter lands at the top of the stack, just above the return address, and the function always finds it in the same place regardless of the number of parameters. This program uses the same string for the title and the text; the two push msg instructions push the same address. Table 3.1.10 traces the state of the stack; 0012FF80h is taken as an example initial value of ESP.
| Instruction | ESP (after) | Address written ← value | EAX |
|---|---|---|---|
| initial | 0012FF80h | — | ???????? |
push 0 (uType) | 0012FF7Ch | 0012FF7Ch ← 0 (MB_OK) | ???????? |
push msg (lpCaption) | 0012FF78h | 0012FF78h ← &msg | ???????? |
| 0012FF78h ← &msg | 0012FF74h | 0012FF74h ← &msg | ???????? |
push 0 (hWnd) | 0012FF70h | 0012FF74h ← &msg | ???????? |
call MessageBoxA | 0012FF6Ch | 0012FF6Ch ← return address | ???????? |
function returns with ret 16 | 0012FF80h | — | 00000001h (IDOK) |
push 0 (uExitCode) | 0012FF7Ch | 0012FF7Ch ← 0 | 00000001h |
call ExitProcess | process ends with exit code 0; the call does not return | ||
The stack grows toward lower addresses. In 32-bit mode every push decreases ESP by 4 and writes the value at the address ESP now points to. Four parameters take 16 bytes. call also pushes the return address; at the moment of entering the function, ESP = 0012FF80h − 20 = 0012FF6Ch. Figure 3.1.11 shows this moment.
call MessageBoxA has executed. At the top is the return address, and above it the first parameter hWnd.When the user presses the OK button in the message box, the function returns. The return value is placed in EAX: 1, that is, IDOK, means “OK was pressed.” Windows API functions use the stdcall calling convention. In this convention the called function cleans the parameters off the stack. MessageBoxA returns with the ret 16 instruction: it first takes the return address (ESP + 4), then discards the 16 bytes of parameters (ESP + 16). ESP becomes 0012FF80h again. In the cdecl convention, used by C's own functions, the caller does this cleanup instead.
At link time one more detail may be encountered. In some 32-bit toolchains, stdcall functions are looked up under decorated names: _MessageBoxA@16. The leading underscore comes from the C naming convention, and the trailing 16 from the number of parameter bytes. At the 8086 level the same stack mechanism can be traced in 16-bit mode, with the only difference that each push takes 2 bytes.
3.1.4.5Motorola 68000, Amiga
Amiga computers use the Motorola 68000 processor. The 68000 is a processor of the same period (1979) as the 8086, but its architecture is different. It has eight data registers (d0–d7) and eight address registers (a0–a7); all are 32 bits. Memory is not divided into segments; addresses are linear.
move.l 4.w,a6 ; a6 = ExecBase
lea dosname(pc),a1 ; library name
moveq #0,d0 ; any version
jsr -552(a6) ; OpenLibrary()
tst.l d0
beq.s quit ; failed → quit
move.l d0,a6 ; a6 = DOSBase
jsr -60(a6) ; Output() → d0
move.l d0,d1 ; file handle
move.l #msg,d2 ; string address
moveq #16,d3 ; byte count
jsr -48(a6) ; Write(d1,d2,d3)
move.l a6,a1
move.l 4.w,a6
jsr -414(a6) ; CloseLibrary()
quit moveq #0,d0 ; return code 0
rts
dosname dc.b 'dos.library',0
msg dc.b 'Welcome, Amiga!',10In AmigaOS, system services are offered as libraries, and each library has a base address. Functions are called through a jump table that sits at negative offsets from this base. At memory address 4 is the base address of exec.library, the core library of the whole system. The first line loads this address into a6. lea dosname(pc),a1 puts the address of the library name into a1. moveq #0,d0 means “any version will do.” jsr -552(a6) jumps to the entry 552 bytes below a6; this entry is OpenLibrary.
On return, d0 holds the base of the opened dos.library. tst.l d0 and beq.s quit leave the program if the library could not be opened (d0 = 0). If it opened, the base is moved into a6. jsr -60(a6) is the Output() function and returns the handle of standard output in d0. The parameters of the Write(d1, d2, d3) call are passed in registers: the handle goes into d1, the address of the text into d2, and the length, 16, into d3. “Welcome, Amiga!” is 15 bytes; with the newline it is 16. jsr -48(a6) does the writing. Finally the library is closed with CloseLibrary (offset -414) and rts is executed with return code d0 = 0.
In 68000 syntax the operand order is like AT&T: source first, then destination. The size is indicated by the suffix .b, .w, or .l at the end of the instruction. Constants are written with #. The library is first opened, used, and then closed. The operating system's resources are managed in this pattern.
3.1.4.6ARM
ARM processors are used today in smartphones, embedded systems, and many laptops. ARM is a RISC (reduced instruction set computer) architecture: its instructions are few, simple, and of fixed length.
.data
msg: .ascii "Welcome, ARM!\n"
len = . - msg @ 14 bytes
.text
.global _start
_start:
mov r7, #4 @ sys_write
mov r0, #1 @ stdout
ldr r1, =msg @ string address
mov r2, #len @ byte count
svc #0 @ call the kernel
mov r7, #1 @ sys_exit
mov r0, #0 @ exit code
svc #0The program is assembled with GNU as. In GNU as, data is defined not with db but with the .ascii directive; \n is the newline. The dot in the line len = . - msg is the location counter, the counterpart of $ in NASM. “Welcome, ARM!” is 13 bytes; with the newline it is 14. The comment character for ARM in GNU as is @.
On 32-bit ARM Linux the service number goes into r7 and the parameters into r0, r1, and r2. The write service is again 4 and exit is 1; although the numbers are the same as on 32-bit x86 Linux, the registers differ. ldr r1, =msg is a special notation. Since ARM instructions are 32 bits, a 32-bit address does not fit inside a single instruction. The assembler stores the address in a literal pool near the code and generates the ldr instruction so that it reads it from there. svc #0 (formerly named swi) hands control to the kernel. On ARM only the ldr (load) and str (store) instructions work with memory. Operations such as addition are performed only on registers. ARM has no instruction that adds directly from memory like add ax, [0202h] on the 8086.
3.1.4.7PowerPC
PowerPC is a RISC architecture developed jointly by IBM, Motorola, and Apple. It has been used in older Macintosh computers, game consoles, and automotive controllers.
.data
msg: .ascii "Welcome, PowerPC!\n"
len = . - msg # 18 bytes
.text
.globl _start
_start:
li 0, 4 # r0 = sys_write
li 3, 1 # r3 = stdout
lis 4, msg@ha # r4 = addr (high)
addi 4, 4, msg@l # + low half
li 5, len # r5 = byte count
sc # call the kernel
li 0, 1 # r0 = sys_exit
li 3, 0 # r3 = exit code
scPowerPC has 32 general-purpose registers. In GNU as these registers are written as plain numbers: the 3 in the instruction li 3, 1 is register r3. li (load immediate) loads a constant into a register. The service number goes into r0 and the parameters into r3, r4, and r5; the switch into the kernel is made with the sc instruction. The comment character is #. “Welcome, PowerPC!” is 17 bytes; with the newline it is 18.
Loading an address is again a two-step affair. PowerPC instructions are also 32 bits and the constant field is 16 bits. A 32-bit address is split into two 16-bit parts. lis 4, msg@ha loads the upper half into the upper 16 bits of the register; addi 4, 4, msg@l adds the lower half. @ha means “high adjusted.” Because addi adds the lower half as a signed number, if the top bit of the lower half is 1, the upper half is increased by 1 beforehand. This detail is left to the assembler.
3.1.4.8Comparing the six environments
Table 3.1.11 puts the six programs side by side.
| Environment | Processor | Switch to the OS | Service no. | Parameters | String end |
|---|---|---|---|---|---|
| Linux | x86 (32) | int 0x80 | EAX | EBX, ECX, EDX | length given |
| DOS | 8086 | int 21h | AH | DX (address) | '$' |
| Windows | x86 (32) | DLL via call | function name | stack | 0 |
| AmigaOS | 68000 | jsr -48(a6) | library offset | d1, d2, d3 | length given |
| Linux | ARM | svc #0 | r7 | r0, r1, r2 | length given |
| Linux | PowerPC | sc | r0 | r3, r4, r5 | length given |
The conclusion from the table is this: assembly code depends on two things at once. The first is the processor: the instruction set, register names, the way addresses are loaded, and the syntax all change with the processor. Even the comment character changes: ; on x86, @ in GNU as for ARM, and # on PowerPC. The second is the operating system: on the same x86 processor, Linux, DOS, and Windows each demand entirely different call paths, numbers, and string conventions. Moving a program to a new environment means rewriting it at the assembly level. The greatest gain of high-level languages is that they hand this dependence over to the compiler and the interpreter. The line printf("Welcome\n") in C is the same in all six environments; each environment's C library and compiler handles the difference.
3.1.5High-level languages
3.1.5.1Compiled, interpreted, hybrid
A program written in a high-level language must also end up running in the processor's machine language. Languages differ in who does this translation and when.
A compiler is a program that examines high-level source code as a whole and translates it into machine code before the program runs. An interpreter is a program that reads and executes the source code statement by statement at run time; it produces no separate executable file. Just-in-time (JIT) compilation translates parts of a program into machine code during execution, as they are needed.
In compiled languages the source code is translated into machine language in advance. Because the compiler sees the whole source, most type and syntax errors are caught at compile time. Since there is no translation overhead at run time, the program runs fast. Compilation has two stages: the compiler translates each source file into an object file, and the linker combines the object files with libraries. The output is specific to a particular processor and a particular operating system. An x86 program compiled for Windows does not run on Linux or on an ARM processor.
In interpreted languages the source code itself is distributed and processed by the interpreter at run time. Since there is no compilation step, a change can be tried immediately; working line by line in an interactive shell is possible. The source code is platform-independent: the same file runs on any computer that has the interpreter. The price is twofold. Some errors surface only when the relevant line runs. In addition, analyzing every statement as it runs takes time, so the program is usually slower.
Between the two models there is also a hybrid model (Figure 3.1.12). Java and C# programs are first compiled to a processor-independent intermediate code. In Java this code is called bytecode, in C# it is called IL (intermediate language). A virtual machine runs the intermediate code: the JVM for Java, the CLR for C#. The virtual machine first interprets the intermediate code; it translates frequently executed parts to real machine code with JIT and caches them. This yields both portability and high speed. Today the Python and JavaScript engines also use bytecode and JIT internally; the boundaries are not sharp.
3.1.5.2The compilation process
A program written in C becomes an executable file in five stages. Take as an example the program oddeven.c, which prints whether a number is odd or even. The gcc compiler runs all the stages with a single command, but it also offers an option to stop at each stage.
- Preprocessor: replaces the
#includelines with the contents of the corresponding header files and expands the names defined with#define. The output is still C code:oddeven.i(gcc -E). The 15-line program grows to thousands of lines oncestdio.his included; with the clang-based compiler used while preparing these notes it came to 1,543 lines. - Compiler: passes the C code through syntax and type checking, then translates it into assembly language:
oddeven.s(gcc -S). Most errors are reported at this stage. - Assembler: translates the assembly code into machine code and produces an object file:
oddeven.o(gcc -c). In this file the addresses of theprintfandscanfcalls are still blank. - Linker: combines the object file with code such as
printfandscanffrom the C library and produces the executable file:oddevenon Linux,oddeven.exeon Windows. - Loader: when the program is run, the operating system loads the file into memory, prepares the stack and the startup environment, and finally jumps to the
mainfunction.
The whole job is done with one command: gcc oddeven.c -o oddeven. To see the intermediate assembly code the compiler produces, in Intel syntax, use gcc -S -masm=intel oddeven.c. Reading this output is the most direct way to see which instructions a high-level line turns into. For example, when the loop of the odd/even program is compiled for x86-64 with optimization (-O2), the comparison i % 2 == 0 becomes not a division instruction but test bl, 1. The compiler tests the lowest bit instead of dividing, because the division instruction is much slower. The same trick can be written by hand in 8086 assembly: test cl, 1.
A common mistake is to confuse a compile error with a link error. Misspelling the name printf may cause only a warning in the compiler. The real error shows up in the linker as an “undefined reference,” because no library contains a function with that name. Looking at which tool an error message came from shows at which stage the problem lies.
3.1.5.3Code trace: a loop generated by the compiler
To see how a compiler translates a loop, take a small piece of C:
sum = 0;
i = 10;
while (i > 0) {
sum += i;
i -= 3;
}One equivalent of this fragment that could be generated for the 8086 is as follows:
org 100h
mov bx, 0 ; sum = 0
mov cx, 10 ; i = 10
cond: cmp cx, 0 ; i > 0 ?
jle done
add bx, cx ; sum += i
sub cx, 3 ; i -= 3
jmp cond
done: mov sum, bx
ret
sum dw ?The compiler has placed the variables in registers: sum lives in BX and i in CX. At the end of the loop the sum is written to the memory variable sum. The while condition is tested at the top of the loop. There is an important transformation here. The condition in C says “if i > 0, enter the body.” In assembly the condition is inverted: “if i ≤ 0, leave the loop.” The instruction cmp cx, 0 performs the subtraction CX − 0 but does not store the result; it only sets the flags. jle done (jump if less or equal) jumps if the signed comparison says less or equal. This condition holds when ZF = 1 or SF ≠ OF. After the body, jmp cond returns unconditionally to the top.
| Step | Lines | BX (sum) | CX (i) | ZF | SF | OF | Decision |
|---|---|---|---|---|---|---|---|
| 1 | mov bx, 0, mov cx, 10 | 0 | 10 | – | – | – | MOV does not change the flags |
| 2 | cmp cx, 0, jle | 0 | 10 | 0 | 0 | 0 | 10 > 0, not taken |
| 3 | body, jmp | 10 | 7 | 0 | 0 | 0 | back to the condition |
| 4 | cmp, jle | 10 | 7 | 0 | 0 | 0 | not taken |
| 5 | body, jmp | 17 | 4 | 0 | 0 | 0 | back to the condition |
| 6 | cmp, jle | 17 | 4 | 0 | 0 | 0 | not taken |
| 7 | body, jmp | 21 | 1 | 0 | 0 | 0 | back to the condition |
| 8 | cmp, jle | 21 | 1 | 0 | 0 | 0 | not taken |
| 9 | body, jmp | 22 | −2 (FFFEh) | 0 | 1 | 0 | back to the condition |
| 10 | cmp, jle | 22 | −2 (FFFEh) | 0 | 1 | 0 | SF ≠ OF, taken |
| 11 | mov sum, bx | 22 | −2 (FFFEh) | 0 | 1 | 0 | sum = 22 |
The flags in Table 3.1.12 come from the last instruction of the body, sub cx, 3; jmp does not change the flags. The loop runs four iterations, and i takes the values 10, 7, 4, 1 in turn. The sum is 10 + 7 + 4 + 1 = 22. At the end of the fourth iteration sub cx, 3 produces 1 − 3 = −2. In 16-bit two's-complement representation −2 is FFFEh; since its top bit is 1, SF = 1. This subtraction is also correct as a signed operation, that is, there is no overflow and OF = 0. In step 10, cmp cx, 0 reproduces the same flags. SF = 1 and OF = 0 means SF ≠ OF; as a signed number CX < 0, and jle is taken. Figure 3.1.13 shows this moment next to the C source.
cmp cx, 0 produces SF = 1, OF = 0 and jle done is taken. The loop has been left; the sum is 22.In this example it matters that the condition is tested with a signed jump. i is an int and can be negative. Had the compiler chosen an unsigned jump, for example jbe, it would have read FFFEh as 65534 and found it greater than 0; the loop would have continued at the wrong place. The variable type in C decides which conditional jump is chosen in assembly. A single C loop has turned into three kinds of instructions: comparison, conditional jump, and unconditional jump. When the same C fragment is compiled and run on a computer, sum also comes out as 22, and the intermediate values (10, 7), (17, 4), (21, 1), (22, −2) are the same.
A common mistake is to forget to invert the loop condition when translating it to assembly. If the C while (i > 0) is written directly as jg body, then in the case where the body is not entered, the flow falls through to the instruction just below the body. The correct pattern is an inverted jump that leaps to the end of the loop when the condition is false, plus a jmp at the end of the body that returns to the top.
3.1.6Compiled languages
Compiled languages work with a compiler that examines the source code as a whole before running. Compiled code runs directly on the processor, so it is fast, and type and syntax errors are caught at compile time. Each language was born from a different need:
- C and C++
- Systems programming, operating systems, embedded software, and high-performance applications. The great majority of microcontroller software is written in C.
- Rust
- Safe and fast systems programming; memory safety is checked by the compiler.
- Fortran
- Scientific and numerical computing; the first widespread high-level language (1957).
- Go
- Server and network software; fast compilation and concurrency.
- Ada
- Systems where safety is critical, such as aviation, defense, and railways.
- Java and C#
- Hybrid: compiled to intermediate code, run with JIT in a virtual machine.
3.1.6.1The common task and C
To see the differences between languages fairly, all of them are given the same task. The program reads a number from the user and prints whether each number from 1 up to that number is odd or even. The task is small, but it contains all the basic parts of a program: input, type conversion, a counted loop, the remainder operation, a condition, and output. The C version is as follows:
#include <stdio.h>
int main() {
int number;
printf("Enter a number: ");
scanf("%d", &number);
for (int i = 1; i <= number; i++) {
if (i % 2 == 0) {
printf("%d is even.\n", i);
} else {
printf("%d is odd.\n", i);
}
}
return 0;
}#include <stdio.h> adds the declarations of the standard input/output functions. The program starts from the main function. int number; reserves an integer variable; its value is not yet defined. printf prints the prompt. scanf("%d", &number) reads a decimal integer from the keyboard. scanf is given not the variable itself but its address (&number). The function writes the value it reads to that address. This is the same idea as giving DOS the address of a string rather than its contents in assembly.
for (int i = 1; i <= number; i++) has three parts: the initialization (i = 1), the condition tested before each iteration (i <= number), and the step done after each iteration (i++). i % 2 is the remainder of dividing i by 2; if the remainder is 0, the number is even. The value of i is printed in place of %d in printf, and \n is the newline. return 0 returns the success exit code to the operating system. Table 3.1.13 is the trace of the program for input 3.
| Step | Line | number | i | i % 2 | Output added |
|---|---|---|---|---|---|
| 1 | printf | ? | – | – | Enter a number: |
| 2 | scanf | 3 | – | – | (user types 3) |
| 3 | for: 1 ≤ 3 | 3 | 1 | – | |
| 4 | if → else | 3 | 1 | 1 | 1 is odd. |
| 5 | i++; 2 ≤ 3 | 3 | 2 | – | |
| 6 | if true | 3 | 2 | 0 | 2 is even. |
| 7 | i++; 3 ≤ 3 | 3 | 3 | – | |
| 8 | if → else | 3 | 3 | 1 | 3 is odd. |
| 9 | i++; 4 ≤ 3 false | 3 | 4 | – | loop ends |
| 10 | return 0 | 3 | – | – | exit code 0 |
The loop variable i is defined in the for line, so it is valid only inside the loop; it cannot be used after the loop ends. The program was compiled and run with inputs 3 and 5 while these notes were prepared; the output is the same as in the table. The strings use no non-ASCII characters for a practical reason: some terminals do not display UTF-8 characters correctly. Every character of these strings is a single byte.
3.1.6.2C++
#include <iostream>
int main() {
int number;
std::cout << "Enter a number: ";
std::cin >> number;
for (int i = 1; i <= number; i++) {
if (i % 2 == 0) {
std::cout << i << " is even."
<< std::endl;
} else {
std::cout << i << " is odd."
<< std::endl;
}
}
return 0;
}C++ (1985, Bjarne Stroustrup) was designed as a superset of C; most valid C code is also valid C++. It adds constructs such as classes, templates, and exceptions. For input and output, streams are used instead of printf/scanf. std::cout << writes and std::cin >> reads. The << operator can be chained: first i, then the text, then the newline is sent to the stream. No address-of operator is needed when reading; C++'s reference mechanism takes care of that.
std::endl adds a newline and also flushes the output buffer. Flushing the buffer on every line is slow for output with many lines; in that case '\n' is faster. Compilation is done with g++ oddeven.cpp -o oddeven. The output is identical to the C version.
3.1.6.3C# and Java
using System;
class Program {
static void Main() {
Console.Write("Enter a number: ");
int number = int.Parse(Console.ReadLine());
for (int i = 1; i <= number; i++) {
if (i % 2 == 0) {
Console.WriteLine($"{i} is even.");
} else {
Console.WriteLine($"{i} is odd.");
}
}
}
}C# (2000, Microsoft) is the language of the .NET platform. The source code is compiled to the IL intermediate language; .NET's virtual machine, the CLR (common language runtime), translates this code to machine code with JIT while running. The program starts with the Main method inside a class. Console.ReadLine() reads a line of text and int.Parse converts it to an integer. If the input is not a number, int.Parse throws an exception and the program stops; int.TryParse is safer because it returns false in that case. The notation $"{i} …" inserts the value of a variable into the string (string interpolation). The program is run with dotnet run.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = scanner.nextInt();
for (int i = 1; i <= number; i++) {
if (i % 2 == 0) {
System.out.println(i + " is even.");
} else {
System.out.println(i + " is odd.");
}
}
}
}Java (1995, Sun Microsystems) is also a hybrid language. The command javac Main.java produces the file Main.class, which contains processor-independent bytecode. The command java Main starts the JVM; the JVM first interprets the bytecode and compiles frequently executed parts with JIT. The same .class file runs on every platform that has a JVM. Java's slogan “write once, run anywhere” comes from this.
In Java everything is inside a class, and the name of the public class must match the file name: the class Main lives in the file Main.java. Input is read with the Scanner class; nextInt() returns the next integer. When the + operator joins a number to a string, it converts the number to text. The program was compiled and run with JDK 21 while these notes were prepared and gave the same output as C.
3.1.6.4Go and Rust
package main
import "fmt"
func main() {
var number int
fmt.Print("Enter a number: ")
fmt.Scan(&number)
for i := 1; i <= number; i++ {
if i%2 == 0 {
fmt.Printf("%d is even.\n", i)
} else {
fmt.Printf("%d is odd.\n", i)
}
}
}Go (2009, Google) compiles directly to machine code and produces a single, self-contained executable that includes all its dependencies. Memory is managed by a garbage collector; memory that is no longer used is reclaimed automatically. For concurrent work there are goroutines, which are very lightweight threads. The syntax resembles C, but conditions and loops use no parentheses. The notation i := 1 defines the variable and infers its type from the value on the right. fmt.Scan(&number) takes an address as in C. The program is run with go run oddeven.go.
use std::io;
fn main() {
let mut input = String::new();
println!("Enter a number:");
io::stdin().read_line(&mut input)
.expect("read error");
let number: i32 = input.trim().parse()
.expect("parse error");
for i in 1..=number {
if i % 2 == 0 {
println!("{} is even.", i);
} else {
println!("{} is odd.", i);
}
}
}Rust (2015, Mozilla) provides memory safety without a garbage collector. Every value has a single owner; the ownership and borrowing rules are checked at compile time. Errors such as accessing freed memory or modifying the same data from two places at once are caught before the program runs. Variables are immutable by default; the variable input is defined with mut because it will be filled with the line read.
Input is read into a string with read_line. trim() discards the newline and parse() converts to a number. These operations can fail; Rust does not allow this possibility to be ignored. .expect("…") prints the message and stops the program if there is an error. 1..=number is a range that includes the upper bound. The program is compiled with rustc oddeven.rs or cargo run.
3.1.6.5Fortran and Ada
program Main
implicit none
integer :: number, i
write(*,*) 'Enter a number:'
read(*,*) number
do i = 1, number
if (mod(i, 2) == 0) then
write(*,*) i, ' is even.'
else
write(*,*) i, ' is odd.'
end if
end do
end program MainFortran (1957, IBM, John Backus) is the first widespread high-level language. Its name comes from FORmula TRANslation, and it aims to let formulas be written directly as code. It is still common today in weather forecasting, fluid dynamics, and physics simulations; most of the large numerical libraries in these fields are written in Fortran.
implicit none requires all variables to be declared explicitly. In old Fortran, variables whose names started with the letters i–n were automatically taken to be integers; this rule is turned off because it hides typing errors. The loop do i = 1, number includes the upper bound. The remainder is computed not with an operator but with the function mod(i, 2). write(*,*) writes in free format; a space may appear before numbers. Compilation is done with gfortran oddeven.f90 -o oddeven.
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;
procedure Main is
Number : Integer;
begin
Put ("Enter a number: ");
Get (Number);
for I in 1 .. Number loop
Put (I, Width => 0);
if I mod 2 = 0 then
Put_Line (" is even.");
else
Put_Line (" is odd.");
end if;
end loop;
end Main;Ada (1983, U.S. Department of Defense) was designed for large systems where safety is critical. Its type checking is very strong; for example, integers of different types cannot be mixed without an explicit conversion. It is used in aviation, defense, and railway software. The with lines name the packages used, and the use lines make it possible to use the names in those packages without writing the package name. Reading and writing integers requires the Ada.Integer_Text_IO package. Put (I, Width => 0) writes the number without leading spaces; Put_Line adds a newline at the end of the text. I mod 2 gives the remainder. Compilation is done with gnatmake main.adb.
The Go, Rust, Fortran, and Ada compilers were not installed on the computer on which these notes were prepared. These four programs were not run; they were checked line by line against each language's documentation.
3.1.7Interpreted languages
3.1.7.1How an interpreter works
An interpreted language has no separate compilation step. The programmer gives the source file directly to the interpreter: python oddeven.py. The interpreter is also an ordinary program running on the processor; it is mostly written in C. Its job is to read the statements in the source code in order and do the work each one asks for. This approach allows rapid development and experimentation. In the interactive shell (REPL, read–eval–print loop) of languages such as Python and Ruby, you type a line and see its result immediately.
The loop in Figure 3.1.14 is the software counterpart of the processor's fetch–decode–execute cycle. The difference is that each step is done by a program instead of hardware. An addition takes a single instruction on the processor but dozens, sometimes hundreds, in an interpreter. The interpreter must first look at the types of the operands, then choose the appropriate addition routine, and then create the result as a new object. This is where the slowness of interpreted languages comes from. Real interpreters do not parse the source code as text each time; they first translate it to bytecode and interpret the bytecode. CPython stores the bytecode it produced in .pyc files, so on the next run it skips the translation too.
Each of the common interpreted languages stands out in a particular area. Python is general-purpose; it is widely used for data science, artificial intelligence, and automation. JavaScript is the language of the web; it runs in the browser and, with Node.js, on the server. Ruby is known for its ease of use and flexibility, especially through the Ruby on Rails web framework.
3.1.7.2Python
# Read input from the user
number = int(input("Enter a number: "))
# Check the numbers from 1 to number
for i in range(1, number + 1):
if i % 2 == 0:
print(f"{i} is even.")
else:
print(f"{i} is odd.")Python (1991, Guido van Rossum) puts readability first. Blocks are determined not by braces but by indentation. The indented lines under the for line are the body of the loop; when the indentation ends, the body ends. Here indentation is not a stylistic habit but a rule of the language. Wrong indentation either gives a syntax error or changes the meaning of the program.
input always returns text. Even if the user types 3, the returned value is the string "3"; int(...) converts it to an integer. range(1, number + 1) produces a sequence of numbers starting at 1, but does not include the upper bound. That is why 1 is added to number. f"{i} is …" is a formatted string (f-string): the value of the expression inside the braces is placed into the text. The program is run with python oddeven.py.
Python is dynamically typed: the type of a variable is determined at run time by the value assigned to it. number is not declared beforehand; the assignment creates it. The job that takes 15 lines in the C version is 6 lines of code here. This is the expressive power of high-level languages. The price is speed: CPython runs the same loop dozens of times slower than compiled C, because on every i % 2 it checks the types and creates new integer objects.
3.1.7.3JavaScript
// Read input from the user
let number = Number(prompt("Enter a number:"));
// Check the numbers from 1 to number
for (let i = 1; i <= number; i++) {
if (i % 2 === 0) {
console.log(i + " is even.");
} else {
console.log(i + " is odd.");
}
}JavaScript (1995, Brendan Eich) is the language of browsers; it also runs on the server with Node.js. Modern engines such as V8 first translate the code to bytecode and interpret it, and compile frequently running functions to machine code with JIT. JavaScript today therefore sits somewhere between “interpreted” and “hybrid.”
prompt opens an input box in the browser and returns what the user typed as text. Number(...) converts this text to a number. Without the conversion, the comparison i <= number would still work, because JavaScript automatically converts the text to a number when comparing a number with text. But an expression such as number + 1 would put “3” and 1 side by side and produce “31.” An explicit conversion prevents surprises of this kind. The === operator tests equality without type conversion: 0 === "0" is false, whereas 0 == "0" is true. console.log writes the output to the browser's developer console or to the terminal. Since Node.js has no prompt function, while these notes were prepared the program was run in Node.js with a small prompt definition that supplies the input, and it wrote the same lines as C.
3.1.7.4Ruby, PHP, and Perl
# Read input from the user
print "Enter a number: "
number = gets.chomp.to_i
# Check the numbers from 1 to number
for i in 1..number do
if i % 2 == 0
puts "#{i} is even."
else
puts "#{i} is odd."
end
endRuby (1995, Yukihiro Matsumoto) is fully object-oriented: everything, numbers included, is an object. gets.chomp.to_i is three method calls in a row. gets reads a line, chomp removes the newline at its end, and to_i converts to an integer. 1..number is a range that includes the upper bound. Blocks are closed with end. "#{i} …" is the counterpart of Python's formatted string: the value of the expression inside #{…} is placed into the text. puts adds a newline at the end of the text it prints. The program is run with ruby oddeven.rb.
<?php
// Read input from the user
echo "Enter a number: ";
$number = (int) trim(fgets(STDIN));
// Check the numbers from 1 to number
for ($i = 1; $i <= $number; $i++) {
if ($i % 2 == 0) {
echo $i . " is even.\n";
} else {
echo $i . " is odd.\n";
}
}
?>PHP (1995, Rasmus Lerdorf) is a web language that runs on the server side. Code is written between <?php and ?> and can be embedded in HTML pages. Variable names begin with $. The . operator concatenates strings; $i . " is …" first converts the number to text and then concatenates. On the command line, fgets(STDIN) reads a line, trim removes the newline, and (int) converts to an integer. The program is run with php oddeven.php.
use strict;
use warnings;
# Read input from the user
print "Enter a number: ";
my $number = <STDIN>;
chomp $number;
# Check the numbers from 1 to number
for my $i (1..$number) {
if ($i % 2 == 0) {
print "$i is even.\n";
} else {
print "$i is odd.\n";
}
}Perl (1987, Larry Wall) was designed for text processing and system administration and is known for its powerful regular expressions. <STDIN> reads a line from standard input; the newline is part of the text read, and chomp removes it. In a double-quoted string, $i is replaced directly by its value. use strict; and use warnings; catch common errors such as using an undeclared variable. my declares a variable. The program is run with perl oddeven.pl.
Of these three languages, only Perl could be run while these notes were prepared; its output is the same as C. The Ruby and PHP interpreters were not installed, so the two programs were checked against the languages' documentation.
3.1.7.5MATLAB
% Read input from the user
number = input('Enter a number: ');
% Check the numbers from 1 to number
for i = 1:number
if mod(i, 2) == 0
fprintf('%d is even.\n', i);
else
fprintf('%d is odd.\n', i);
end
endMATLAB (1984, MathWorks) takes its name from MATrix LABoratory and was designed for matrix-based numerical computing. It is very common in engineering, especially in signal processing and control systems. input evaluates what the user types as an expression; when 3 is typed, 3 is returned as a number. 1:number produces a row vector made of the values 1, 2, …, number, and for walks through the elements of this vector in turn. The remainder is found with mod(i, 2). A ; at the end of a line suppresses printing the result on the screen. Comments begin with %. MATLAB is a commercial product; a free and largely compatible alternative is GNU Octave. Newer versions of MATLAB also use JIT internally.
3.1.7.6Comparing the fourteen languages
Table 3.1.14 compares the same program in fourteen languages on three points: the loop header, the remainder operation, and printing.
| Language | Model | Loop header | Remainder | Printing |
|---|---|---|---|---|
| C | compiled | for (int i = 1; i <= n; i++) | i % 2 | printf |
| C++ | compiled | for (int i = 1; i <= n; i++) | i % 2 | std::cout << |
| C# | IL + JIT | for (int i = 1; i <= n; i++) | i % 2 | Console.WriteLine |
| Java | bytecode + JIT | for (int i = 1; i <= n; i++) | i % 2 | System.out.println |
| Go | compiled | for i := 1; i <= n; i++ | i%2 | fmt.Printf |
| Rust | compiled | for i in 1..=n | i % 2 | println! |
| Fortran | compiled | do i = 1, n | mod(i, 2) | write(*,*) |
| Ada | compiled | for I in 1 .. N loop | I mod 2 | Put_Line |
| Python | interpreted | for i in range(1, n + 1): | i % 2 | print |
| JavaScript | interpreted/JIT | for (let i = 1; i <= n; i++) | i % 2 | console.log |
| Ruby | interpreted | for i in 1..n do | i % 2 | puts |
| PHP | interpreted | for ($i = 1; $i <= $n; $i++) | $i % 2 | echo |
| Perl | interpreted | for my $i (1..$n) | $i % 2 | print |
| MATLAB | interpreted/JIT | for i = 1:n | mod(i, 2) | fprintf |
Two families are clearly visible in the table. The languages derived from C (C++, C#, Java, JavaScript, PHP, Go) keep the three-part for header and the % operator. The other languages run the loop over a range or a vector: 1..=n in Rust, range in Python, 1..n in Ruby, (1..$n) in Perl, 1:n in MATLAB, and a pair of bounds in Fortran and Ada. In range notation the most frequent source of errors is whether the upper bound is included. Python's range leaves the upper bound out; in Rust, 1..n leaves it out and 1..=n includes it. In Ruby, 1..n includes the upper bound and 1...n does not. For the remainder, Fortran, Ada, and MATLAB use mod instead of an operator.
A common mistake is to carry the range rule of one language over to another. If the C loop for (i = 1; i <= n; i++) is translated to Python as for i in range(1, n):, the last value (n) is skipped. The program is syntactically correct and gives no error; the missing line is noticed only when the output is examined.
3.1.8Compiled or interpreted?
3.1.8.1Criteria
The three execution models can be compared on five criteria (Table 3.1.15).
| Criterion | Compiled | Interpreted | Hybrid (bytecode + JIT) |
|---|---|---|---|
| Translation time | before running, once | at every run | first to intermediate code, then while running |
| Speed | highest | lowest | high (after warm-up) |
| Distributed | machine code | source code | intermediate code (.class, .dll) |
| Portability | recompiled for each platform | wherever there is an interpreter | wherever there is a virtual machine |
| Error detection | mostly at compile time | mostly at run time | type errors at compile time |
| Examples | C, C++, Go, Rust, Fortran, Ada | Python, Ruby, PHP, Perl, MATLAB | Java, C#, JavaScript (V8) |
“After warm-up” describes a property of JIT. When the program starts, the virtual machine interprets the code and counts which parts run often. When a frequently running loop or function crosses a certain threshold, it is compiled to machine code. A hybrid program is therefore slow in the first seconds and then runs at a speed close to compiled code. In some cases a JIT compiler can even produce better code than an ahead-of-time compiler, because it sees which values the program actually runs with.
Being “compiled” or “interpreted” is a property not of a language but of its implementation. Both a compiler and an interpreter can be written for the same language.
C is usually compiled, but C interpreters exist. Python is usually interpreted by CPython, but Cython translates Python-like code to C and compiles it, and PyPy runs it with JIT. Instead of saying “Python is a slow language,” it is more accurate to say “the CPython interpreter is slow.” The language itself is a definition; its speed is determined by the tool that runs it.
3.1.8.2Intermediate code and the stack machine
Intermediate code is the machine language of an imaginary processor that belongs to no real processor. Virtual machines such as the JVM and the CLR define this imaginary processor as a stack machine. In a stack machine, instructions have no operand fields. The operands sit on an operand stack. An instruction takes the top items off the stack, performs the operation, and pushes the result back. Because the number of registers varies from processor to processor, a design without registers makes the intermediate code portable. Mapping this code onto the registers of a real processor is the JIT's job.
For the expression x = (a + b) * c, the intermediate code produced by the compiler is as follows:
// x = (a + b) * c;
iload a // push a
iload b // push b
iadd // add the top two
iload c
imul // multiply the top two
istore x // pop into x
returnLet the local variables be a = 6, b = 7, c = 3. Table 3.1.16 writes the operand stack from bottom to top.
| Instruction | Operation | Operand stack (bottom → top) | x |
|---|---|---|---|
iload a | push a | [6] | ? |
iload b | push b | [6, 7] | ? |
iadd | pop 7 and 6, push 13 | [13] | ? |
iload c | push c | [13, 3] | ? |
imul | pop 3 and 13, push 39 | [39] | ? |
istore x | pop the top, store in x | [ ] | 39 |
return | return | [ ] | 39 |
The iadd instruction has no operand name; the instruction knows which values to add from the state of the stack. The i at the start of the instructions indicates that the operation is on integers. The parenthesized expression has become an order of operations in the intermediate code: the addition is done before the multiplication because it is written first. This order of the intermediate code is the same as the postfix notation of the expression, a b + c *.
iadd. The top two items (6 and 7) have been popped and their sum, 13, has been pushed; the local variables are unchanged.Real Java bytecode has the same structure. Only, local variables are referred to not by name but by index. When the following Java method is compiled with JDK 21 and disassembled with javap -c, this code appears:
static int compute(int a, int b, int c) {
int x = (a + b) * c;
return x;
}
0: iload_0 // a (local 0)
1: iload_1 // b
2: iadd
3: iload_2 // c
4: imul
5: istore_3 // x (local 3)
6: iload_3
7: ireturnThe numbers on the left are byte positions inside the bytecode; each instruction here is a single byte. The call compute(6, 7, 3) returns 39. The bytecode produced by CPython has the same form: the line x = (a + b) * c is translated into the instructions LOAD_NAME a, LOAD_NAME b, BINARY_OP +, LOAD_NAME c, BINARY_OP *, STORE_NAME x. Both virtual machines are stack machines.
This intermediate code is tied to no processor. The virtual machine either interprets each instruction or translates it with JIT into the machine code of a real processor such as the 8086, x86-64, or ARM. On the 8086 this expression takes a few instructions using registers instead of an operand stack: mov ax, a, add ax, b, imul c, mov x, ax. The “push onto the stack” and “pop from the stack” operations of the stack machine turn into loads into registers and stores from registers on a real processor.
3.1.9The same task in 8086 assembly
3.1.9.1Program and memory layout
Finally, the odd/even task is written in 8086 assembly. The program is assembled in emu8086 as a COM file. Two simplifications keep the task short. n = 3 is written into the code as a constant; it is not read from the keyboard. The numbers are single-digit, so printing a number means printing a single ASCII character.
org 100h
mov cx, 1 ; i = 1
again: cmp cx, 3 ; compare i with n
ja done ; done if i > n
mov dl, cl
add dl, '0' ; digit → ASCII
mov ah, 02h
int 21h ; print DL
test cl, 1 ; lowest bit
jnz odd ; 1 means odd
lea dx, even_m
jmp print
odd: lea dx, odd_m
print: mov ah, 09h
int 21h ; print string
inc cx ; i++
jmp again
done: ret
odd_m db ' is odd.',0Dh,0Ah,'$'
even_m db ' is even.',0Dh,0Ah,'$'The CX register is the loop counter and stands in for i in C. The cmp cx, 3 and ja done at the label again are the inverted form of the C condition i <= n: leave the loop if i > n. ja (jump if above) jumps on “greater” in an unsigned comparison; the jump is taken when CF = 0 and ZF = 0. Since the counter is never negative, an unsigned jump is correct here.
The first four lines of the body print the number. mov dl, cl copies the low byte of the counter into DL. add dl, '0' adds to it the ASCII code of the character '0', that is, 30h. In the ASCII table the digits run in order from 30h to 39h; 1 + 30h = 31h is the character '1'. mov ah, 02h and int 21h are DOS's “print the character in DL” service.
The next two lines are the counterpart of the C test i % 2 == 0. The remainder of division by 2 is the lowest bit of the number. test cl, 1 performs a bitwise AND of CL and 1, does not store the result, and only sets the flags. If the lowest bit is 1, the result is 1 and ZF = 0; if the bit is 0, the result is 0 and ZF = 1. jnz odd (jump if not zero) jumps when ZF = 0. The division instruction (div) can take more than 80 clock periods on the 8086; test takes only a few. Compilers choose the same route.
For an even number the flow continues without jumping: lea dx, even_m loads the address of the even message into DX, and jmp print goes to the common printing code. For an odd number the jump goes to the label odd and the address of the odd message is loaded into DX. The two paths merge at the label print: service 09h prints from the address in DX up to $. The 0Dh, 0Ah at the end of the messages are the carriage return and line feed characters; in DOS both are needed to move to a new line. inc cx increments the counter, and jmp again returns to the condition. ret returns the COM program to DOS.
The program is laid out in memory as follows. The lengths and addresses of the instructions are given in Table 3.1.17; the code is 38 bytes, and the messages begin right after the code.
| Address | Bytes | Line |
|---|---|---|
| 0100h | 3 | mov cx, 1 |
| 0103h | 3 | again: cmp cx, 3 |
| 0106h | 2 | ja done |
| 0108h | 2 | mov dl, cl |
| 010Ah | 3 | add dl, '0' |
| 010Dh | 2 + 2 | mov ah, 02h, int 21h |
| 0111h | 3 | test cl, 1 |
| 0114h | 2 | jnz odd |
| 0116h | 3 | lea dx, even_m |
| 0119h | 2 | jmp print |
| 011Bh | 3 | odd: lea dx, odd_m |
| 011Eh | 2 + 2 | print: mov ah, 09h, int 21h |
| 0122h | 1 | inc cx |
| 0123h | 2 | jmp again |
| 0125h | 1 | done: ret |
| 0126h | 11 | odd_m db … (8 characters + 0Dh + 0Ah + '$') |
| 0131h | 12 | even_m db … (9 characters + 0Dh + 0Ah + '$') |
All the conditional and unconditional jumps are two bytes. The first byte is the opcode and the second is a signed displacement: the target is found by adding this displacement to the address of the next instruction. For example, ja done is at 0106h; the next instruction starts at 0108h and the target is 0125h. The displacement is 0125h − 0108h = 1Dh, and the instruction is encoded as 77 1D. Thanks to this relative addressing, the jumps work wherever in memory the program is loaded.
3.1.9.2Code trace
Table 3.1.18 traces the whole program. The flags are the values after the last flag-affecting instruction of the row group. MOV, LEA, the return from INT 21h, and the jump instructions do not change the flags.
| Step | Lines | CX | DL / DX | ZF | CF | Event |
|---|---|---|---|---|---|---|
| 1 | mov cx, 1 | 0001h | – | – | – | i = 1 |
| 2 | cmp cx, 3, ja | 0001h | – | 0 | 1 | 1 − 3 borrows; not taken |
| 3 | mov dl, cl … int 21h | 0001h | DL = 31h | 0 | 0 | “1” is printed |
| 4 | test cl, 1, jnz | 0001h | DL = 31h | 0 | 0 | 1 AND 1 = 1; taken (odd) |
| 5 | lea dx, odd_m … int 21h | 0001h | DX = 0126h | 0 | 0 | “ is odd.” |
| 6 | inc cx, jmp | 0002h | 0126h | 0 | 0 | i = 2 |
| 7 | cmp cx, 3, ja | 0002h | 0126h | 0 | 1 | not taken |
| 8 | mov dl, cl … int 21h | 0002h | DL = 32h | 0 | 0 | “2” is printed |
| 9 | test cl, 1, jnz | 0002h | DL = 32h | 1 | 0 | 2 AND 1 = 0; not taken (even) |
| 10 | lea dx, even_m, jmp print | 0002h | DX = 0131h | 1 | 0 | go to the common printing code |
| 11 | mov ah, 09h, int 21h | 0002h | DX = 0131h | 1 | 0 | “ is even.” |
| 12 | inc cx, jmp | 0003h | 0131h | 0 | 0 | i = 3 |
| 13 | cmp cx, 3, ja | 0003h | 0131h | 1 | 0 | 3 − 3 = 0; ZF = 1, not taken |
| 14 | mov dl, cl … jnz | 0003h | DL = 33h | 0 | 0 | “3” is printed; odd |
| 15 | lea dx, odd_m … int 21h | 0003h | DX = 0126h | 0 | 0 | “ is odd.” |
| 16 | inc cx, jmp | 0004h | 0126h | 0 | 0 | i = 4 |
| 17 | cmp cx, 3, ja | 0004h | 0126h | 0 | 0 | 4 − 3 = 1; taken |
| 18 | done: ret | 0004h | 0126h | 0 | 0 | return to DOS |
In the second step, cmp cx, 3 performs the subtraction 1 − 3. As unsigned numbers 1 is less than 3; the subtraction borrows and CF = 1. ja jumps only when CF = 0 and ZF = 0, so it is not taken. In the third step add dl, '0' produces 01h + 30h = 31h; there is no carry, so CF = 0. In the fourth step test leaves ZF = 0 and jnz is taken. The test instruction always clears CF and OF.
The inc cx in the sixth step carries a subtlety: INC updates ZF, SF, and OF but does not change CF. Here CF is already 0, but in loop counters this property matters; the carry of a previous addition can be preserved through an INC. In the thirteenth step 3 − 3 = 0: ZF = 1, CF = 0. Because the condition of ja also requires ZF = 0, the jump is not taken; equality does not count as “above.” In the seventeenth step 4 − 3 = 1: ZF = 0, CF = 0 and ja done is taken. In the end the screen shows these three lines:
1 is odd.
2 is even.
3 is odd.The output is the same as the output of the C program with input 3, apart from the prompt line.
3.1.9.3Comparison with C
The for and if constructs of C do not exist on the 8086. All of them are built from compare + conditional jump pairs. Table 3.1.19 gives this mapping line by line.
| C | 8086 |
|---|---|
int i = 1 | mov cx, 1 (a register instead of a variable) |
i <= number | cmp cx, 3 + ja done (inverted condition) |
i++ | inc cx + jmp again |
i % 2 == 0 | test cl, 1 + jnz odd (lowest bit) |
if … else | two branches: two lea instructions that merge with jmp print |
printf("%d …", i) | add dl, '0' + service 02h, then service 09h |
return 0 | ret |
The C version is 15 lines and can print any number. The 8086 version is 20 lines, but it prints only single-digit numbers and does not read n. Printing a multi-digit number needs a loop that repeatedly divides the number by 10 and converts the remainders to digits, and reading from the keyboard needs a loop that assembles the digits. That is the work printf and scanf do in C. One line of a high-level language often takes a whole routine in assembly. In return, the assembly programmer controls every byte and every clock period: the 8086 program is 61 bytes and needs no library.
3.1.10Common mistakes
Confusing an address with its contents. Every service that prints a string asks for the address of the string: DX in DOS, ECX in Linux, r1 on ARM, a value pushed on the stack in Windows. In assembly, the notation mov dx, msg in some assemblers loads not the address but the word at that address. For the address, use lea dx, msg or mov dx, offset msg. Forgetting the & in the C call scanf("%d", &number) is the high-level form of the same mistake.
Not choosing the string-end rule for the environment. DOS service 09h expects $; the Windows API and the C library expect a 0 byte; Linux's write call looks at no terminator and takes the length as a parameter. If $ is put at the end of the string in a Linux program, this character is printed to the screen; in a DOS program, a string ending in 0 runs on until a $ is found.
Putting the data before the code. A COM program starts running at its first byte. If a db line is put right after org 100h, the processor decodes the bytes of the string as instructions. Data is either put after the code, or a jmp at the start of the code jumps over the data.
Mixing up signed and unsigned jumps. After the same cmp instruction, ja/jb make an unsigned comparison and jg/jl a signed one. If ja is used with a counter that can be negative, −1 (FFFFh) is seen as the largest unsigned number and the loop continues on the wrong branch.
Thinking “an interpreted language has no errors.” In an interpreted language the program starts to run, but a syntax or type error in a branch that never runs shows up only when that branch runs. During testing, inputs that run every branch at least once must be chosen.
Not following the calling convention. If, after calling a stdcall function, the caller also cleans the stack with add esp, 16, the stack is cleaned twice. ESP moves up by an extra 16 bytes and the next ret takes the wrong return address. Which convention applies must be read from the function's documentation.
3.1.11Exercises and solutions
The exercises in the slides are solved here with their intermediate steps. The first three exercises use the sample instruction format of Figure 3.1.5: 4-bit opcode, 2-bit destination, 2-bit source; HALT = 0000, ADD = 0001, SUB = 0010, AND = 0011, OR = 0100; R0 = 00, R1 = 01, R2 = 10, R3 = 11.
1. What are the binary and hexadecimal codes of the instructions SUB R3, R0 and OR R0, R2?
The code of SUB is 0010. The destination is R3 = 11 and the source is R0 = 00. Written in order, the fields give 0010 1100. The four-bit groups convert to hexadecimal digits: 0010 = 2, 1100 = C. The result is 2Ch. The code of OR is 0100; the destination is R0 = 00 and the source is R2 = 10. The instruction is 0100 0010 = 42h.
2. Which instruction is 0010 0111? What is the result if R1 = 9 and R3 = 4?
The first four bits 0010 = SUB. The remaining four bits are 01 11: destination R1, source R3. The instruction is SUB R1, R3 and performs R1 ← R1 − R3. R1 = 9 − 4 = 5; R3 stays 4. Binary check: 1001 − 0100 = 0101.
3. How many different opcodes can be defined in this design? How must the instruction format change to raise the number of registers to 8?
The opcode field is 4 bits: 24 = 16 opcodes. Selecting one of eight registers takes log2 8 = 3 bits. The destination and source fields grow to 3 bits each, and the instruction becomes 4 + 3 + 3 = 10 bits. If the instruction is to stay at 8 bits, the register fields take 6 bits and 2 bits remain for the opcode. With 2 bits only 22 = 4 operations can be defined; the five operations of the design would not fit. This is the basic trade-off among instruction length, number of registers, and number of instructions.
4. What happens in a DOS program if the '$' at the end of the string is forgotten?
Service 09h prints every byte starting at DS:DX and stops when it sees a byte with the value 24h. If there is no terminator, the memory bytes after the string are printed too. These bytes may be the program's own code, other data, or random values. Among them, a 07h byte produces a beep, and 0Dh and 0Ah produce cursor movement. Printing continues until the first $ character in memory is met.
5. What would appear on the screen if len were written by hand as 15 in the Linux example?
sys_write writes exactly as many bytes as EDX. The first 15 bytes of the string are the text “Welcome, Linux!”; the 16th byte is the newline. If EDX = 15, the text is printed but the newline is not. The terminal's prompt line comes right after the text, on the same line. On return EAX = 15.
6. Why are the parameters pushed in reverse order in the Windows example? What is ESP right after the call?
In C calling conventions the first parameter must be at the top of the stack, just above the return address. Because the stack grows downward, the value pushed last stays on top; that is why the parameters are pushed from last to first. The function always finds the first parameter at [ESP + 4] and the second at [ESP + 8]. Four push instructions and the return address pushed by call take 5 × 4 = 20 bytes. ESP = 0012FF80h − 14h = 0012FF6Ch.
7. Why can Java not be classified in a single word as “compiled” or “interpreted”?
Java source code is compiled with javac, but the output is bytecode, not machine code. This bytecode is first interpreted in the JVM; its frequently running parts are compiled to machine code with JIT at run time. The program is both compiled in advance and interpreted and recompiled while running. That is why Java is an example of the hybrid model. Moreover, the compiled/interpreted distinction is a property of the implementation, not of the language: there are also tools that compile Java ahead of time directly to machine code.
3.1.12Summary
- Software manages the hardware. The operating system is the fundamental software; applications reach the hardware through its system calls. Programming languages are used to develop software.
- Languages are at three levels: machine language, assembly language, and high-level languages. As the level rises, readability and portability increase and direct control over the hardware decreases.
- Machine language is the only language the processor understands: binary instructions made of opcode and operand fields. It depends entirely on the hardware;
B0 05on the 8086 andE3A00005on ARM do the same job. The 8086 stores multi-byte numbers low byte first. - In an instruction format, a field of k bits encodes one of 2k alternatives. Decoding an instruction means splitting the bits into their fields and reading each field from a table.
- Assembly language writes machine instructions with mnemonics. The assembler translates source code into an object file, the linker turns object files and libraries into an executable file, and the loader places the program in memory. A two-pass assembler fills the symbol table in the first pass and produces the bytes in the second.
- Assembly code depends on both the processor and the operating system:
int 0x80,int 21h, a DLL call,jsr,svc,sc. Service numbers, parameter registers, and string-end rules change with the environment. - Compiled languages (C, C++, Go, Rust, Fortran, Ada) are translated to machine code in advance: they are fast, but the output is platform-specific. Interpreted languages (Python, Ruby, PHP, Perl, MATLAB) are processed while running: they give fast development and portable source, but run more slowly. Java and C# sit between the two with intermediate code + JIT; JavaScript engines use JIT too.
- Intermediate code is the language of a stack machine that uses no registers; operands are taken from the stack and results are put on the stack.
- High-level
while,for, andifconstructs are realized in assembly as compare + conditional jump; the condition is usually inverted. Whether a variable is signed or unsigned determines which jump instruction is chosen.
3.1.13Key terms
- software
- operating system
- high-level / low-level language
- machine language
- machine code
- assembly language
- mnemonic
- instruction set
- instruction format
- opcode
- operand
- encoder / decoder
- source code
- assembler
- object file
- linker
- loader
- executable file
- listing file
- directive
- location counter ($)
- symbol table
- syntax (Intel / AT&T)
- system call
- little-endian
- string
- calling convention
- compiler
- interpreter
- bytecode / intermediate language
- virtual machine
- just-in-time (JIT) compilation
- stack machine
- implementation
3.1.14Test Yourself
In the sample instruction format, addresses 0, 1, and 2 hold the bytes 13h, 2Ch, and 00h in that order. Initially R0 = 2, R1 = 0, R2 = 5, R3 = 9. What are the registers at HALT?
Answer
13h = 0001 00 11: ADD R0, R3 → R0 = 2 + 9 = 11. 2Ch = 0010 11 00: SUB R3, R0 → R3 = 9 − 11 = −2; in an 8-bit register, in two's complement, 1111 1110 = FEh. 00h: HALT. Result: R0 = 11, R1 = 0, R2 = 5, R3 = FEh (−2). The second instruction uses the value of R0 left by the first.
On the 8086 the instruction
mov ax, [0300h]is encoded asA1 00 03. If address 0300h holds34and address 0301h holds12, what is AX? What would change on the data bus if the instruction read a word from address 0301h?Answer
Because the low byte is stored first, AX = 1234h. 0301h is an odd address. The 8086's 16-bit data bus can read in one cycle only a word that starts at an even address. A word at an odd address arrives with two separate byte reads, that is, two bus cycles. The result is the same, but the access takes at least 4 clock periods longer.
Why does the first pass of a two-pass assembler not produce the bytes of the instructions? If all labels were defined before they were used, would a single pass be enough?
Answer
In the first pass the addresses of forward references are not yet known; an operand such as
offset msgcannot be encoded. This pass only adds up the lengths and fills the symbol table. If all labels were defined before use, every address would be known when needed and a single pass would be enough. But most jump instructions go forward, for example to the end of a loop; this restriction cannot be applied in practice.In a DOS COM program the line
msg db 'Hello$'starts at address 0110h. What is the machine code of the instructionlea dx, msg? How many characters does service 09h print?Answer
emu8086 encodes a direct-address
lea dx, …likemov dx, offset …:BAand the little-endian address, that is,BA 10 01(3 bytes). In MASM the same instruction would be8D 16 10 01. Service 09h prints the 5 characters of the word “Hello”; the$is not printed.What does the sequence
mov eax, 1/mov ebx, 7/int 0x80do on 32-bit Linux? With which registers and which instruction is the same job done on 64-bit Linux?Answer
EAX = 1 is
sys_exit; the process terminates with exit code 7. On 64-bit Linux the number of the exit service is 60 and it goes in RAX, the exit code in RDI; the switch into the kernel is made with thesyscallinstruction.Before a function with two parameters is called under the stdcall convention, ESP = 0012FF40h. What is ESP at the moment of entering the function, and what does [ESP + 8] hold? With which instruction must the function return?
Answer
Two
pushinstructions and the return address take 12 bytes: ESP = 0012FF40h − 0Ch = 0012FF34h. [ESP] is the return address, [ESP + 4] the first parameter, and [ESP + 8] the second parameter. To discard the 8 bytes of parameters itself, the function returns withret 8; on return ESP is 0012FF40h again.What is the intermediate code of the expression
a * (b − c)on a stack machine? For a = 4, b = 10, c = 3, what is the maximum depth of the stack?Answer
iload a,iload b,iload c,isub,imul,istore x. The stack goes through [4], [4, 10], [4, 10, 3], [4, 7], [28], [ ]. The maximum depth is 3; the result is x = 28.In the 8086 odd/even program,
cmp cx, 5is written instead ofcmp cx, 3andjaeis mistakenly used instead ofja. Which numbers does the program print?Answer
jaejumps when CF = 0, that is, when CX ≥ 5. For CX = 1, 2, 3, 4, CF = 1 and the body runs; at CX = 5, 5 − 5 = 0 and CF = 0, and the loop is left. The program prints 1 through 4; 5 is missing. The correct choice isja: the body must also run on equality.When a Python program is written with
for i in range(1, n):, over which values does it iterate for n = 4? What happens if the same loop is written in Ruby as1..nand as1...n?Answer
Python iterates over 1, 2, 3; the upper bound is not included. In Ruby,
1..4iterates over 1, 2, 3, 4 and1...4over 1, 2, 3. Two dots include the upper bound; three dots leave it out.
3.1.15Further reading
- K. R. Irvine, Assembly Language for x86 Processors (7th ed.), Chapters 1–3: language levels, the assembler and linker, listing files, and first programs on x86; it is the source closest to the assembly sections of these notes.
- B. B. Brey, The Intel Microprocessors (8th ed.), Chapters 1 and 4: machine language, encoding of 8086 instructions, the ModR/M byte, and the structure of COM/EXE programs.
- A. S. Tanenbaum and H. Bos, Modern Operating Systems (3rd ed.), Section 1.6: how system calls work, user and kernel modes.
- J. R. Levine, Linkers and Loaders, Morgan Kaufmann: describes object files, symbol resolution, relocation, and the loading process in detail.
3.1.16References
- A. S. Tanenbaum, H. Bos, Modern Operating Systems, 3rd edition, Pearson.
- B. B. Brey, The Intel Microprocessors, 8th edition, Pearson.
- K. R. Irvine, Assembly Language for x86 Processors, 7th edition, Pearson.
- NASM documentation (nasm.us) and the GNU Binutils as manual.
- Ralf Brown's Interrupt List (DOS INT 21h services); Microsoft Win32 API documentation (
MessageBoxA,ExitProcess). - emu8086 documentation and the 8086 instruction set reference.
- J. R. Levine, Linkers and Loaders, Morgan Kaufmann, 1999.
Related pages: Chapter 3.1 slides · © Sercan Külcü. All rights reserved.