Skip to content

Commit

Permalink
Merge pull request #64 from orca-app/rjd/bytebox-integration
Browse files Browse the repository at this point in the history
Bytebox wasm backend
  • Loading branch information
martinfouilleul authored May 8, 2024
2 parents 2160c7f + abe25b5 commit eb06208
Show file tree
Hide file tree
Showing 36 changed files with 20,755 additions and 97 deletions.
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,8 @@ src/orca_surface.c
src/graphics/orca_gl31.h
*bind_gen.c
*_stubs.c
src/ext/bytebox/zig-cache
src/ext/bytebox/zig-out

.vscode/launch.json
.vscode/settings.json
Expand Down
96 changes: 77 additions & 19 deletions scripts/dev.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ def attach_dev_commands(subparsers):
build_cmd = subparsers.add_parser("build", help="Build Orca from source.")
build_cmd.add_argument("--version", help="embed a version string in the Orca CLI tool (default is git commit hash)")
build_cmd.add_argument("--release", action="store_true", help="compile in release mode (default is debug)")
build_cmd.add_argument("--wasm-backend", help="specify a wasm backend. Options: wasm3 (default), bytebox")
build_cmd.set_defaults(func=dev_shellish(build_all))

platform_layer_cmd = subparsers.add_parser("build-platform-layer", help="Build the Orca platform layer from source.")
Expand All @@ -45,6 +46,7 @@ def attach_dev_commands(subparsers):

runtime_cmd = subparsers.add_parser("build-runtime", help="Build the Orca runtime from source.")
runtime_cmd.add_argument("--release", action="store_true", help="compile in release mode (default is debug)")
runtime_cmd.add_argument("--wasm-backend", help="specify a wasm backend. Options: wasm3 (default), bytebox")
runtime_cmd.set_defaults(func=dev_shellish(build_runtime))

libc_cmd = subparsers.add_parser("build-orca-libc", help="Build the Orca libC from source.")
Expand Down Expand Up @@ -84,7 +86,7 @@ def func_from_source(args):
def build_all(args):
ensure_programs()

build_runtime_internal(args.release) # this also builds the platform layer
build_runtime_internal(args.release, args.wasm_backend) # this also builds the platform layer
build_libc_internal(args.release)
build_sdk_internal(args.release)
build_tool(args)
Expand Down Expand Up @@ -563,28 +565,46 @@ def build_wasm3_lib_mac(release):
subprocess.run(["libtool", "-static", "-o", "build/lib/libwasm3.a", "-no_warning_for_no_symbols", *glob.glob("build/obj/*.o")], check=True)
subprocess.run(["rm", "-rf", "build/obj"], check=True)

def build_bytebox(release):
print("Building bytebox...")
args = ["zig", "build", "-Doptimize=ReleaseFast"]
subprocess.run(args, cwd="src/ext/bytebox/")

if platform.system() == "Windows":
shutil.copy("src/ext/bytebox/zig-out/lib/bytebox.lib", "build/bin")
elif platform.system() == "Darwin":
shutil.copy("src/ext/bytebox/zig-out/lib/libbytebox.a", "build/bin")
else:
log_error(f"can't build bytebox for unknown platform '{platform.system()}'")
exit(1)


def build_runtime(args):
ensure_programs()
build_runtime_internal(args.release)
build_runtime_internal(args.release, args.wasm_backend)

def build_runtime_internal(release):
def build_runtime_internal(release, wasm_backend):
build_platform_layer_internal(release)
build_wasm3(release)

if wasm_backend == "bytebox":
build_bytebox(release)
else:
build_wasm3(release)

print("Building Orca runtime...")

os.makedirs("build/bin", exist_ok=True)
os.makedirs("build/lib", exist_ok=True)

if platform.system() == "Windows":
build_runtime_win(release)
build_runtime_win(release, wasm_backend)
elif platform.system() == "Darwin":
build_runtime_mac(release)
build_runtime_mac(release, wasm_backend)
else:
log_error(f"can't build Orca for unknown platform '{platform.system()}'")
exit(1)

def build_runtime_win(release):
def build_runtime_win(release, wasm_backend):

gen_all_bindings()

Expand All @@ -593,28 +613,61 @@ def build_runtime_win(release):
"/I", "src",
"/I", "src/ext",
"/I", "src/ext/angle/include",
"/I", "src/ext/wasm3/source",
]

