/
state.rs
466 lines (422 loc) 路 14.2 KB
/
state.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
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
// use wasmer_runtime_abi::vfs::{
// vfs::Vfs,
// file_like::{FileLike, Metadata};
// };
use crate::syscalls::types::*;
use generational_arena::{Arena, Index as Inode};
use hashbrown::hash_map::{Entry, HashMap};
use std::{
cell::Cell,
fs,
io::{self, Read, Seek, Write},
path::PathBuf,
time::SystemTime,
};
use wasmer_runtime_core::debug;
pub const MAX_SYMLINKS: usize = 100;
#[derive(Debug)]
pub enum WasiFile {
HostFile(fs::File),
}
impl Write for WasiFile {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
match self {
WasiFile::HostFile(hf) => hf.write(buf),
}
}
fn flush(&mut self) -> io::Result<()> {
match self {
WasiFile::HostFile(hf) => hf.flush(),
}
}
fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
match self {
WasiFile::HostFile(hf) => hf.write_all(buf),
}
}
fn write_fmt(&mut self, fmt: ::std::fmt::Arguments) -> io::Result<()> {
match self {
WasiFile::HostFile(hf) => hf.write_fmt(fmt),
}
}
}
impl Read for WasiFile {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
match self {
WasiFile::HostFile(hf) => hf.read(buf),
}
}
fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
match self {
WasiFile::HostFile(hf) => hf.read_to_end(buf),
}
}
fn read_to_string(&mut self, buf: &mut String) -> io::Result<usize> {
match self {
WasiFile::HostFile(hf) => hf.read_to_string(buf),
}
}
fn read_exact(&mut self, buf: &mut [u8]) -> io::Result<()> {
match self {
WasiFile::HostFile(hf) => hf.read_exact(buf),
}
}
}
impl Seek for WasiFile {
fn seek(&mut self, pos: io::SeekFrom) -> io::Result<u64> {
match self {
WasiFile::HostFile(hf) => hf.seek(pos),
}
}
}
#[derive(Debug)]
pub struct InodeVal {
pub stat: __wasi_filestat_t,
pub is_preopened: bool,
pub name: String,
pub kind: Kind,
}
impl InodeVal {
// TODO: clean this up
pub fn from_file_metadata(
metadata: &std::fs::Metadata,
name: String,
is_preopened: bool,
kind: Kind,
) -> Self {
InodeVal {
stat: __wasi_filestat_t {
st_filetype: if metadata.is_dir() {
__WASI_FILETYPE_DIRECTORY
} else {
__WASI_FILETYPE_REGULAR_FILE
},
st_size: metadata.len(),
st_atim: metadata
.accessed()
.ok()
.and_then(|sys_time| sys_time.duration_since(SystemTime::UNIX_EPOCH).ok())
.map(|duration| duration.as_nanos() as u64)
.unwrap_or(0),
st_ctim: metadata
.created()
.ok()
.and_then(|sys_time| sys_time.duration_since(SystemTime::UNIX_EPOCH).ok())
.map(|duration| duration.as_nanos() as u64)
.unwrap_or(0),
st_mtim: metadata
.modified()
.ok()
.and_then(|sys_time| sys_time.duration_since(SystemTime::UNIX_EPOCH).ok())
.map(|duration| duration.as_nanos() as u64)
.unwrap_or(0),
..__wasi_filestat_t::default()
},
is_preopened,
name,
kind,
}
}
}
#[allow(dead_code)]
#[derive(Debug)]
pub enum Kind {
File {
handle: WasiFile,
},
Dir {
/// Parent directory
parent: Option<Inode>,
/// The path on the host system where the directory is located
// TODO: wrap it like WasiFile
path: PathBuf,
/// The entries of a directory are lazily filled.
entries: HashMap<String, Inode>,
},
Symlink {
forwarded: Inode,
},
Buffer {
buffer: Vec<u8>,
},
}
#[derive(Clone, Debug)]
pub struct Fd {
pub rights: __wasi_rights_t,
pub rights_inheriting: __wasi_rights_t,
pub flags: __wasi_fdflags_t,
pub offset: u64,
pub inode: Inode,
}
#[derive(Debug)]
pub struct WasiFs {
//pub repo: Repo,
pub name_map: HashMap<String, Inode>,
pub inodes: Arena<InodeVal>,
pub fd_map: HashMap<u32, Fd>,
pub next_fd: Cell<u32>,
pub inode_counter: Cell<u64>,
}
impl WasiFs {
pub fn new(preopened_dirs: &[String]) -> Result<Self, String> {
/*let repo = RepoOpener::new()
.create(true)
.open("mem://wasmer-test-fs", "")
.map_err(|e| e.to_string())?;*/
debug!("wasi::fs::inodes");
let inodes = Arena::new();
let mut wasi_fs = Self {
//repo: repo,
name_map: HashMap::new(),
inodes: inodes,
fd_map: HashMap::new(),
next_fd: Cell::new(3),
inode_counter: Cell::new(1000),
};
for dir in preopened_dirs {
debug!("Attempting to preopen {}", &dir);
// TODO: think about this
let default_rights = 0x1FFFFFFF; // all rights
let cur_dir = PathBuf::from(dir);
let cur_dir_metadata = cur_dir.metadata().expect("Could not find directory");
let kind = if cur_dir_metadata.is_dir() {
Kind::Dir {
parent: None,
path: cur_dir.clone(),
entries: Default::default(),
}
} else {
return Err(format!(
"WASI only supports pre-opened directories right now; found \"{}\"",
&dir
));
};
// TODO: handle nested pats in `file`
let inode_val =
InodeVal::from_file_metadata(&cur_dir_metadata, dir.clone(), true, kind);
let inode = wasi_fs.inodes.insert(inode_val);
wasi_fs.inodes[inode].stat.st_ino = wasi_fs.inode_counter.get();
wasi_fs
.create_fd(default_rights, default_rights, 0, inode)
.expect("Could not open fd");
}
debug!("wasi::fs::end");
Ok(wasi_fs)
}
#[allow(dead_code)]
fn get_inode(&mut self, path: &str) -> Option<Inode> {
Some(match self.name_map.entry(path.to_string()) {
Entry::Occupied(o) => *o.get(),
Entry::Vacant(_v) => {
return None;
// let file = if let Ok(file) = OpenOptions::new()
// .read(true)
// .write(true)
// .create(false)
// .open(&mut self.repo, path)
// {
// file
// } else {
// return None;
// };
// let metadata = file.metadata().unwrap();
// let inode_index = {
// let index = self.inode_counter.get();
// self.inode_counter.replace(index + 1)
// };
// let systime_to_nanos = |systime: SystemTime| {
// let duration = systime
// .duration_since(SystemTime::UNIX_EPOCH)
// .expect("should always be after unix epoch");
// duration.as_nanos() as u64
// };
// let inode = self.inodes.insert(InodeVal {
// stat: __wasi_filestat_t {
// st_dev: 0,
// st_ino: inode_index,
// st_filetype: match metadata.file_type() {
// FileType::File => __WASI_FILETYPE_REGULAR_FILE,
// FileType::Dir => __WASI_FILETYPE_DIRECTORY,
// },
// st_nlink: 0,
// st_size: metadata.content_len() as u64,
// st_atim: systime_to_nanos(SystemTime::now()),
// st_mtim: systime_to_nanos(metadata.modified_at()),
// st_ctim: systime_to_nanos(metadata.created_at()),
// },
// is_preopened: false,
// name: path.to_string(),
// kind: match metadata.file_type() {
// FileType::File => Kind::File { handle: file },
// FileType::Dir => Kind::Dir {
// handle: file,
// entries: HashMap::new(),
// },
// },
// });
// v.insert(inode);
// inode
}
})
}
#[allow(dead_code)]
fn filestat_inode(
&self,
inode: Inode,
flags: __wasi_lookupflags_t,
) -> Result<__wasi_filestat_t, __wasi_errno_t> {
let inode_val = &self.inodes[inode];
if let (true, Kind::Symlink { mut forwarded }) =
(flags & __WASI_LOOKUP_SYMLINK_FOLLOW != 0, &inode_val.kind)
{
// Time to follow the symlink.
let mut counter = 0;
while counter <= MAX_SYMLINKS {
let inode_val = &self.inodes[forwarded];
if let &Kind::Symlink {
forwarded: new_forwarded,
} = &inode_val.kind
{
counter += 1;
forwarded = new_forwarded;
} else {
return Ok(inode_val.stat);
}
}
Err(__WASI_EMLINK)
} else {
Ok(inode_val.stat)
}
}
#[allow(dead_code)]
pub fn filestat_path(
&mut self,
preopened_fd: __wasi_fd_t,
flags: __wasi_lookupflags_t,
path: &str,
) -> Result<__wasi_filestat_t, __wasi_errno_t> {
warn!("Should use preopned_fd: {}", preopened_fd);
let inode = self.get_inode(path).ok_or(__WASI_EINVAL)?;
self.filestat_inode(inode, flags)
}
pub fn filestat_fd(&self, fd: __wasi_fd_t) -> Result<__wasi_filestat_t, __wasi_errno_t> {
let fd = self.fd_map.get(&fd).ok_or(__WASI_EBADF)?;
Ok(self.inodes[fd.inode].stat)
}
pub fn fdstat(&self, fd: __wasi_fd_t) -> Result<__wasi_fdstat_t, __wasi_errno_t> {
let fd = self.fd_map.get(&fd).ok_or(__WASI_EBADF)?;
debug!("fdstat: {:?}", fd);
Ok(__wasi_fdstat_t {
fs_filetype: match self.inodes[fd.inode].kind {
Kind::File { .. } => __WASI_FILETYPE_REGULAR_FILE,
Kind::Dir { .. } => __WASI_FILETYPE_DIRECTORY,
Kind::Symlink { .. } => __WASI_FILETYPE_SYMBOLIC_LINK,
_ => __WASI_FILETYPE_UNKNOWN,
},
fs_flags: fd.flags,
fs_rights_base: fd.rights,
fs_rights_inheriting: fd.rights_inheriting, // TODO(lachlan): Is this right?
})
}
pub fn prestat_fd(&self, fd: __wasi_fd_t) -> Result<__wasi_prestat_t, __wasi_errno_t> {
let fd = self.fd_map.get(&fd).ok_or(__WASI_EBADF)?;
debug!("in prestat_fd {:?}", fd);
let inode_val = &self.inodes[fd.inode];
if inode_val.is_preopened {
Ok(__wasi_prestat_t {
pr_type: __WASI_PREOPENTYPE_DIR,
u: PrestatEnum::Dir {
// REVIEW:
pr_name_len: inode_val.name.len() as u32 + 1,
}
.untagged(),
})
} else {
Err(__WASI_EBADF)
}
}
pub fn flush(&mut self, fd: __wasi_fd_t) -> Result<(), __wasi_errno_t> {
match fd {
0 => (),
1 => io::stdout().flush().map_err(|_| __WASI_EIO)?,
2 => io::stderr().flush().map_err(|_| __WASI_EIO)?,
_ => {
let fd = self.fd_map.get(&fd).ok_or(__WASI_EBADF)?;
if fd.rights & __WASI_RIGHT_FD_DATASYNC == 0 {
return Err(__WASI_EACCES);
}
let inode = &mut self.inodes[fd.inode];
match &mut inode.kind {
Kind::File { handle } => handle.flush().map_err(|_| __WASI_EIO)?,
// TODO: verify this behavior
Kind::Dir { .. } => return Err(__WASI_EISDIR),
Kind::Symlink { .. } => unimplemented!(),
Kind::Buffer { .. } => (),
}
}
}
Ok(())
}
pub fn create_fd(
&mut self,
rights: __wasi_rights_t,
rights_inheriting: __wasi_rights_t,
flags: __wasi_fdflags_t,
inode: Inode,
) -> Result<u32, __wasi_errno_t> {
let idx = self.next_fd.get();
self.next_fd.set(idx + 1);
self.fd_map.insert(
idx,
Fd {
rights,
rights_inheriting,
flags,
offset: 0,
inode,
},
);
Ok(idx)
}
pub fn get_base_path_for_directory(&self, directory: Inode) -> Option<String> {
let mut path_segments = vec![];
let mut cur_inode = directory;
loop {
path_segments.push(self.inodes[cur_inode].name.clone());
if let Kind::Dir { parent, .. } = &self.inodes[cur_inode].kind {
if let Some(p_inode) = parent {
cur_inode = *p_inode;
} else {
break;
}
} else {
return None;
}
}
path_segments.reverse();
Some(
path_segments
.iter()
.skip(1)
.fold(path_segments.first()?.clone(), |a, b| a + "/" + b),
)
}
}
#[derive(Debug)]
pub struct WasiState<'a> {
pub fs: WasiFs,
pub args: &'a [Vec<u8>],
pub envs: &'a [Vec<u8>],
}
pub fn host_file_type_to_wasi_file_type(file_type: fs::FileType) -> __wasi_filetype_t {
// TODO: handle other file types
if file_type.is_dir() {
__WASI_FILETYPE_DIRECTORY
} else if file_type.is_file() {
__WASI_FILETYPE_REGULAR_FILE
} else if file_type.is_symlink() {
__WASI_FILETYPE_SYMBOLIC_LINK
} else {
__WASI_FILETYPE_UNKNOWN
}
}