init
This commit is contained in:
commit
85f4931a63
3
.gitignore
vendored
Normal file
3
.gitignore
vendored
Normal file
@ -0,0 +1,3 @@
|
||||
zig-out
|
||||
.zig-cache
|
||||
.idea
|
5
LICENSE
Normal file
5
LICENSE
Normal file
@ -0,0 +1,5 @@
|
||||
Copyright 2023 Evan Burkey <evan@burkey.co>
|
||||
|
||||
Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
|
7
README.md
Normal file
7
README.md
Normal file
@ -0,0 +1,7 @@
|
||||
# Synacor Challenge
|
||||
|
||||
Solution to the Synacor challenge using Zig
|
||||
|
||||
## Checking Solutions
|
||||
|
||||
The `checker` binary takes a solution code from the project as an argument and verifies it against known checksums of correct answers. It only works with the supplied binary `challenge.bin`
|
79
arch-spec
Executable file
79
arch-spec
Executable file
@ -0,0 +1,79 @@
|
||||
== Synacor OSCON 2012 Challenge ==
|
||||
In this challenge, your job is to use this architecture spec to create a
|
||||
virtual machine capable of running the included binary. Along the way,
|
||||
you will find codes; submit these to the challenge website to track
|
||||
your progress. Good luck!
|
||||
|
||||
|
||||
== architecture ==
|
||||
- three storage regions
|
||||
- memory with 15-bit address space storing 16-bit values
|
||||
- eight registers
|
||||
- an unbounded stack which holds individual 16-bit values
|
||||
- all numbers are unsigned integers 0..32767 (15-bit)
|
||||
- all math is modulo 32768; 32758 + 15 => 5
|
||||
|
||||
== binary format ==
|
||||
- each number is stored as a 16-bit little-endian pair (low byte, high byte)
|
||||
- numbers 0..32767 mean a literal value
|
||||
- numbers 32768..32775 instead mean registers 0..7
|
||||
- numbers 32776..65535 are invalid
|
||||
- programs are loaded into memory starting at address 0
|
||||
- address 0 is the first 16-bit value, address 1 is the second 16-bit value, etc
|
||||
|
||||
== execution ==
|
||||
- After an operation is executed, the next instruction to read is immediately after the last argument of the current operation. If a jump was performed, the next operation is instead the exact destination of the jump.
|
||||
- Encountering a register as an operation argument should be taken as reading from the register or setting into the register as appropriate.
|
||||
|
||||
== hints ==
|
||||
- Start with operations 0, 19, and 21.
|
||||
- Here's a code for the challenge website: LDOb7UGhTi
|
||||
- The program "9,32768,32769,4,19,32768" occupies six memory addresses and should:
|
||||
- Store into register 0 the sum of 4 and the value contained in register 1.
|
||||
- Output to the terminal the character with the ascii code contained in register 0.
|
||||
|
||||
== opcode listing ==
|
||||
halt: 0
|
||||
stop execution and terminate the program
|
||||
set: 1 a b
|
||||
set register <a> to the value of <b>
|
||||
push: 2 a
|
||||
push <a> onto the stack
|
||||
pop: 3 a
|
||||
remove the top element from the stack and write it into <a>; empty stack = error
|
||||
eq: 4 a b c
|
||||
set <a> to 1 if <b> is equal to <c>; set it to 0 otherwise
|
||||
gt: 5 a b c
|
||||
set <a> to 1 if <b> is greater than <c>; set it to 0 otherwise
|
||||
jmp: 6 a
|
||||
jump to <a>
|
||||
jt: 7 a b
|
||||
if <a> is nonzero, jump to <b>
|
||||
jf: 8 a b
|
||||
if <a> is zero, jump to <b>
|
||||
add: 9 a b c
|
||||
assign into <a> the sum of <b> and <c> (modulo 32768)
|
||||
mult: 10 a b c
|
||||
store into <a> the product of <b> and <c> (modulo 32768)
|
||||
mod: 11 a b c
|
||||
store into <a> the remainder of <b> divided by <c>
|
||||
and: 12 a b c
|
||||
stores into <a> the bitwise and of <b> and <c>
|
||||
or: 13 a b c
|
||||
stores into <a> the bitwise or of <b> and <c>
|
||||
not: 14 a b
|
||||
stores 15-bit bitwise inverse of <b> in <a>
|
||||
rmem: 15 a b
|
||||
read memory at address <b> and write it to <a>
|
||||
wmem: 16 a b
|
||||
write the value from <b> into memory at address <a>
|
||||
call: 17 a
|
||||
write the address of the next instruction to the stack and jump to <a>
|
||||
ret: 18
|
||||
remove the top element from the stack and jump to it; empty stack = halt
|
||||
out: 19 a
|
||||
write the character represented by ascii code <a> to the terminal
|
||||
in: 20 a
|
||||
read a character from the terminal and write its ascii code to <a>; it can be assumed that once input starts, it will continue until a newline is encountered; this means that you can safely read whole lines from the keyboard instead of having to figure out how to read individual characters
|
||||
noop: 21
|
||||
no operation
|
24
build.zig
Normal file
24
build.zig
Normal file
@ -0,0 +1,24 @@
|
||||
const std = @import("std");
|
||||
|
||||
// Although this function looks imperative, note that its job is to
|
||||
// declaratively construct a build graph that will be executed by an external
|
||||
// runner.
|
||||
pub fn build(b: *std.Build) void {
|
||||
const target = b.standardTargetOptions(.{});
|
||||
const optimize = b.standardOptimizeOption(.{});
|
||||
const zynacor = b.addExecutable(.{
|
||||
.name = "zynacor",
|
||||
.root_source_file = b.path("src/main.zig"),
|
||||
.target = target,
|
||||
.optimize = optimize,
|
||||
});
|
||||
const checker = b.addExecutable(.{
|
||||
.name = "checker",
|
||||
.root_source_file = b.path("src/checker.zig"),
|
||||
.target = target,
|
||||
.optimize = optimize,
|
||||
});
|
||||
|
||||
b.installArtifact(zynacor);
|
||||
b.installArtifact(checker);
|
||||
}
|
67
build.zig.zon
Normal file
67
build.zig.zon
Normal file
@ -0,0 +1,67 @@
|
||||
.{
|
||||
.name = "zynacor",
|
||||
// This is a [Semantic Version](https://semver.org/).
|
||||
// In a future version of Zig it will be used for package deduplication.
|
||||
.version = "0.0.0",
|
||||
|
||||
// This field is optional.
|
||||
// This is currently advisory only; Zig does not yet do anything
|
||||
// with this value.
|
||||
//.minimum_zig_version = "0.11.0",
|
||||
|
||||
// This field is optional.
|
||||
// Each dependency must either provide a `url` and `hash`, or a `path`.
|
||||
// `zig build --fetch` can be used to fetch all dependencies of a package, recursively.
|
||||
// Once all dependencies are fetched, `zig build` no longer requires
|
||||
// internet connectivity.
|
||||
.dependencies = .{
|
||||
// See `zig fetch --save <url>` for a command-line interface for adding dependencies.
|
||||
//.example = .{
|
||||
// // When updating this field to a new URL, be sure to delete the corresponding
|
||||
// // `hash`, otherwise you are communicating that you expect to find the old hash at
|
||||
// // the new URL.
|
||||
// .url = "https://example.com/foo.tar.gz",
|
||||
//
|
||||
// // This is computed from the file contents of the directory of files that is
|
||||
// // obtained after fetching `url` and applying the inclusion rules given by
|
||||
// // `paths`.
|
||||
// //
|
||||
// // This field is the source of truth; packages do not come from a `url`; they
|
||||
// // come from a `hash`. `url` is just one of many possible mirrors for how to
|
||||
// // obtain a package matching this `hash`.
|
||||
// //
|
||||
// // Uses the [multihash](https://multiformats.io/multihash/) format.
|
||||
// .hash = "...",
|
||||
//
|
||||
// // When this is provided, the package is found in a directory relative to the
|
||||
// // build root. In this case the package's hash is irrelevant and therefore not
|
||||
// // computed. This field and `url` are mutually exclusive.
|
||||
// .path = "foo",
|
||||
|
||||
// // When this is set to `true`, a package is declared to be lazily
|
||||
// // fetched. This makes the dependency only get fetched if it is
|
||||
// // actually used.
|
||||
// .lazy = false,
|
||||
//},
|
||||
},
|
||||
|
||||
// Specifies the set of files and directories that are included in this package.
|
||||
// Only files and directories listed here are included in the `hash` that
|
||||
// is computed for this package.
|
||||
// Paths are relative to the build root. Use the empty string (`""`) to refer to
|
||||
// the build root itself.
|
||||
// A directory listed here means that all files within, recursively, are included.
|
||||
.paths = .{
|
||||
// This makes *all* files, recursively, included in this package. It is generally
|
||||
// better to explicitly list the files and directories instead, to insure that
|
||||
// fetching from tarballs, file system paths, and version control all result
|
||||
// in the same contents hash.
|
||||
"",
|
||||
// For example...
|
||||
//"build.zig",
|
||||
//"build.zig.zon",
|
||||
//"src",
|
||||
//"LICENSE",
|
||||
//"README.md",
|
||||
},
|
||||
}
|
BIN
challenge.bin
Normal file
BIN
challenge.bin
Normal file
Binary file not shown.
54
src/checker.zig
Normal file
54
src/checker.zig
Normal file
@ -0,0 +1,54 @@
|
||||
const std = @import("std");
|
||||
|
||||
const sums: [8][]const u8 = .{
|
||||
"76ec2408e8fe3f1753c25db51efd8eb3",
|
||||
"0e6aa7be1f68d930926d72b3741a145c",
|
||||
"7997a3b2941eab92c1c0345d5747b420",
|
||||
"186f842951c0dcfe8838af1e7222b7d4",
|
||||
"2bf84e54b95ce97aefd9fc920451fc45",
|
||||
"e09640936b3ef532b7b8e83ce8f125f4",
|
||||
"4873cf6b76f62ac7d5a53605b2535a0c",
|
||||
"d0c54d4ed7f943280ce3e19532dbb1a6"
|
||||
};
|
||||
|
||||
pub fn main() !void {
|
||||
var gpa = std.heap.GeneralPurposeAllocator(.{}).init;
|
||||
const allocator = gpa.allocator();
|
||||
var args = try std.process.argsWithAllocator(allocator);
|
||||
defer args.deinit();
|
||||
|
||||
var input: []const u8 = undefined;
|
||||
|
||||
// Skip arg[0]
|
||||
_ = args.skip();
|
||||
|
||||
const argVal = args.next();
|
||||
if (argVal) |a| {
|
||||
input = a;
|
||||
} else {
|
||||
std.debug.print("USAGE: checker ANSWER\n", .{});
|
||||
std.process.exit(1);
|
||||
}
|
||||
|
||||
var hasher = std.crypto.hash.Md5.init(.{});
|
||||
var buf: [std.crypto.hash.Md5.digest_length]u8 = undefined;
|
||||
hasher.update(input);
|
||||
hasher.final(buf[0..]);
|
||||
const digest = try std.fmt.allocPrint(allocator, "{x}", .{std.fmt.fmtSliceHexLower(&buf)});
|
||||
|
||||
var matched = false;
|
||||
for (sums, 0..) |sum, i| {
|
||||
if (std.mem.eql(u8, digest, sum)) {
|
||||
std.debug.print("CORRECT! {s} matches sum #{d}: {s}\n", .{input, i, sum});
|
||||
matched = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (!matched) {
|
||||
std.debug.print("FAILURE! {s} matches no sums\n", .{input});
|
||||
}
|
||||
|
||||
allocator.free(digest);
|
||||
}
|
||||
|
7
src/main.zig
Normal file
7
src/main.zig
Normal file
@ -0,0 +1,7 @@
|
||||
const vm = @import("vm.zig");
|
||||
|
||||
pub fn main() !void {
|
||||
var v = try vm.init();
|
||||
try v.run();
|
||||
}
|
||||
|
235
src/vm.zig
Normal file
235
src/vm.zig
Normal file
@ -0,0 +1,235 @@
|
||||
const std = @import("std");
|
||||
|
||||
const maxMemory = 0x8000;
|
||||
const regSize = 8;
|
||||
const maxStackSize= 32;
|
||||
const regStart = 32768;
|
||||
const regEnd = 32775;
|
||||
|
||||
const VmState = enum {
|
||||
Reset,
|
||||
Running,
|
||||
Paused,
|
||||
Halted,
|
||||
Error,
|
||||
AwaitingInput,
|
||||
};
|
||||
|
||||
const VmError = error {
|
||||
PoppedEmptyStack,
|
||||
PushedMaxStack,
|
||||
InvalidAddress,
|
||||
InvalidRegValue,
|
||||
Unknown,
|
||||
};
|
||||
|
||||
pub const Vm = struct {
|
||||
mem: [maxMemory]u16,
|
||||
reg: [regSize]u16,
|
||||
pc: u16,
|
||||
|
||||
stack: [maxStackSize]u16,
|
||||
stackSize: usize,
|
||||
|
||||
inputBuffer: std.ArrayList(u8),
|
||||
|
||||
allocator: std.mem.Allocator,
|
||||
state: VmState,
|
||||
|
||||
const outWriter = std.io.getStdOut().writer();
|
||||
const inReader = std.io.getStdIn().reader();
|
||||
|
||||
fn pop(self: *Vm) VmError!u16 {
|
||||
if (self.stackSize == 0) {
|
||||
return VmError.PoppedEmptyStack;
|
||||
}
|
||||
const v = self.stack[self.stackSize - 1];
|
||||
self.stackSize -= 1;
|
||||
return v;
|
||||
}
|
||||
|
||||
fn push(self: *Vm, v: u16) !void {
|
||||
if (self.stackSize == maxStackSize) {
|
||||
return VmError.PushedMaxStack;
|
||||
}
|
||||
self.stack[self.stackSize] = v;
|
||||
self.stackSize += 1;
|
||||
}
|
||||
|
||||
fn getVal(self: *Vm, o: u16) !u16 {
|
||||
const val = self.mem[self.pc + o];
|
||||
if (val < regStart) {
|
||||
return val;
|
||||
} else if (val <= regEnd) {
|
||||
return self.reg[val - regStart];
|
||||
}
|
||||
return VmError.InvalidAddress;
|
||||
}
|
||||
|
||||
fn getReg(self: *Vm, o: u16) !*u16 {
|
||||
const val = self.mem[self.pc + o];
|
||||
if (val < regStart or val > regEnd) {
|
||||
return VmError.InvalidRegValue;
|
||||
}
|
||||
return &self.reg[val - regStart];
|
||||
}
|
||||
|
||||
pub fn run(self: *Vm) !void {
|
||||
self.state = VmState.Running;
|
||||
while (self.state == VmState.Running) {
|
||||
switch (self.mem[self.pc]) {
|
||||
// halt: 0
|
||||
0 => self.state = VmState.Halted,
|
||||
// set: 1 a b
|
||||
1 => {
|
||||
const r = try self.getReg(1);
|
||||
r.* = try self.getVal(2);
|
||||
self.pc += 3;
|
||||
},
|
||||
// push: 2 a
|
||||
2 => {
|
||||
try self.push(try self.getVal(1));
|
||||
self.pc += 2;
|
||||
},
|
||||
// pop: 3 a
|
||||
3 => {
|
||||
const r = try self.getReg(1);
|
||||
r.* = try self.pop();
|
||||
self.pc += 2;
|
||||
},
|
||||
// eq: 4 a b c
|
||||
4 => {
|
||||
const r = try self.getReg(1);
|
||||
r.* = if (try self.getVal(2) == try self.getVal(3)) 1 else 0;
|
||||
self.pc += 4;
|
||||
},
|
||||
// gt: 5 a b c
|
||||
5 => {
|
||||
const r = try self.getReg(1);
|
||||
r.* = if (try self.getVal(2) > try self.getVal(3)) 1 else 0;
|
||||
self.pc += 4;
|
||||
},
|
||||
// jmp: 6 a
|
||||
6 => self.pc = self.mem[self.pc + 1],
|
||||
// jt: 7 a b
|
||||
7 => self.pc = if (try self.getVal(1) != 0) try self.getVal(2) else self.pc + 3,
|
||||
// jf: 8 a b
|
||||
8 => self.pc = if (try self.getVal(1) == 0) try self.getVal(2) else self.pc + 3,
|
||||
// add: 9 a b c
|
||||
9 => {
|
||||
const r = try self.getReg(1);
|
||||
r.* = (try self.getVal(2) +% try self.getVal(3)) % regStart;
|
||||
self.pc += 4;
|
||||
},
|
||||
// mult: 10 a b c
|
||||
10 => {
|
||||
const r = try self.getReg(1);
|
||||
r.* = (try self.getVal(2) *% try self.getVal(3)) % regStart;
|
||||
self.pc += 4;
|
||||
},
|
||||
// mod: 11 a b c
|
||||
11 => {
|
||||
const r = try self.getReg(1);
|
||||
r.* = (try self.getVal(2) % try self.getVal(3));
|
||||
self.pc += 4;
|
||||
},
|
||||
// and: 12 a b c
|
||||
12 => {
|
||||
const r = try self.getReg(1);
|
||||
r.* = (try self.getVal(2) & try self.getVal(3));
|
||||
self.pc += 4;
|
||||
},
|
||||
// or: 13 a b c
|
||||
13 => {
|
||||
const r = try self.getReg(1);
|
||||
r.* = (try self.getVal(2) | try self.getVal(3));
|
||||
self.pc += 4;
|
||||
},
|
||||
// not: 14 a b
|
||||
14 => {
|
||||
const r = try self.getReg(1);
|
||||
r.* = ~(try self.getVal(2)) & 0x7FFF;
|
||||
self.pc += 3;
|
||||
},
|
||||
// rmem: 15 a b
|
||||
15 => {
|
||||
const r = try self.getReg(1);
|
||||
const b: usize = @intCast(try self.getVal(2));
|
||||
r.* = self.mem[b];
|
||||
self.pc += 3;
|
||||
},
|
||||
// wmem: 16 a b
|
||||
16 => {
|
||||
self.mem[try self.getVal(1)] = try self.getVal(2);
|
||||
self.pc += 3;
|
||||
},
|
||||
// call: 17 a
|
||||
17 => {
|
||||
try self.push(self.pc + 2);
|
||||
self.pc = try self.getVal(1);
|
||||
},
|
||||
// ret: 18
|
||||
18 => self.pc = try self.pop(),
|
||||
// out: 19 a
|
||||
19 => {
|
||||
const a: u8 = @intCast(try self.getVal(1));
|
||||
try outWriter.print("{c}", .{a});
|
||||
self.pc += 2;
|
||||
},
|
||||
// in: 20 a
|
||||
20 => {
|
||||
if (self.inputBuffer.items.len == 0) {
|
||||
self.inputBuffer = std.ArrayList(u8).init(self.allocator);
|
||||
try inReader.streamUntilDelimiter(self.inputBuffer.writer(), '\n', null);
|
||||
try self.inputBuffer.append('\n');
|
||||
}
|
||||
const r = try self.getReg(1);
|
||||
r.* = self.inputBuffer.items[0];
|
||||
_ = self.inputBuffer.orderedRemove(0);
|
||||
if (self.inputBuffer.items.len == 0) {
|
||||
self.inputBuffer.deinit();
|
||||
}
|
||||
self.pc += 2;
|
||||
},
|
||||
// noop: 21
|
||||
21 => self.pc += 1,
|
||||
else => {
|
||||
try outWriter.print("Unknown opcode {d}\n", .{self.mem[self.pc]});
|
||||
self.state = VmState.Error;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
pub fn init() !Vm {
|
||||
var vm = Vm {
|
||||
.mem = [_]u16{0} ** maxMemory,
|
||||
.reg = [_]u16{0} ** regSize,
|
||||
.pc = 0,
|
||||
.stack = [_]u16{0} ** maxStackSize,
|
||||
.stackSize = 0,
|
||||
.allocator = std.heap.GeneralPurposeAllocator(.{}).init.backing_allocator,
|
||||
.state = VmState.Reset,
|
||||
.inputBuffer = undefined,
|
||||
};
|
||||
|
||||
const cwd = std.fs.cwd();
|
||||
const fp = try cwd.openFile("challenge.bin", .{});
|
||||
defer fp.close();
|
||||
|
||||
const sz = (try fp.stat()).size;
|
||||
const buf = try fp.readToEndAlloc(vm.allocator, sz);
|
||||
defer vm.allocator.free(buf);
|
||||
|
||||
var i: usize = 0;
|
||||
var j: usize = 0;
|
||||
while (i < sz) : (i += 2) {
|
||||
const a: u16 = @intCast(buf[i]);
|
||||
const b: u16 = @intCast(buf[i+1]);
|
||||
vm.mem[j] = a | (b << 8);
|
||||
j += 1;
|
||||
}
|
||||
|
||||
return vm;
|
||||
}
|
Loading…
x
Reference in New Issue
Block a user