ahrightos-kernel 0.1.0

RISC-V 64 Rust teaching kernel for AhRightOS.
Documentation
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
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
//! AhRightOS Shell
//!
//! A simple command-line shell running as a kernel task.
//! Reads input via SBI console_getchar, executes built-in commands
//! directly via VFS/process APIs, and supports external program
//! execution via fork+exec.

use crate::fs::file::File;
use crate::fs::pipe;
use crate::fs::vfs;
use crate::process;
use crate::process::ProcessId;
use crate::serial_print;
use crate::serial_println;
use alloc::string::String;
use alloc::vec::Vec;
use spin::Mutex;

// ── Console input ─────────────────────────────────────────────────

fn console_getchar() -> Option<u8> {
    let ret: isize;
    unsafe {
        core::arch::asm!(
            "li a7, 2",
            "ecall",
            "mv {}, a0",
            out(reg) ret,
            options(nostack)
        );
    }
    if ret >= 0 {
        Some(ret as u8)
    } else {
        None
    }
}

// ── Line editing ───────────────────────────────────────────────────

fn read_line() -> String {
    let mut buf = String::new();
    loop {
        // Poll SBI directly for input
        let mut ch = console_getchar();
        // Also drain the keyboard module's scan-code queue (populated
        // by the timer interrupt handler) so no characters are lost.
        if ch.is_none() {
            ch = crate::task::keyboard::try_pop_char();
        }
        if let Some(c) = ch {
            match c {
                b'\r' | b'\n' => {
                    serial_println!();
                    return buf;
                }
                0x08 | 0x7f => {
                    if !buf.is_empty() {
                        buf.pop();
                        serial_print!("\x08 \x08");
                    }
                }
                0x20..=0x7e => {
                    buf.push(c as char);
                    serial_print!("{}", c as char);
                }
                _ => {}
            }
        } else {
            // Brief pause to reduce CPU burn between polls
            riscv::asm::wfi();
        }
    }
}

// ── Tokenisation ───────────────────────────────────────────────────

fn tokenize(line: &str) -> Vec<&str> {
    line.split_whitespace().collect()
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct Redirect<'a> {
    path: &'a str,
    append: bool,
}

#[derive(Debug, PartialEq, Eq)]
struct CommandPlan<'a> {
    argv: Vec<&'a str>,
    stdin: Option<&'a str>,
    stdout: Option<Redirect<'a>>,
    background: bool,
}

fn parse_command_plan<'a>(tokens: &[&'a str]) -> Result<CommandPlan<'a>, &'static str> {
    let mut argv = Vec::new();
    let mut stdin = None;
    let mut stdout = None;
    let mut background = false;
    let mut i = 0usize;

    while i < tokens.len() {
        match tokens[i] {
            "<" => {
                i += 1;
                if i >= tokens.len() {
                    return Err("missing input redirection target");
                }
                stdin = Some(tokens[i]);
            }
            ">" | ">>" => {
                let append = tokens[i] == ">>";
                i += 1;
                if i >= tokens.len() {
                    return Err("missing output redirection target");
                }
                stdout = Some(Redirect {
                    path: tokens[i],
                    append,
                });
            }
            "&" => {
                if i + 1 != tokens.len() {
                    return Err("background marker must be last");
                }
                background = true;
            }
            token => argv.push(token),
        }
        i += 1;
    }

    if argv.is_empty() {
        return Err("empty command");
    }

    Ok(CommandPlan {
        argv,
        stdin,
        stdout,
        background,
    })
}

enum ShellOutput<'a> {
    Console,
    File(&'a mut dyn File),
}

