The File That Was Not There
CI checks the runnable examples on this page every night, and they currently run on Zig 0.18.0-dev.1272+2ff397f75. Nothing checks the plain code blocks, and they may not compile now.
Monday, 9:12 AM
Vishaka wrote a small tool for the team. The name of the tool was phrase.
The tool made passphrases from random words, for example grape-habit-buddy-hammer-diner-river. The team used phrase for shared test accounts. Thus nobody had to invent a password.
On Monday morning, Tejas sent a message.
~/Downloads $ ./phrase
error: FileNotFound
The tool worked on Vishaka’s laptop. The tool also worked on Vishaka’s laptop for all of the previous week.
9:20 AM: what the program looked for
The words came from a file with the name words.txt. The file has 256 words, with one word on each line.
The first version read the file with this line:
const text = try std.Io.Dir.cwd().readFileAlloc(io, "words.txt", init.gpa, .limited(1 << 20));
cwd() is the current directory. The current directory is the directory where you are when you run the program. The current directory is not the directory that holds the program.
Vishaka always ran phrase from the project folder, and words.txt was in that folder. Tejas ran phrase from ~/Downloads, and ~/Downloads had no words.txt.
Thus the program was correct, but the program failed on all machines except Vishaka’s.
9:31 AM: three ways to fix it
Vishaka thought of three fixes:
- Send two files, and tell people to keep the two files together. Vishaka knew that people do not keep two files together.
- Look for
words.txtnext to the program, not in the current directory. This fix is better, but it still uses two files. A person can copy one file and forget the other file. - Put the words inside the program.
Zig can do the third fix with one line:
const words_txt = @embedFile("words.txt");
@embedFile runs at compile time, not at run time.
The compiler reads words.txt from the directory of the source file. Then the compiler stores the bytes of the file in the program.
words_txt is a pointer to those bytes. The compiler knows the length at compile time: 1,582 bytes.
At run time, the program opens no file. Thus no file open can fail.
9:48 AM: the compiler parses the list
Vishaka could split words_txt into lines each time that the program starts. But the words do not change while the program runs. Thus Vishaka let the compiler split the words one time, during the build.
/// The table, which the compiler builds. A bad line in words.txt is a compile
/// error. Thus nobody can build a program with a broken word list.
const words = parseWords(words_txt);That line is outside all functions. In Zig, the compiler calculates a const that is outside all functions at compile time. Thus parseWords runs inside the compiler.
fn parseWords(comptime text: []const u8) [word_count][]const u8 {
// The check for duplicates below compares each pair of words, about 32,000
// comparisons. The compiler stops a long computation, unless you tell the
// compiler to expect one.
@setEvalBranchQuota(2_000_000);
var list: [word_count][]const u8 = undefined;
var n: usize = 0;
var line_number: usize = 0;
var lines = std.mem.splitScalar(u8, text, '\n');
while (lines.next()) |line| {
line_number += 1;
if (line.len == 0) continue;
for (line) |c| {
if (c < 'a' or c > 'z') @compileError(std.fmt.comptimePrint(
"words.txt line {d}: \"{s}\" must be one word in lowercase a to z",
.{ line_number, line },
));
}
for (list[0..n]) |seen| {
if (std.mem.eql(u8, seen, line)) @compileError(std.fmt.comptimePrint(
"words.txt line {d}: \"{s}\" is already in the list",
.{ line_number, line },
));
}
if (n == word_count) @compileError(std.fmt.comptimePrint(
"words.txt has more than {d} words",
.{word_count},
));
list[n] = line;
n += 1;
}
if (n != word_count) @compileError(std.fmt.comptimePrint(
"words.txt has {d} words, and it needs exactly {d}",
.{ n, word_count },
));
return list;
}The result is a table of 256 words. The words are already split, and the table is in the program. When phrase starts, the work is already complete.
The checks in parseWords also run inside the compiler:
@compileErrorstops the build with a message.std.fmt.comptimePrintmakes that message, and puts the line number in the message.- The code calls
@setEvalBranchQuotabecause the check for duplicates makes about 32,000 comparisons. The compiler stops a long computation, unless you tell the compiler to expect one.
Wednesday, 2:05 PM: Tejas edits the list
Tejas wanted a home city in the word list. Tejas replaced line 87, crate, with navi mumbai. Then Tejas built the program again.
phrase.zig:35:37: error: words.txt line 87: "navi mumbai" must be one word in lowercase a to z
if (c < 'a' or c > 'z') @compileError(std.fmt.comptimePrint(
^~~~~~~~~~~~~
phrase.zig:15:25: note: called at comptime here
const words = parseWords(words_txt);
~~~~~~~~~~^~~~~~~~~~~
A word with a space puts a space between two dashes in some passphrases. The compiler did not build the program.
Next, Tejas tried maple.
phrase.zig:41:46: error: words.txt line 200: "maple" is already in the list
Line 200 was mosaic, and maple was already on line 194. A duplicate word makes some passphrases more probable than others. Those passphrases are easier to guess.
Then a line was deleted by mistake.
phrase.zig:54:26: error: words.txt has 255 words, and it needs exactly 256
The build stopped at each mistake, on Tejas’s machine, with the line number. The compiler never built a program with a broken word list.
Why exactly 256
One byte holds a number from 0 to 255. Thus, with 256 words, one random byte selects one word. There is no bias and no extra arithmetic:
/// One word per byte, joined with dashes.
fn writePhrase(out: *Io.Writer, bytes: []const u8) !void {
for (bytes, 0..) |b, i| {
if (i > 0) try out.writeByte('-');
try out.writeAll(words[b]);
}
try out.writeByte('\n');
}The full lookup is words[b]. Each word adds 8 bits. Thus six words make a 48-bit passphrase.
Press Run
const std = @import("std");
const Io = std.Io;
/// The bytes of words.txt, read by the compiler and stored in the program.
const words_txt = @embedFile("words.txt");
/// The table, which the compiler builds. A bad line in words.txt is a compile
/// error. Thus nobody can build a program with a broken word list.
const words = parseWords(words_txt);
/// 256 words, so one random byte picks one word, and each word adds 8 bits.
const word_count = 256;
fn parseWords(comptime text: []const u8) [word_count][]const u8 {
// The check for duplicates below compares each pair of words, about 32,000
// comparisons. The compiler stops a long computation, unless you tell the
// compiler to expect one.
@setEvalBranchQuota(2_000_000);
var list: [word_count][]const u8 = undefined;
var n: usize = 0;
var line_number: usize = 0;
var lines = std.mem.splitScalar(u8, text, '\n');
while (lines.next()) |line| {
line_number += 1;
if (line.len == 0) continue;
for (line) |c| {
if (c < 'a' or c > 'z') @compileError(std.fmt.comptimePrint(
"words.txt line {d}: \"{s}\" must be one word in lowercase a to z",
.{ line_number, line },
));
}
for (list[0..n]) |seen| {
if (std.mem.eql(u8, seen, line)) @compileError(std.fmt.comptimePrint(
"words.txt line {d}: \"{s}\" is already in the list",
.{ line_number, line },
));
}
if (n == word_count) @compileError(std.fmt.comptimePrint(
"words.txt has more than {d} words",
.{word_count},
));
list[n] = line;
n += 1;
}
if (n != word_count) @compileError(std.fmt.comptimePrint(
"words.txt has {d} words, and it needs exactly {d}",
.{ n, word_count },
));
return list;
}
/// One word per byte, joined with dashes.
fn writePhrase(out: *Io.Writer, bytes: []const u8) !void {
for (bytes, 0..) |b, i| {
if (i > 0) try out.writeByte('-');
try out.writeAll(words[b]);
}
try out.writeByte('\n');
}
pub fn main(init: std.process.Init) !void {
const io = init.io;
var out_buf: [1024]u8 = undefined;
var stdout = Io.File.stdout().writerStreaming(io, &out_buf);
const out = &stdout.interface;
defer out.flush() catch {};
try out.print("{d} words, {d} bytes of words.txt, inside the program\n", .{ words.len, words_txt.len });
try out.print("first word: {s}, last word: {s}\n\n", .{ words[0], words[words.len - 1] });
// Six words of 8 bits each is a 48-bit passphrase.
var bytes: [6]u8 = undefined;
try out.print("{d} words, {d} bits:\n", .{ bytes.len, bytes.len * 8 });
// A fixed seed. Thus these three are the same on each run, and the page can
// check them. Never use a seeded generator for a real passphrase. A person
// with the seed gets the same words.
var prng: std.Random.Xoshiro256 = .init(2026);
for (0..3) |_| {
prng.random().bytes(&bytes);
try writePhrase(out, &bytes);
}
try out.flush();
// The real passphrase. `io.random` comes from the secure random source of
// the operating system. Thus this line is different each time. The line goes
// to stderr, because the check that runs this program compares stdout. This
// line can never match.
io.random(&bytes);
var err_buf: [256]u8 = undefined;
var stderr = Io.File.stderr().writerStreaming(io, &err_buf);
try stderr.interface.writeAll("\nyours, from the system's random source:\n");
try writePhrase(&stderr.interface, &bytes);
try stderr.interface.flush();
}The program ran in your browser. You did not download a words.txt. The words were inside the 51 KB of WebAssembly that the page fetched.
The three passphrases under “6 words, 48 bits” are the same each time. These passphrases come from a generator with a fixed seed. Thus the checks of this site can compare them each night.
The last passphrase, under “yours”, is different each time that you press Run. This passphrase comes from io.random. io.random reads from the secure random source of the operating system.
Never use a seeded generator for a real passphrase. If a person knows the seed, that person gets the same words.
Friday: one file for everyone
Vishaka built phrase for the three systems of the team.
$ zig build-exe -O ReleaseSmall -fstrip -target x86_64-linux-musl phrase.zig
$ zig build-exe -O ReleaseSmall -fstrip -target x86_64-windows phrase.zig
$ zig build-exe -O ReleaseSmall -fstrip -target aarch64-macos phrase.zig
| Target | Size |
|---|---|
| Linux, x86-64 | 153 KB |
| Windows, x86-64 | 442 KB |
| macOS, Apple silicon | 166 KB |
Each build is a single file, and each file contains the word list.
Tejas ran the new build from ~/Downloads.
~/Downloads $ ./phrase
256 words, 1582 bytes of words.txt, inside the program
Check it yourself
The strings command shows the readable text in a binary file. Use strings to see the words inside the program:
$ strings -n 3 phrase | grep -c -x -F -f words.txt
256
All 256 words are in the file.
The -n 3 option is necessary here. By default, strings skips text that is shorter than four characters, and the word fig has three characters.
What else to embed
@embedFile is good for a small file that the program must have. For example:
- A SQL schema or a list of migrations.
- An HTML template.
- A default config file.
- The text for
--help. - A test fixture.
@embedFile is not a good tool for a large file, because each byte of the file goes into the program.
These chapters give more detail about the parts:
- Imports. This chapter also shows
@embedFileand the type that it returns. - Comptime. This chapter shows how to run code inside the compiler.
- Cross-compilation. This chapter explains the Friday builds.
About the numbers
Vishaka and Tejas are not real. The error messages, the sizes and the 256-word list are real. Each of them came from the Zig version at the top of this post.
The 256-word list is short on purpose, to make the step from byte to word easy to see. Six words from the list give 48 bits. That is sufficient for a test account.
For a password that protects something important, use more words or a longer list. With the 7,776-word list of diceware, six words give about 77 bits.