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
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
use anyhow::Context;
use std::fs::{read_dir, File, OpenOptions, ReadDir};
use std::io::{self, Read, Seek, Write};
use std::path::PathBuf;
use wasmer::{ImportObject, Instance, Module, Store};
use wasmer_vfs::{host_fs, mem_fs, FileSystem};
use wasmer_wasi::types::{__wasi_filesize_t, __wasi_timestamp_t};
use wasmer_wasi::{
    generate_import_object_from_env, get_wasi_version, FsError, Pipe, VirtualFile, WasiEnv,
    WasiState, WasiVersion,
};
use wast::parser::{self, Parse, ParseBuffer, Parser};

/// The kind of filesystem `WasiTest` is going to use.
#[derive(Debug)]
pub enum WasiFileSystemKind {
    /// Instruct the test runner to use `wasmer_vfs::host_fs`.
    Host,

    /// Instruct the test runner to use `wasmer_vfs::mem_fs`.
    InMemory,
}

/// Crate holding metadata parsed from the WASI WAST about the test to be run.
#[derive(Debug, Clone, Hash)]
pub struct WasiTest<'a> {
    wasm_path: &'a str,
    args: Vec<&'a str>,
    envs: Vec<(&'a str, &'a str)>,
    dirs: Vec<&'a str>,
    mapped_dirs: Vec<(&'a str, &'a str)>,
    temp_dirs: Vec<&'a str>,
    assert_return: Option<AssertReturn>,
    stdin: Option<Stdin<'a>>,
    assert_stdout: Option<AssertStdout<'a>>,
    assert_stderr: Option<AssertStderr<'a>>,
}

// TODO: add `test_fs` here to sandbox better
const BASE_TEST_DIR: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/../../wasi-wast/wasi/");

fn get_stdout_output(wasi_state: &WasiState) -> anyhow::Result<String> {
    let stdout_boxed = wasi_state.fs.stdout()?.as_ref().unwrap();
    let stdout = (&**stdout_boxed)
        .downcast_ref::<OutputCapturerer>()
        .unwrap();
    let stdout_str = std::str::from_utf8(&stdout.output)?;
    #[cfg(target_os = "windows")]
    // normalize line endings
    return Ok(stdout_str.replace("\r\n", "\n"));

    #[cfg(not(target_os = "windows"))]
    return Ok(stdout_str.to_string());
}

fn get_stderr_output(wasi_state: &WasiState) -> anyhow::Result<String> {
    let stderr_boxed = wasi_state.fs.stderr()?.as_ref().unwrap();
    let stderr = (&**stderr_boxed)
        .downcast_ref::<OutputCapturerer>()
        .unwrap();
    let stderr_str = std::str::from_utf8(&stderr.output)?;

    #[cfg(target_os = "windows")]
    // normalize line endings
    return Ok(stderr_str.replace("\r\n", "\n"));

    #[cfg(not(target_os = "windows"))]
    return Ok(stderr_str.to_string());
}

