如何在生锈中创建并传递以空值终止的C字符串数组(char **)?

时间:2022-09-06 21:24:15

I'm playing around with a new init system with #![no_std] and extern crate rlibc and making syscalls with asm, and currently trying to not allocate memory either. So the scope of possible tools I have is limited.

我正在使用#![no_std]和extern crate rlibc以及使用asm进行系统调用的新init系统,并且当前也尝试不分配内存。所以我所拥有的可能工具的范围是有限的。

I need to call the execve syscall, and it requires a char** argv, and a char **envp. I can hack together c-style strings as arrays of bytes with zeros, but how can I null-terminate a statically declared list of such (the last pointer being NULL)?

我需要调用execve系统调用,它需要一个char ** argv和一个char ** envp。我可以将c样式的字符串作为零的字节数组合在一起,但是我怎么能无效地终止静态声明的这样的列表(最后一个指针是NULL)?

1 个解决方案

#1


5  

After sleeping on this, I woke up with the answer, and it seems obvious to me now. Use slices of integers and set the last one to 0.

在睡觉之后,我醒了回答,现在我觉得很明显。使用整数切片并将最后一个设置为0。

// Execute something as an example:
let filename: &[u8] = b"/usr/bin/sensors\x00";     // <-- Make c strings like this
let argv1: &[u8] = b"/usr/bin/sensors\x00";
let argv2: &[u8] = b"-h\x00";
let argv: &[int] = [                               // <-- store them in this
    ::core::intrinsics::transmute(argv1.as_ptr()), // <-- transmuting 
    ::core::intrinsics::transmute(argv2.as_ptr()),
    0                                              // <-- and NULL terminate
];
let envp: &[int] = [0];

::linux64::execve(filename,argv,envp);

#1


5  

After sleeping on this, I woke up with the answer, and it seems obvious to me now. Use slices of integers and set the last one to 0.

在睡觉之后,我醒了回答,现在我觉得很明显。使用整数切片并将最后一个设置为0。

// Execute something as an example:
let filename: &[u8] = b"/usr/bin/sensors\x00";     // <-- Make c strings like this
let argv1: &[u8] = b"/usr/bin/sensors\x00";
let argv2: &[u8] = b"-h\x00";
let argv: &[int] = [                               // <-- store them in this
    ::core::intrinsics::transmute(argv1.as_ptr()), // <-- transmuting 
    ::core::intrinsics::transmute(argv2.as_ptr()),
    0                                              // <-- and NULL terminate
];
let envp: &[int] = [0];

::linux64::execve(filename,argv,envp);