Programming Search⌘K

Conceptcore

Machine code

Also called machine code, machine language, native code, object code, binary code, instruction set, instruction set architecture, ISA, opcode, instruction encoding, assembly language.

Machine code is a program as the processor runs it: instructions encoded as bytes in memory. Each family of processors has its own instruction set, so machine code for one does not run on another.

Applies to
core-languages

Idea

A processor does not read source code. It reads instructions from memory, each one a pattern of bits that says what to do: add two registers, load a word from an address, jump to another instruction. A program in this form is machine code. The set of instructions and their encoding is the instruction set architecture of the processor, and it differs between families: machine code for ARM64 means nothing to an x86-64 processor. Compilers write machine code from source code, and assemblers write it from a text form, assembly language, in which each line names one instruction.

# A tiny assembler and simulator for three ARM64 instructions.
def movz(rd, imm16):
    return 0xD2800000 | imm16 << 5 | rd


def mul(rd, rn, rm):
    return 0x9B007C00 | rm << 16 | rn << 5 | rd


RET = 0xD65F03C0

program = [movz(0, 6), movz(1, 7), mul(0, 0, 1), RET]
code = b"".join(w.to_bytes(4, "little") for w in program)
print("words:", " ".join(f"{w:08x}" for w in program))
print("bytes:", code.hex(" "))


def run(code):
    x = [0] * 32
    pc = 0
    while True:
        w = int.from_bytes(code[pc:pc + 4], "little")  # fetch
        pc += 4
        rd, rn, rm = w & 31, w >> 5 & 31, w >> 16 & 31  # decode the register fields
        if w & 0xFF800000 == 0xD2800000:  # execute
            x[rd] = w >> 5 & 0xFFFF
        elif w & 0xFFE0FC00 == 0x9B007C00:
            x[rd] = x[rn] * x[rm] % 2**64
        elif w == RET:
            return x[0]
        else:
            raise ValueError(f"unknown instruction {w:08x}")


print("x0 =", run(code))
Output
words: d28000c0 d28000e1 9b017c00 d65f03c0
bytes: c0 00 80 d2 e1 00 80 d2 00 7c 01 9b c0 03 5f d6
x0 = 42

The program is an assembler and a processor in a few lines. Each ARM64 instruction is one 32-bit word with fields at fixed places: the low 5 bits name the destination register, and other bits hold a constant or two more register numbers. The words are stored low byte first, so movz x0, #6 is the word d28000c0 and the bytes c0 00 80 d2. The simulator repeats the cycle of every processor: fetch the next word, decode its fields, execute it. The words are the same ones that the system assembler gives for the same four lines.

How it works

Instructions and their encoding. An instruction set defines the registers, the instructions and the bits of each one. An instruction has an opcode, which says which operation, and operands: register numbers, a constant, or a way to find a memory address. ARM64 and RISC-V use fixed-length words of 4 bytes, so the decoder knows where each instruction starts; RISC-V adds an optional 2-byte form to make code smaller. x86-64 instructions take from 1 to 15 bytes, with optional prefixes, an opcode, a byte that names registers and modes, and constants, so a decoder must read each instruction to find the next one.

Running instructions. The processor keeps the address of the next instruction in the program counter. It fetches the instruction there, decodes it and executes it, and the program counter moves to the next instruction unless the instruction is a jump, a branch or a call. Real processors overlap these steps for many instructions at once and run them out of order, but the result must be the same as one at a time. See processor and memory.

Conventions around the code. Machine code alone does not say how functions call each other. An application binary interface, or ABI, sets the rules: which registers hold the arguments and the result, which registers a function must keep, and how the stack is laid out. On ARM64 a function returns its result in x0, and on x86-64 Linux and macOS in rax, which is why the C example puts 42 in those registers. Object files and executables, in the formats ELF, Mach-O and PE, hold the machine code with the names, addresses and relocations that the linker and the loader need.

