Skip to content

Instantly share code, notes, and snippets.

@woxtu
Last active July 10, 2021 03:35
Show Gist options
  • Save woxtu/57697a2f1c51b4e59e87a4b7f9f92047 to your computer and use it in GitHub Desktop.
Save woxtu/57697a2f1c51b4e59e87a4b7f9f92047 to your computer and use it in GitHub Desktop.
Write bash builtin command in Rust
[package]
name = "hello_world"
version = "0.1.0"
authors = []
[lib]
name = "hello_world"
path = "./lib.rs"
crate-type = ["cdylib"]
#![allow(non_camel_case_types, non_upper_case_globals)]
use std::marker::Sync;
use std::os::raw::{c_char, c_int};
const EXECUTION_SUCCESS: c_int = 0;
const BUILTIN_ENABLED: c_int = 0x01;
#[repr(C)]
pub struct WORD_DESC {
word: *mut c_char,
dollar_present: c_int,
quoted: c_int,
assignment: c_int,
}
#[repr(C)]
pub struct WORD_LIST {
next: *mut WORD_LIST,
word: *mut WORD_DESC,
}
pub type sh_builtin_func_t = extern fn (*mut WORD_LIST) -> c_int;
#[repr(C)]
pub struct builtin {
name: *mut c_char,
function: sh_builtin_func_t,
flags: c_int,
long_doc: *mut *const c_char,
short_doc: *mut c_char,
handle: *mut c_char,
}
unsafe impl Sync for builtin {}
pub extern fn hello_world(_list: *mut WORD_LIST) -> c_int {
println!("Hello, World!");
EXECUTION_SUCCESS
}
const LONG_DOC: &'static [*const c_char] = &[
b"Show a greeting message.\0" as *const _ as *const _,
b"\0" as *const _ as *const _,
b"It's far faster than launching executable file\0" as *const _ as *const _,
b"because it't not necessary to call exec() and fork().\0" as *const _ as *const _,
0 as *const _,
];
#[no_mangle]
pub static mut hello_world_struct: builtin = builtin {
name: b"hello_world\0" as *const _ as *mut _,
function: hello_world,
flags: BUILTIN_ENABLED,
long_doc: LONG_DOC as *const _ as *mut _,
short_doc: b"hello_world\0" as *const _ as *mut _,
handle: 0 as *mut _,
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment