Skip to content

Instantly share code, notes, and snippets.

@ikskuh
Created April 27, 2025 20:40
Show Gist options
  • Save ikskuh/45d5ac3e0c8f9a164be1897279737edd to your computer and use it in GitHub Desktop.
Save ikskuh/45d5ac3e0c8f9a164be1897279737edd to your computer and use it in GitHub Desktop.
Arbitrary Memory Location Tagger
const std = @import("std");
const Tag = extern struct {
addr: *const anyopaque,
value: [*:0]const u8,
};
pub inline fn export_metadata(comptime addr: *const anyopaque, comptime metadata: [:0]const u8) void
{
const T = struct {
const tag_ptr: *volatile const Tag = &tag;
const string: [metadata.len:0]u8 linksection(".microzig.strings") = metadata[0..metadata.len:0].*;
const tag: Tag linksection(".microzig.tags") = .{
.addr = addr,
.value = &string,
};
};
asm volatile(""::[ptr] "i" (&T.tag) : "memory");
}
export fn tagme() void {
export_metadata(tagme, "hello, world!");
}
export fn tagme2() void {
export_metadata(tagme2, "goodbye, cruella!");
}
const HilRequest = union(enum) {
set_pin_level: struct { pin: u32, value: enum { high, low } },
set_pin_dir: struct { pin: u32, dir: enum { out_high, out_low, in } },
assert_pin: struct { pin: u32, value: enum { high, low } },
};
fn HilRequester(comptime req: HilRequest) type {
return struct {
noinline fn request() void {
@breakpoint();
const string = comptime blk: {
var buffer: [1024]u8 = undefined;
var fbs = std.io.fixedBufferStream(&buffer);
std.json.stringify(req, .{}, fbs.writer()) catch unreachable;
fbs.writer().writeByte(0) catch unreachable;
const written = fbs.getWritten();
break :blk written[0..written.len-1:0].*;
};
export_metadata(request, &string);
}
};
}
pub inline fn hil_request(comptime req: HilRequest) void {
HilRequester(req).request();
}
extern fn set_dir(pin: u32, dir: enum(u8) { in ,out }) void;
extern fn set_pin(pin: u32, level: enum(u8) { low, high }) void;
export fn hil_demo() void {
hil_request(.{ .assert_pin = .{ .pin = 5, .value = .high } });
set_dir(5, .out);
set_pin(5, .low);
hil_request(.{ .assert_pin = .{ .pin = 5, .value = .low } });
set_pin(5, .high);
hil_request(.{ .assert_pin = .{ .pin = 5, .value = .high } });
set_pin(5, .low);
hil_request(.{ .assert_pin = .{ .pin = 5, .value = .low } });
set_dir(5, .out);
hil_request(.{ .assert_pin = .{ .pin = 5, .value = .high } });
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment