Skip to content

Commit 75d7d70

Browse files
SchmErikflaubshkoonategrafweikengchen
committed
zkvm: add partial std support
Co-authored-by: Frank Laub <[email protected]> Co-authored-by: nils <[email protected]> Co-authored-by: Victor Graf <[email protected]> Co-authored-by: weikengchen <[email protected]>
1 parent 966b94e commit 75d7d70

File tree

11 files changed

+487
-5
lines changed

11 files changed

+487
-5
lines changed

library/std/build.rs

+1
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@ fn main() {
3535
|| target.contains("hurd")
3636
|| target.contains("uefi")
3737
|| target.contains("teeos")
38+
|| target.contains("zkvm")
3839
// See src/bootstrap/synthetic_targets.rs
3940
|| env::var("RUSTC_BOOTSTRAP_SYNTHETIC_TARGET").is_ok()
4041
{

library/std/src/sys/pal/common/alloc.rs

+5-5
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ use crate::ptr;
1616
target_arch = "sparc",
1717
target_arch = "wasm32",
1818
target_arch = "hexagon",
19-
all(target_arch = "riscv32", not(target_os = "espidf")),
19+
all(target_arch = "riscv32", not(any(target_os = "espidf", target_os = "zkvm"))),
2020
all(target_arch = "xtensa", not(target_os = "espidf")),
2121
))]
2222
pub const MIN_ALIGN: usize = 8;
@@ -32,11 +32,11 @@ pub const MIN_ALIGN: usize = 8;
3232
target_arch = "wasm64",
3333
))]
3434
pub const MIN_ALIGN: usize = 16;
35-
// The allocator on the esp-idf platform guarantees 4 byte alignment.
36-
#[cfg(any(
37-
all(target_arch = "riscv32", target_os = "espidf"),
35+
// The allocator on the esp-idf and zkvm platforms guarantee 4 byte alignment.
36+
#[cfg(all(any(
37+
all(target_arch = "riscv32", any(target_os = "espidf", target_os = "zkvm")),
3838
all(target_arch = "xtensa", target_os = "espidf"),
39-
))]
39+
)))]
4040
pub const MIN_ALIGN: usize = 4;
4141

4242
pub unsafe fn realloc_fallback(

library/std/src/sys/pal/mod.rs

+3
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,9 @@ cfg_if::cfg_if! {
5555
} else if #[cfg(target_os = "teeos")] {
5656
mod teeos;
5757
pub use self::teeos::*;
58+
} else if #[cfg(target_os = "zkvm")] {
59+
mod zkvm;
60+
pub use self::zkvm::*;
5861
} else {
5962
mod unsupported;
6063
pub use self::unsupported::*;

library/std/src/sys/pal/zkvm/abi.rs

+55
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
//! ABI definitions for symbols exported by risc0-zkvm-platform.
2+
3+
// Included here so we don't have to depend on risc0-zkvm-platform.
4+
//
5+
// FIXME: Should we move this to the "libc" crate? It seems like other
6+
// architectures put a lot of this kind of stuff there. But there's
7+
// currently no risc0 fork of the libc crate, so we'd either have to
8+
// fork it or upstream it.
9+
10+
#![allow(dead_code)]
11+
pub const DIGEST_WORDS: usize = 8;
12+
13+
/// Standard IO file descriptors for use with sys_read and sys_write.
14+
pub mod fileno {
15+
pub const STDIN: u32 = 0;
16+
pub const STDOUT: u32 = 1;
17+
pub const STDERR: u32 = 2;
18+
pub const JOURNAL: u32 = 3;
19+
}
20+
21+
extern "C" {
22+
// Wrappers around syscalls provided by risc0-zkvm-platform:
23+
pub fn sys_halt();
24+
pub fn sys_output(output_id: u32, output_value: u32);
25+
pub fn sys_sha_compress(
26+
out_state: *mut [u32; DIGEST_WORDS],
27+
in_state: *const [u32; DIGEST_WORDS],
28+
block1_ptr: *const [u32; DIGEST_WORDS],
29+
block2_ptr: *const [u32; DIGEST_WORDS],
30+
);
31+
pub fn sys_sha_buffer(
32+
out_state: *mut [u32; DIGEST_WORDS],
33+
in_state: *const [u32; DIGEST_WORDS],
34+
buf: *const u8,
35+
count: u32,
36+
);
37+
pub fn sys_rand(recv_buf: *mut u32, words: usize);
38+
pub fn sys_panic(msg_ptr: *const u8, len: usize) -> !;
39+
pub fn sys_log(msg_ptr: *const u8, len: usize);
40+
pub fn sys_cycle_count() -> usize;
41+
pub fn sys_read(fd: u32, recv_buf: *mut u8, nrequested: usize) -> usize;
42+
pub fn sys_write(fd: u32, write_buf: *const u8, nbytes: usize);
43+
pub fn sys_getenv(
44+
recv_buf: *mut u32,
45+
words: usize,
46+
varname: *const u8,
47+
varname_len: usize,
48+
) -> usize;
49+
pub fn sys_argc() -> usize;
50+
pub fn sys_argv(out_words: *mut u32, out_nwords: usize, arg_index: usize) -> usize;
51+
52+
// Allocate memory from global HEAP.
53+
pub fn sys_alloc_words(nwords: usize) -> *mut u32;
54+
pub fn sys_alloc_aligned(nwords: usize, align: usize) -> *mut u8;
55+
}

library/std/src/sys/pal/zkvm/alloc.rs

+15
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
use super::abi;
2+
use crate::alloc::{GlobalAlloc, Layout, System};
3+
4+
#[stable(feature = "alloc_system_type", since = "1.28.0")]
5+
unsafe impl GlobalAlloc for System {
6+
#[inline]
7+
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
8+
abi::sys_alloc_aligned(layout.size(), layout.align())
9+
}
10+
11+
#[inline]
12+
unsafe fn dealloc(&self, _ptr: *mut u8, _layout: Layout) {
13+
// this allocator never deallocates memory
14+
}
15+
}

library/std/src/sys/pal/zkvm/args.rs

+80
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
use super::{abi, WORD_SIZE};
2+
use crate::ffi::OsString;
3+
use crate::fmt;
4+
use crate::sys_common::FromInner;
5+
6+
pub struct Args {
7+
i_forward: usize,
8+
i_back: usize,
9+
count: usize,
10+
}
11+
12+
pub fn args() -> Args {
13+
let count = unsafe { abi::sys_argc() };
14+
Args { i_forward: 0, i_back: 0, count }
15+
}
16+
17+
impl Args {
18+
/// Use sys_argv to get the arg at the requested index. Does not check that i is less than argc
19+
/// and will not return if the index is out of bounds.
20+
fn argv(i: usize) -> OsString {
21+
let arg_len = unsafe { abi::sys_argv(crate::ptr::null_mut(), 0, i) };
22+
23+
let arg_len_words = (arg_len + WORD_SIZE - 1) / WORD_SIZE;
24+
let words = unsafe { abi::sys_alloc_words(arg_len_words) };
25+
26+
let arg_len2 = unsafe { abi::sys_argv(words, arg_len_words, i) };
27+
debug_assert_eq!(arg_len, arg_len2);
28+
29+
// Convert to OsString.
30+
//
31+
// FIXME: We can probably get rid of the extra copy here if we
32+
// reimplement "os_str" instead of just using the generic unix
33+
// "os_str".
34+
let arg_bytes: &[u8] =
35+
unsafe { crate::slice::from_raw_parts(words.cast() as *const u8, arg_len) };
36+
OsString::from_inner(super::os_str::Buf { inner: arg_bytes.to_vec() })
37+
}
38+
}
39+
40+
impl fmt::Debug for Args {
41+
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
42+
f.debug_list().finish()
43+
}
44+
}
45+
46+
impl Iterator for Args {
47+
type Item = OsString;
48+
49+
fn next(&mut self) -> Option<OsString> {
50+
if self.i_forward >= self.count - self.i_back {
51+
None
52+
} else {
53+
let arg = Self::argv(self.i_forward);
54+
self.i_forward += 1;
55+
Some(arg)
56+
}
57+
}
58+
59+
fn size_hint(&self) -> (usize, Option<usize>) {
60+
(self.count, Some(self.count))
61+
}
62+
}
63+
64+
impl ExactSizeIterator for Args {
65+
fn len(&self) -> usize {
66+
self.count
67+
}
68+
}
69+
70+
impl DoubleEndedIterator for Args {
71+
fn next_back(&mut self) -> Option<OsString> {
72+
if self.i_back >= self.count - self.i_forward {
73+
None
74+
} else {
75+
let arg = Self::argv(self.count - 1 - self.i_back);
76+
self.i_back += 1;
77+
Some(arg)
78+
}
79+
}
80+
}