From source to machine code. A compiler such as GCC, Clang, rustc or the Go compiler translates source code to machine code before the program runs. Most compilers go through an intermediate form, and the Go toolchain's assembler "is not a direct representation of the underlying machine": it works on "a kind of semi-abstract instruction set", and the final instructions are chosen later.6 C, C++ and Rust allow assembly inside a function: GCC has asm statements,8 and in Rust, inline assembly "can be used to embed handwritten assembly in the assembly output generated by the compiler".7

Virtual machine code. Many languages compile to the instructions of a machine that does not exist as hardware. A Java class file holds bytecode for the JVM, and the specification says of its first four bytes, the magic number, that "it has the value 0xCAFEBABE".3 The package java.lang.classfile "Provides classfile parsing, generation, and transformation library", so a program can write bytecode and load it.4 .NET assemblies hold the Common Intermediate Language, and a DynamicMethod lets a program write its own IL: it "Defines and represents a dynamic method that can be compiled, executed, and discarded".5 WebAssembly is "a safe, portable, low-level code format designed for efficient execution and compact representation".1 Its binary module "starts with a preamble containing a 4-byte magic number", the bytes 00 61 73 6d, and a version.2 A just-in-time compiler turns these instructions into real machine code while the program runs. See bytecode and just-in-time compilation.

Code is data in memory. Machine code is bytes in memory like any other data, so a program can write instructions and then run them. Just-in-time compilers do this all the time. Operating systems protect against attacks that inject code by a rule called W^X: a page of memory is writable or executable, not both at the same time. A JIT asks for a special mapping and switches the page between the two states, as the C example does with MAP_JIT on macOS.

In languages

LanguageVerdictNote
PythonAbsent
C++Native
JavaAbsent
CNative
C#Absent
JavaScriptAbsent
TypeScriptAbsentTypeScript compiles to JavaScript, so the program reaches machine code only as WebAssembly bytes, as in JavaScript, but no example file exists.
GoNative
RustNative
KotlinAbsentKotlin on the JVM compiles to bytecode, and Kotlin/Native compiles to machine code with LLVM but has no inline assembly, and no example file exists because kotlinc is not installed.
SQLDoes not applyA query says what data to get, and the database decides how to run it.
BashAbsentThe shell interprets commands and runs programs that are already machine code, and it cannot write instructions.
PowerShellAbsentPowerShell runs on .NET, whose JIT makes the machine code, and a script can reach CIL only through the .NET Reflection.Emit types, but no example file exists because pwsh is not installed.
HTMLDoes not applyHTML describes a document and has no instructions.
CSSDoes not applyCSS describes presentation and has no instructions.
Regular expressionsDoes not applySome engines compile a pattern to machine code, but the pattern language has no instructions.
Language Verdict Mechanism
Python absent CPython runs bytecode; machine code only through C extensions or ctypes
JavaScript absent the engine compiles to machine code; WebAssembly bytes from the program
TypeScript absent as JavaScript
Java absent bytecode in class files; the JIT makes machine code; java.lang.classfile
Kotlin absent JVM bytecode; Kotlin/Native compiles to machine code
C# absent CIL in assemblies; the JIT or Native AOT makes machine code; Reflection.Emit
Go native the compiler writes machine code; assembly files in the Plan 9 syntax
Rust native the compiler writes machine code; asm!, global_asm!
C native the compiler writes machine code; asm in GCC and Clang
C++ native as C
Bash absent the shell interprets commands and runs other programs
PowerShell absent runs on .NET, which makes the machine code
SQL n/a the database decides how to run a query
Regex n/a some engines compile patterns to machine code, but the pattern cannot
HTML n/a no instructions
CSS n/a no instructions

Go, Rust, C and C++ compile to machine code before the program runs, and Rust, C and C++ let the programmer write instructions inside a function, so the verdict for them is native. Java, C# and JavaScript run on virtual machines that make machine code with a just-in-time compiler, and the program sees only the virtual instructions: JVM bytecode, CIL or WebAssembly. CPython interprets its own bytecode. For these languages the verdict is absent, because the program cannot write or see the machine code in the normal way.

