Modula-2 low-level programming
last modified November 27, 2026 Modula-2
Modula-2 was designed to write operating systems, so it lets a program
step outside its type system when it has to. All such facilities are
collected in one module, SYSTEM. A program that imports from
SYSTEM declares in its first lines that it depends on the
machine, and the rest of the program keeps the usual checks. The module
is built into the compiler, and its definition module only documents it.
This article uses the ISO SYSTEM, compiled with
-fiso. The PIM version is smaller and differs in details;
its coroutines appear in the coroutines
article. The outputs come from x86-64 Linux; on another machine sizes and
byte order may differ, which is exactly the point of the module.
Storage units
ISO SYSTEM describes memory in LOCs, the
smallest addressable units. BYTE and WORD are
built from them, and ADDRESS is a pointer to a
LOC.
MODULE sizes;
FROM SYSTEM IMPORT LOC, BYTE, WORD, ADDRESS, BITSPERLOC, LOCSPERWORD, TSIZE;
FROM STextIO IMPORT WriteString, WriteLn;
FROM SWholeIO IMPORT WriteCard;
PROCEDURE Show(name: ARRAY OF CHAR; value: CARDINAL);
BEGIN
WriteString(name); WriteCard(value, 3); WriteLn
END Show;
BEGIN
Show("BITSPERLOC ", BITSPERLOC);
Show("LOCSPERWORD ", LOCSPERWORD);
Show("TSIZE(LOC) ", TSIZE(LOC));
Show("TSIZE(BYTE) ", TSIZE(BYTE));
Show("TSIZE(WORD) ", TSIZE(WORD));
Show("TSIZE(ADDRESS) ", TSIZE(ADDRESS));
Show("TSIZE(INTEGER) ", TSIZE(INTEGER));
Show("TSIZE(LONGINT) ", TSIZE(LONGINT))
END sizes.
TSIZE returns the size of a type in LOCs, the
companion of SIZE, which takes a variable or a type. On
x86-64 a LOC has 8 bits, so it is a byte, and an address
takes 8 bytes. The ISO definition says that a WORD is
LOCSPERWORD locations, here 8, but gm2 15.2 makes it 4 bytes,
the size of an INTEGER. Code that relies on the size of a
WORD should use TSIZE(WORD) rather than the
constant.
$ gm2 -fiso sizes.mod -o sizes $ ./sizes BITSPERLOC 8 LOCSPERWORD 8 TSIZE(LOC) 1 TSIZE(BYTE) 1 TSIZE(WORD) 4 TSIZE(ADDRESS) 8 TSIZE(INTEGER) 4 TSIZE(LONGINT) 8
Addresses
ADR returns the address of a variable, and DIFADR
the distance between two addresses in LOCs. Addresses change
from run to run, but distances do not, so they show how the compiler lays
out data.
MODULE addresses;
FROM SYSTEM IMPORT ADR, DIFADR;
FROM STextIO IMPORT WriteString, WriteLn;
FROM SWholeIO IMPORT WriteInt;
TYPE
Item = RECORD
code: CHAR;
count: INTEGER;
price: REAL;
flag: BOOLEAN
END;
VAR
a: ARRAY [0..3] OF INTEGER;
item: Item;
BEGIN
WriteString("a[1] - a[0] "); WriteInt(DIFADR(ADR(a[1]), ADR(a[0])), 3);
WriteLn;
WriteString("a[3] - a[0] "); WriteInt(DIFADR(ADR(a[3]), ADR(a[0])), 3);
WriteLn;
WriteString("offset of count "); WriteInt(DIFADR(ADR(item.count), ADR(item)), 3);
WriteLn;
WriteString("offset of price "); WriteInt(DIFADR(ADR(item.price), ADR(item)), 3);
WriteLn;
WriteString("offset of flag "); WriteInt(DIFADR(ADR(item.flag), ADR(item)), 3);
WriteLn;
WriteString("SIZE(item) "); WriteInt(SIZE(item), 3); WriteLn
END addresses.
The elements of an array are 4 bytes apart, the size of an
INTEGER. The fields of a record are not packed tightly: after
the one-byte code come three unused bytes, because the
INTEGER starts at an offset divisible by 4, and the
REAL at an offset divisible by 8. The BOOLEAN at
offset 16 is followed by seven more unused bytes, so that the next record
in an array starts aligned again. The record takes 24 bytes although its
fields need 14. The unused bytes are called padding; putting
the large fields first reduces it.
$ gm2 -fiso addresses.mod -o addresses $ ./addresses a[1] - a[0] 4 a[3] - a[0] 12 offset of count 4 offset of price 8 offset of flag 16 SIZE(item) 24
Address arithmetic
ADDADR and SUBADR move an address forward and
back by a number of LOCs. An ADDRESS can be
assigned to any pointer type and back, so a typed pointer can read what
lies at a computed address.
MODULE walk;
FROM SYSTEM IMPORT ADDRESS, ADR, ADDADR, SUBADR, TSIZE;
FROM STextIO IMPORT WriteString, WriteLn;
FROM SWholeIO IMPORT WriteInt;
TYPE
IntPtr = POINTER TO INTEGER;
VAR
data: ARRAY [0..5] OF INTEGER;
p: IntPtr;
a: ADDRESS;
i, sum: INTEGER;
BEGIN
FOR i := 0 TO 5 DO data[i] := (i + 1) * (i + 1) END;
sum := 0;
a := ADR(data);
FOR i := 0 TO 5 DO
p := a;
sum := sum + p^;
a := ADDADR(a, TSIZE(INTEGER))
END;
WriteString("sum "); WriteInt(sum, 0); WriteLn;
WriteString("backwards");
FOR i := 0 TO 5 DO
a := SUBADR(a, TSIZE(INTEGER));
p := a;
WriteInt(p^, 4)
END;
WriteLn
END walk.
ADR(data) is the address of the first element. The first loop
assigns the address to the pointer p, reads the integer
through it and moves the address by TSIZE(INTEGER). After the
loop the address points just past the array; the second loop steps back
through it with SUBADR. This is how C walks an array with
pointers. In Modula-2 it bypasses the index checks: an address moved one
step too far reads whatever comes after the array, even with
-fsoft-check-all. An index does the same job safely, so
address arithmetic belongs where memory has no Modula-2 type, such as a
buffer from a C library.
$ gm2 -fiso walk.mod -o walk $ ./walk sum 91 backwards 36 25 16 9 4 1
Untyped parameters
A formal parameter of type ARRAY OF LOC accepts a variable of
any type; inside the procedure it is an open array of the bytes of the
variable. With it, one procedure can show how values are stored.
MODULE anybytes;
FROM SYSTEM IMPORT LOC, CAST, CARDINAL8;
FROM STextIO IMPORT WriteString, WriteChar, WriteLn;
VAR
n: INTEGER;
x: REAL;
word: ARRAY [0..5] OF CHAR;
PROCEDURE WriteHex(value: CARDINAL);
PROCEDURE Digit(d: CARDINAL);
BEGIN
IF d < 10 THEN
WriteChar(CHR(ORD('0') + d))
ELSE
WriteChar(CHR(ORD('a') + d - 10))
END
END Digit;
BEGIN
Digit(value DIV 16); Digit(value MOD 16)
END WriteHex;
PROCEDURE Dump(name: ARRAY OF CHAR; data: ARRAY OF LOC);
VAR
i: CARDINAL;
BEGIN
WriteString(name);
FOR i := 0 TO HIGH(data) DO
WriteChar(' '); WriteHex(CAST(CARDINAL8, data[i]))
END;
WriteLn
END Dump;
BEGIN
n := 258; Dump("258 ", n);
n := -2; Dump("-2 ", n);
x := 1.0; Dump("1.0 ", x);
word := "Hi"; Dump('"Hi" ', word)
END anybytes.
HIGH(data) is the size of the actual parameter minus one.
A LOC cannot be printed or compared, so CAST
reads each one as a CARDINAL8, a gm2 type from
SYSTEM for an unsigned byte, and WriteHex
writes it in two hexadecimal digits. 258 is 102H, and its lowest byte
comes first: x86-64 is a little-endian machine. -2 is stored
in two's complement, and the eight bytes of 1.0 hold the IEEE pattern
3FF0000000000000H, again lowest byte first. The string fills its array
with 0C.
ISO allows any type as the actual parameter, but gm2 15.2 rejects a record: passing one fails with "a ‘Entry’ is incompatible with a unbounded parameter". The next section works around that with addresses.
$ gm2 -fiso anybytes.mod -o anybytes $ ./anybytes 258 02 01 00 00 -2 fe ff ff ff 1.0 00 00 00 00 00 00 f0 3f "Hi" 48 69 00 00 00 00
Bytes of a record
The address of a variable and its size are enough to read its bytes,
whatever its type. A pointer to CARDINAL8 reads one byte at
a time.
MODULE layout;
FROM SYSTEM IMPORT ADDRESS, ADR, ADDADR, CARDINAL8;
FROM STextIO IMPORT WriteLn;
FROM SWholeIO IMPORT WriteCard;
TYPE
Entry = RECORD
tag: CHAR;
count: INTEGER;
mark: CHAR
END;
BytePtr = POINTER TO CARDINAL8;
VAR
e: Entry;
PROCEDURE DumpAt(start: ADDRESS; size: CARDINAL);
VAR
i: CARDINAL;
p: BytePtr;
BEGIN
FOR i := 0 TO size - 1 DO
p := ADDADR(start, i);
WriteCard(p^, 4)
END;
WriteLn
END DumpAt;
BEGIN
e.tag := 'A';
e.count := 1;
e.mark := 'B';
DumpAt(ADR(e), SIZE(e));
DumpAt(ADR(e.count), SIZE(e.count))
END layout.
DumpAt takes the address and the size from the caller,
ADR(e) and SIZE(e), and prints the bytes as
decimal numbers. 65 and 66 are the codes of A and
B, each followed by three bytes of padding, and the
INTEGER 1 sits between them, lowest byte first. The padding
reads as zero because a module-level variable starts zeroed; in a local
variable it holds whatever was in memory before. The second call shows
that ADR works on a single field too.
$ gm2 -fiso layout.mod -o layout $ ./layout 65 0 0 0 1 0 0 0 66 0 0 0 1 0 0 0
Type casts
CAST(T, x) reads the bits of x as a value of
type T. Nothing is converted; only the type changes. The
type conversions article shows
the PIM type transfers such as CARDINAL(x);
CAST is their ISO form.
MODULE cast;
FROM SYSTEM IMPORT CAST, CARDINAL8;
FROM STextIO IMPORT WriteString, WriteLn;
FROM SWholeIO IMPORT WriteCard;
FROM SRealIO IMPORT WriteFloat;
IMPORT SLongWholeIO;
VAR
x: REAL;
bits: LONGCARD;
i: INTEGER;
c: CARDINAL;
small: CARDINAL8;
BEGIN
x := 1.0;
bits := CAST(LONGCARD, x);
WriteString("bits of 1.0 "); SLongWholeIO.WriteCard(bits, 0); WriteLn;
bits := bits + 1;
x := CAST(REAL, bits);
WriteString("next - 1.0 "); WriteFloat(x - 1.0, 7, 0); WriteLn;
i := -1;
c := CAST(CARDINAL, i);
WriteString("-1 as CARDINAL "); WriteCard(c, 0); WriteLn;
i := 300;
small := CAST(CARDINAL8, i);
WriteString("300 as CARDINAL8 "); WriteCard(small, 0); WriteLn
END cast.
The bits of the REAL 1.0 read as a LONGCARD
make 4607182418800017408, which is 3FF0000000000000H, and they are
printed with SLongWholeIO, because SWholeIO
prints only the low 32 bits of a long number. Adding 1 to the bits and
casting back gives the next larger REAL; its distance from
1.0 is the machine epsilon of 64-bit reals. -1 read as a
CARDINAL is the largest cardinal. The last cast is a trap:
an INTEGER has 4 bytes and a CARDINAL8 one, and
gm2 accepts the cast silently and keeps the low byte, 300 - 256 = 44.
Check that both types have the same TSIZE before casting.
$ gm2 -fiso cast.mod -o cast $ ./cast bits of 1.0 4607182418800017408 next - 1.0 2.220446E-16 -1 as CARDINAL 4294967295 300 as CARDINAL8 44
Sets as bit fields
A set is stored as a row of bits, one per possible element, the first element in the lowest bit. A set over an enumeration therefore gives names to the bits of a number. Unix file permissions are nine such bits.
MODULE modes;
FROM SYSTEM IMPORT CAST;
FROM STextIO IMPORT WriteString, WriteChar, WriteLn;
FROM SWholeIO IMPORT WriteCard;
TYPE
Perm = (OtherX, OtherW, OtherR, GroupX, GroupW, GroupR,
UserX, UserW, UserR);
Mode = SET OF Perm;
VAR
mode: Mode;
PROCEDURE WriteOctal(n: CARDINAL);
BEGIN
IF n >= 8 THEN WriteOctal(n DIV 8) END;
WriteChar(CHR(ORD('0') + n MOD 8))
END WriteOctal;
PROCEDURE Show(m: Mode);
CONST
Letters = "xwrxwrxwr";
VAR
p: Perm;
letters: ARRAY [0..8] OF CHAR;
BEGIN
letters := Letters;
FOR p := UserR TO OtherX BY -1 DO
IF p IN m THEN WriteChar(letters[ORD(p)]) ELSE WriteChar('-') END
END;
WriteString(" "); WriteOctal(CAST(CARDINAL, m));
WriteString(" "); WriteCard(CAST(CARDINAL, m), 0); WriteLn
END Show;
BEGIN
WriteString("SIZE(Mode) "); WriteCard(SIZE(Mode), 0); WriteLn;
mode := Mode{UserR, UserW, UserX, GroupR, GroupX, OtherR, OtherX};
Show(mode);
mode := CAST(Mode, VAL(CARDINAL, 420));
Show(mode);
EXCL(mode, OtherR);
Show(mode)
END modes.
The enumeration lists the permissions from the lowest bit, the execute
right of others, to the highest, the read right of the owner. The set of
nine elements takes 4 bytes, the size of a CARDINAL, so
CAST turns it into the number that chmod uses,
and WriteOctal prints it in the familiar octal form. The
cast also works the other way: 420 is octal 644. After that, the
permissions are changed by name with EXCL, and the number
follows. Show walks the enumeration backwards to print the
permissions as ls -l does.
$ gm2 -fiso modes.mod -o modes $ ./modes SIZE(Mode) 4 rwxr-xr-x 755 493 rw-r--r-- 644 420 rw-r----- 640 416
SHIFT and ROTATE
SHIFT moves the bits of a set up or down; bits pushed out at
one end are lost, and zeros come in at the other. ROTATE
puts the bits that leave at one end back in at the other. Both take sets
only; SHIFT on a CARDINAL is rejected with "SYSTEM
procedure SHIFT expects a constant or variable which has a type of SET".
MODULE shifts;
FROM SYSTEM IMPORT SHIFT, ROTATE, CAST;
FROM STextIO IMPORT WriteString, WriteChar, WriteLn;
FROM SWholeIO IMPORT WriteCard;
TYPE
Bits8 = SET OF [0..7];
Bits32 = SET OF [0..31];
VAR
b: Bits8;
mode: CARDINAL;
field: Bits32;
PROCEDURE Show(label: ARRAY OF CHAR; s: Bits8);
VAR
i: CARDINAL;
BEGIN
WriteString(label);
FOR i := 7 TO 0 BY -1 DO
IF i IN s THEN WriteChar('1') ELSE WriteChar('0') END
END;
WriteLn
END Show;
BEGIN
b := Bits8{0, 1, 7};
Show("start ", b);
Show("SHIFT 2 ", SHIFT(b, 2));
Show("SHIFT -2 ", SHIFT(b, -2));
Show("ROTATE 2 ", ROTATE(b, 2));
Show("ROTATE -2 ", ROTATE(b, -2));
mode := 493;
field := CAST(Bits32, mode);
field := SHIFT(field, -3) * Bits32{0..2};
WriteString("group digit "); WriteCard(CAST(CARDINAL, field), 0); WriteLn
END shifts.
Show prints a set of eight bits with the highest bit first,
as numbers are written. A positive count shifts or rotates towards the
high bits, a negative one towards the low bits. Rotating
10000011 by 2 brings the high bit around to bit 1. The last
lines extract one octal digit of the permissions 755: the number is cast
to a set of 32 bits, shifted down by three, and intersected with the
three lowest bits, which leaves 5, the permissions of the group. Shifting
and masking a set is how Modula-2 takes apart a packed hardware register
or a binary file format.
$ gm2 -fiso shifts.mod -o shifts $ ./shifts start 10000011 SHIFT 2 00001100 SHIFT -2 00100000 ROTATE 2 00001110 ROTATE -2 11100000 group digit 5
Source
GNU Modula-2: the ISO system module
GNU Modula-2: the ISO SYSTEM definition module
In this article we have measured storage units, taken addresses and
computed with them, printed the bytes of values and of a record, cast
between types and used sets as bit fields with SHIFT and
ROTATE. The pointers
article covers typed pointers and the heap, and the
calling C article uses addresses to pass
data to C functions.
Author
List all Modula-2 tutorials.