subprocess.run([
defines = []
link_commands = ["build/bin/orca.dll.lib"]

if wasm_backend == "bytebox":
includes += ["/I", "src/ext/bytebox/zig-out/include"]
defines += ["/DOC_WASM_BACKEND_WASM3=0", "/DOC_WASM_BACKEND_BYTEBOX=1"]

# Bytebox uses zig libraries that depend on NTDLL on Windows. Additionally, some zig APIs expect there to be
# a large stack to use for scratch space, as zig stacks are 8MB by default. When linking bytebox, we must
# ensure we provide the same amount of stack space, else risk stack overflows.
link_commands += ["build/bin/bytebox.lib", "ntdll.lib", "/STACK:8388608,8388608"]
else:
includes += ["/I", "src/ext/wasm3/source"]
defines += ["/DOC_WASM_BACKEND_WASM3=1", "/DOC_WASM_BACKEND_BYTEBOX=0"]
link_commands += ["build/bin/wasm3.lib"]

compile_args=[
"cl",
"/c",
"/Zi", "/Zc:preprocessor",
"/std:c11", "/experimental:c11atomics",
*defines,
*includes,
"src/runtime.c",
"/Fo:build/bin/runtime.obj",
], check=True)
"/Fe:build/bin/orca_runtime.exe",
"/link",
*link_commands
]

backend_deps = "ntdll.lib ";

def build_runtime_mac(release):
subprocess.run(compile_args, check=True)

def build_runtime_mac(release, wasm_backend):

includes = [
"-Isrc",
"-Isrc/ext",
"-Isrc/ext/angle/include",
"-Isrc/ext/wasm3/source"
]
libs = ["-Lbuild/bin", "-Lbuild/lib", "-lorca", "-lwasm3"]

defines = []

libs = ["-Lbuild/bin", "-Lbuild/lib", "-lorca"]

if wasm_backend == "bytebox":
includes += ["-Isrc/ext/bytebox/zig-out/include"]
defines += ["-DOC_WASM_BACKEND_WASM3=0", "-DOC_WASM_BACKEND_BYTEBOX=1"]
libs += ["-lbytebox"]
else:
includes += ["-Isrc/ext/wasm3/source"]
defines += ["-DOC_WASM_BACKEND_WASM3=1", "-DOC_WASM_BACKEND_BYTEBOX=0"]
libs += ["-lwasm3"]

debug_flags = ["-O2"] if release else ["-g", "-DOC_DEBUG -DOC_LOG_COMPILE_DEBUG"]
flags = [
*debug_flags,
Expand All @@ -625,7 +678,7 @@ def build_runtime_mac(release):

# compile orca
subprocess.run([
"clang", *flags, *includes, *libs,
"clang", *flags, *defines, *includes, *libs,
"-o", "build/bin/orca_runtime",
"src/runtime.c",
], check=True)
Expand Down Expand Up @@ -775,6 +828,10 @@ def build_platform_layer_lib_win(release):
"/IMPLIB:build/bin/orca.dll.lib",
], check=True)

build_dir = os.path.join("build", "bin")
# ensure orca.exe debug pdb doesn't override orca.dll pdb
shutil.copy(os.path.join(build_dir, "orca.pdb"), os.path.join(build_dir, "orca_dll.pdb"))

def build_platform_layer_lib_mac(release):

