~retzkek/zlispc

669e987971bfa7bf7f5fff31f6a6f549706a46da — Kevin Retzke 1 year, 24 days ago master
part 1: execute bytecode demo
2 files changed, 53 insertions(+), 0 deletions(-)

A LICENSE
A first_jit.zig
A  => LICENSE +18 -0
@@ 1,18 @@
Copyright 2020 Kevin Retzke

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

A  => first_jit.zig +35 -0
@@ 1,35 @@
// Implementing the tiniest of JIT compilers in zig
// Following https://bernsteinbear.com/blog/compiling-a-lisp-1/
// 
// Copyright 2020 Kevin Retzke. See LICENSE

const std = @import("std");

const program = [_]u8{
    // mov eax, 42 (0x2a)
    0xb8, 0x2a, 0x00, 0x00, 0x00,
    // ret
    0xc3,
};

const kProgramLen = program.len;

const JitFunction = fn()u8;

pub fn main() u8 {
    // allocate program memory that is page-aligned and of page-aligned len
    const kProgramSize = (program.len/std.mem.page_size+1)*std.mem.page_size; 
    var memory: [kProgramSize]u8 align(std.mem.page_size) = undefined;
    std.log.info("allocated {} bytes program memory", .{kProgramSize});
    // copy program
    std.mem.copy(u8, memory[0..kProgramLen], program[0..kProgramLen]);
    // set executable
    std.os.mprotect(&memory, std.os.PROT_EXEC) catch |err| {
        std.log.err("unable to make memory executable {}", .{err});
        return 1;
    };
    // cast to function
    var function: JitFunction = @ptrCast(JitFunction, &memory);
    // run it
    return function();
}