#[allow(dead_code)]
impl<'a> WasiTest<'a> {
    /// Turn a WASI WAST string into a list of tokens.
    pub fn lex_string(wast: &'a str) -> parser::Result<ParseBuffer<'a>> {
        ParseBuffer::new(wast)
    }

    /// Turn a WASI WAST list of tokens into a `WasiTest` struct.
    pub fn parse_tokens(tokens: &'a ParseBuffer<'a>) -> parser::Result<Self> {
        parser::parse(tokens)
    }

    /// Execute the WASI test and assert.
    pub fn run(
        &self,
        store: &Store,
        base_path: &str,
        filesystem_kind: WasiFileSystemKind,
    ) -> anyhow::Result<bool> {
        let mut pb = PathBuf::from(base_path);
        pb.push(self.wasm_path);
        let wasm_bytes = {
            let mut wasm_module = File::open(pb)?;
            let mut out = vec![];
            wasm_module.read_to_end(&mut out)?;
            out
        };
        let module = Module::new(&store, &wasm_bytes)?;
        let (env, _tempdirs) = self.create_wasi_env(filesystem_kind)?;
        let imports = self.get_imports(store, &module, env.clone())?;
        let instance = Instance::new(&module, &imports)?;

        let start = instance.exports.get_function("_start")?;

        if let Some(stdin) = &self.stdin {
            let mut state = env.state();
            let wasi_stdin = state.fs.stdin_mut()?.as_mut().unwrap();
            // Then we can write to it!
            write!(wasi_stdin, "{}", stdin.stream)?;
        }

        // TODO: handle errors here when the error fix gets shipped
        match start.call(&[]) {
            Ok(_) => {}
            Err(e) => {
                let wasi_state = env.state();
                let stdout_str = get_stdout_output(&wasi_state)?;
                let stderr_str = get_stderr_output(&wasi_state)?;
                Err(e).with_context(|| {
                    format!(
                        "failed to run WASI `_start` function: failed with stdout: \"{}\"\nstderr: \"{}\"",
                        stdout_str,
                        stderr_str,
                    )
                })?;
            }
        }

        let wasi_state = env.state();

        if let Some(expected_stdout) = &self.assert_stdout {
            let stdout_str = get_stdout_output(&wasi_state)?;
            assert_eq!(stdout_str, expected_stdout.expected);
        }

        if let Some(expected_stderr) = &self.assert_stderr {
            let stderr_str = get_stderr_output(&wasi_state)?;
            assert_eq!(stderr_str, expected_stderr.expected);
        }

        Ok(true)
    }

    /// Create the wasi env with the given metadata.
    fn create_wasi_env(
        &self,
        filesystem_kind: WasiFileSystemKind,
    ) -> anyhow::Result<(WasiEnv, Vec<tempfile::TempDir>)> {
        let mut builder = WasiState::new(self.wasm_path);

        let stdin_pipe = Pipe::new();
        builder.stdin(Box::new(stdin_pipe));

        for (name, value) in &self.envs {
            builder.env(name, value);
        }

        let mut host_temp_dirs_to_not_drop = vec![];

        match filesystem_kind {
            WasiFileSystemKind::Host => {
                let fs = host_fs::FileSystem::default();

                for (alias, real_dir) in &self.mapped_dirs {
                    let mut dir = PathBuf::from(BASE_TEST_DIR);
                    dir.push(real_dir);
                    builder.map_dir(alias, dir)?;
                }

                // due to the structure of our code, all preopen dirs must be mapped now
                for dir in &self.dirs {
                    let mut new_dir = PathBuf::from(BASE_TEST_DIR);
                    new_dir.push(dir);
                    builder.map_dir(dir, new_dir)?;
                }

                for alias in &self.temp_dirs {
                    let temp_dir = tempfile::tempdir()?;
                    builder.map_dir(alias, temp_dir.path())?;
                    host_temp_dirs_to_not_drop.push(temp_dir);
                }

                builder.set_fs(Box::new(fs));
            }

            WasiFileSystemKind::InMemory => {
                let fs = mem_fs::FileSystem::default();
                let mut temp_dir_index: usize = 0;

                let root = PathBuf::from("/");

                map_host_fs_to_mem_fs(&fs, read_dir(BASE_TEST_DIR)?, &root)?;

                for (alias, real_dir) in &self.mapped_dirs {
                    let mut path = root.clone();
                    path.push(real_dir);
                    builder.map_dir(alias, path)?;
                }

                for dir in &self.dirs {
                    let mut new_dir = PathBuf::from("/");
                    new_dir.push(dir);

                    builder.map_dir(dir, new_dir)?;
                }

                for alias in &self.temp_dirs {
                    let temp_dir_name =
                        PathBuf::from(format!("/.tmp_wasmer_wast_{}", temp_dir_index));
                    fs.create_dir(temp_dir_name.as_path())?;
                    builder.map_dir(alias, temp_dir_name)?;
                    temp_dir_index += 1;
                }

                builder.set_fs(Box::new(fs));
            }
        }

        let out = builder
            .args(&self.args)
            // adding this causes some tests to fail. TODO: investigate this
            //.env("RUST_BACKTRACE", "1")
            .stdout(Box::new(OutputCapturerer::new()))
            .stderr(Box::new(OutputCapturerer::new()))
            .finalize()?;

        Ok((out, host_temp_dirs_to_not_drop))
    }

    /// Get the correct [`WasiVersion`] from the Wasm [`Module`].
    fn get_version(&self, module: &Module) -> anyhow::Result<WasiVersion> {
        let version = get_wasi_version(module, true)
            .with_context(|| "failed to detect a version of WASI from the module")?;
        Ok(version)
    }

    /// Get the correct WASI import object for the given module and set it up with the
    /// [`WasiEnv`].
    fn get_imports(
        &self,
        store: &Store,
        module: &Module,
        env: WasiEnv,
    ) -> anyhow::Result<ImportObject> {
        let version = self.get_version(module)?;
        Ok(generate_import_object_from_env(store, env, version))
    }
}

mod wasi_kw {
    wast::custom_keyword!(wasi_test);
    wast::custom_keyword!(envs);
    wast::custom_keyword!(args);
    wast::custom_keyword!(preopens);
    wast::custom_keyword!(map_dirs);
    wast::custom_keyword!(temp_dirs);
    wast::custom_keyword!(assert_return);
    wast::custom_keyword!(stdin);
    wast::custom_keyword!(assert_stdout);
    wast::custom_keyword!(assert_stderr);
    wast::custom_keyword!(fake_i64_const = "i64.const");
}

impl<'a> Parse<'a> for WasiTest<'a> {
    fn parse(parser: Parser<'a>) -> parser::Result<Self> {
        parser.parens(|parser| {
            parser.parse::<wasi_kw::wasi_test>()?;
            // TODO: improve error message here
            let wasm_path = parser.parse::<&'a str>()?;

            // TODO: allow these to come in any order
            let envs = if parser.peek2::<wasi_kw::envs>() {
                parser.parens(|p| p.parse::<Envs>())?.envs
            } else {
                vec![]
            };

            let args = if parser.peek2::<wasi_kw::args>() {
                parser.parens(|p| p.parse::<Args>())?.args
            } else {
                vec![]
            };

            let dirs = if parser.peek2::<wasi_kw::preopens>() {
                parser.parens(|p| p.parse::<Preopens>())?.preopens
            } else {
                vec![]
            };

            let mapped_dirs = if parser.peek2::<wasi_kw::map_dirs>() {
                parser.parens(|p| p.parse::<MapDirs>())?.map_dirs
            } else {
                vec![]
            };

            let temp_dirs = if parser.peek2::<wasi_kw::temp_dirs>() {
                parser.parens(|p| p.parse::<TempDirs>())?.temp_dirs
            } else {
                vec![]
            };

            let assert_return = if parser.peek2::<wasi_kw::assert_return>() {
                Some(parser.parens(|p| p.parse::<AssertReturn>())?)
            } else {
                None
            };

            let stdin = if parser.peek2::<wasi_kw::stdin>() {
                Some(parser.parens(|p| p.parse::<Stdin>())?)
            } else {
                None
            };

            let assert_stdout = if parser.peek2::<wasi_kw::assert_stdout>() {
                Some(parser.parens(|p| p.parse::<AssertStdout>())?)
            } else {
                None
            };

            let assert_stderr = if parser.peek2::<wasi_kw::assert_stderr>() {
                Some(parser.parens(|p| p.parse::<AssertStderr>())?)
            } else {
                None
            };

            Ok(Self {
                wasm_path,
                args,
                envs,
                dirs,
                mapped_dirs,
                temp_dirs,
                assert_return,
                stdin,
                assert_stdout,
                assert_stderr,
            })
        })
    }
}