library/std/src/sys/pal/zkvm/env.rs

+9
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
pub mod os {
2+
pub const FAMILY: &str = "";
3+
pub const OS: &str = "";
4+
pub const DLL_PREFIX: &str = "";
5+
pub const DLL_SUFFIX: &str = ".elf";
6+
pub const DLL_EXTENSION: &str = "elf";
7+
pub const EXE_SUFFIX: &str = ".elf";
8+
pub const EXE_EXTENSION: &str = "elf";
9+
}

library/std/src/sys/pal/zkvm/mod.rs

+93
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,93 @@
1+
//! System bindings for the risc0 zkvm platform
2+
//!
3+
//! This module contains the facade (aka platform-specific) implementations of
4+
//! OS level functionality for zkvm.
5+
//!
6+
//! This is all super highly experimental and not actually intended for
7+
//! wide/production use yet, it's still all in the experimental category. This
8+
//! will likely change over time.
9+
10+
const WORD_SIZE: usize = core::mem::size_of::<u32>();
11+
12+
pub mod alloc;
13+
#[path = "../zkvm/args.rs"]
14+
pub mod args;
15+
#[path = "../unix/cmath.rs"]
16+
pub mod cmath;
17+
pub mod env;
18+
#[path = "../unsupported/fs.rs"]
19+
pub mod fs;
20+
#[path = "../unsupported/io.rs"]
21+
pub mod io;
22+
#[path = "../unsupported/net.rs"]
23+
pub mod net;
24+
#[path = "../unsupported/once.rs"]
25+
pub mod once;
26+
pub mod os;
27+
#[path = "../unix/os_str.rs"]
28+
pub mod os_str;
29+
#[path = "../unix/path.rs"]
30+
pub mod path;
31+
#[path = "../unsupported/pipe.rs"]
32+
pub mod pipe;
33+
#[path = "../unsupported/process.rs"]
34+
pub mod process;
35+
pub mod stdio;
36+
pub mod thread_local_key;
37+
#[path = "../unsupported/time.rs"]
38+
pub mod time;
39+
40+
#[path = "../unsupported/locks/mod.rs"]
41+
pub mod locks;
42+
#[path = "../unsupported/thread.rs"]
43+
pub mod thread;
44+
45+
#[path = "../unsupported/thread_parking.rs"]
46+
pub mod thread_parking;
47+
48+
mod abi;
49+
50+
use crate::io as std_io;
51+
52+
pub mod memchr {
53+
pub use core::slice::memchr::{memchr, memrchr};
54+
}
55+
56+
// SAFETY: must be called only once during runtime initialization.
57+
// NOTE: this is not guaranteed to run, for example when Rust code is called externally.
58+
pub unsafe fn init(_argc: isize, _argv: *const *const u8, _sigpipe: u8) {}
59+
60+
// SAFETY: must be called only once during runtime cleanup.
61+
// NOTE: this is not guaranteed to run, for example when the program aborts.
62+
pub unsafe fn cleanup() {}
63+
64+
pub fn unsupported<T>() -> std_io::Result<T> {
65+
Err(unsupported_err())
66+
}
67+
68+
pub fn unsupported_err() -> std_io::Error {
69+
std_io::const_io_error!(
70+
std_io::ErrorKind::Unsupported,
71+
"operation not supported on this platform",
72+
)
73+
}
74+
75+
pub fn is_interrupted(_code: i32) -> bool {
76+
false
77+
}
78+
79+
pub fn decode_error_kind(_code: i32) -> crate::io::ErrorKind {
80+
crate::io::ErrorKind::Uncategorized
81+
}
82+
83+
pub fn abort_internal() -> ! {
84+
core::intrinsics::abort();
85+
}
86+
87+
pub fn hashmap_random_keys() -> (u64, u64) {
88+
let mut buf = [0u32; 4];
89+
unsafe {
90+
abi::sys_rand(buf.as_mut_ptr(), 4);
91+
};
92+
((buf[0] as u64) << 32 + buf[1] as u64, (buf[2] as u64) << 32 + buf[3] as u64)
93+
}

0 commit comments

Comments
 (0)