fn shell_write(output: &mut ShellOutput<'_>, bytes: &[u8]) -> Result<(), &'static str> {
    match output {
        ShellOutput::Console => {
            crate::serial::write_bytes(bytes);
            Ok(())
        }
        ShellOutput::File(file) => file.write(bytes).map(|_| ()).map_err(|_| "write failed"),
    }
}

fn shell_writeln(output: &mut ShellOutput<'_>, text: &str) -> Result<(), &'static str> {
    shell_write(output, text.as_bytes())?;
    shell_write(output, b"\n")
}

fn open_redirect_target(
    path: &str,
    append: bool,
) -> Result<alloc::sync::Arc<Mutex<dyn File>>, &'static str> {
    let abs_path = resolve_path(path);
    if !append {
        let _ = vfs::remove_file(&abs_path);
    }
    match vfs::open_file(&abs_path) {
        Ok(file) => Ok(file),
        Err(_) => vfs::create_file(&abs_path).map_err(|_| "cannot create redirection target"),
    }
}

// ── Current working directory ──────────────────────────────────────

static CWD: Mutex<Option<String>> = Mutex::new(None);

fn get_cwd() -> String {
    let mut guard = CWD.lock();
    if guard.is_none() {
        *guard = Some(String::from("/"));
    }
    guard.clone().unwrap()
}

fn set_cwd(path: String) {
    *CWD.lock() = Some(path);
}

// ── Path resolution helpers ────────────────────────────────────────

/// Resolve a path relative to CWD into an absolute path.
fn resolve_path(raw: &str) -> String {
    if raw.is_empty() {
        return get_cwd();
    }
    if raw.starts_with('/') {
        String::from(raw)
    } else {
        let cwd = get_cwd();
        if cwd == "/" {
            alloc::format!("/{}", raw)
        } else {
            alloc::format!("{}/{}", cwd, raw)
        }
    }
}

/// List directory entries using the unified VFS readdir.
fn list_dir(abs_path: &str) -> Result<Vec<String>, &'static str> {
    vfs::readdir_path(abs_path).map_err(|_| "cannot access directory")
}

/// Check if an absolute path exists and is a directory (via stat).
fn is_directory(abs_path: &str) -> bool {
    match vfs::stat_path(abs_path) {
        Ok(meta) => meta.file_type == crate::fs::FileType::Directory,
        Err(_) => false,
    }
}

// ── Built-in commands ──────────────────────────────────────────────

fn cmd_echo(args: &[&str], output: &mut ShellOutput<'_>) {
    for (i, arg) in args.iter().enumerate() {
        if i > 0 {
            let _ = shell_write(output, b" ");
        }
        let _ = shell_write(output, arg.as_bytes());
    }
    let _ = shell_write(output, b"\n");
}

fn cmd_pwd(output: &mut ShellOutput<'_>) {
    let _ = shell_writeln(output, &get_cwd());
}

fn cmd_cd(args: &[&str]) {
    let target = if args.is_empty() { "/" } else { args[0] };
    let abs_path = resolve_path(target);
    if is_directory(&abs_path) {
        set_cwd(abs_path);
    } else {
        serial_println!("cd: {}: not a directory", target);
    }
}

fn cmd_ls(args: &[&str], output: &mut ShellOutput<'_>) {
    let target = if args.is_empty() { "." } else { args[0] };
    let abs_path = resolve_path(target);
    match list_dir(&abs_path) {
        Ok(entries) => {
            for name in &entries {
                let _ = shell_writeln(output, name);
            }
        }
        Err(e) => {
            serial_println!("ls: {}: {}", target, e);
        }
    }
}

fn cmd_cat(args: &[&str], output: &mut ShellOutput<'_>) {
    if args.is_empty() {
        serial_println!("cat: missing file operand");
        return;
    }
    for &arg in args {
        let abs_path = resolve_path(arg);
        match vfs::open_file(&abs_path) {
            Ok(file_handle) => {
                let mut buf = [0u8; 512];
                loop {
                    match file_handle.lock().read(&mut buf) {
                        Ok(0) => break,
                        Ok(n) => {
                            let _ = shell_write(output, &buf[..n]);
                        }
                        Err(_) => break,
                    }
                }
            }
            Err(_) => {
                serial_println!("cat: {}: no such file", arg);
            }
        }
    }
}

fn cmd_exit() -> ! {
    serial_println!("Shell exiting.");
    // Halt the system — the shell is a kernel task.
    crate::hlt_loop();
}

fn cmd_mkdir(args: &[&str]) {
    if args.is_empty() {
        crate::println!("mkdir: missing operand");
        return;
    }
    for &arg in args {
        let abs_path = resolve_path(arg);
        match vfs::create_dir(&abs_path) {
            Ok(()) => crate::println!("mkdir: created '{}'", abs_path),
            Err(e) => crate::println!("mkdir: {}: {}", arg, e),
        }
    }
}

fn cmd_rm(args: &[&str]) {
    if args.is_empty() {
        crate::println!("rm: missing operand");
        return;
    }
    for &arg in args {
        let abs_path = resolve_path(arg);
        match crate::fs::remove_file(&abs_path) {
            Ok(()) => crate::println!("rm: removed '{}'", abs_path),
            Err(e) => crate::println!("rm: {}: {}", arg, e),
        }
    }
}