The example files show machine code at the level that each language can reach. Python decodes x86-64 instructions of different lengths. JavaScript writes a WebAssembly module byte by byte and runs it. Java writes and runs JVM bytecode with the class file API, and C# writes CIL with Reflection.Emit. Go runs RISC-V machine code in a small emulator. Rust uses inline assembly, C copies the bytes of a function into executable memory and calls them, and C++ checks a small ARM64 assembler at compile time.

PythonGitHub
# x86-64 instructions have different lengths. A decoder must read each one to find the next.
code = bytes.fromhex("b8 2a 00 00 00 48 01 c8 90 48 b8 88 77 66 55 44 33 22 11 c3")
REG = ["ax", "cx", "dx", "bx", "sp", "bp", "si", "di"]

pc = 0
while pc < len(code):
    start = pc
    rex_w = code[pc] == 0x48  # REX.W prefix: the operation uses 64 bits
    if rex_w:
        pc += 1
    op = code[pc]
    pc += 1
    size = "r" if rex_w else "e"
    if 0xB8 <= op <= 0xBF:  # mov register, immediate
        n = 8 if rex_w else 4
        imm = int.from_bytes(code[pc:pc + n], "little")
        pc += n
        text = f"mov {size}{REG[op - 0xB8]}, {imm:#x}"
    elif op == 0x01:  # add r/m, register: a ModRM byte names the two registers
        modrm = code[pc]
        pc += 1
        text = f"add {size}{REG[modrm & 7]}, {size}{REG[modrm >> 3 & 7]}"
    elif op == 0x90:
        text = "nop"
    elif op == 0xC3:
        text = "ret"
    else:
        raise ValueError(f"unknown opcode {op:#x}")
    n = pc - start
    print(f"{code[start:pc].hex(' '):30} {n:2} byte{'s' if n > 1 else ' '}  {text}")
Output
b8 2a 00 00 00                  5 bytes  mov eax, 0x2a
48 01 c8                        3 bytes  add rax, rcx
90                              1 byte   nop
48 b8 88 77 66 55 44 33 22 11  10 bytes  mov rax, 0x1122334455667788
c3                              1 byte   ret
  • Verdict: absent. CPython compiles source to its own bytecode and interprets it, so a Python program does not see machine code. The example treats machine code as data: it decodes five x86-64 instructions of 1, 3, 5 and 10 bytes. The 48 prefix makes an operation 64 bits wide, and the mov of a 64-bit constant carries all 8 bytes of it, low byte first. The decoder must read each instruction to know where the next one starts.
#include <array>
#include <cstdint>
#include <cstdio>

// A compile-time assembler for three ARM64 instructions. Each one is a 32-bit word.
constexpr std::uint32_t movz(unsigned rd, unsigned imm16) { return 0xD2800000u | imm16 << 5 | rd; }
constexpr std::uint32_t add(unsigned rd, unsigned rn, unsigned rm) { return 0x8B000000u | rm << 16 | rn << 5 | rd; }
constexpr std::uint32_t ret() { return 0xD65F03C0u; }

// The compiler checks the encodings against the words that an assembler gives.
static_assert(movz(0, 42) == 0xD2800540u);
static_assert(add(0, 0, 1) == 0x8B010000u);

constexpr std::array<std::uint32_t, 4> program{movz(0, 40), movz(1, 2), add(0, 0, 1), ret()};
constexpr std::array<const char*, 4> text{"movz x0, #40", "movz x1, #2", "add x0, x0, x1", "ret"};

int main() {
    for (std::size_t k = 0; k < program.size(); ++k) {
        std::uint32_t w = program[k];
        // Store the word in little-endian order, as ARM64 processors read it.
        std::printf("%08x ->", static_cast<unsigned>(w));
        for (int i = 0; i < 4; ++i) std::printf(" %02x", static_cast<unsigned>(w >> (8 * i) & 0xFF));
        std::printf("  %s\n", text[k]);
    }
    std::printf("%zu instructions, %zu bytes\n", program.size(), program.size() * 4);
}
Output
d2800500 -> 00 05 80 d2  movz x0, #40
d2800041 -> 41 00 80 d2  movz x1, #2
8b010000 -> 00 00 01 8b  add x0, x0, x1
d65f03c0 -> c0 03 5f d6  ret
4 instructions, 16 bytes
  • Verdict: native. C++ compiles to machine code and allows asm in GCC and Clang. The example writes a small ARM64 assembler with constexpr functions, so the compiler builds the program at compile time and static_assert checks two encodings against an assembler. Each instruction is 4 bytes, stored in little-endian order.
