Compare commits

...

3 Commits

Author SHA1 Message Date
94bf91d9b9 add injection targets 2026-03-12 01:42:34 +01:00
355c3f6024 add build + fail recipes 2026-03-12 01:42:25 +01:00
a21ddb9ae9 add wasi/wamr dependencies 2026-03-12 01:41:43 +01:00
15 changed files with 3505 additions and 24 deletions

1
.gitignore vendored Normal file
View File

@ -0,0 +1 @@
/build-*

5
db.conf Normal file
View File

@ -0,0 +1,5 @@
[client]
host=127.0.0.1
user=fail
password=fail
database=fail

11
docker-compose.yaml Normal file
View File

@ -0,0 +1,11 @@
services:
fail-db:
image: mysql
container_name: fail-db
environment:
MYSQL_ROOT_PASSWORD: fail
MYSQL_USER: fail
MYSQL_PASSWORD: fail
MYSQL_DATABASE: fail
ports:
- "3306:3306"

254
flake.nix
View File

@ -22,7 +22,19 @@ rec {
overlays = [];
};
boost174_pkgs =
i386_pkgs = import nixpkgs {
inherit system;
config.allowUnfree = true;
overlays = [];
# Build crosscompiler
crossSystem = {
config = "i386-elf";
libc = "newlib";
};
};
boost_pkgs =
import (builtins.fetchTarball {
url = "https://github.com/NixOS/nixpkgs/archive/824421b1796332ad1bcb35bc7855da832c43305f.tar.gz";
sha256 = "sha256:1w6cjnakz1yi66rs8c6nmhymsr7bj82vs2hz200ipi1sfiq8dy4y";
@ -30,6 +42,14 @@ rec {
inherit system;
};
libdwarf_pkgs =
import (builtins.fetchTarball {
url = "https://github.com/NixOS/nixpkgs/archive/a054d7450768069084142fe597ed2da367813a4a.tar.gz";
sha256 = "sha256:1wlbz6glkzrl3y7pprw1v4sgkwwzi26qlxqfjzxghdlnny91l3cj";
}) {
inherit system;
};
inherit (pkgs) lib stdenv;
# =========================================================================================
@ -82,9 +102,6 @@ rec {
# Determine the project root, used e.g. in cmake scripts
set -g -x FLAKE_PROJECT_ROOT (git rev-parse --show-toplevel)
# Rust Bevy:
# abbr -a build-release-windows "CARGO_FEATURE_PURE=1 cargo xwin build --release --target x86_64-pc-windows-msvc"
# C/C++:
# abbr -a cmake-debug "${cmakeDebug}"
# abbr -a cmake-release "${cmakeRelease}"
@ -111,14 +128,12 @@ rec {
pyyaml
]);
boost174 = boost174_pkgs.boost174;
libpcl = stdenv.mkDerivation rec {
pname = "libpcl1";
version = "1.12-2";
src = pkgs.fetchurl {
url = "http://launchpadlibrarian.net/521269537/libpcl1_1.12-2_amd64.deb";
url = "http://launchpadlibrarian.net/521269537/${pname}_${version}_amd64.deb";
hash = "sha256-GL3mjPAccAtRMAJPnDMCHiDf6xNvGi4oUWylOIqBjP0=";
};
@ -131,9 +146,6 @@ rec {
installPhase = ''
runHook preInstall
ls -al
# dpkg-deb -x ${pname}_${version}_amd64.deb libpcl
mkdir -p $out/lib
cp -rv usr/lib/x86_64-linux-gnu/* $out/lib/
@ -141,6 +153,170 @@ rec {
'';
};
wasi-sdk = stdenv.mkDerivation rec {
pname = "wasi-sdk";
version = "29";
src = let
baseurl = "https://github.com/WebAssembly/wasi-sdk/releases/download";
in
builtins.fetchTarball {
url = "${baseurl}/${pname}-${version}/${pname}-${version}.0-x86_64-linux.tar.gz";
sha256 = "sha256:16afis71iqfvwiny4dz0lk9f7wbary0wa67ybwyhywr8g57ss6hq";
};
nativeBuildInputs = with pkgs; [
autoPatchelfHook
];
buildInputs = with pkgs; [
libgcc.lib
];
dontBuild = true;
installPhase = ''
runHook preInstall
mkdir -p $out
cp -rv ./* $out/
runHook postInstall
'';
};
iwasm = stdenv.mkDerivation rec {
pname = "iwasm";
version = "2.4.4";
src = let
baseurl = "https://github.com/bytecodealliance/wasm-micro-runtime/releases/download";
in
builtins.fetchTarball {
url = "${baseurl}/WAMR-${version}/${pname}-${version}-x86_64-ubuntu-22.04.tar.gz";
sha256 = "sha256:05irihz3yf7hpc0a59qz9i62imhrsni9xy9nxwsn6b8s92c1yzrp";
};
nativeBuildInputs = with pkgs; [
autoPatchelfHook
];
buildInputs = with pkgs; [
libz
zstd
libgcc.lib
];
dontBuild = true;
installPhase = ''
runHook preInstall
mkdir -p $out/bin
cp -rv ./* $out/bin/
runHook postInstall
'';
};
wamrc = stdenv.mkDerivation rec {
pname = "wamrc";
version = "2.4.4";
src = let
baseurl = "https://github.com/bytecodealliance/wasm-micro-runtime/releases/download";
in
builtins.fetchTarball {
url = "${baseurl}/WAMR-${version}/${pname}-${version}-x86_64-ubuntu-22.04.tar.gz";
sha256 = "sha256:0264arh03gc35z0zdvw07qdvqgfvsxr3qgl1aszghwicmdmh4sqj";
};
nativeBuildInputs = with pkgs; [
autoPatchelfHook
];
buildInputs = with pkgs; [
libz
zstd
libgcc.lib
];
dontBuild = true;
installPhase = ''
runHook preInstall
mkdir -p $out/bin
cp -rv ./* $out/bin/
runHook postInstall
'';
};
wamr = stdenv.mkDerivation rec {
pname = "wamr";
version = "2.4.4";
src = pkgs.fetchFromGitea {
domain = "gitea.local.chriphost.de";
owner = "christoph";
repo = "wamr";
rev = "fd69a4e76ec0d384bd79f514772b7dfa240fc0d7";
hash = "sha256-rlCx4isI0k6rC9E0hWIA9LeinqiACug7zxj9z/e4SBQ=";
};
dontBuild = true;
installPhase = ''
runHook preInstall
mkdir -p $out
cp -rv ./* $out/
runHook postInstall
'';
};
libiwasm = buildtype: flags:
i386_pkgs.stdenv.mkDerivation rec {
pname = "libiwasm";
version = "2.4.4";
src = pkgs.fetchFromGitea {
domain = "gitea.local.chriphost.de";
owner = "christoph";
repo = "wamr";
rev = "fd69a4e76ec0d384bd79f514772b7dfa240fc0d7";
hash = "sha256-rlCx4isI0k6rC9E0hWIA9LeinqiACug7zxj9z/e4SBQ=";
};
nativeBuildInputs = with pkgs; [cmake];
cmakeBuildType = buildtype;
cmakeFlags = [
"-DCMAKE_SYSTEM_NAME=Generic"
"-DCMAKE_SYSTEM_PROCESSOR=i386"
"-DCMAKE_TRY_COMPILE_TARGET_TYPE=STATIC_LIBRARY"
"-DCMAKE_VERBOSE_MAKEFILE=ON"
"-DCMAKE_COLOR_DIAGNOSTICS=ON"
"-DWAMR_BUILD_PLATFORM=baremetal"
"-DWAMR_BUILD_TARGET=X86_32"
"-DWAMR_BUILD_AOT=1"
"-DWAMR_BUILD_WAMR_COMPILER=0"
"-DWAMR_BUILD_INTERP=1"
"-DWAMR_BUILD_FAST_INTERP=0"
"-DWAMR_BUILD_JIT=0"
"-DWAMR_BUILD_FAST_JIT=0"
"-DWAMR_BUILD_LIBC_BUILTIN=1"
"-DWAMR_BUILD_LIBC_WASI=0"
"-DWAMR_BUILD_SIMD=0"
];
# Since GCC 15, implicit declarations are an error. Disable this.
NIX_CFLAGS_COMPILE = "-Wno-error=implicit-function-declaration " + flags;
};
libiwasm_debug = libiwasm "Debug" "-O0 -ggdb";
libiwasm_release = libiwasm "Release" "-O2 -DNDEBUG";
# ===========================================================================================
# Specify dependencies
# https://nixos.org/manual/nixpkgs/stable/#ssec-stdenv-dependencies-overview
@ -149,7 +325,7 @@ rec {
# Add dependencies to nativeBuildInputs if they are executed during the build:
# - Those which are needed on $PATH during the build, for example cmake and pkg-config
# - Setup hooks, for example makeWrapper
# - Setup hooks, for example makeWrapper/autoPatchelfHook
# - Interpreters needed by patchShebangs for build scripts (with the --build flag), which can be the case for e.g. perl
nativeBuildInputs = with pkgs; [
autoPatchelfHook
@ -159,25 +335,27 @@ rec {
# - Libraries used by compilers, for example zlib
# - Interpreters needed by patchShebangs for scripts which are installed, which can be the case for e.g. perl
buildInputs = with pkgs; [
python # For resultbrowser
# FAIL runtime dependencies
python # bochs-experiment-runner.py, resultbrowser.py
alsa-lib # libasound.so.2
boost174 # libboost_coroutine.so.1.74.0, libboost_regex.so.1.74.0, libboost_thread.so.1.74.0
boost_pkgs.boost174 # libboost_coroutine.so.1.74.0, libboost_regex.so.1.74.0, libboost_thread.so.1.74.0
capstone_4 # libcapstone.so.4
libdwarf # libdwarf.so.1
libelf # libelf.so.1
mariadb-connector-c # libmariadb.so.3
libdwarf_pkgs.libdwarf # libdwarf.so.1
elfutils # libelf.so.1
mariadb # libmariadb.so.3
libpcl # libpcl.so.1
protobuf # libprotobuf.so.32
protobuf_21 # libprotobuf.so.32
SDL # libSDL-1.2.so.0
libx11 # libX11.so.6
libxrandr # libXrandr.so.2
libz # libz.so.1
];
# ===========================================================================================
# Define buildable + installable packages
# ===========================================================================================
package = stdenv.mkDerivation rec {
fail-bin = stdenv.mkDerivation {
inherit nativeBuildInputs buildInputs;
pname = "fail";
version = "1.0.0";
@ -193,26 +371,54 @@ rec {
runHook postInstall
'';
};
in rec {
in {
# Provide package for "nix build"
packages = {
default = package;
default = fail-bin;
};
apps = {
default = flake-utils.lib.mkApp {drv = fail-bin;};
};
apps.default = flake-utils.lib.mkApp {drv = package;};
devShells = {
# Provide default environment for "nix develop".
# Other environments can be added below.
default = pkgs.mkShell {
inherit nativeBuildInputs buildInputs shellHook;
inherit shellHook;
name = description;
nativeBuildInputs = with pkgs; [
just
xxd
wabt
grub2
xorriso
mariadb.client
iwasm
wamrc
fail-bin
# Don't install to not pollute our PATH. Just export as environment variable.
# wasi-sdk
# libiwasm_debug
# libiwasm_release
];
# =========================================================================================
# Define environment variables
# =========================================================================================
# Dynamic libraries from buildinputs:
LD_LIBRARY_PATH = pkgs.lib.makeLibraryPath buildInputs;
# LD_LIBRARY_PATH = pkgs.lib.makeLibraryPath buildInputs;
# Those are read by the justfile
FAIL_SHARE = "${fail-bin}/share";
WASI_ROOT = wasi-sdk;
WAMR_ROOT = wamr;
LIBIWASM_DEBUG = "${libiwasm_debug}/lib";
LIBIWASM_RELEASE = "${libiwasm_release}/lib";
CROSSCC = "${i386_pkgs.buildPackages.gcc}/bin/i386-elf-gcc";
CROSSCXX = "${i386_pkgs.buildPackages.gcc}/bin/i386-elf-g++";
};
};
});

246
justfile Normal file
View File

@ -0,0 +1,246 @@
BUILD_DIR := "build"
# Load environment variables set by "nix develop"-shell
FAIL_SHARE := env("FAIL_SHARE")
WASI_ROOT := env("WASI_ROOT")
WAMR_ROOT := env("WAMR_ROOT")
LIBIWASM_DEBUG := env("LIBIWASM_DEBUG")
LIBIWASM_RELEASE := env("LIBIWASM_RELEASE")
CROSS_CC := env("CROSSCC")
CROSS_CXX := env("CROSSCXX")
# C -> WASM
WASI_CC := f"{{WASI_ROOT}}/bin/clang"
WASI_CFLAGS := "\
--target=wasm32 \
--sysroot={{WASI_ROOT}}/share/wasi-sysroot \
-z stack-size=4096 \
-O0 \
-nostdlib \
-Wl,--no-entry \
-Wl,--export-all \
-Wl,--no-gc-sections \
-Wl,--initial-memory=65536 \
-Wl,--export=__heap_base \
-Wl,--export=__data_end \
"
# WASM -> AOT
WAMRC := "wamrc"
WAMRCFLAGS := "\
--target=i386 \
--cpu=generic \
--opt-level=0 \
"
XXD := "xxd"
# Load AOT from WAMR
CROSS_CFLAGS := "\
-I./targets/wasm-host \
-O2 \
-m32 \
-ffunction-sections \
-fdata-sections \
-ffreestanding \
-fomit-frame-pointer \
-ggdb \
"
CROSS_LDFLAGS := f"\
-Wl,--build-id=none \
-static \
-nostdlib \
-m32 \
-L{{LIBIWASM_RELEASE}} \
-liwasm \
-lc \
-lgcc \
-lm \
"
CROSS_INCLUDES := f"\
-I{{WAMR_ROOT}}/core/iwasm/include \
-I{{WAMR_ROOT}}/core/shared/utils \
-I{{WAMR_ROOT}}/core/shared/platform/baremetal \
"
# Build recipes
[default]
[private]
list:
@just --list --unsorted
[private]
create-build-dir module:
mkdir -p {{ BUILD_DIR }}-{{ module }}
[doc("Delete the build directory")]
clean module:
rm -rf {{ BUILD_DIR }}-{{ module }}
[doc("C -> WASM: Compile a C function to a WASM module using WASI-SDK")]
[group("build")]
build-wasm-module module: (create-build-dir module)
{{ WASI_CC }} {{ WASI_CFLAGS }} targets/wasm-module/{{ module }}.c -o {{ BUILD_DIR }}-{{ module }}/wasm_module.wasm
[doc("WASM -> AOT: Compile a WASM module ahead-of-time using WAMR")]
[group("build")]
build-wasm-aot module: (build-wasm-module module)
{{ WAMRC }} {{ WAMRCFLAGS }} -o {{ BUILD_DIR }}-{{ module }}/wasm_module.aot {{ BUILD_DIR }}-{{ module }}/wasm_module.wasm
[doc("AOT -> C-Array: Dump a WASM module compiled ahead-of-time to a binary array")]
[group("build")]
build-wasm-aot-array module: (build-wasm-aot module)
{{ XXD }} -i {{ BUILD_DIR }}-{{ module }}/wasm_module.aot > {{ BUILD_DIR }}-{{ module }}/wasm_module_array.c
[doc("Compile C-Host: The host uses WAMR to load the AOT module")]
[group("build")]
build-wasm-host module target="fail": (build-wasm-aot-array module)
cp targets/wasm-host/{{ target }}.c {{ BUILD_DIR }}-{{ module }}/module_host.c
sed -i \
-e "s/__WASM_ARRAY_FILE__/wasm_module_array.c/g" \
-e "s/__WASM_ARRAY__/build_{{ module }}_wasm_module_aot/g" \
-e "s/__WASM_ARRAY_LEN__/build_{{ module }}_wasm_module_aot_len/g" \
{{ BUILD_DIR }}-{{ module }}/module_host.c
{{ CROSS_CC }} {{ CROSS_CFLAGS }} {{ CROSS_INCLUDES }} \
-c {{ BUILD_DIR }}-{{ module }}/module_host.c \
-o {{ BUILD_DIR }}-{{ module }}/system.o
[doc("Compile bootloader")]
[group("build")]
build-system-startup module:
{{ CROSS_CC }} targets/startup.s {{ CROSS_CFLAGS }} -c -o {{ BUILD_DIR }}-{{ module }}/startup.o
[doc("Compile newlib syscall stubs")]
[group("build")]
build-system-syscalls module:
{{ CROSS_CC }} targets/syscalls.c {{ CROSS_CFLAGS }} -c -o {{ BUILD_DIR }}-{{ module }}/syscalls.o
[doc("Link C-Host, syscall stubs and bootloader")]
[group("build")]
build-system module target="fail": (build-wasm-host module target) (build-system-syscalls module) (build-system-startup module)
{{ CROSS_CC }} -Wl,-T targets/linker.ld \
{{ BUILD_DIR }}-{{ module }}/system.o \
{{ BUILD_DIR }}-{{ module }}/syscalls.o \
{{ BUILD_DIR }}-{{ module }}/startup.o \
{{ CROSS_LDFLAGS }} -o {{ BUILD_DIR }}-{{ module }}/system.elf
[doc("Create bootdisk")]
[group("build")]
build-iso module target="fail": (build-system module target)
mkdir -p {{ BUILD_DIR }}-{{ module }}/grub/boot/grub
cp targets/grub.cfg {{ BUILD_DIR }}-{{ module }}/grub/boot/grub/
cp {{ BUILD_DIR }}-{{ module }}/system.elf {{ BUILD_DIR }}-{{ module }}/grub/boot/
grub-mkrescue -o {{ BUILD_DIR }}-{{ module }}/system.iso {{ BUILD_DIR }}-{{ module }}/grub
# FAIL* recipes
BOCHS_RUNNER := "bochs-experiment-runner.py"
FAIL_TRACE := "fail-x86-tracing"
FAIL_DUMP := "dump-trace"
FAIL_IMPORT := "import-trace --database-option-file ./db.conf"
FAIL_PRUNE := "prune-trace --database-option-file ./db.conf"
FAIL_SERVER := "generic-experiment-server --database-option-file ./db.conf"
FAIL_INJECT := "generic-experiment-client"
RESULT_BROWSER := "resultbrowser.py -c ./db.conf"
[doc("Start MySQL to receive FAIL* trace/campaign results")]
[group("fail")]
start-db:
docker compose up
[doc("Stop MySQL")]
[group("fail")]
stop-db:
docker compose down
[doc("Trace a golden run using FAIL*")]
[group("fail")]
trace module:
{{ BOCHS_RUNNER }} \
-V {{ FAIL_SHARE }}/vgabios.bin \
-b {{ FAIL_SHARE }}/BIOS-bochs-latest \
-1 \
-f {{ FAIL_TRACE }} \
-e {{ BUILD_DIR }}-{{ module }}/system.elf \
-i {{ BUILD_DIR }}-{{ module }}/system.iso \
-- \
-Wf,--start-symbol=start_trace \
-Wf,--save-symbol=start_trace \
-Wf,--end-symbol=stop_trace \
-Wf,--state-file={{ BUILD_DIR }}-{{ module }}/state \
-Wf,--trace-file={{ BUILD_DIR }}-{{ module }}/trace.pb \
-Wf,--elf-file={{ BUILD_DIR }}-{{ module }}/system.elf
@echo "Next step: \"just import {{ module }}\""
[doc("Import a FAIL* golden run trace")]
[group("fail")]
import module:
{{ FAIL_IMPORT }} -t {{ BUILD_DIR }}-{{ module }}/trace.pb -i MemoryImporter \
-e {{ BUILD_DIR }}-{{ module }}/system.elf -v {{ module }} -b mem
{{ FAIL_IMPORT }} -t {{ BUILD_DIR }}-{{ module }}/trace.pb -i RegisterImporter \
-e {{ BUILD_DIR }}-{{ module }}/system.elf -v {{ module }} -b regs --flags
{{ FAIL_IMPORT }} -t {{ BUILD_DIR }}-{{ module }}/trace.pb -i RegisterImporter \
-e {{ BUILD_DIR }}-{{ module }}/system.elf -v {{ module }} -b ip --no-gp --ip
# TODO: Failed to decode DWARF data - wrong libdwarf version?
#
# {{ FAIL_IMPORT }} -t {{ BUILD_DIR }}-{{ module }}/trace.pb -i ElfImporter --objdump objdump \
# -e {{ BUILD_DIR }}-{{ module }}/system.elf -v {{ module }} -b ip
# {{ FAIL_IMPORT }} -t {{ BUILD_DIR }}-{{ module }}/trace.pb -i ElfImporter --objdump objdump \
# -e {{ BUILD_DIR }}-{{ module }}/system.elf -v {{ module }} -b mem
# {{ FAIL_IMPORT }} -t {{ BUILD_DIR }}-{{ module }}/trace.pb -i ElfImporter --objdump objdump \
# -e {{ BUILD_DIR }}-{{ module }}/system.elf -v {{ module }} -b regs
# {{ FAIL_IMPORT }} -t {{ BUILD_DIR }}-{{ module }}/trace.pb -i ElfImporter --objdump objdump \
# -e {{ BUILD_DIR }}-{{ module }}/system.elf -v {{ module }} -b ip --sources
# {{ FAIL_IMPORT }} -t {{ BUILD_DIR }}-{{ module }}/trace.pb -i ElfImporter --objdump objdump \
# -e {{ BUILD_DIR }}-{{ module }}/system.elf -v {{ module }} -b mem --sources
# {{ FAIL_IMPORT }} -t {{ BUILD_DIR }}-{{ module }}/trace.pb -i ElfImporter --objdump objdump \
# -e {{ BUILD_DIR }}-{{ module }}/system.elf -v {{ module }} -b regs --sources
{{ FAIL_PRUNE }} -v {{ module }} -b %% --overwrite
@echo "Next step: \"just server {{ module }}\""
[doc("Start the FAIL* campaign server")]
[group("fail")]
server module:
{{ FAIL_SERVER }} -v {{ module }} -b % --inject-single-bit --inject-registers &
@echo "Next step: \"just client {{ module }}\""
[doc("Start a FAIL* campaign client")]
[group("fail")]
client module:
{{ BOCHS_RUNNER }} \
-V {{ FAIL_SHARE }}/vgabios.bin \
-b {{ FAIL_SHARE }}/BIOS-bochs-latest \
-f {{ FAIL_INJECT }} \
-e {{ BUILD_DIR }}-{{ module }}/system.elf \
-i {{ BUILD_DIR }}-{{ module }}/system.iso \
-j {{ num_cpus() }} \
-- \
-Wf,--state-dir={{ BUILD_DIR }}-{{ module }}/state \
-Wf,--trap \
-Wf,--timeout=500000 \
-Wf,--ok-marker=ok_marker \
-Wf,--fail-marker=fail_marker \
2>/dev/null | grep -B 2 -A 8 'INJECT'
@echo "Next step: \"just result {{ module }}\" or \"just resultbrowser\""
[doc("Query FAIL* marker statistics from the database")]
[group("fail")]
result module:
@echo "select variant, benchmark, resulttype, sum(t.time2 - t.time1 + 1) as faults \
FROM variant v \
JOIN trace t ON v.id = t.variant_id \
JOIN fspgroup g ON g.variant_id = t.variant_id AND g.instr2 = t.instr2 AND g.data_address = t.data_address \
JOIN result_GenericExperimentMessage r ON r.pilot_id = g.pilot_id \
JOIN fsppilot p ON r.pilot_id = p.id \
WHERE v.variant = \"{{ module }}\" \
GROUP BY v.id, resulttype \
ORDER BY variant, benchmark, resulttype;" | mariadb --defaults-file=./db.conf -t
[doc("Start the FAIL* resultbrowser")]
[group("fail")]
resultbrowser:
{{ RESULT_BROWSER }} --host=0.0.0.0 --port=5000

7
targets/grub.cfg Normal file
View File

@ -0,0 +1,7 @@
set timeout=0
set default=0
menuentry "CoRedOS" {
multiboot /boot/system.elf
boot
}

82
targets/linker.ld Normal file
View File

@ -0,0 +1,82 @@
/* Kernel entry function */
ENTRY(_start)
OUTPUT_FORMAT(elf32-i386)
SECTIONS {
/DISCARD/ : {
*(".text.inlined*")
*(.comment)
*(.eh_frame)
*(.note.gnu.build-id)
}
/* Set kernel start address */
. = 0x100000;
/* Code and readonly data */
.text : {
/* fill gaps with int3 opcode to detect invalid jumps */
/* TODO: Crashes */
FILL(0xcc)
/* multiboot header */
multiboot_header = .;
KEEP (*(".rodata.multiboot"))
/* /\* fixed address for IRQ handlers *\/ */
/* . = 0x1000; */
/* /\* start of interrupt handlers *\/ */
/* _stext_irqs = .; */
/* /\* IRQ Handlers *\/ */
/* KEEP (*(".text.irqhandlers*")) /\* ASM *\/ */
/* KEEP (*(".text.irq_handler*")) /\* C *\/ */
/* *(".text.isrs*") /\* C *\/ */
/* *(".text.isr_*") /\* C *\/ */
/* KEEP (*(".text.OSEKOS_ISR*")) */
/* KEEP (*(".text.idt")) /\* ASM *\/ */
/* /\* sysenter handler *\/ */
/* KEEP (*(".text.sysenter_syscall")) */
/* _etext_irqs = .; */
/* . += 16; /\* padding after data, workaround for import-trace *\/ */
KEEP (*(".text.startup"))
*(".text*")
*(".rodata*")
}
/* Data and Stacks */
. = 0x200000;
.data : {
KEEP (*(".startup_stack"))
KEEP (*(".kernel_stack"))
*(".data*")
}
/* Uninitialized data */
.bss : {
_sbss = .;
*(.bss*)
*(COMMON)
_ebss = .;
}
/* Align and mark end of all sections — heap starts here */
. = ALIGN(4096);
_end = .;
/* Memory-mapped I/O APIC */
_sioapic = 0xFEC00000;
ioapic = 0xFEC00000;
_eioapic = 0xFEC00FFF;
/* Memory-mapped Local APIC */
_slapic = 0xFEE00000;
lapic = 0xFEE00000;
_elapic = 0xFEE00FFF;
}

110
targets/startup.s Normal file
View File

@ -0,0 +1,110 @@
## Bare bone boot.s from wiki.osdev.org
# multiboot header
.section .rodata.multiboot
.align 4
# magic number
.long 0x1BADB002
# flags: align, meminfo
.long 0x3
# checksum: -(magic+flags)
.long -(0x1BADB002 + 0x3)
# the initial kernel stack
.section .kernel_stack
.global os_stack
.size os_stack, 4096
# NOTE: New Start
# .section .gdt
# gdt_start:
# .quad 0x0000000000000000 # null descriptor
# .quad 0x00cf9a000000ffff # code segment descriptor: base=0, limit=4GB, 32-bit code
# .quad 0x00cf92000000ffff # data segment descriptor: base=0, limit=4GB, 32-bit data
# gdt_end:
#
# gdt_descriptor:
# .word gdt_end - gdt_start - 1 # limit
# .long gdt_start # base
#
# .section .idt
# idt_table:
# .space 256*8 # 256 entries x 8 bytes each
# idt_descriptor:
# .word 256*8-1 # limit
# .long idt_table # base
# NOTE: New End
#.Lstack_bottom:
os_stack:
.byte 0
.skip 65565 # 64 KiB
# .skip 16384 # 16 KiB
# .skip 4094 # 4 KiB
.byte 0
.Lstack_top:
# The linker script specifies _start as the entry point to the kernel and the
# bootloader will jump to this position once the kernel has been loaded. It
# doesn't make sense to return from this function as the bootloader is gone.
.section .text.startup
.global _start
.type _start, @function
_start:
# NOTE: Old Start
# Welcome to kernel mode!
# To set up a stack, we simply set the esp register to point to the top of
# our stack (as it grows downwards).
movl $.Lstack_top, %esp
# We are now ready to actually execute C code. (see ./startup.cc)
call os_main
# In case the function returns, we'll want to put the computer into an
# infinite loop. To do that, we use the clear interrupt ('cli') instruction
# to disable interrupts, the halt instruction ('hlt') to stop the CPU until
# the next interrupt arrives, and jumping to the halt instruction if it ever
# continues execution, just to be safe. We will create a local label rather
# than real symbol and jump to there endlessly.
cli
hlt
.Lhang:
jmp .Lhang
# NOTE: Old End
# NOTE: New Start
# cli
#
# lgdt gdt_descriptor # GDT
# lidt idt_descriptor # IDT Stub
#
# # set up segment registers (flat 32-bit)
# movw $0x10, %ax
# movw %ax, %ds
# movw %ax, %es
# movw %ax, %fs
# movw %ax, %gs
# movw %ax, %ss
# movl $.Lstack_top, %esp # set stack
#
# # call main C function
# call os_main
#
# cli
# hlt
# .Lhang:
# jmp .Lhang
# NOTE: New End
# Set the size of the _start symbol to the current location '.' minus its start.
# This is useful when debugging or when you implement call tracing.
.size _start, . - _start

35
targets/syscalls.c Normal file
View File

@ -0,0 +1,35 @@
#include <errno.h>
#include <sys/stat.h>
extern char _end; /* provided by linker script */
static char *heap_ptr = &_end;
void *sbrk(int incr) {
char *prev = heap_ptr;
heap_ptr += incr;
return prev;
}
int write(int fd, const char *buf, int len) { return len; }
int read(int fd, char *buf, int len) { return 0; }
int close(int fd) { return -1; }
int fstat(int fd, struct stat *st) {
st->st_mode = S_IFCHR;
return 0;
}
int isatty(int fd) { return 1; }
int lseek(int fd, int offset, int whence) { return 0; }
void _exit(int status) {
while (1)
;
}
void exit(int status) {
while (1)
;
}
int kill(int pid, int sig) {
errno = EINVAL;
return -1;
}
int getpid(void) { return 1; }

View File

@ -0,0 +1,74 @@
#include "bh_platform.h"
#include "wasm_export.h"
#include "__WASM_ARRAY_FILE__"
#define STACK_SIZE (4 * 1024)
#define HEAP_SIZE STACK_SIZE
#define RUNTIME_POOL_SIZE (4 * STACK_SIZE)
int main(int argc, char *argv[]) {
char error_buf[128];
wasm_module_t module;
wasm_module_inst_t module_inst;
wasm_function_inst_t func;
wasm_exec_env_t exec_env;
/* initialize the wasm runtime */
static char global_heap_buf[RUNTIME_POOL_SIZE];
static RuntimeInitArgs init_args;
memset(&init_args, 0, sizeof(RuntimeInitArgs));
init_args.mem_alloc_type = Alloc_With_Pool;
init_args.mem_alloc_option.pool.heap_buf = global_heap_buf;
init_args.mem_alloc_option.pool.heap_size = sizeof(global_heap_buf);
init_args.max_thread_num = 1;
if (!wasm_runtime_full_init(&init_args)) {
return 1;
}
/* parse the WASM file from buffer and create a WASM module */
module = wasm_runtime_load(__WASM_ARRAY__, __WASM_ARRAY_LEN__, error_buf,
sizeof(error_buf));
if (!module) {
return 1;
}
/* create an instance of the WASM module (WASM linear memory is ready) */
module_inst = wasm_runtime_instantiate(module, STACK_SIZE, HEAP_SIZE,
error_buf, sizeof(error_buf));
if (!module_inst) {
return 1;
}
/* lookup a WASM function by its name, the function signature can NULL here */
func = wasm_runtime_lookup_function(module_inst, "wasm_module");
/* create an execution environment to execute arbitrary WASM functions */
exec_env = wasm_runtime_create_exec_env(module_inst, STACK_SIZE);
/* arguments are always transferred in 32-bit element */
uint32_t args[1] = {0};
/* call an arbitrary WASM function */
if (!wasm_runtime_call_wasm(exec_env, func, 0, args)) {
/* function wasn't called correctly */
return 1;
}
/* the return value is stored in args[0] */
uint32_t result = args[0];
wasm_runtime_destroy_exec_env(exec_env);
wasm_runtime_deinstantiate(module_inst);
wasm_runtime_unload(module);
wasm_runtime_destroy();
if (result == 100) {
return 0;
} else {
return 1;
}
}

79
targets/wasm-host/fail.c Normal file
View File

@ -0,0 +1,79 @@
#include "lib.h"
#include "bh_platform.h"
#include "wasm_export.h"
#include "__WASM_ARRAY_FILE__"
#define STACK_SIZE (4 * 1024)
#define HEAP_SIZE STACK_SIZE
#define RUNTIME_POOL_SIZE 4 * STACK_SIZE
MAIN() {
char error_buf[128];
wasm_module_t module;
wasm_module_inst_t module_inst;
wasm_function_inst_t func;
wasm_exec_env_t exec_env;
/* initialize the wasm runtime */
static char global_heap_buf[RUNTIME_POOL_SIZE];
static RuntimeInitArgs init_args;
memset(&init_args, 0, sizeof(RuntimeInitArgs));
init_args.mem_alloc_type = Alloc_With_Pool;
init_args.mem_alloc_option.pool.heap_buf = global_heap_buf;
init_args.mem_alloc_option.pool.heap_size = sizeof(global_heap_buf);
init_args.max_thread_num = 1;
if (!wasm_runtime_full_init(&init_args)) {
return;
}
/* parse the WASM file from buffer and create a WASM module */
module = wasm_runtime_load(__WASM_ARRAY__, __WASM_ARRAY_LEN__, error_buf,
sizeof(error_buf));
if (!module) {
return;
}
/* create an instance of the WASM module (WASM linear memory is ready) */
module_inst = wasm_runtime_instantiate(module, STACK_SIZE, HEAP_SIZE,
error_buf, sizeof(error_buf));
if (!module_inst) {
return;
}
/* lookup a WASM function by its name, the function signature can NULL here */
func = wasm_runtime_lookup_function(module_inst, "wasm_module");
/* create an execution environment to execute arbitrary WASM functions */
exec_env = wasm_runtime_create_exec_env(module_inst, STACK_SIZE);
/* arguments are always transferred in 32-bit element */
uint32_t args[1] = {0};
/* call an arbitrary WASM function */
MARKER(start_trace);
if (!wasm_runtime_call_wasm(exec_env, func, 0, args)) {
/* function wasn't called correctly */
}
MARKER(stop_trace);
uint32_t result = args[0];
/* the return value is stored in args[0] */
if (result == 100) {
MARKER(ok_marker);
} else {
MARKER(fail_marker);
}
wasm_runtime_destroy_exec_env(exec_env);
wasm_runtime_deinstantiate(module_inst);
wasm_runtime_unload(module);
wasm_runtime_destroy();
return;
}

35
targets/wasm-host/lib.h Normal file
View File

@ -0,0 +1,35 @@
#pragma once
#define INLINE __attribute__((always_inline)) inline
#define NOINLINE __attribute__((noinline))
#define __QUOTE(x) #x
#define QUOTE(x) __QUOTE(x)
#ifndef ARCH_ASM_CLOBBER_ALL
#define ARCH_ASM_CLOBBER_ALL "eax", "ebx", "ecx", "edx", "esi", "edi", "ebp"
#endif
#ifndef MARKER
#define MARKER(str) \
__asm__ volatile(QUOTE(str) ":" \
: /* no inputs */ \
: /* no outputs */ \
: "memory", ARCH_ASM_CLOBBER_ALL)
#endif
#ifndef MAIN
#define MAIN() void os_main(void)
#endif
#ifndef POSIX_PRINTF
#define POSIX_PRINTF(...)
#endif
typedef __UINT8_TYPE__ uint8_t;
typedef __UINT16_TYPE__ uint16_t;
typedef __UINT32_TYPE__ uint32_t;
typedef __INT8_TYPE__ int8_t;
typedef __INT16_TYPE__ int16_t;
typedef __INT32_TYPE__ int32_t;

80
targets/wasm-host/linux.c Normal file
View File

@ -0,0 +1,80 @@
#include "bh_platform.h"
#include "wasm_export.h"
#include "__WASM_ARRAY_FILE__"
#include <stdio.h>
#define STACK_SIZE (4 * 1024)
#define HEAP_SIZE STACK_SIZE
#define RUNTIME_POOL_SIZE 4 * STACK_SIZE
int main(int argc, char *argv[]) {
char error_buf[128];
wasm_module_t module;
wasm_module_inst_t module_inst;
wasm_function_inst_t func;
wasm_exec_env_t exec_env;
/* initialize the wasm runtime */
static char global_heap_buf[RUNTIME_POOL_SIZE];
static RuntimeInitArgs init_args;
memset(&init_args, 0, sizeof(RuntimeInitArgs));
// init_args.mem_alloc_type = Alloc_With_System_Allocator;
init_args.mem_alloc_type = Alloc_With_Pool;
init_args.mem_alloc_option.pool.heap_buf = global_heap_buf;
init_args.mem_alloc_option.pool.heap_size = sizeof(global_heap_buf);
init_args.max_thread_num = 1;
if (!wasm_runtime_full_init(&init_args)) {
return 1;
}
/* parse the WASM file from buffer and create a WASM module */
module = wasm_runtime_load(__WASM_ARRAY__, __WASM_ARRAY_LEN__, error_buf,
sizeof(error_buf));
if (!module) {
printf("Load failed: %s\n", error_buf);
return 1;
}
/* create an instance of the WASM module (WASM linear memory is ready) */
module_inst = wasm_runtime_instantiate(module, STACK_SIZE, HEAP_SIZE,
error_buf, sizeof(error_buf));
if (!module_inst) {
printf("Inst failed: %s\n", error_buf);
return 1;
}
/* lookup a WASM function by its name, the function signature can NULL here */
func = wasm_runtime_lookup_function(module_inst, "wasm_module");
/* create an execution environment to execute arbitrary WASM functions */
exec_env = wasm_runtime_create_exec_env(module_inst, STACK_SIZE);
/* arguments are always transferred in 32-bit element */
uint32_t args[1] = {0};
/* call an arbitrary WASM function */
if (!wasm_runtime_call_wasm(exec_env, func, 0, args)) {
/* function wasn't called correctly */
printf("Failed to call function 'wasm_module'!\n");
}
/* the return value is stored in args[0] */
uint32_t result = args[0];
wasm_runtime_destroy_exec_env(exec_env);
wasm_runtime_deinstantiate(module_inst);
wasm_runtime_unload(module);
wasm_runtime_destroy();
if (result == 100) {
printf("OK Marker\n");
return 0;
} else {
printf("FAIL Marker\n");
return 1;
}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,7 @@
int wasm_module(void) {
int sum = 0;
for (int i = 0; i < 100; ++i) {
sum += 1;
}
return sum;
}