fn cmd_touch(args: &[&str]) {
    if args.is_empty() {
        crate::println!("touch: missing file operand");
        return;
    }
    for &arg in args {
        let abs_path = resolve_path(arg);
        match vfs::open_file(&abs_path) {
            Ok(_) => {}
            Err(_) => match vfs::create_file(&abs_path) {
                Ok(_) => crate::println!("touch: created '{}'", abs_path),
                Err(e) => crate::println!("touch: {}: {}", arg, e),
            },
        }
    }
}

fn cmd_ps() {
    let sched = crate::process::SCHEDULER.lock();
    serial_println!("  PID  NAME        STATE");
    serial_println!("  ───  ──────────  ─────");
    for pcb in sched.all_processes() {
        serial_println!(
            "  {:>3}  {:<10}  {:?}",
            pcb.pid().as_usize(),
            pcb.name(),
            pcb.state(),
        );
    }
    serial_println!("  ───  ──────────  ─────");
}

fn cmd_jobs() {
    serial_println!("jobs: full POSIX job control is not implemented");
    serial_println!("jobs: external commands are queued as AhRightOS tasks; use ps to inspect them");
    serial_println!("jobs: signals/fg/bg remain documented future work");
}

fn cmd_help(output: &mut ShellOutput<'_>) {
    let _ = shell_writeln(output, "AhRightOS Shell — built-in commands:");
    let _ = shell_writeln(output, "  echo <text>       Print text");
    let _ = shell_writeln(output, "  pwd               Print working directory");
    let _ = shell_writeln(output, "  cd  <path>        Change directory");
    let _ = shell_writeln(output, "  ls  [path]        List directory");
    let _ = shell_writeln(output, "  cat <file>        Print file contents");
    let _ = shell_writeln(output, "  mkdir <dir>       Create directory");
    let _ = shell_writeln(output, "  rm   <file>       Remove file");
    let _ = shell_writeln(output, "  touch <file>      Create empty file");
    let _ = shell_writeln(output, "  ps                List processes");
    let _ = shell_writeln(output, "  jobs              Show job-control limitation");
    let _ = shell_writeln(output, "  exit              Halt the system");
    let _ = shell_writeln(output, "  help              Show this message");
    let _ = shell_writeln(
        output,
        "Redirection: >, >>, and cat < file are supported for teaching built-ins.",
    );
}

fn cmd_external(name: &str, _args: &[&str]) {
    // Try to load and execute an ELF binary from the VFS.
    let abs_path = resolve_path(name);

    // Check if the file exists and try to execute it
    match vfs::open_file(&abs_path) {
        Ok(file_handle) => {
            // Read the ELF into a buffer
            let mut elf_data = alloc::vec![0u8; 65536];
            let n = match file_handle.lock().read(&mut elf_data) {
                Ok(n) => n,
                Err(_) => {
                    serial_println!("{}: read error", name);
                    return;
                }
            };
            if n == 0 {
                serial_println!("{}: empty file", name);
                return;
            }
            elf_data.truncate(n);

            let elf = match process::elf::Elf::parse(&elf_data) {
                Ok(e) => e,
                Err(_) => {
                    serial_println!("{}: not an ELF executable", name);
                    return;
                }
            };

            // Create user address space + PCB
            let kernel_paddr = match process::kernel_page_table_paddr() {
                Some(paddr) => paddr,
                None => {
                    serial_println!("{}: kernel page table root is not registered", name);
                    return;
                }
            };

            let result = process::with_frame_allocator(|allocator| {
                let addr_space = match process::user::create_user_address_space(
                    &elf,
                    &elf_data,
                    allocator,
                    kernel_paddr,
                ) {
                    Ok(a) => a,
                    Err(_) => return -1isize,
                };

                let new_satp = {
                    let ppn = addr_space.page_table_paddr().as_usize() >> 12;
                    (8usize << 60) | ppn
                };

                let user_stack_top = 0x7FFF_F000usize;
                let name_static: &'static str = alloc::string::String::from(name).leak();
                let user_task = process::user::create_user_task(
                    ProcessId::new(),
                    name_static,
                    elf.entry,
                    user_stack_top,
                    new_satp,
                );

                let mut sched = process::SCHEDULER.lock();
                if sched.add_process(user_task).is_err() {
                    return -1isize;
                }
                0isize
            });

            if result < 0 {
                serial_println!("{}: failed to create process", name);
            }
        }
        Err(_) => {
            serial_println!("{}: command not found", name);
        }
    }
}

