1 unstable release

0.0.1-alpha Jul 2, 2020

#19 in #assemble

Download history 129/week @ 2024-05-20 93/week @ 2024-05-27 135/week @ 2024-06-03 147/week @ 2024-06-10 113/week @ 2024-06-17 75/week @ 2024-06-24 203/week @ 2024-07-01 129/week @ 2024-07-08 280/week @ 2024-07-15 287/week @ 2024-07-22 332/week @ 2024-07-29 320/week @ 2024-08-05 286/week @ 2024-08-12 247/week @ 2024-08-19 365/week @ 2024-08-26 112/week @ 2024-09-02

1,011 downloads per month
Used in syscall-linux-raw

Unlicense

29KB
618 lines

direct-asm

A Rust proc-macro to include pre-assembled instructions as a function call.

What

use libc::{c_int, c_void, size_t, ssize_t, c_long};

// Call write as a syscall on SysV x86-64 abi.
// WIP: The constant SYS_write needs to be provided by the caller for now.
#[direct_asm::assemble]
unsafe extern "C" 
fn sys_write(fd: c_int, ptr: *const c_void, len: size_t, wcall: c_long)
    -> ssize_t 
{
    "mov rax, rcx"; // Move sys call number to rax as required
    // Other arguments are already in correct register
    "syscall"; // Invoke actual system call placed in rax
    "ret" //Return actual result
}

fn sys_print(what: &str) -> libc::ssize_t {
    unsafe {
        sys_write(1, what.as_ptr() as *const libc::c_void, what.len(), SYS_write)
    }
}

Why

To show an alternative to inline-asm from gcc, possibly with more control while having well defined semantics. This will not be sufficient for all purposes but it is enough to read stack registers, to make system calls (I think) and much more. The included code must be position independent, has no access to globals (pass as arguments instead), and can not introduce any new symbols.

How

By aliasing two definitions with #[no_mangle] abuse. We precompile the asm using nasm into a raw binary form, then define a static byte array containing this code in the .text section and finally define an extern "C" function with the same symbol name. The linker then resolve that function to the array definition and hence calls the code as intended.

Wtf

Indeed. Don't use in prod.

Demo?

Within the minimal-rust folder we build a 186-byte binary on stable Rust.

License

The base software: Unlicense

The modified dynasm backend: Mozilla Public License Version 2.0

Dependencies

~3MB
~60K SLoC