#[derive(Debug, Clone, Hash)]
struct Envs<'a> {
    envs: Vec<(&'a str, &'a str)>,
}

impl<'a> Parse<'a> for Envs<'a> {
    fn parse(parser: Parser<'a>) -> parser::Result<Self> {
        let mut envs = vec![];
        parser.parse::<wasi_kw::envs>()?;

        while parser.peek::<&'a str>() {
            let res = parser.parse::<&'a str>()?;
            let mut strs = res.split('=');
            let first = strs.next().unwrap();
            let second = strs.next().unwrap();
            //debug_assert!(strs.next().is_none());
            envs.push((first, second));
        }
        Ok(Self { envs })
    }
}

#[derive(Debug, Clone, Hash)]
struct Args<'a> {
    args: Vec<&'a str>,
}

impl<'a> Parse<'a> for Args<'a> {
    fn parse(parser: Parser<'a>) -> parser::Result<Self> {
        let mut args = vec![];
        parser.parse::<wasi_kw::args>()?;

        while parser.peek::<&'a str>() {
            let res = parser.parse::<&'a str>()?;
            args.push(res);
        }
        Ok(Self { args })
    }
}

#[derive(Debug, Clone, Hash)]
struct Preopens<'a> {
    preopens: Vec<&'a str>,
}