// ── Pipe support ────────────────────────────────────────────────────

/// Execute two built-in commands connected by a pipe.
/// Left command writes to pipe, right command reads from pipe.
fn run_pipe(left_tokens: &[&str], right_tokens: &[&str]) {
    let (read_end, write_end) = pipe::make_pipe();
    let mut write_file = write_end;
    let left_cmd = left_tokens[0];
    let left_args = &left_tokens[1..];

    match left_cmd {
        "echo" => {
            for (i, arg) in left_args.iter().enumerate() {
                if i > 0 {
                    let _ = write_file.write(b" ");
                }
                let _ = write_file.write(arg.as_bytes());
            }
            let _ = write_file.write(b"\n");
        }
        "ls" => {
            let target = if left_args.is_empty() {
                "."
            } else {
                left_args[0]
            };
            let abs_path = resolve_path(target);
            if let Ok(entries) = list_dir(&abs_path) {
                for name in &entries {
                    let _ = write_file.write(name.as_bytes());
                    let _ = write_file.write(b"\n");
                }
            }
        }
        "cat" => {
            for &arg in left_args {
                let abs_path = resolve_path(arg);
                if let Ok(fh) = vfs::open_file(&abs_path) {
                    let mut buf = [0u8; 512];
                    loop {
                        match fh.lock().read(&mut buf) {
                            Ok(0) => break,
                            Ok(n) => {
                                let _ = write_file.write(&buf[..n]);
                            }
                            Err(_) => break,
                        }
                    }
                }
            }
        }
        "pwd" => {
            let _ = write_file.write(get_cwd().as_bytes());
            let _ = write_file.write(b"\n");
        }
        _ => {
            serial_println!("{}: unsupported in pipe", left_cmd);
            return;
        }
    }
    drop(write_file); // close write end → right side can see EOF

    // Right side: read from pipe
    let mut read_file = read_end;
    let right_cmd = right_tokens[0];
    let _right_args = &right_tokens[1..];

    match right_cmd {
        "cat" => {
            let mut buf = [0u8; 512];
            loop {
                match read_file.read(&mut buf) {
                    Ok(0) => break,
                    Ok(n) => crate::serial::write_bytes(&buf[..n]),
                    Err(_) => break,
                }
            }
        }
        _ => {
            serial_println!("{}: unsupported in pipe", right_cmd);
        }
    }
}

fn run_output_builtin(cmd: &str, args: &[&str], output: &mut ShellOutput<'_>) -> bool {
    match cmd {
        "echo" => cmd_echo(args, output),
        "pwd" => cmd_pwd(output),
        "ls" => cmd_ls(args, output),
        "cat" => cmd_cat(args, output),
        "help" => cmd_help(output),
        _ => return false,
    }
    true
}

fn supports_output_redirection(cmd: &str) -> bool {
    matches!(cmd, "echo" | "pwd" | "ls" | "cat" | "help")
}

fn run_command_plan(plan: &CommandPlan<'_>) {
    let cmd = plan.argv[0];
    let mut args = &plan.argv[1..];
    let stdin_arg;

    if let Some(input) = plan.stdin {
        if cmd == "cat" && args.is_empty() {
            stdin_arg = [input];
            args = &stdin_arg;
        } else {
            serial_println!("shell: input redirection is currently supported only by cat");
            return;
        }
    }

    if plan.background && supports_output_redirection(cmd) {
        serial_println!(
            "shell: background marker ignored for built-in command '{}'",
            cmd
        );
    }

    if let Some(redirect) = plan.stdout {
        if !supports_output_redirection(cmd) {
            serial_println!("shell: redirection is unsupported for '{}'", cmd);
            return;
        }
        let file_handle = match open_redirect_target(redirect.path, redirect.append) {
            Ok(file) => file,
            Err(e) => {
                serial_println!("shell: {}: {}", redirect.path, e);
                return;
            }
        };
        let mut guard = file_handle.lock();
        if redirect.append {
            let _ = guard.seek(crate::fs::SeekFrom::End(0));
        }
        let mut output = ShellOutput::File(&mut *guard);
        if run_output_builtin(cmd, args, &mut output) {
            return;
        }
        unreachable!("redirect-supported command must be an output builtin");
    }

    let mut output = ShellOutput::Console;
    if run_output_builtin(cmd, args, &mut output) {
        return;
    }

    match cmd {
        "cd" => cmd_cd(args),
        "mkdir" => cmd_mkdir(args),
        "rm" => cmd_rm(args),
        "touch" => cmd_touch(args),
        "ps" => cmd_ps(),
        "jobs" => cmd_jobs(),
        "exit" => cmd_exit(),
        _ => cmd_external(cmd, args),
    }
}