JavaGitHub
import java.lang.classfile.ClassFile;
import java.lang.classfile.CodeElement;
import java.lang.classfile.Instruction;
import java.lang.constant.ClassDesc;
import java.lang.constant.ConstantDescs;
import java.lang.constant.MethodTypeDesc;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.lang.reflect.AccessFlag;

public class Main {
    public static void main(String[] args) throws Throwable {
        // Write the bytecode of "static int add(int a, int b) { return a + b; }" by hand.
        MethodTypeDesc type = MethodTypeDesc.of(ConstantDescs.CD_int, ConstantDescs.CD_int, ConstantDescs.CD_int);
        byte[] cls = ClassFile.of().build(ClassDesc.of("Main$Adder"), cb -> cb
            .withMethodBody("add", type, ClassFile.ACC_PUBLIC | ClassFile.ACC_STATIC, code -> code
                .iload(0)
                .iload(1)
                .iadd()
                .ireturn()));
        System.out.println("class file: " + cls.length + " bytes");

        // Read the instructions back from the class file.
        var model = ClassFile.of().parse(cls);
        for (var m : model.methods()) {
            if (!m.flags().has(AccessFlag.STATIC)) continue;
            for (CodeElement e : m.code().orElseThrow()) {
                if (e instanceof Instruction i) {
                    System.out.println("  " + i.opcode().name().toLowerCase() + " (" + i.sizeInBytes() + " byte)");
                }
            }
        }

        // The JVM loads the class, checks the bytecode and runs it.
        var lookup = MethodHandles.lookup().defineHiddenClass(cls, true);
        var add = lookup.findStatic(lookup.lookupClass(), "add", MethodType.methodType(int.class, int.class, int.class));
        System.out.println("add(40, 2) = " + (int) add.invokeExact(40, 2));
    }
}
Output
class file: 113 bytes
  iload_0 (1 byte)
  iload_1 (1 byte)
  iadd (1 byte)
  ireturn (1 byte)
add(40, 2) = 42
  • Verdict: absent. A Java program runs as JVM bytecode, and the JIT compiler makes the machine code out of sight. The class file API writes a method of four one-byte instructions that push the two arguments, add them and return the result. The program reads the instructions back from the class file and loads it as a hidden class; the JVM verifies the bytecode before it runs it.
#define _DARWIN_C_SOURCE
#include <stdio.h>
#include <string.h>
#include <sys/mman.h>
#if defined(__APPLE__)
#include <libkern/OSCacheControl.h>
#include <pthread.h>
#endif

/* The machine code of a function that returns 42, for two processors. */
#if defined(__aarch64__)
static const unsigned char code[] = {
    0x40, 0x05, 0x80, 0xd2, /* movz x0, #42 */
    0xc0, 0x03, 0x5f, 0xd6, /* ret */
};
#elif defined(__x86_64__)
static const unsigned char code[] = {
    0xb8, 0x2a, 0x00, 0x00, 0x00, /* mov eax, 42 */
    0xc3,                         /* ret */
};
#else
#error "no machine code for this processor"
#endif