impl<'a> Parse<'a> for Preopens<'a> {
    fn parse(parser: Parser<'a>) -> parser::Result<Self> {
        let mut preopens = vec![];
        parser.parse::<wasi_kw::preopens>()?;

        while parser.peek::<&'a str>() {
            let res = parser.parse::<&'a str>()?;
            preopens.push(res);
        }
        Ok(Self { preopens })
    }
}

#[derive(Debug, Clone, Hash)]
struct MapDirs<'a> {
    map_dirs: Vec<(&'a str, &'a str)>,
}

impl<'a> Parse<'a> for MapDirs<'a> {
    fn parse(parser: Parser<'a>) -> parser::Result<Self> {
        let mut map_dirs = vec![];
        parser.parse::<wasi_kw::map_dirs>()?;

        while parser.peek::<&'a str>() {
            let res = parser.parse::<&'a str>()?;
            let mut iter = res.split(':');
            let dir = iter.next().unwrap();
            let alias = iter.next().unwrap();
            map_dirs.push((dir, alias));
        }
        Ok(Self { map_dirs })
    }
}

#[derive(Debug, Clone, Hash)]
struct TempDirs<'a> {
    temp_dirs: Vec<&'a str>,
}

impl<'a> Parse<'a> for TempDirs<'a> {
    fn parse(parser: Parser<'a>) -> parser::Result<Self> {
        let mut temp_dirs = vec![];
        parser.parse::<wasi_kw::temp_dirs>()?;

        while parser.peek::<&'a str>() {
            let alias = parser.parse::<&'a str>()?;
            temp_dirs.push(alias);
        }
        Ok(Self { temp_dirs })
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
struct AssertReturn {
    return_value: i64,
}

impl<'a> Parse<'a> for AssertReturn {
    fn parse(parser: Parser<'a>) -> parser::Result<Self> {
        parser.parse::<wasi_kw::assert_return>()?;
        let return_value = parser.parens(|p| {
            p.parse::<wasi_kw::fake_i64_const>()?;
            p.parse::<i64>()
        })?;
        Ok(Self { return_value })
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
struct Stdin<'a> {
    stream: &'a str,
}

impl<'a> Parse<'a> for Stdin<'a> {
    fn parse(parser: Parser<'a>) -> parser::Result<Self> {
        parser.parse::<wasi_kw::stdin>()?;
        Ok(Self {
            stream: parser.parse()?,
        })
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
struct AssertStdout<'a> {
    expected: &'a str,
}

impl<'a> Parse<'a> for AssertStdout<'a> {
    fn parse(parser: Parser<'a>) -> parser::Result<Self> {
        parser.parse::<wasi_kw::assert_stdout>()?;
        Ok(Self {
            expected: parser.parse()?,
        })
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
struct AssertStderr<'a> {
    expected: &'a str,
}

impl<'a> Parse<'a> for AssertStderr<'a> {
    fn parse(parser: Parser<'a>) -> parser::Result<Self> {
        parser.parse::<wasi_kw::assert_stderr>()?;
        Ok(Self {
            expected: parser.parse()?,
        })
    }
}

#[cfg(test)]
mod test {
    use super::*;

    #[test]
    fn test_parse() {
        let pb = wast::parser::ParseBuffer::new(
            r#"(wasi_test "my_wasm.wasm"
                    (envs "HELLO=WORLD" "RUST_BACKTRACE=1")
                    (args "hello" "world" "--help")
                    (preopens "." "src/io")
                    (assert_return (i64.const 0))
                    (stdin "This is another \"string\" inside a string!")
                    (assert_stdout "This is a \"string\" inside a string!")
                    (assert_stderr "")
)"#,
        )
        .unwrap();
        let result = wast::parser::parse::<WasiTest>(&pb).unwrap();

