### Quick start C++ example using rax::Engine Source: https://github.com/hexrayssa/rax/blob/master/capi/README.md Initializes a 64-bit x86 engine, writes code to memory, hooks execution, sets RSP, starts execution, and reads the result from RAX. Throws rax::Error on a fault. ```cpp #include rax::Engine e(rax::Arch::X86, RAX_MODE_64); e.memWrite(0x1000, code); // std::vector e.hookCode([](rax::Engine&, uint64_t pc, uint32_t) { printf("exec 0x%llx\n", (unsigned long long)pc); }); e.setReg(RAX_X86_REG_RSP, uint64_t(0x8000)); e.start(0x1000); // throws rax::Error on a fault uint64_t result = e.regU64(RAX_X86_REG_RAX); ``` -------------------------------- ### Install timer handler and display periodic message in timer.c Source: https://github.com/hexrayssa/rax/blob/master/docs/hardware/pit.txt Example of using the system timer from 'timer.c'. The first block shows a timer handler that prints a message every 18 ticks (about 1 second). The second block installs that handler on IRQ0. Remember to call 'timer_install' in 'main' and add a prototype to 'system.h'. ```c /* Every 18 clocks (approximately 1 second), we will * display a message on the screen */ if (timer_ticks % 18 == 0) { puts("One second has passed\n"); } } ``` ```c /* Sets up the system clock by installing the timer handler * into IRQ0 */ void timer_install() { /* Installs 'timer_handler' to IRQ0 */ irq_install_handler(0, timer_handler); } ``` -------------------------------- ### Quick start C example using rax_engine_open and rax_emu_start Source: https://github.com/hexrayssa/rax/blob/master/capi/README.md Opens an x86-64 engine in user mode, writes a small machine-code program to guest memory, sets RSP, runs it, and prints the resulting RAX value (0x1338). Requires RAX_MODE_USER (ABI 1.5) for unprivileged execution; system calls and exceptions are returned to the embedder. ```c #include #include int main(void) { rax_engine *e; rax_engine_open(RAX_ARCH_X86, RAX_MODE_64, &e); /* mov rax,0x1337 ; mov rcx,1 ; add rax,rcx ; hlt */ unsigned char code[] = {0x48,0xC7,0xC0,0x37,0x13,0,0, 0x48,0xC7,0xC1,1,0,0,0, 0x48,0x01,0xC8, 0xF4}; rax_mem_write(e, 0x1000, code, sizeof code); rax_reg_write_u64(e, RAX_X86_REG_RSP, 0x8000); rax_emu_start(e, 0x1000, RAX_NO_ADDR, /*timeout_us*/0, /*count*/0); uint64_t rax; rax_reg_read_u64(e, RAX_X86_REG_RAX, &rax); printf("RAX = 0x%llx\n", (unsigned long long)rax); /* 0x1338 */ rax_engine_close(e); } ``` -------------------------------- ### Example output from ARGS.C Source: https://github.com/hexrayssa/rax/blob/master/docs/specifications/windows/crt-initializers/microsoft/parsing-c-command-line-arguments.md Example output from the ARGS.C program, showing the command-line arguments and environment variables as displayed by the program. This output corresponds to the ARGS.C example above. ```text Command-line arguments: argv[0] C:\MSC\ARGS.EXE Environment variables: COMSPEC=C:\NT\SYSTEM32\CMD.EXE PATH=c:\nt;c:\binb;c:\binr;c:\nt\system32;c:\word;c:\help;c:\msc;c:\; PROMPT=[$p] TEMP=c:\tmp TMP=c:\tmp EDITORS=c:\binr WINDIR=c:\nt ``` -------------------------------- ### Build and install with CMake Source: https://github.com/hexrayssa/rax/blob/master/capi/README.md Configures, builds, and installs the C API using CMake. Both shared and static libraries are installed by default. RAX_BUILD_SHARED and RAX_BUILD_STATIC select installed targets. ```sh cmake -S capi -B build -DCMAKE_INSTALL_PREFIX=/path/to/sdk cmake --build build --config Release cmake --install build --config Release ``` -------------------------------- ### Set file mode with _set_fmode and write binary data Source: https://github.com/hexrayssa/rax/blob/master/docs/specifications/windows/crt-stdio/microsoft/set-fmode.md Complete example that gets the current mode with _get_fmode, sets it to _O_BINARY with _set_fmode, writes binary data to a file, and displays the file contents. The output shows the default mode as binary and the written integer values as characters. ```c // crt_set_fmode.c #include #include #include /* for _O_TEXT and _O_BINARY */ #include /* for EINVAL */ #include /* for _S_IWRITE */ #include /* for _SH_DENYNO */ int main() { int mode, fd, ret; errno_t err; int buf[12] = { 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76 }; char * filename = "fmode.out"; err = _get_fmode(&mode); if (err == EINVAL) { printf( "Invalid parameter: mode\n"); return 1; } else printf( "Default Mode is %s\n", mode == _O_TEXT ? "text" : "binary"); err = _set_fmode(_O_BINARY); if (err == EINVAL) { printf( "Invalid mode.\n"); return 1; } if ( _sopen_s(&fd, filename, _O_RDWR | _O_CREAT, _SH_DENYNO, _S_IWRITE | _S_IREAD) != 0 ) { printf( "Error opening the file %s\n", filename); return 1; } if (ret = _write(fd, buf, 12*sizeof(int)) < 12*sizeof(int)) { printf( "Problem writing to the file %s.\n", filename); printf( "Number of bytes written: %d\n", ret); } if (_close(fd) != 0) { printf("Error closing the file %s. Error code %d.\n", filename, errno); } system("type fmode.out"); } ``` ```output Default Mode is binary A B C D E F G H I J K L ``` -------------------------------- ### Run Foundation Platform with hello.axf Source: https://github.com/hexrayssa/rax/blob/master/docs/specifications/arm/armv8_a_fp_ug_100961_1111_00_en.pdf Run the Foundation Platform with the example program. The output shows the platform initializing and executing the example, demonstrating semihosting calls for printing and stopping. ```bash ./Foundation_Platform --image hello.axf ``` ```text terminal_0: Listening for serial connection on port 5000 terminal_1: Listening for serial connection on port 5001 terminal_2: Listening for serial connection on port 5002 terminal_3: Listening for serial connection on port 5003 Simulation is started Hello, 64-bit world! Simulation is terminating. Reason: Simulation stopped ``` -------------------------------- ### Install rax SDK with make Source: https://github.com/hexrayssa/rax/blob/master/capi/README.md Installs the rax SDK to a custom prefix using make. The .pc and CMake package paths are relative to the install location, so the SDK can be moved. ```sh make -C capi install PREFIX=/path/to/sdk ``` -------------------------------- ### Expected output for stdin binary mode example Source: https://github.com/hexrayssa/rax/blob/master/docs/specifications/windows/crt-stdio/microsoft/setmode.md Expected output from the previous example. This demonstrates that the mode change was successful. ```Output 'stdin' successfully changed to binary mode ``` -------------------------------- ### Run a step in the background with wait Source: https://github.com/hexrayssa/rax/blob/master/docs/development/capi-releases/references/github-workflow-syntax.md Shows how to run a step in the background with `background: true`, assign it an `id` so it can be referenced, and then synchronize with it using a `wait` step. The example starts a server, runs tests, and waits for the server step to finish. ```yaml steps: - name: Start server id: server run: npm start background: true - name: Run tests against the server run: npm test - name: Wait for the server step to finish wait: server ``` -------------------------------- ### Example of hardcoded paths in FooConfig.cmake Source: https://github.com/hexrayssa/rax/blob/master/docs/development/capi-releases/references/cmake-package-config-helpers.html Illustrates the problematic pattern of hardcoding absolute install destinations in a config file, which the configure_package_config_file() command is designed to avoid. ```cmake set(FOO_INCLUDE_DIR "@CMAKE_INSTALL_FULL_INCLUDEDIR@" ) set(FOO_DATA_DIR "@CMAKE_INSTALL_PREFIX@/@RELATIVE_DATA_INSTALL_DIR@" ) set(FOO_ICONS_DIR "@CMAKE_INSTALL_PREFIX@/share/icons" ) #...logic to determine installedPrefix from the own location... set(FOO_CONFIG_DIR "${installedPrefix}/@CONFIG_INSTALL_DIR@" ) ``` -------------------------------- ### CMake build and install Source: https://github.com/hexrayssa/rax/blob/master/docs/embedding.md Builds and installs the rax C API using CMake. The install prefix is set to /usr/local. ```sh cmake -S capi -B build -DCMAKE_INSTALL_PREFIX=/usr/local cmake --build build cmake --install build ``` -------------------------------- ### CMakeLists.txt: Configure and install package files Source: https://github.com/hexrayssa/rax/blob/master/docs/development/capi-releases/references/cmake-package-config-helpers.html This CMakeLists.txt uses configure_package_config_file() and write_basic_package_version_file() to generate FooConfig.cmake and FooConfigVersion.cmake, then installs them. It sets INCLUDE_INSTALL_DIR and SYSCONFIG_INSTALL_DIR as cache paths for PATH_VARS. ```cmake include(GNUInstallDirs) set(INCLUDE_INSTALL_DIR ${CMAKE_INSTALL_INCLUDEDIR}/Foo CACHE PATH "Location of header files" ) set(SYSCONFIG_INSTALL_DIR ${CMAKE_INSTALL_SYSCONFDIR}/foo CACHE PATH "Location of configuration files" ) #... include(CMakePackageConfigHelpers) configure_package_config_file(FooConfig.cmake.in ${CMAKE_CURRENT_BINARY_DIR}/FooConfig.cmake INSTALL_DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/Foo PATH_VARS INCLUDE_INSTALL_DIR SYSCONFIG_INSTALL_DIR) write_basic_package_version_file( ${CMAKE_CURRENT_BINARY_DIR}/FooConfigVersion.cmake VERSION 1.2.3 COMPATIBILITY SameMajorVersion ) install(FILES ${CMAKE_CURRENT_BINARY_DIR}/FooConfig.cmake ${CMAKE_CURRENT_BINARY_DIR}/FooConfigVersion.cmake DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/Foo ) ``` -------------------------------- ### pkg-config and Make install and compile Source: https://github.com/hexrayssa/rax/blob/master/docs/embedding.md Installs the C API via make and compiles an application using pkg-config to obtain flags and libraries. ```sh make -C capi install PREFIX=/usr/local cc app.c $(pkg-config --cflags --libs rax) -o app ``` -------------------------------- ### Example output Source: https://github.com/hexrayssa/rax/blob/master/docs/specifications/windows/crt-stdio/microsoft/clearerr.md The expected output from the example program when run with the given input. ```Output Write error: No error Will input cause an error? n No read error ``` -------------------------------- ### Example: crt_expand.c using _expand Source: https://github.com/hexrayssa/rax/blob/master/docs/specifications/windows/crt-foundation/allocation/expand.md Example program that allocates a 512-byte buffer with calloc, expands it to 1024 bytes using _expand, and prints the sizes and addresses. Requires and . ```C // crt_expand.c #include #include #include int main( void ) { char *bufchar; printf( "Allocate a 512 element buffer\n" ); if( (bufchar = (char *)calloc( 512, sizeof( char ) )) == NULL ) exit( 1 ); printf( "Allocated %d bytes at %Fp\n", _msize( bufchar ), (void *)bufchar ); if( (bufchar = (char *)_expand( bufchar, 1024 )) == NULL ) printf( "Can't expand" ); else printf( "Expanded block to %d bytes at %Fp\n", _msize( bufchar ), (void *)bufchar ); // Free memory free( bufchar ); exit( 0 ); } ``` -------------------------------- ### memset example with output Source: https://github.com/hexrayssa/rax/blob/master/docs/specifications/windows/crt-foundation/memory/memset-wmemset.md Complete example for memset. It includes memory.h and stdio.h, sets the first four characters of a char buffer to '*', and prints the buffer before and after. The output shows the first four characters replaced by asterisks. ```C // crt_memset.c /* This program uses memset to * set the first four chars of buffer to "*". */ #include #include int main( void ) { char buffer[] = "This is a test of the memset function"; printf( "Before: %s\n", buffer ); memset( buffer, '*', 4 ); printf( "After: %s\n", buffer ); } ``` ```Output Before: This is a test of the memset function After: **** is a test of the memset function ``` -------------------------------- ### Install and build for x86_64-unknown-none with rustup and cargo Source: https://github.com/hexrayssa/rax/blob/master/docs/development/microkernel-references/rust-x86_64-unknown-none.html Install the cross-compile toolchain via rustup and build a program for the target using cargo with the `--target` flag. ```bash # install cross-compile toolchain rustup target add x86_64-unknown-none # target flag may be used with any cargo or rustc command cargo build --target x86_64-unknown-none ``` -------------------------------- ### RAX_CMDLINE usage example Source: https://github.com/hexrayssa/rax/blob/master/docs/reference/environment-variables.md Example of setting multiple environment variables, including RAX_CMDLINE, to override the helper's known x86 software-boot kernel command line when running run.sh. ```sh RAX_KERNEL=linux/vmlinux \ RAX_INITRD=initrd.cpio.gz \ RAX_ARCH=x86-64 \ RAX_BACKEND=emulator \ RAX_MEMORY=1G \ RAX_CMDLINE='console=ttyS0 earlyprintk=serial,ttyS0,115200 nokaslr' \ ./run.sh ``` -------------------------------- ### setvbuf example with output Source: https://github.com/hexrayssa/rax/blob/master/docs/specifications/windows/crt-stdio/microsoft/setvbuf.md Complete example showing how to use setvbuf to assign a user-defined buffer of 1024 bytes to stream1 and no buffer to stream2. The output shows the expected messages when the calls succeed. ```C // crt_setvbuf.c // This program opens two streams: stream1 // and stream2. It then uses setvbuf to give stream1 a // user-defined buffer of 1024 bytes and stream2 no buffer. // #include int main( void ) { char buf[1024]; FILE *stream1, *stream2; if( fopen_s( &stream1, "data1", "a" ) == 0 && fopen_s( &stream2, "data2", "w" ) == 0 ) { if( setvbuf( stream1, buf, _IOFBF, sizeof( buf ) ) != 0 ) printf( "Incorrect type or size of buffer for stream1\n" ); else printf( "'stream1' now has a buffer of 1024 bytes\n" ); if( setvbuf( stream2, NULL, _IONBF, 0 ) != 0 ) printf( "Incorrect type or size of buffer for stream2\n" ); else printf( "'stream2' now has no buffer\n" ); _fcloseall(); } } ``` ```Output 'stream1' now has a buffer of 1024 bytes 'stream2' now has no buffer ``` -------------------------------- ### wmemset example with output Source: https://github.com/hexrayssa/rax/blob/master/docs/specifications/windows/crt-foundation/memory/memset-wmemset.md Complete example for wmemset. It includes wchar.h and stdio.h, sets the first four wide characters of a wchar_t buffer to L'*', and prints the buffer before and after. The output shows the first four wide characters replaced by asterisks. ```C // crt_wmemset.c /* This program uses memset to * set the first four chars of buffer to "*". */ #include #include int main( void ) { wchar_t buffer[] = L"This is a test of the wmemset function"; wprintf( L"Before: %s\n", buffer ); wmemset( buffer, L'*', 4 ); wprintf( L"After: %s\n", buffer ); } ``` ```Output Before: This is a test of the wmemset function After: **** is a test of the wmemset function ``` -------------------------------- ### fread example with output Source: https://github.com/hexrayssa/rax/blob/master/docs/specifications/windows/crt-stdio/microsoft/fread.md Complete example that writes 25 characters to a file and then reads them back using fread. The output shows the number of items written and read, and the contents of the buffer. Note that the file is opened in text mode, which may affect newline conversion. ```C // crt_fread.c // This program opens a file named FREAD.OUT and // writes 25 characters to the file. It then tries to open // FREAD.OUT and read in 25 characters. If the attempt succeeds, // the program displays the number of actual items read. #include int main( void ) { FILE *stream; char list[30]; int i, numread, numwritten; // Open file in text mode: if( fopen_s( &stream, "fread.out", "w+t" ) == 0 ) { for ( i = 0; i < 25; i++ ) list[i] = (char)('z' - i); // Write 25 characters to stream numwritten = fwrite( list, sizeof( char ), 25, stream ); printf( "Wrote %d items\n", numwritten ); fclose( stream ); } else printf( "Problem opening the file\n" ); if( fopen_s( &stream, "fread.out", "r+t" ) == 0 ) { // Attempt to read in 25 characters numread = fread( list, sizeof( char ), 25, stream ); printf( "Number of items read = %d\n", numread ); printf( "Contents of buffer = %.25s\n", list ); fclose( stream ); } else printf( "File could not be opened\n" ); } ``` ```Output Wrote 25 items Number of items read = 25 Contents of buffer = zyxwvutsrqponmlkjihgfedcb ``` -------------------------------- ### --initrd examples Source: https://github.com/hexrayssa/rax/blob/master/docs/reference/command-line.md Selects an initial ramdisk. The path is validated during ordinary configuration; its format must match what the selected guest kernel expects. ```sh --initrd initrd.cpio.gz --initrd linux-aarch64/initramfs.cpio ``` -------------------------------- ### Example: Get file descriptors for standard C streams Source: https://github.com/hexrayssa/rax/blob/master/docs/specifications/windows/crt-stdio/microsoft/fileno.md This example demonstrates how to use _fileno to obtain the file descriptor for stdin, stdout, and stderr. It prints the descriptors to the console. The output shows the expected values: 0 for stdin, 1 for stdout, and 2 for stderr. ```C // crt_fileno.c // This program uses _fileno to obtain // the file descriptor for some standard C streams. // #include int main( void ) { printf( "The file descriptor for stdin is %d\n", _fileno( stdin ) ); printf( "The file descriptor for stdout is %d\n", _fileno( stdout ) ); printf( "The file descriptor for stderr is %d\n", _fileno( stderr ) ); } ``` ```Output The file descriptor for stdin is 0 The file descriptor for stdout is 1 The file descriptor for stderr is 2 ``` -------------------------------- ### Build and boot rax with clean config Source: https://github.com/hexrayssa/rax/blob/master/docs/architecture/x86_64/linux-boot-busybox.md Build the rax binary and boot it with the clean config to reach the busybox prompt in about 15–20 seconds of guest time. ```bash cargo build --release --bin rax ./target/release/rax --config linux/config-clean.toml # minimal cmdline → busybox /# ``` -------------------------------- ### Meltdown core example Source: https://github.com/hexrayssa/rax/blob/master/docs/development/2506.17154v1.pdf This is the core Meltdown example, showing a bounds check followed by a speculative memory access. The processor may speculatively execute the second line before the bounds check is resolved, allowing a transient execution attack to leak secret data via the cache. ```c 1 if (x < array1_size) 2 y = array2[array1[x]]; ``` -------------------------------- ### Start Cortex-M55 FVP with PMU enabled and eight counters Source: https://github.com/hexrayssa/rax/blob/master/docs/specifications/arm/armv8.1-m_performance_monitoring_user_guide_ARM051-799564642-251.pdf Use this command to launch the Cortex-M55 FVP with the PMU present and configured with eight counters. The parameters has_pmu=1 and num_pmu_counters=8 are set for cpu0. The default num_pmu_counters value (0x1F) is not valid for Cortex-M55, so it must be changed to 8 or 0 to match RTL configuration. ```shell FVP_MPS2_Cortex-M55.exe -c cpu0.has_pmu=1 -c cpu0.num_pmu_counters=8 ``` -------------------------------- ### Wait for debugger connection (--wait-gdb) Source: https://github.com/hexrayssa/rax/blob/master/docs/reference/command-line.md Example of pairing --wait-gdb with --gdb to wait for a debugger connection before starting guest execution. ```sh --gdb 1234 --wait-gdb ``` -------------------------------- ### Example of jobs..steps[*].with Source: https://github.com/hexrayssa/rax/blob/master/docs/development/capi-releases/references/github-workflow-syntax.md Defines three input parameters (first_name, middle_name, last_name) for the hello_world action. These inputs are accessible as INPUT_FIRST_NAME, INPUT_MIDDLE_NAME, and INPUT_LAST_NAME environment variables. ```yaml jobs: my_first_job: steps: - name: My first step uses: actions/hello_world@main with: first_name: Mona middle_name: The last_name: Octocat ``` -------------------------------- ### Filter pattern cheat sheet: valid and invalid YAML Source: https://github.com/hexrayssa/rax/blob/master/docs/development/capi-releases/references/github-workflow-syntax.md YAML examples showing valid and invalid filter patterns for paths and branches. Patterns starting with `*`, `[`, or `!` must be quoted to avoid YAML parse errors. The invalid examples create parse errors that prevent the workflow from running. ```yaml # Valid paths: - '**/README.md' # Invalid - creates a parse error that # prevents your workflow from running. paths: - **/README.md # Valid branches: [ main, 'release/v[0-9].[0-9]' ] # Invalid - creates a parse error branches: [ main, release/v[0-9].[0-9] ] ``` -------------------------------- ### Register forwarding hazard example: VMOV S0,R0; VMOV S1,R1; VADD D2,D1,D0 Source: https://github.com/hexrayssa/rax/blob/master/docs/specifications/arm/cortex_a72_software_optimization_guide_external.pdf Shows the abnormal scenario where two S-register writes (VMOV S0,R0 and VMOV S1,R1) are followed by a D-register read (VADD D2,D1,D0). The Cortex-A72 serializes the VADD until the S-register writes are committed, causing significant latency. This example is used to illustrate the hazard condition. ```assembly VMOV S0,R0 VMOV S1,R1 VADD D2, D1, D0 ``` -------------------------------- ### --kernel examples Source: https://github.com/hexrayssa/rax/blob/master/docs/reference/command-line.md Selects the guest image. Required for ordinary launch, not required when --checkpoint restores a self-contained snapshot. Supports various formats: vmlinux, bzImage, AArch64 Image, bare-metal ELF, bootable ISO, or firmware. ```sh --kernel linux/vmlinux --kernel linux-aarch64/Image --kernel program.elf --kernel /path/to/bootable.iso ``` -------------------------------- ### C example: crt_set_invalid_parameter_handler.c Source: https://github.com/hexrayssa/rax/blob/master/docs/specifications/windows/crt-foundation/allocation/set-invalid-parameter-handler-set-thread-local-invalid-parameter-handler.md Installs a custom invalid parameter handler that prints the function, file, line, and expression, then aborts. Disables assertion message boxes with _CrtSetReportMode. Compile with /Zi /MTd. ```C // crt_set_invalid_parameter_handler.c // compile with: /Zi /MTd #include #include #include // For _CrtSetReportMode void myInvalidParameterHandler(const wchar_t* expression, const wchar_t* function, const wchar_t* file, unsigned int line, uintptr_t pReserved) { wprintf(L"Invalid parameter detected in function %s." L" File: %s Line: %d\n", function, file, line); wprintf(L"Expression: %s\n", expression); abort(); } int main( ) { char* formatString; _invalid_parameter_handler oldHandler, newHandler; newHandler = myInvalidParameterHandler; oldHandler = _set_invalid_parameter_handler(newHandler); // Disable the message box for assertions. _CrtSetReportMode(_CRT_ASSERT, 0); // Call printf_s with invalid parameters. formatString = NULL; printf(formatString); } ``` ```Output Invalid parameter detected in function common_vfprintf. File: minkernel\crts\ucrt\src\appcrt\stdio\output.cpp Line: 32 Expression: format != nullptr ``` -------------------------------- ### C++17 Wrapper Usage Source: https://github.com/hexrayssa/rax/blob/master/docs/embedding.md Example of using the rax::Engine C++ wrapper to create an engine, write memory, hook code, set registers, start execution, and read a register value. ```APIDOC ## C++17 Wrapper ### Description Header-only RAII wrapper with typed access, exceptions, and lambda hooks. ### Usage Example ```cpp #include rax::Engine engine(rax::Arch::X86, RAX_MODE_64); engine.memWrite(0x1000, code); engine.hookCode([](rax::Engine&, std::uint64_t pc, std::uint32_t size) { // Observe one instruction on a stepping-capable engine. }); engine.setReg(RAX_X86_REG_RSP, std::uint64_t{0x8000}); engine.start(0x1000); auto result = engine.regU64(RAX_X86_REG_RAX); ``` ### Notes - The wrapper improves lifetime and error handling. - It does not make one engine safe for concurrent use. ``` -------------------------------- ### Transient execution attack example (Meltdown-style) Source: https://github.com/hexrayssa/rax/blob/master/docs/development/2506.17154v1.pdf Illustrates a transient execution attack pattern: a user-space process attempts to load a byte from kernel memory via ecx, which causes an exception. The second instruction, which depends on the loaded value, is never architecturally executed but may be transiently executed, leaking the kernel address through the cache. ```x86 assembly 1 movsx eax, byte [ecx] ;; kernel address. ;; ecx: The line below is never executed. 2 mov ebx, [ebx+eax] ;; Load contents of ebx+eax, an address ;; that depends on the contents of [ecx]. ``` -------------------------------- ### DebugMon_Handler overflow counter Source: https://github.com/hexrayssa/rax/blob/master/docs/specifications/arm/armv8.1-m_performance_monitoring_user_guide_ARM051-799564642-251.pdf Example DebugMonitor exception handler that increments a counter on each overflow. The user is responsible for writing this handler. ```c static uint32_t overflow_count; void DebugMon_Handler(void) { overflow_count++; return; } ``` -------------------------------- ### Example 2: Frame-chained, full-form with mirror Prolog & Epilog Source: https://github.com/hexrayssa/rax/blob/master/docs/specifications/windows/microsoft-docs/arm64-exception-handling.md Shows a frame-chained function with a full-form .xdata record and a mirror epilog. The Epilog Start Index [0] points to the same sequence of prolog unwind code. ```asm |Bar| PROC |$LN19| stp x19,x20,[sp,#-0x10]! // save_regp_x stp fp,lr,[sp,#-0x90]! // save_fplr_x mov fp,sp // set_fp // end of prolog ... // begin of epilog, a mirror sequence of Prolog mov sp,fp ldp fp,lr,[sp],#0x90 ldp x19,x20,[sp],#0x10 ret lr |$pdata$Bar| DCD imagerel |$LN19| DCD imagerel |$unwind$cse2| |$unwind$Bar| DCD 0x1040003d DCD 0x1000038 DCD 0xe42291e1 DCD 0xe42291e1 ;Code Words[2], Epilog Count[1], E[0], X[0], Function Length[6660] ;Epilog Start Index[0], Epilog Start Offset[56] ;set_fp ;save_fplr_x ;save_r19r20_x ;end ``` -------------------------------- ### Example 3: Variadic unchained Function Source: https://github.com/hexrayssa/rax/blob/master/docs/specifications/windows/microsoft-docs/arm64-exception-handling.md Shows a variadic unchained function with a full-form .xdata record. The Epilog Start Index [4] points to the middle of the prolog unwind code, partially reusing the unwind array. ```asm |Delegate| PROC |$LN4| sub sp,sp,#0x50 stp x19,lr,[sp] stp x0,x1,[sp,#0x10] // save incoming register to home area stp x2,x3,[sp,#0x20] // ... stp x4,x5,[sp,#0x30] stp x6,x7,[sp,#0x40] // end of prolog ... ldp x19,lr,[sp] // beginning of epilog add sp,sp,#0x50 ret lr AREA |.pdata|, PDATA |$pdata$Delegate| DCD imagerel |$LN4| DCD imagerel |$unwind$Delegate| AREA |.xdata|, DATA |$unwind$Delegate| DCD 0x18400012 DCD 0x200000f DCD 0xe3e3e3e3 DCD 0xe40500d6 DCD 0xe40500d6 ;Code Words[3], Epilog Count[1], E[0], X[0], Function Length[18] ;Epilog Start Index[4], Epilog Start Offset[15] ;nop // nop for saving in home area ;nop // ditto ;nop // ditto ;nop // ditto ;save_lrpair ;alloc_s ;end ``` -------------------------------- ### Create a ring buffer with VirtualAlloc2 and MapViewOfFile3 Source: https://github.com/hexrayssa/rax/blob/master/docs/specifications/windows/services/shared-memory/nf-memoryapi-virtualalloc2.md This example creates a ring buffer by allocating a pagefile-backed section and mapping two views of that section next to each other, allowing linear access even when the buffer wraps. It uses VirtualAlloc2 with MEM_RESERVE_PLACEHOLDER, VirtualFree with MEM_PRESERVE_PLACEHOLDER, and MapViewOfFile3 with MEM_REPLACE_PLACEHOLDER. The buffer size must be a multiple of the system allocation granularity. ```cpp #include #include #include // // This function creates a ring buffer by allocating a pagefile-backed section // and mapping two views of that section next to each other. This way if the // last record in the buffer wraps it can still be accessed in a linear fashion // using its base VA. // void* CreateRingBuffer ( unsigned int bufferSize, _Outptr_ void** secondaryView ) { BOOL result; HANDLE section = nullptr; SYSTEM_INFO sysInfo; void* ringBuffer = nullptr; void* placeholder1 = nullptr; void* placeholder2 = nullptr; void* view1 = nullptr; void* view2 = nullptr; GetSystemInfo (&sysInfo); if ((bufferSize % sysInfo.dwAllocationGranularity) != 0) { return nullptr; } // // Reserve a placeholder region where the buffer will be mapped. // placeholder1 = (PCHAR) VirtualAlloc2 ( nullptr, nullptr, 2 * bufferSize, MEM_RESERVE | MEM_RESERVE_PLACEHOLDER, PAGE_NOACCESS, nullptr, 0 ); if (placeholder1 == nullptr) { printf ("VirtualAlloc2 failed, error %#x\n", GetLastError()); goto Exit; } // // Split the placeholder region into two regions of equal size. // result = VirtualFree ( placeholder1, bufferSize, MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER ); if (result == FALSE) { printf ("VirtualFreeEx failed, error %#x\n", GetLastError()); goto Exit; } placeholder2 = (void*) ((ULONG_PTR) placeholder1 + bufferSize); // // Create a pagefile-backed section for the buffer. // section = CreateFileMapping ( INVALID_HANDLE_VALUE, nullptr, PAGE_READWRITE, 0, bufferSize, nullptr ); if (section == nullptr) { printf ("CreateFileMapping failed, error %#x\n", GetLastError()); goto Exit; } // // Map the section into the first placeholder region. // view1 = MapViewOfFile3 ( section, nullptr, placeholder1, 0, bufferSize, MEM_REPLACE_PLACEHOLDER, PAGE_READWRITE, nullptr, 0 ); if (view1 == nullptr) { printf ("MapViewOfFile3 failed, error %#x\n", GetLastError()); goto Exit; } // // Ownership transferred, don't free this now. // placeholder1 = nullptr; // // Map the section into the second placeholder region. // view2 = MapViewOfFile3 ( section, nullptr, placeholder2, 0, bufferSize, MEM_REPLACE_PLACEHOLDER, PAGE_READWRITE, nullptr, 0 ); if (view2 == nullptr) { printf ("MapViewOfFile3 failed, error %#x\n", GetLastError()); goto Exit; } // // Success, return both mapped views to the caller. // ringBuffer = view1; *secondaryView = view2; placeholder2 = nullptr; view1 = nullptr; view2 = nullptr; Exit: if (section != nullptr) { CloseHandle (section); } if (placeholder1 != nullptr) { VirtualFree (placeholder1, 0, MEM_RELEASE); } if (placeholder2 != nullptr) { VirtualFree (placeholder2, 0, MEM_RELEASE); } if (view1 != nullptr) { UnmapViewOfFileEx (view1, 0); } if (view2 != nullptr) { UnmapViewOfFileEx (view2, 0); } return ringBuffer; } int __cdecl wmain() { char* ringBuffer; void* secondaryView; unsigned int bufferSize = 0x10000; ringBuffer = (char*) CreateRingBuffer (bufferSize, &secondaryView); if (ringBuffer == nullptr) { printf ("CreateRingBuffer failed\n"); return 0; } // // Make sure the buffer wraps properly. // ringBuffer[0] = 'a'; if (ringBuffer[bufferSize] == 'a') { printf ("The buffer wraps as expected\n"); } UnmapViewOfFile (ringBuffer); UnmapViewOfFile (secondaryView); } ``` -------------------------------- ### Build and run x86-64 software Linux path Source: https://github.com/hexrayssa/rax/blob/master/docs/getting-started/linux-guests.md Build an uncompressed ELF kernel and launch it with the repository initramfs using the maintained helper path. `make linux` obtains the configured Linux source release and builds `linux/vmlinux`; the helper script uses `initrd.cpio.gz` and a command line chosen for the current software machine. ```sh make linux make run-linux ``` -------------------------------- ### Handle multiple PMU counter overflows in DebugMon_Handler Source: https://github.com/hexrayssa/rax/blob/master/docs/specifications/arm/armv8.1-m_performance_monitoring_user_guide_ARM051-799564642-251.pdf Handles multiple PMU counter overflows in DebugMon_Handler() by looping through each set overflow bit. Reads and clears the overflow status, then uses __CLZ to find the highest set bit, increments the corresponding overflow_count, and clears that bit until no overflow bits remain. The note suggests temporarily disabling the counters that caused the interrupt at the start of the handler and re-enabling them before returning. ```c /* Create a word array for each counters' overflows count */ static uint32_t overflow_count[__PMU_NUM_EVENTCNT+1]; void DebugMon_Handler(void) { uint32_t temp; /* Read PMU overflow status */ uint32_t pmu_overflow_status = ARM_PMU_Get_CNTR_OVS(); /* Clear overflow status */ ARM_PMU_Set_CNTR_OVS(pmu_overflow_status); while(pmu_overflow_status) { /* Count leading zeroes to find out the highest bit position set */ temp = __CLZ(pmu_overflow_status); /* Calculate trailing zeroes: take away no. of leading zeroes from no. of reg bits */ temp = (32 -temp)-1; /* Increment overflow count for counter that overflowed */ overflow_count[temp]++; /* Clear highest overflow bit set */ pmu_overflow_status &= ~(1UL << temp); } return; } ``` -------------------------------- ### Example of jobs..steps[*].with.args Source: https://github.com/hexrayssa/rax/blob/master/docs/development/capi-releases/references/github-workflow-syntax.md Shows how to pass arguments to a Docker container action using the with.args parameter. The args are passed to the container's ENTRYPOINT and replace the CMD instruction in the Dockerfile. ```yaml steps: - name: Explain why this job ran uses: octo-org/action-name@main with: entrypoint: /bin/echo args: The ${{ github.event_name }} event triggered this step. ``` -------------------------------- ### Concatenate overflow count with counter value Source: https://github.com/hexrayssa/rax/blob/master/docs/specifications/arm/armv8.1-m_performance_monitoring_user_guide_ARM051-799564642-251.pdf Combines the overflow count with the current counter value to form a larger 48-bit counter. The example uses Event Counter 3 to count retired instructions. ```c /* Create 64-bit variable for storing 48-bit counter value */ Uint64_t count_combined; /* Read Event Counter Register 3 */ instructions_retired_count = ARM_PMU_Get_EVCNTR(3); /* Concatenate current value for Event Counter 3 with its overflow Count */ count_combined = (unsigned long long(overflow_count << 16)) | PMU_EVCNTR_CNT_Msk & instructions_retired_count); ``` -------------------------------- ### Run executable from command line to initialize _pgmptr Source: https://github.com/hexrayssa/rax/blob/master/docs/specifications/windows/crt-startup/microsoft/pgmptr-wpgmptr.md Example command that triggers initialization of _pgmptr to the full path of the executable (e.g., C:\BIN\Hello.exe) when run from the command interpreter. ```cmd C> hello ``` -------------------------------- ### Build and run with instruction tracing (--trace) Source: https://github.com/hexrayssa/rax/blob/master/docs/reference/command-line.md Shows how to build with the trace feature and run the emulator with --trace. The trace Cargo feature is required. The interpreter owns the instruction step loop; KVM/HVF do not become equivalent instruction-trace sources through this option. ```sh cargo build --release --features trace ./target/release/rax ... --backend emulator --trace boot.trace ``` -------------------------------- ### Build and run rax-user with a static guest Source: https://github.com/hexrayssa/rax/blob/master/docs/getting-started/overview.md Build the rax-user binary and run a checked-in static guest. The fixture prints its argument/environment report and exits with 41 by design (40 + argc), exercising guest exit-status propagation. ```sh cargo build --release --locked --no-default-features --features smir-jit --bin rax-user ./target/release/rax-user tests/fixtures/user/linux/bin/aarch64/hello ``` -------------------------------- ### Run x86-64 guest with trace and snapshots Source: https://github.com/hexrayssa/rax/blob/master/docs/reference/command-line.md Runs a software x86-64 guest with trace output to boot.trace, snapshots at cycles 1000000 and 10000000 saved to snapshots/, and a manual snapshot written to manual.rxc. ```sh ./target/release/rax \ --arch x86-64 \ --backend emulator \ --memory 1G \ --kernel linux/vmlinux \ --initrd initrd.cpio.gz \ --trace boot.trace \ --snapshot-at 1000000,10000000 \ --snapshot-dir snapshots \ --snapshot-out manual.rxc ``` -------------------------------- ### RAX_JIT_VERIFY example Source: https://github.com/hexrayssa/rax/blob/master/docs/reference/environment-variables.md Enables runtime comparison for supported x86-64 compiled regions. Verification is scoped and not formal proof; may alter performance substantially. ```sh RAX_JIT_VERIFY=1 ./target/release/rax ... ``` -------------------------------- ### Example input Source: https://github.com/hexrayssa/rax/blob/master/docs/specifications/windows/crt-stdio/microsoft/clearerr.md The input provided to the example program, which is a single character 'n'. ```Input n ``` -------------------------------- ### Output of crt_fdopen example Source: https://github.com/hexrayssa/rax/blob/master/docs/specifications/windows/crt-stdio/microsoft/fdopen-wfdopen.md The expected output when running the example program with the provided input file. ```text Lines in file: 2 ``` -------------------------------- ### Build workspace with x86_64-suite and smir-jit features Source: https://github.com/hexrayssa/rax/blob/master/docs/architecture/user-mode/windows-crt-initializers.md Builds the entire workspace with all targets, no default features, and the x86_64-suite and smir-jit features enabled. Passed in 20.35 seconds. Both builds reported a pre-existing library filename collision, so this is not warning-free validation. ```bash cargo +stable build --locked --workspace --all-targets --no-default-features --features x86_64-suite,smir-jit ``` -------------------------------- ### Run initial quick tests with make test-quick Source: https://github.com/hexrayssa/rax/blob/master/docs/getting-started/overview.md Runs the initial quick test suite. A zero exit status may indicate that prerequisites were absent and the suite deliberately skipped, so check the output for skips. ```sh make test-quick ``` -------------------------------- ### Example: crt_exit.c Source: https://github.com/hexrayssa/rax/blob/master/docs/specifications/windows/crt-initializers/microsoft/exit-exit-exit.md Complete example that calls exit with status 1, which can be tested in a batch file. Requires or . ```C // crt_exit.c // This program returns an exit code of 1. The // error code could be tested in a batch file. #include int main( void ) { exit( 1 ); } ``` -------------------------------- ### Output of crt_matherr.c example Source: https://github.com/hexrayssa/rax/blob/master/docs/specifications/windows/crt-bootstrap/microsoft/matherr.md Output of the crt_matherr.c example. Shows the custom handling for _DOMAIN errors and the default handling for other errors. ```output Special: using absolute value: log: _DOMAIN error log( -2.0 ) = 6.931472e-01 Special: using absolute value: log10: _DOMAIN error log10( -5.0 ) = 6.989700e-01 Normal: log( 0.0 ) = -inf ``` -------------------------------- ### atexit example program Source: https://github.com/hexrayssa/rax/blob/master/docs/specifications/windows/crt-initializers/microsoft/atexit.md Registers four functions with atexit and prints a message. On exit, the functions run in LIFO order, producing the output shown. ```C // crt_atexit.c #include #include void fn1( void ), fn2( void ), fn3( void ), fn4( void ); int main( void ) { atexit( fn1 ); atexit( fn2 ); atexit( fn3 ); atexit( fn4 ); printf( "This is executed first.\n" ); } void fn1() { printf( "next.\n" ); } void fn2() { printf( "executed " ); } void fn3() { printf( "is " ); } void fn4() { printf( "This " ); } ``` ```Output This is executed first. This is executed next. ``` -------------------------------- ### PGO_TARGET_CPU usage example Source: https://github.com/hexrayssa/rax/blob/master/docs/reference/environment-variables.md Example of setting PGO_TARGET_CPU to an explicit baseline when the output must run elsewhere. The script defaults to 'native'. ```sh PGO_TARGET_CPU=x86-64-v3 make pgo ``` -------------------------------- ### Example of jobs..uses Source: https://github.com/hexrayssa/rax/blob/master/docs/development/capi-releases/references/github-workflow-syntax.md Shows the supported syntaxes for jobs..uses: {owner}/{repo}/.github/workflows/{filename}@{ref}, ./.github/workflows/{filename}, and $/.github/workflows/{filename}. The $/ syntax is not available in GitHub Enterprise Server and must not include an @{ref} suffix. ```yaml jobs: call-workflow-1-in-local-repo: uses: octo-org/this-repo/.github/workflows/workflow-1.yml@172239021f7ba04fe7327647b213799853a9eb89 call-workflow-2-in-local-repo: uses: ./.github/workflows/workflow-2.yml # The `$/` syntax is not available in GitHub Enterprise Server. call-workflow-in-same-repo-at-running-commit: uses: $/.github/workflows/workflow-2.yml call-workflow-in-another-repo: uses: octo-org/another-repo/.github/workflows/workflow.yml@v1 ``` -------------------------------- ### RAX_KERNEL usage example Source: https://github.com/hexrayssa/rax/blob/master/docs/reference/environment-variables.md Example of setting the RAX_KERNEL environment variable to override the default kernel path when running the run.sh helper. ```sh RAX_KERNEL=/tmp/linux/vmlinux ./run.sh ``` -------------------------------- ### Example output for crt_get_errno.c Source: https://github.com/hexrayssa/rax/blob/master/docs/specifications/windows/crt-foundation/allocation/get-errno.md Shows the expected output of the example program, indicating that errno is set to 2 (ENOENT) after attempting to open a nonexistent file. ```Output errno = 2 fyi, ENOENT = 2 ```