int main(void) {
    int flags = MAP_PRIVATE | MAP_ANON;
#if defined(__APPLE__)
    flags |= MAP_JIT; /* macOS allows writable and executable memory only with MAP_JIT */
#endif
    void *mem = mmap(NULL, 4096, PROT_READ | PROT_WRITE | PROT_EXEC, flags, -1, 0);
    if (mem == MAP_FAILED) {
        perror("mmap");
        return 1;
    }
#if defined(__APPLE__)
    pthread_jit_write_protect_np(0); /* make the page writable for this thread */
#endif
    memcpy(mem, code, sizeof code);
#if defined(__APPLE__)
    pthread_jit_write_protect_np(1); /* and executable again */
    sys_icache_invalidate(mem, sizeof code);
#else
    __builtin___clear_cache((char *)mem, (char *)mem + sizeof code);
#endif
    int (*f)(void) = (int (*)(void))mem; /* treat the bytes as a function */
    printf("f() = %d\n", f());
    munmap(mem, 4096);
    return 0;
}
Output
f() = 42
  • Verdict: native. The program holds the machine code of a function that returns 42, for ARM64 and for x86-64, and copies it into a page of memory that can run code. On macOS the page needs MAP_JIT and a switch from writable to executable, because of the W^X rule, and on ARM the instruction cache must be cleared. Casting the address to a function pointer and calling it runs the bytes. ISO C does not allow this cast; POSIX systems support it.
#:property PublishAot=false
using System.Reflection.Emit;

// Write the IL of "static int Add(int a, int b) => a + b" by hand.
var dm = new DynamicMethod("Add", typeof(int), [typeof(int), typeof(int)]);
ILGenerator il = dm.GetILGenerator();
OpCode[] ops = [OpCodes.Ldarg_0, OpCodes.Ldarg_1, OpCodes.Add, OpCodes.Ret];
foreach (OpCode op in ops)
{
    il.Emit(op);
    Console.WriteLine($"  {op.Name,-8} 0x{op.Value:x2} ({op.Size} byte)");
}

// The JIT compiler turns the IL into machine code the first time the method runs.
var add = dm.CreateDelegate<Func<int, int, int>>();
Console.WriteLine($"Add(40, 2) = {add(40, 2)}");
Console.WriteLine($"Add(int.MaxValue, 1) = {add(int.MaxValue, 1)}");
Output
  ldarg.0  0x02 (1 byte)
  ldarg.1  0x03 (1 byte)
  add      0x58 (1 byte)
  ret      0x2a (1 byte)
Add(40, 2) = 42
Add(int.MaxValue, 1) = -2147483648
  • Verdict: absent. C# compiles to CIL, and the JIT compiler or Native AOT makes the machine code. DynamicMethod and ILGenerator let the program write CIL at run time; the loop prints the name, the byte value and the size of each opcode. The first call compiles the method to machine code. The line #:property PublishAot=false is needed in a file-based app, because Native AOT cannot run code that the program writes at run time.
JavaScriptGitHub
// A WebAssembly module, written byte by byte: one function that adds two 32-bit integers.
const bytes = new Uint8Array([
  0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00, // magic "\0asm" and version 1
  0x01, 0x07, 0x01, 0x60, 0x02, 0x7f, 0x7f, 0x01, 0x7f, // type: (i32, i32) -> i32
  0x03, 0x02, 0x01, 0x00, // function 0 has type 0
  0x07, 0x07, 0x01, 0x03, 0x61, 0x64, 0x64, 0x00, 0x00, // export function 0 as "add"
  0x0a, 0x09, 0x01, 0x07, 0x00, // code: one body of 7 bytes, no locals
  0x20, 0x00, // local.get 0
  0x20, 0x01, // local.get 1
  0x6a, // i32.add
  0x0b, // end
]);

console.log("valid:", WebAssembly.validate(bytes), "size:", bytes.length, "bytes");
const { instance } = await WebAssembly.instantiate(bytes);
console.log("add(40, 2) =", instance.exports.add(40, 2));
console.log("add(2147483647, 1) =", instance.exports.add(2147483647, 1)); // i32 wraps around

// Change one byte of the code: 0x6b is i32.sub.
const sub = bytes.slice();
sub[sub.length - 2] = 0x6b;
const m2 = await WebAssembly.instantiate(sub);
console.log("after one byte changes: add(40, 2) =", m2.instance.exports.add(40, 2));
Output
valid: true size: 41 bytes
add(40, 2) = 42
add(2147483647, 1) = -2147483648
after one byte changes: add(40, 2) = 38
  • Verdict: absent. The engine compiles JavaScript to machine code, but the program cannot see it. WebAssembly is the closest form: the program writes a module of 41 bytes, with the magic number, a function type, an export and a body of four instructions. WebAssembly.instantiate checks the bytes and compiles them, and the 32-bit add wraps around. Changing the one byte 6a to 6b makes the function subtract.