        assert_eq!(result.args, vec!["hello", "world", "--help"]);
        assert_eq!(
            result.envs,
            vec![("HELLO", "WORLD"), ("RUST_BACKTRACE", "1")]
        );
        assert_eq!(result.dirs, vec![".", "src/io"]);
        assert_eq!(result.assert_return.unwrap().return_value, 0);
        assert_eq!(
            result.assert_stdout.unwrap().expected,
            "This is a \"string\" inside a string!"
        );
        assert_eq!(
            result.stdin.unwrap().stream,
            "This is another \"string\" inside a string!"
        );
        assert_eq!(result.assert_stderr.unwrap().expected, "");
    }
}

#[derive(Debug)]
struct OutputCapturerer {
    output: Vec<u8>,
}

impl OutputCapturerer {
    fn new() -> Self {
        Self { output: vec![] }
    }
}

impl Read for OutputCapturerer {
    fn read(&mut self, _buf: &mut [u8]) -> io::Result<usize> {
        Err(io::Error::new(
            io::ErrorKind::Other,
            "can not read from logging wrapper",
        ))
    }
    fn read_to_end(&mut self, _buf: &mut Vec<u8>) -> io::Result<usize> {
        Err(io::Error::new(
            io::ErrorKind::Other,
            "can not read from logging wrapper",
        ))
    }
    fn read_to_string(&mut self, _buf: &mut String) -> io::Result<usize> {
        Err(io::Error::new(
            io::ErrorKind::Other,
            "can not read from logging wrapper",
        ))
    }
    fn read_exact(&mut self, _buf: &mut [u8]) -> io::Result<()> {
        Err(io::Error::new(
            io::ErrorKind::Other,
            "can not read from logging wrapper",
        ))
    }
}
impl Seek for OutputCapturerer {
    fn seek(&mut self, _pos: io::SeekFrom) -> io::Result<u64> {
        Err(io::Error::new(
            io::ErrorKind::Other,
            "can not seek logging wrapper",
        ))
    }
}
impl Write for OutputCapturerer {
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        self.output.extend_from_slice(buf);
        Ok(buf.len())
    }
    fn flush(&mut self) -> io::Result<()> {
        Ok(())
    }
    fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
        self.output.extend_from_slice(buf);
        Ok(())
    }
    fn write_fmt(&mut self, fmt: std::fmt::Arguments) -> io::Result<()> {
        self.output.write_fmt(fmt)
    }
}

impl VirtualFile for OutputCapturerer {
    fn last_accessed(&self) -> __wasi_timestamp_t {
        0
    }
    fn last_modified(&self) -> __wasi_timestamp_t {
        0
    }
    fn created_time(&self) -> __wasi_timestamp_t {
        0
    }
    fn size(&self) -> u64 {
        0
    }
    fn set_len(&mut self, _new_size: __wasi_filesize_t) -> Result<(), FsError> {
        Ok(())
    }
    fn unlink(&mut self) -> Result<(), FsError> {
        Ok(())
    }
    fn bytes_available(&self) -> Result<usize, FsError> {
        Ok(1024)
    }
}

/// When using `wasmer_vfs::mem_fs`, we cannot rely on `BASE_TEST_DIR`
/// because the host filesystem cannot be used. Instead, we are
/// copying `BASE_TEST_DIR` to the `mem_fs`.
fn map_host_fs_to_mem_fs(
    fs: &mem_fs::FileSystem,
    directory_reader: ReadDir,
    path_prefix: &PathBuf,
) -> anyhow::Result<()> {
    for entry in directory_reader {
        let entry = entry?;
        let entry_type = entry.file_type()?;

        let mut path = path_prefix.clone();
        path.push(entry.path().file_name().unwrap());

        if entry_type.is_dir() {
            fs.create_dir(&path)?;

            map_host_fs_to_mem_fs(fs, read_dir(entry.path())?, &path)?
        } else if entry_type.is_file() {
            let mut host_file = OpenOptions::new().read(true).open(entry.path())?;
            let mut mem_file = fs
                .new_open_options()
                .create_new(true)
                .write(true)
                .open(path)?;
            let mut buffer = Vec::new();
            host_file.read_to_end(&mut buffer)?;
            mem_file.write_all(&buffer)?;
        } else if entry_type.is_symlink() {
            //unimplemented!("`mem_fs` does not support symlink for the moment");
        }
    }

    Ok(())
}