1
// Skipped under Miri: these tests compile+run wasm via wasmtime, whose
2
// Cranelift backend refuses to run under Miri.
3
#![cfg(not(miri))]
4

            
5
//! Output that does not fit the 64 KiB output buffer raises `OUTPUT-OVERFLOW`
6
//! rather than writing past it. After the 24-byte output header 65512 bytes
7
//! remain: a debug value takes 56 of them, a tag 48 plus its name and value
8
//! bytes (which grow down from the buffer end), a delete record 32.
9

            
10
use nms::interpreter::Interpreter;
11
use scripting::{EntityHeaderArgs, MemorySerializer, ScriptExecutor, TransactionArgs};
12
use scripting_format::{ContextType, EntityType};
13

            
14
const OUTPUT_SIZE: u32 = 64 * 1024;
15

            
16
/// Runs `source` against one input transaction; the output entity count.
17
11
fn run(source: &str) -> Result<usize, String> {
18
11
    let _interp = Interpreter::new(false).map_err(|e| e.to_string())?;
19
11
    let wasm = rpc::compile_script(source).map_err(|e| e.to_string())?;
20
11
    let mut ser = MemorySerializer::new();
21
11
    ser.set_context(ContextType::BatchProcess, EntityType::Transaction);
22
11
    let tx = ser.add_transaction(
23
11
        EntityHeaderArgs {
24
11
            id: [1; 16],
25
11
            parent_idx: -1,
26
11
            is_primary: true,
27
11
            is_context: false,
28
11
        },
29
11
        TransactionArgs {
30
11
            post_date: 0,
31
11
            enter_date: 0,
32
11
            split_count: 0,
33
11
            tag_count: 0,
34
11
            is_multi_currency: false,
35
11
        },
36
11
    );
37
11
    ser.set_primary(tx);
38
11
    let input = ser.finalize(OUTPUT_SIZE);
39
11
    let executor = ScriptExecutor::try_new().map_err(|e| e.to_string())?;
40
11
    executor
41
11
        .execute(&wasm, &input, Some(OUTPUT_SIZE))
42
5
        .map(|entities| entities.len())
43
6
        .map_err(|e| format!("{e:?}"))
44
11
}
45

            
46
/// A runtime list of `len` numbers: `len` + 2 debug values.
47
6
fn list_of(len: usize) -> String {
48
6
    format!(
49
6
        "(let ((r nil)) (do ((i 0 (+ i 1))) ((= i {len})) (setf r (cons (+ i (entity-count)) r))) r)"
50
    )
51
6
}
52

            
53
/// `count` tags on the input transaction in a runtime loop, then `nil`.
54
3
fn tags(count: usize, value: &str) -> String {
55
3
    format!(
56
3
        "(do ((i 0 (+ i 1))) ((= i (+ {count} (* 0 (entity-count))))) (create-tag 0 \"k\" \"{value}\"))"
57
    )
58
3
}
59

            
60
/// `count` deletes of the input transaction in a runtime loop, then `nil`.
61
3
fn deletes(count: usize) -> String {
62
3
    format!("(do ((i 0 (+ i 1))) ((= i (+ {count} (* 0 (entity-count))))) (delete-entity 0))")
63
3
}
64

            
65
6
fn assert_overflows(source: &str) {
66
6
    let err = run(source).expect_err("the output overflows the buffer");
67
6
    assert!(err.contains("__nomi_raise:OUTPUT-OVERFLOW"), "{err}");
68
6
}
69

            
70
#[test]
71
1
fn a_result_that_just_fits_is_written_whole() {
72
1
    assert_eq!(run(&list_of(1167)), Ok(1169));
73
1
}
74

            
75
#[test]
76
1
fn a_result_one_entity_too_large_raises_output_overflow() {
77
1
    assert_overflows(&list_of(1168));
78
1
    assert_overflows(&list_of(3000));
79
1
}
80

            
81
#[test]
82
1
fn tags_that_just_fit_are_all_written() {
83
1
    assert_eq!(run(&tags(1309, "v")), Ok(1310));
84
1
}
85

            
86
#[test]
87
1
fn a_tag_past_the_buffer_raises_output_overflow() {
88
1
    assert_overflows(&tags(1311, "v"));
89
1
}
90

            
91
/// 70-byte tags: 935 fit, and the 62 bytes left still hold the `nil` result.
92
#[test]
93
1
fn a_tag_overflow_is_catchable_inside_the_script() {
94
1
    let source = format!(
95
        "(handler-case {} (output-overflow (e) nil))",
96
1
        tags(2000, "vvvvvvvvvvvvvvvvvvvvv")
97
    );
98
1
    assert_eq!(run(&source), Ok(936));
99
1
}
100

            
101
/// 2045 records and the `nil` result fill 65496 of 65512 bytes.
102
#[test]
103
1
fn deletes_that_just_fit_are_all_written() {
104
1
    assert_eq!(run(&deletes(2045)), Ok(2046));
105
1
}
106

            
107
/// 2046 records still fit, so the `nil` result write overflows; the 2048th
108
/// record itself does not fit, so the delete writer overflows.
109
#[test]
110
1
fn a_delete_past_the_buffer_raises_output_overflow() {
111
1
    assert_overflows(&deletes(2046));
112
1
    assert_overflows(&deletes(2048));
113
1
}
114

            
115
/// A PRINT longer than the guest's staging area below the input used to
116
/// overwrite the input header's output size, lifting the limit.
117
3
fn after_long_print(source: &str) -> String {
118
3
    format!("(print \"{}\") {source}", "A".repeat(4200))
119
3
}
120

            
121
#[test]
122
1
fn a_long_print_does_not_lift_the_output_limit() {
123
1
    assert_eq!(run(&after_long_print(&list_of(1167))), Ok(1169));
124
1
    assert_overflows(&after_long_print(&list_of(1168)));
125
1
}
126

            
127
#[test]
128
1
fn a_long_print_does_not_lift_the_interpreter_output_limit() {
129
1
    let mut interp = Interpreter::new(false).expect("interpreter");
130
1
    let err = interp.eval(&after_long_print(&list_of(1200)));
131
1
    assert!(err.is_err(), "{err:?}");
132
1
}