package main

import (
	"encoding/binary"
	"fmt"
)

// The machine code of a RISC-V function that returns 6 * 7, as little-endian bytes.
var code = []byte{
	0x13, 0x05, 0x60, 0x00, // addi a0, zero, 6
	0x93, 0x05, 0x70, 0x00, // addi a1, zero, 7
	0x33, 0x05, 0xb5, 0x02, // mul a0, a0, a1
	0x67, 0x80, 0x00, 0x00, // ret (jalr zero, 0(ra))
}

func main() {
	var x [32]int64 // x10 is a0, x11 is a1
	for pc := 0; ; pc += 4 {
		w := binary.LittleEndian.Uint32(code[pc:])
		// Each field is at a fixed place in the 32-bit word.
		op, rd, f3 := w&0x7f, w>>7&31, w>>12&7
		rs1, rs2, f7 := w>>15&31, w>>20&31, w>>25
		switch {
		case op == 0x13 && f3 == 0:
			imm := int64(int32(w) >> 20) // sign-extend the 12-bit immediate
			fmt.Printf("%08x  addi x%d, x%d, %d\n", w, rd, rs1, imm)
			x[rd] = x[rs1] + imm
		case op == 0x33 && f3 == 0 && f7 == 1:
			fmt.Printf("%08x  mul  x%d, x%d, x%d\n", w, rd, rs1, rs2)
			x[rd] = x[rs1] * x[rs2]
		case op == 0x67:
			fmt.Printf("%08x  ret\n", w)
			fmt.Println("a0 =", x[10])
			return
		default:
			panic(fmt.Sprintf("unknown instruction %08x", w))
		}
		x[0] = 0 // register x0 is always zero
	}
}
Output
00600513  addi x10, x0, 6
00700593  addi x11, x0, 7
02b50533  mul  x10, x10, x11
00008067  ret
a0 = 42
  • Verdict: native. The Go compiler writes machine code, and Go has assembly files in its own syntax but no inline assembly. The example runs RISC-V machine code in a small emulator: each instruction is a 32-bit word with the register numbers and the operation at fixed bit positions, and addi keeps a 12-bit signed constant in the top bits. The words are the ones that an assembler gives for the same lines.
RustGitHub
use std::arch::asm;

// Inline assembly puts machine instructions into a Rust function.
// The compiler picks the registers and fills in {0} and {1}.
fn add(mut a: u64, b: u64) -> u64 {
    unsafe {
        #[cfg(target_arch = "aarch64")]
        asm!("add {0}, {0}, {1}", inout(reg) a, in(reg) b);
        #[cfg(target_arch = "x86_64")]
        asm!("add {0}, {1}", inout(reg) a, in(reg) b);
    }
    a
}

fn leading_zeros(x: u64) -> u64 {
    let n: u64;
    unsafe {
        #[cfg(target_arch = "aarch64")]
        asm!("clz {0}, {1}", out(reg) n, in(reg) x);
        #[cfg(target_arch = "x86_64")]
        asm!("bsr {0}, {1}", "xor {0}, 63", out(reg) n, in(reg) x); // x must not be 0
    }
    n
}