embed_text_files("src/graphics/wgpu_renderer_shaders.h", "oc_wgsl_", [
Expand Down Expand Up @@ -1117,6 +1174,7 @@ def build_tool_win(release, version):
"shlwapi.lib",
"shell32.lib",
"ole32.lib",
"Kernel32.lib",

# libs needed by curl
"advapi32.lib",
Expand Down Expand Up @@ -1173,6 +1231,7 @@ def build_tool_mac(release, version):

"-Lsrc/ext/zlib/build", "-lz",
]

subprocess.run([
"clang",
f"-mmacos-version-min={MACOS_VERSION_MIN}",
Expand Down Expand Up @@ -1237,9 +1296,7 @@ def package_sdk_internal(dest, target):
if target == "Windows":
shutil.copy(os.path.join("build", "bin", "orca.exe"), bin_dir)
shutil.copy(os.path.join("build", "bin", "orca.dll"), bin_dir)
shutil.copy(os.path.join("build", "bin", "orca.dll.lib"), bin_dir)
shutil.copy(os.path.join("build", "bin", "wasm3.lib"), bin_dir)
shutil.copy(os.path.join("build", "bin", "runtime.obj"), bin_dir)
shutil.copy(os.path.join("build", "bin", "orca_runtime.exe"), bin_dir)
shutil.copy(os.path.join("build", "bin", "liborca_wasm.a"), bin_dir)
shutil.copy(os.path.join("build", "bin", "libEGL.dll"), bin_dir)
shutil.copy(os.path.join("build", "bin", "libGLESv2.dll"), bin_dir)
Expand All @@ -1253,6 +1310,7 @@ def package_sdk_internal(dest, target):
shutil.copy(os.path.join("build", "bin", "libGLESv2.dylib"), bin_dir)
shutil.copy(os.path.join("build", "bin", "libwebgpu.dylib"), bin_dir)


shutil.copytree(os.path.join("build", "orca-libc"), libc_dir, dirs_exist_ok=True)
shutil.copytree("resources", res_dir, dirs_exist_ok=True)

Expand Down
21 changes: 21 additions & 0 deletions src/ext/bytebox/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2022 Reuben Dunnington

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.
65 changes: 65 additions & 0 deletions src/ext/bytebox/bench/main.zig
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
const std = @import("std");
const bytebox = @import("bytebox");
const Val = bytebox.Val;
const Timer = std.time.Timer;

const Benchmark = struct {
name: []const u8,
filename: []const u8,
param: i32,
};

fn elapsedMilliseconds(timer: *std.time.Timer) f64 {
var ns_elapsed: f64 = @as(f64, @floatFromInt(timer.read()));
const ms_elapsed = ns_elapsed / 1000000.0;
return ms_elapsed;
}

fn run(allocator: std.mem.Allocator, benchmark: Benchmark) !void {
var cwd = std.fs.cwd();
var wasm_data: []u8 = try cwd.readFileAlloc(allocator, benchmark.filename, 1024 * 64); // Our wasm programs aren't very large

var timer = try Timer.start();

var module_def = try bytebox.createModuleDefinition(allocator, .{});
defer module_def.destroy();
try module_def.decode(wasm_data);

var module_instance = try bytebox.createModuleInstance(.Stack, module_def, allocator);
defer module_instance.destroy();
try module_instance.instantiate(.{});

const handle = try module_instance.getFunctionHandle("run");
var input = [1]Val{.{ .I32 = benchmark.param }};
var output = [1]Val{.{ .I32 = 0 }};
try module_instance.invoke(handle, &input, &output, .{});

const ms_elapsed: f64 = elapsedMilliseconds(&timer);
std.log.info("{s} decode+instantiate+run took {d}ms\n", .{ benchmark.name, ms_elapsed });
}

pub fn main() !void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
var allocator: std.mem.Allocator = gpa.allocator();

const benchmarks = [_]Benchmark{ .{
.name = "add-one",
.filename = "zig-out/lib/add-one.wasm",
.param = 123456789,
}, .{
.name = "fibonacci",
.filename = "zig-out/lib/fibonacci.wasm",
.param = 20,
}, .{
.name = "mandelbrot",
.filename = "zig-out/lib/mandelbrot.wasm",
.param = 20,
} };

for (benchmarks) |benchmark| {
run(allocator, benchmark) catch |e| {
std.log.err("{s} 'run' invocation failed with error: {}\n", .{ benchmark.name, e });
return e;
};
}
}
3 changes: 3 additions & 0 deletions src/ext/bytebox/bench/samples/add-one.zig
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export fn run(n: i32) i32 {
return n + 1;
}
9 changes: 9 additions & 0 deletions src/ext/bytebox/bench/samples/fibonacci.zig
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
export fn run(n: i32) i32 {
if (n < 2) {
return 1;
} else {
var a = run(n - 1);
var b = run(n - 2);
return a + b;
}
}
44 changes: 44 additions & 0 deletions src/ext/bytebox/bench/samples/mandelbrot.zig
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
const std = @import("std");
const complex = std.math.complex;
const Complex = complex.Complex(f32);

const Color = struct {
R: u8,
G: u8,
B: u8,
};

const COLOR_BLACK = Color{ .R = 0, .G = 0, .B = 0 };
const COLOR_WHITE = Color{ .R = 255, .G = 255, .B = 255 };

const WIDTH = 256;
const HEIGHT = 256;

var pixels = [_]Color{.{ .R = 0, .G = 0, .B = 0 }} ** (WIDTH * HEIGHT);

fn mandelbrot(c: Complex, max_counter: i32) Color {
var counter: u32 = 0;
var z = Complex.init(0, 0);
while (counter < max_counter) : (counter += 1) {
z = z.mul(z).add(c);
if (2.0 <= complex.abs(z)) {
return COLOR_WHITE;
}
}

return COLOR_BLACK;
}

export fn run(max_counter: i32) i32 {
var y: u32 = 0;
while (y < HEIGHT) : (y += 1) {
var x: u32 = 0;
while (x < WIDTH) : (x += 1) {
const c = Complex.init(@as(f32, @floatFromInt(x)), @as(f32, @floatFromInt(y)));
const color: Color = mandelbrot(c, max_counter);
pixels[y * HEIGHT + x] = color;
}
}

return 0;
}
Loading

0 comments on commit eb06208

Please sign in to comment.