-
Notifications
You must be signed in to change notification settings - Fork 21
/
Copy pathwasi_ctx_builder.rs
383 lines (341 loc) · 13.5 KB
/
wasi_ctx_builder.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
use super::{root, WasiCtx};
use crate::error;
use crate::helpers::OutputLimitedBuffer;
use cap_std::fs::Dir;
use magnus::{
class, function, gc::Marker, method, typed_data::Obj, value::Opaque, DataTypeFunctions, Error,
Integer, Module, Object, RArray, RHash, RString, Ruby, TryConvert, TypedData,
};
use std::cell::RefCell;
use std::path::Path;
use std::{fs::File, path::PathBuf};
use wasi_common::pipe::{ReadPipe, WritePipe};
enum ReadStream {
Inherit,
Path(Opaque<RString>),
String(Opaque<RString>),
}
impl ReadStream {
pub fn mark(&self, marker: &Marker) {
match self {
Self::Inherit => (),
Self::Path(s) => marker.mark(*s),
Self::String(s) => marker.mark(*s),
}
}
}
enum WriteStream {
Inherit,
Path(Opaque<RString>),
Buffer(Opaque<RString>, usize),
}
impl WriteStream {
pub fn mark(&self, marker: &Marker) {
match self {
Self::Inherit => (),
Self::Path(v) => marker.mark(*v),
Self::Buffer(v, _) => marker.mark(*v),
}
}
}
#[derive(Default)]
struct WasiCtxBuilderInner {
stdin: Option<ReadStream>,
stdout: Option<WriteStream>,
stderr: Option<WriteStream>,
env: Option<Opaque<RHash>>,
args: Option<Opaque<RArray>>,
mapped_directories: Option<Opaque<RArray>>,
}
impl WasiCtxBuilderInner {
pub fn mark(&self, marker: &Marker) {
if let Some(v) = self.stdin.as_ref() {
v.mark(marker);
}
if let Some(v) = self.stdout.as_ref() {
v.mark(marker);
}
if let Some(v) = self.stderr.as_ref() {
v.mark(marker);
}
if let Some(v) = self.env.as_ref() {
marker.mark(*v);
}
if let Some(v) = self.args.as_ref() {
marker.mark(*v);
}
}
}
/// @yard
/// WASI context builder to be sent as {Store#new}’s +wasi_ctx+ keyword argument.
///
/// Instance methods mutate the current object and return +self+.
///
/// @see https://docs.rs/wasmtime-wasi/latest/wasmtime_wasi/sync/struct.WasiCtxBuilder.html
/// Wasmtime's Rust doc
// #[derive(Debug)]
#[derive(Default, TypedData)]
#[magnus(class = "Wasmtime::WasiCtxBuilder", size, mark, free_immediately)]
pub struct WasiCtxBuilder {
inner: RefCell<WasiCtxBuilderInner>,
}
impl DataTypeFunctions for WasiCtxBuilder {
fn mark(&self, marker: &Marker) {
self.inner.borrow().mark(marker);
}
}
type RbSelf = Obj<WasiCtxBuilder>;
impl WasiCtxBuilder {
/// @yard
/// Create a new {WasiCtxBuilder}. By default, it has nothing: no stdin/out/err,
/// no env, no argv, no file access.
/// @return [WasiCtxBuilder]
pub fn new() -> Self {
Self::default()
}
/// @yard
/// Inherit stdin from the current Ruby process.
/// @return [WasiCtxBuilder] +self+
pub fn inherit_stdin(rb_self: RbSelf) -> RbSelf {
let mut inner = rb_self.inner.borrow_mut();
inner.stdin = Some(ReadStream::Inherit);
rb_self
}
/// @yard
/// Set stdin to read from the specified file.
/// @param path [String] The path of the file to read from.
/// @def set_stdin_file(path)
/// @return [WasiCtxBuilder] +self+
pub fn set_stdin_file(rb_self: RbSelf, path: RString) -> RbSelf {
let mut inner = rb_self.inner.borrow_mut();
inner.stdin = Some(ReadStream::Path(path.into()));
rb_self
}
/// @yard
/// Set stdin to the specified String.
/// @param content [String]
/// @def set_stdin_string(content)
/// @return [WasiCtxBuilder] +self+
pub fn set_stdin_string(rb_self: RbSelf, content: RString) -> RbSelf {
let mut inner = rb_self.inner.borrow_mut();
inner.stdin = Some(ReadStream::String(content.into()));
rb_self
}
/// @yard
/// Inherit stdout from the current Ruby process.
/// @return [WasiCtxBuilder] +self+
pub fn inherit_stdout(rb_self: RbSelf) -> RbSelf {
let mut inner = rb_self.inner.borrow_mut();
inner.stdout = Some(WriteStream::Inherit);
rb_self
}
/// @yard
/// Set stdout to write to a file. Will truncate the file if it exists,
/// otherwise try to create it.
/// @param path [String] The path of the file to write to.
/// @def set_stdout_file(path)
/// @return [WasiCtxBuilder] +self+
pub fn set_stdout_file(rb_self: RbSelf, path: RString) -> RbSelf {
let mut inner = rb_self.inner.borrow_mut();
inner.stdout = Some(WriteStream::Path(path.into()));
rb_self
}
/// @yard
/// Set stdout to write to a string buffer.
/// If the string buffer is frozen, Wasm execution will raise a Wasmtime::Error error.
/// No encoding checks are done on the resulting string, it is the caller's responsibility to ensure the string contains a valid encoding
/// @param buffer [String] The string buffer to write to.
/// @param capacity [Integer] The maximum number of bytes that can be written to the output buffer.
/// @def set_stdout_buffer(buffer, capacity)
/// @return [WasiCtxBuilder] +self+
pub fn set_stdout_buffer(rb_self: RbSelf, buffer: RString, capacity: usize) -> RbSelf {
let mut inner = rb_self.inner.borrow_mut();
inner.stdout = Some(WriteStream::Buffer(buffer.into(), capacity));
rb_self
}
/// @yard
/// Inherit stderr from the current Ruby process.
/// @return [WasiCtxBuilder] +self+
pub fn inherit_stderr(rb_self: RbSelf) -> RbSelf {
let mut inner = rb_self.inner.borrow_mut();
inner.stderr = Some(WriteStream::Inherit);
rb_self
}
/// @yard
/// Set stderr to write to a file. Will truncate the file if it exists,
/// otherwise try to create it.
/// @param path [String] The path of the file to write to.
/// @def set_stderr_file(path)
/// @return [WasiCtxBuilder] +self+
pub fn set_stderr_file(rb_self: RbSelf, path: RString) -> RbSelf {
let mut inner = rb_self.inner.borrow_mut();
inner.stderr = Some(WriteStream::Path(path.into()));
rb_self
}
/// @yard
/// Set stderr to write to a string buffer.
/// If the string buffer is frozen, Wasm execution will raise a Wasmtime::Error error.
/// No encoding checks are done on the resulting string, it is the caller's responsibility to ensure the string contains a valid encoding
/// @param buffer [String] The string buffer to write to.
/// @param capacity [Integer] The maximum number of bytes that can be written to the output buffer.
/// @def set_stderr_buffer(buffer, capacity)
/// @return [WasiCtxBuilder] +self+
pub fn set_stderr_buffer(rb_self: RbSelf, buffer: RString, capacity: usize) -> RbSelf {
let mut inner = rb_self.inner.borrow_mut();
inner.stderr = Some(WriteStream::Buffer(buffer.into(), capacity));
rb_self
}
/// @yard
/// Set env to the specified +Hash+.
/// @param env [Hash<String, String>]
/// @def set_env(env)
/// @return [WasiCtxBuilder] +self+
pub fn set_env(rb_self: RbSelf, env: RHash) -> RbSelf {
let mut inner = rb_self.inner.borrow_mut();
inner.env = Some(env.into());
rb_self
}
/// @yard
/// Set the arguments (argv) to the specified +Array+.
/// @param args [Array<String>]
/// @def set_argv(args)
/// @return [WasiCtxBuilder] +self+
pub fn set_argv(rb_self: RbSelf, argv: RArray) -> RbSelf {
let mut inner = rb_self.inner.borrow_mut();
inner.args = Some(argv.into());
rb_self
}
/// @yard
/// Set mapped directories to the specified +Array+.
/// @param mapped_directories [Array<Array<String>>]
/// @def set_mapped_directories(mapped_directories)
/// @return [WasiCtxBuilder] +self+
pub fn set_mapped_directories(rb_self: RbSelf, mapped_directories: RArray) -> RbSelf {
let mut inner = rb_self.inner.borrow_mut();
inner.mapped_directories = Some(mapped_directories.into());
rb_self
}
pub fn build(ruby: &Ruby, rb_self: RbSelf) -> Result<WasiCtx, Error> {
let mut builder = wasi_common::sync::WasiCtxBuilder::new();
let inner = rb_self.inner.borrow();
if let Some(stdin) = inner.stdin.as_ref() {
match stdin {
ReadStream::Inherit => builder.inherit_stdin(),
ReadStream::Path(path) => {
builder.stdin(file_r(ruby.get_inner(*path)).map(wasi_file)?)
}
ReadStream::String(input) => {
// SAFETY: &[u8] copied before calling in to Ruby, no GC can happen before.
let pipe = ReadPipe::from(unsafe { ruby.get_inner(*input).as_slice() });
builder.stdin(Box::new(pipe))
}
};
}
if let Some(stdout) = inner.stdout.as_ref() {
match stdout {
WriteStream::Inherit => builder.inherit_stdout(),
WriteStream::Path(path) => {
builder.stdout(file_w(ruby.get_inner(*path)).map(wasi_file)?)
}
WriteStream::Buffer(buffer, capacity) => {
let buf = OutputLimitedBuffer::new(*buffer, *capacity);
builder.stdout(Box::new(WritePipe::new(buf)))
}
};
}
if let Some(stderr) = inner.stderr.as_ref() {
match stderr {
WriteStream::Inherit => builder.inherit_stderr(),
WriteStream::Path(path) => {
builder.stderr(file_w(ruby.get_inner(*path)).map(wasi_file)?)
}
WriteStream::Buffer(buffer, capacity) => {
let buf = OutputLimitedBuffer::new(*buffer, *capacity);
builder.stderr(Box::new(WritePipe::new(buf)))
}
};
}
if let Some(args) = inner.args.as_ref() {
// SAFETY: no gc can happen nor do we write to `args`.
for item in unsafe { ruby.get_inner(*args).as_slice() } {
let arg = RString::try_convert(*item)?;
// SAFETY: &str copied before calling in to Ruby, no GC can happen before.
let arg = unsafe { arg.as_str() }?;
builder.arg(arg).map_err(|e| error!("{}", e))?;
}
}
if let Some(env_hash) = inner.env.as_ref() {
let env_vec: Vec<(String, String)> = ruby.get_inner(*env_hash).to_vec()?;
builder.envs(&env_vec).map_err(|e| error!("{}", e))?;
}
if let Some(mapped_directories) = inner.mapped_directories.as_ref() {
for item in unsafe { ruby.get_inner(*mapped_directories).as_slice() } {
let mapped_directory = RArray::try_convert(*item)?;
if mapped_directory.len() == 2 {
let host_path =
RString::try_convert(mapped_directory.entry(0)?)?.to_string()?;
let guest_path =
RString::try_convert(mapped_directory.entry(1)?)?.to_string()?;
let host_path_dir = Dir::from_std_file(File::open(host_path).unwrap());
let guest_path_path = PathBuf::from(guest_path.as_str());
builder
.preopened_dir(host_path_dir, guest_path_path)
.map_err(|e| error!("{}", e))?;
}
}
}
let ctx = WasiCtx::from_inner(builder.build());
Ok(ctx)
}
}
pub fn file_r(path: RString) -> Result<File, Error> {
// SAFETY: &str copied before calling in to Ruby, no GC can happen before.
File::open(PathBuf::from(unsafe { path.as_str()? }))
.map_err(|e| error!("Failed to open file {}\n{}", path, e))
}
pub fn file_w(path: RString) -> Result<File, Error> {
// SAFETY: &str copied before calling in to Ruby, no GC can happen before.
File::create(unsafe { path.as_str()? })
.map_err(|e| error!("Failed to write to file {}\n{}", path, e))
}
pub fn wasi_file(file: File) -> Box<wasi_common::sync::file::File> {
let file = cap_std::fs::File::from_std(file);
let file = wasi_common::sync::file::File::from_cap_std(file);
Box::new(file)
}
pub fn init() -> Result<(), Error> {
let class = root().define_class("WasiCtxBuilder", class::object())?;
class.define_singleton_method("new", function!(WasiCtxBuilder::new, 0))?;
class.define_method("inherit_stdin", method!(WasiCtxBuilder::inherit_stdin, 0))?;
class.define_method("set_stdin_file", method!(WasiCtxBuilder::set_stdin_file, 1))?;
class.define_method(
"set_stdin_string",
method!(WasiCtxBuilder::set_stdin_string, 1),
)?;
class.define_method("inherit_stdout", method!(WasiCtxBuilder::inherit_stdout, 0))?;
class.define_method(
"set_stdout_file",
method!(WasiCtxBuilder::set_stdout_file, 1),
)?;
class.define_method(
"set_stdout_buffer",
method!(WasiCtxBuilder::set_stdout_buffer, 2),
)?;
class.define_method("inherit_stderr", method!(WasiCtxBuilder::inherit_stderr, 0))?;
class.define_method(
"set_stderr_file",
method!(WasiCtxBuilder::set_stderr_file, 1),
)?;
class.define_method(
"set_stderr_buffer",
method!(WasiCtxBuilder::set_stderr_buffer, 2),
)?;
class.define_method("set_env", method!(WasiCtxBuilder::set_env, 1))?;
class.define_method("set_argv", method!(WasiCtxBuilder::set_argv, 1))?;
class.define_method(
"set_mapped_directories",
method!(WasiCtxBuilder::set_mapped_directories, 1),
)?;
class.define_method("build", method!(WasiCtxBuilder::build, 0))?;
Ok(())
}