fn main() {
    println!("add(40, 2) = {}", add(40, 2));
    println!("add(u64::MAX, 1) = {}", add(u64::MAX, 1)); // the machine add wraps around
    println!("leading zeros of 1: {}", leading_zeros(1));
    println!("same as the library: {}", leading_zeros(1 << 20) == u64::from((1u64 << 20).leading_zeros()));
}
Output
add(40, 2) = 42
add(u64::MAX, 1) = 0
leading zeros of 1: 63
same as the library: true
  • Verdict: native. asm! puts instructions inside a Rust function, with one version for each processor, chosen by cfg. The operands say which values go in and out, and the compiler chooses the registers. The machine add wraps around, unlike the + of Rust in a debug build, which panics on overflow. The leading-zero count uses clz on ARM64 and bsr on x86-64, and gives the same result as the library function.
  • Assembly language. A text form of machine code with one line for each instruction, names for registers and labels for addresses. An assembler turns it into machine code, and a disassembler turns machine code back into it.
  • Microcode. Many processors run complex instructions as sequences of simpler internal operations, which the vendor can update.
  • RISC and CISC. Reduced instruction set designs, such as ARM and RISC-V, use simple instructions of one length that load and store memory separately. Complex instruction set designs, such as x86, have instructions of many lengths that can work on memory directly.
  • Position-independent code. Code that uses addresses relative to the program counter can run at any address, which shared libraries and address space layout randomization need.
  • Fat binaries and emulation. A universal binary holds machine code for two instruction sets, and translators such as Rosetta 2 turn x86-64 code into ARM64 code.
  • Bytecode. Bytecode is machine code for a virtual machine, designed to be easy to interpret or compile.

Pitfalls

  • Machine code is not portable. A binary built for x86-64 Linux does not run on ARM64 macOS, because the instruction set, the ABI and the file format all differ. Build for each target, or use a portable form such as bytecode or WebAssembly.
  • Writing code into memory. A program that writes and runs machine code must follow the W^X rules of the system and flush the instruction cache on ARM, or the processor runs old bytes.
  • Inline assembly that lies to the compiler. The compiler trusts the list of registers and memory that an asm block says it uses. A block that changes other registers corrupts the code around it.
  • Code injection. An attacker who can write bytes and make the program jump to them controls the program. W^X, stack canaries, address space layout randomization and control-flow integrity make this harder.
  • Undefined instructions and features. An instruction that the processor does not support stops the program. On x86, lzcnt on an older processor runs as bsr and gives a different result, so code must check the processor features first.

Cost

Machine code is the fastest form of a program, because the processor runs it with no interpreter. An instruction such as an add takes about one cycle, and a modern processor can start several each cycle. The cost of a program is mostly in branches that the processor predicts wrong, which cost about 15 to 20 cycles each, and in loads that miss the caches, which can cost hundreds. Interpreting bytecode is often several times to tens of times slower than running compiled machine code, which is why virtual machines use just-in-time compilers. The size of the code matters too: code that does not fit in the instruction cache runs slower.

History

The stored-program computers of 1948 and 1949, such as the Manchester Baby and the EDSAC, ran instructions that were stored in memory as numbers. Programmers first wrote the bits by hand. Kathleen Booth described an assembly notation in 1947, and David Wheeler's initial orders for the EDSAC, in 1949, read instructions as letters and decimal numbers and stored them as binary, an early assembler in daily use. Maurice Wilkes described microprogramming in 1951.

IBM's System/360, from 1964, with Gene Amdahl as one of its architects, separated the instruction set from the hardware: one set of machine code ran on a family of machines of different sizes. Intel's 8086 of 1978 started the x86 family, which AMD extended to 64 bits in 2003. Sophie Wilson and Steve Furber designed the first ARM processor in 1985, and ARM64 followed in 2011. RISC-V, started at Berkeley in 2010 by Krste Asanović and others, is an open instruction set. Java's virtual machine of 1995 and WebAssembly, which shipped in the major browsers in 2017, made portable instruction sets for code that runs on any processor.

References

  1. Introduction, WebAssembly Specification, Introduction
  2. Modules, Binary Format, WebAssembly Specification, Binary Module
  3. Chapter 4, The class File Format, The Java Virtual Machine Specification, Java SE 25, 4.1 The ClassFile Structure
  4. Package java.lang.classfile, Java SE 25 API documentation, Description
  5. DynamicMethod Class, .NET API documentation, Definition
  6. A Quick Guide to Go's Assembler, The Go Programming Language, Introduction
  7. Inline assembly, The Rust Reference, asm.intro
  8. Basic Asm, Using the GNU Compiler Collection, 6.11.1

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/F8ZJ8N/text.yaml