I am creating a code to be able to print text on the screen with the rust macro (asm!) and this is the code:
fn printmsg(string: &str) {
let length: usize = string.len();
unsafe {
asm!("syscall" :: "{rax}"(1), "{rdi}"(1), "{rsi}"(&string), "{rdx}"(length));
}
}
fn main() {
let s = "hello world!";
printmsg(s);
}
When I run the code it prints random letters...
How do I get it to print "hello world!" and not something else?
A string slice consists of a pointer to the string and a length. If you pass the output by
od
you get:The first 8 are a pointer, the next (0x0c = 12) are the length. Another way of looking at it:
To access the pointer to the actual string, the () method can be used
as_ptr
.Note that this string is not terminated by a NUL byte, so if you wanted to pass it to a library written in C or similar you would have to convert it to
CString
del modulestd::ffi::CString
.