// ── REPL entry point ───────────────────────────────────────────────

/// Shell main loop. Runs as a kernel task — never returns.
pub fn shell_main() -> ! {
    serial_println!();
    serial_println!("  ╔══════════════════════════════╗");
    serial_println!("  ║     AhRightOS Shell v0.1      ║");
    serial_println!("  ╚══════════════════════════════╝");
    serial_println!();
    serial_println!("Type 'help' for available commands.");
    serial_println!();

    loop {
        serial_print!("{} $ ", get_cwd());

        let line = read_line();
        let tokens = tokenize(&line);

        if tokens.is_empty() {
            continue;
        }

        // Check for pipe
        if let Some(pipe_pos) = tokens.iter().position(|&t| t == "|") {
            let left = &tokens[..pipe_pos];
            let right = &tokens[pipe_pos + 1..];
            if left.is_empty() || right.is_empty() {
                serial_println!("shell: invalid pipe syntax");
                continue;
            }
            run_pipe(left, right);
            continue;
        }

        match parse_command_plan(&tokens) {
            Ok(plan) => run_command_plan(&plan),
            Err(e) => {
                serial_println!("shell: {}", e);
            }
        }
    }
}

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

    #[test_case]
    fn command_plan_parses_output_append_input_and_background() {
        let tokens = tokenize("cat < in.txt >> out.txt &");
        let plan = parse_command_plan(&tokens).expect("parse command plan");
        assert_eq!(plan.argv, alloc::vec!["cat"]);
        assert_eq!(plan.stdin, Some("in.txt"));
        assert_eq!(
            plan.stdout,
            Some(Redirect {
                path: "out.txt",
                append: true
            })
        );
        assert!(plan.background);
    }

    #[test_case]
    fn command_plan_rejects_malformed_redirection() {
        let tokens = tokenize("echo hi >");
        assert_eq!(
            parse_command_plan(&tokens),
            Err("missing output redirection target")
        );

        let tokens = tokenize("echo & hi");
        assert_eq!(
            parse_command_plan(&tokens),
            Err("background marker must be last")
        );
    }

    #[test_case]
    fn output_redirection_support_is_checked_before_opening_target() {
        assert!(supports_output_redirection("echo"));
        assert!(supports_output_redirection("cat"));
        assert!(!supports_output_redirection("unknown"));
        assert!(!supports_output_redirection("cd"));
    }

    #[test_case]
    fn unsupported_output_redirection_does_not_clobber_target_file() {
        crate::fs::init_filesystem();
        let path = "/shell-no-clobber.txt";
        let _ = vfs::remove_file(path);
        let file = vfs::create_file(path).expect("create target");
        file.lock().write(b"kept").expect("seed target");

        let tokens = tokenize("cd > /shell-no-clobber.txt");
        let plan = parse_command_plan(&tokens).expect("parse unsupported redirection");
        run_command_plan(&plan);

        let file = vfs::open_file(path).expect("target should still exist");
        let mut buf = [0u8; 8];
        let n = file.lock().read(&mut buf).expect("read target");
        assert_eq!(&buf[..n], b"kept");
    }

    #[test_case]
    fn single_greater_output_redirection_overwrites_existing_file() {
        crate::fs::init_filesystem();
        let path = "/shell-truncate.txt";
        let _ = vfs::remove_file(path);
        let file = vfs::create_file(path).expect("create target");
        file.lock()
            .write(b"old-longer-content\n")
            .expect("seed target");

        let tokens = tokenize("echo ok > /shell-truncate.txt");
        let plan = parse_command_plan(&tokens).expect("parse overwrite redirection");
        run_command_plan(&plan);

        let file = vfs::open_file(path).expect("target should exist");
        let mut buf = [0u8; 32];
        let n = file.lock().read(&mut buf).expect("read target");
        assert_eq!(&buf[..n], b"ok\n");
    }
}