kecc/
tests.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
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
use std::fs::{self, File};
use std::io::{self, Read, Write};
use std::path::Path;
use std::process::{Command, Stdio};
use std::time::Duration;

use lang_c::*;
use rand::Rng;
use tempfile::tempdir;
use wait_timeout::ChildExt;

use crate::*;

const NONCE_NAME: &str = "nonce";

fn modify_c(path: &Path, rand_num: i32) -> String {
    let mut src = File::open(path).expect("`path` must exist");
    let mut data = String::new();
    let _ = src
        .read_to_string(&mut data)
        .expect("`src` must be converted to string");
    drop(src);

    let from = format!("int {NONCE_NAME} = 1");
    let to = format!("int {NONCE_NAME} = {rand_num}");
    data.replace(&from, &to)
}

fn ast_initializer(number: i32) -> ast::Initializer {
    let expr = ast::Expression::Constant(Box::new(span::Node::new(
        ast::Constant::Integer(ast::Integer {
            base: ast::IntegerBase::Decimal,
            number: Box::from(number.to_string()),
            suffix: ast::IntegerSuffix {
                size: ast::IntegerSize::Int,
                unsigned: false,
                imaginary: false,
            },
        }),
        span::Span::none(),
    )));

    ast::Initializer::Expression(Box::new(span::Node::new(expr, span::Span::none())))
}

fn modify_ir(unit: &mut ir::TranslationUnit, rand_num: i32) {
    for (name, decl) in &mut unit.decls {
        if name == NONCE_NAME {
            let (dtype, _) = decl.get_variable().expect("`decl` must be variable");
            let initializer = ast_initializer(rand_num);
            let new_decl = ir::Declaration::Variable {
                dtype: dtype.clone(),
                initializer: Some(initializer),
            };

            *decl = new_decl;
        }
    }
}

fn modify_asm(unit: &mut asm::Asm, rand_num: i32) {
    for variable in &mut unit.unit.variables {
        let body = &mut variable.body;
        if body.label == asm::Label(NONCE_NAME.to_string()) {
            let directive =
                asm::Directive::try_from_data_size(asm::DataSize::Word, rand_num as u64);

            body.directives = vec![directive];
        }
    }
}

// Rust sets an exit code of 101 when the process panicked.
// Set exit code of 102 after 101 to denote that the test skipped.
const SKIP_TEST: i32 = 102;

/// Tests write_c.
pub fn test_write_c(path: &Path) {
    assert_eq!(path.extension(), Some(std::ffi::OsStr::new("c")));
    let unit = Parse
        .translate(&path)
        .unwrap_or_else(|_| panic!("parse failed {}", path.display()));

    let temp_dir = tempdir().expect("temp dir creation failed");
    let temp_file_path = temp_dir.path().join("temp.c");
    let mut temp_file = File::create(&temp_file_path).unwrap();

    write(&unit, &mut temp_file).unwrap();

    let new_unit = Parse
        .translate(&temp_file_path.as_path())
        .expect("parse failed while parsing the output from implemented printer");

    if !unit.is_equiv(&new_unit) {
        let mut buf = String::new();
        // FIXME: For some reason we cannot reuse `temp_file`.
        let _ = File::open(&temp_file_path)
            .unwrap()
            .read_to_string(&mut buf)
            .unwrap();

        panic!("[write-c] Failed to correctly write {path:?}.\n\n[incorrect result]\n\n{buf}");
    }
}

/// Tests irgen.
pub fn test_irgen(path: &Path) {
    // Check if the file has .c extension
    assert_eq!(path.extension(), Some(std::ffi::OsStr::new("c")));
    let unit = Parse
        .translate(&path)
        .unwrap_or_else(|_| panic!("parse failed {}", path.display()));

    let mut ir = Irgen::default()
        .translate(&unit)
        .unwrap_or_else(|irgen_error| panic!("{}", irgen_error));

    let rand_num = rand::rng().random_range(1..100);
    let new_c = modify_c(path, rand_num);
    modify_ir(&mut ir, rand_num);

    // compile recolved c example
    let temp_dir = tempdir().expect("temp dir creation failed");
    let temp_file_path = temp_dir.path().join("temp.c");
    let mut temp_file = File::create(&temp_file_path).unwrap();
    temp_file.write_all(new_c.as_bytes()).unwrap();

    let file_path = temp_file_path.display().to_string();
    let bin_path = temp_file_path
        .with_extension("irgen")
        .as_path()
        .display()
        .to_string();

    // Compile c file: If fails, test is vacuously success
    if !Command::new("clang")
        .args([
            "-fsanitize=float-divide-by-zero",
            "-fsanitize=undefined",
            "-fno-sanitize-recover=all",
            &file_path,
            "-o",
            &bin_path,
        ])
        .stderr(Stdio::null())
        .status()
        .unwrap()
        .success()
    {
        ::std::process::exit(SKIP_TEST);
    }

    // Execute compiled executable
    let mut child = Command::new(fs::canonicalize(bin_path).unwrap())
        .stderr(Stdio::piped())
        .spawn()
        .expect("failed to execute the compiled executable");

    let Some(status) = child
        .wait_timeout(Duration::from_millis(1000))
        .expect("failed to obtain exit status from child process")
    else {
        println!("timeout occurs");
        child.kill().unwrap();
        let _ = child.wait().unwrap();
        ::std::process::exit(SKIP_TEST);
    };

    if child
        .stderr
        .expect("`stderr` of `child` must be `Some`")
        .bytes()
        .next()
        .is_some()
    {
        println!("error occurs");
        ::std::process::exit(SKIP_TEST);
    }

    let status = some_or_exit!(status.code(), SKIP_TEST);

    // Interpret resolved ir
    let args = Vec::new();
    let result = ir::interp(&ir, args).unwrap_or_else(|interp_error| panic!("{interp_error}"));
    // We only allow a main function whose return type is `int`
    let (value, width, is_signed) = result.get_int().expect("non-integer value occurs");
    assert_eq!(width, 32);
    assert!(is_signed);

    // When obtaining status from `clang` executable process, the status value is truncated to byte
    // size. For this reason, we make `fuzzer` generate the C source code which returns values
    // typecasted to `unsigned char`. However, during `creduce` to reduce the code, typecasting may
    // be nullified. So, we truncate the result value to byte size one more time here.
    println!("clang (expected): {}, kecc: {}", status as u8, value as u8);
    if status as u8 != value as u8 {
        let mut stderr = io::stderr().lock();
        stderr
            .write_fmt(format_args!(
                "[irgen] Failed to correctly generate {path:?}.\n\n [incorrect ir]"
            ))
            .unwrap();
        write(&ir, &mut stderr).unwrap();
        drop(stderr);
        panic!("[irgen]");
    }
}

/// Tests irparse.
pub fn test_irparse(path: &Path) {
    // Check if the file has .c extension
    assert_eq!(path.extension(), Some(std::ffi::OsStr::new("c")));
    let unit = Parse
        .translate(&path)
        .unwrap_or_else(|_| panic!("parse failed {}", path.display()));

    // Test parse
    let _unused = Parse
        .translate(&path)
        .expect("failed to parse the given program");

    let temp_dir = tempdir().expect("temp dir creation failed");

    // Test for original IR
    let ir = Irgen::default()
        .translate(&unit)
        .unwrap_or_else(|irgen_error| panic!("{}", irgen_error));
    let temp_file_path = temp_dir.path().join("ir0.ir");
    let mut temp_file = File::create(&temp_file_path).unwrap();
    write(&ir, &mut temp_file).unwrap();

    let ir0 = ir::Parse::default()
        .translate(&temp_file_path.as_path())
        .expect("parse failed while parsing the output from implemented printer");
    drop(temp_file);
    assert_eq!(ir, ir0);

    // Test for optimized IR
    let ir1 =
        test_irparse_for_optimized_ir(ir0, &temp_dir.path().join("ir1.ir"), SimplifyCfg::default());
    let ir2 =
        test_irparse_for_optimized_ir(ir1, &temp_dir.path().join("ir2.ir"), Mem2reg::default());
    let ir3 =
        test_irparse_for_optimized_ir(ir2, &temp_dir.path().join("ir3.ir"), Deadcode::default());
    let _unused =
        test_irparse_for_optimized_ir(ir3, &temp_dir.path().join("ir4.ir"), Gvn::default());

    temp_dir.close().expect("temp dir deletion failed");
}

#[inline]
fn test_irparse_for_optimized_ir<O: Optimize<ir::TranslationUnit>>(
    mut ir: ir::TranslationUnit,
    temp_file_path: &Path,
    mut opt: O,
) -> ir::TranslationUnit {
    let _ = opt.optimize(&mut ir);
    let mut temp_file = File::create(temp_file_path).unwrap();
    write(&ir, &mut temp_file).unwrap();

    let optimized_ir = ir::Parse::default()
        .translate(&temp_file_path)
        .expect("parse failed while parsing the output from implemented printer");
    drop(temp_file);
    assert_eq!(ir, optimized_ir);

    optimized_ir
}

/// Tests optimizations.
pub fn test_opt<P1: AsRef<Path>, P2: AsRef<Path>, O: Optimize<ir::TranslationUnit>>(
    from: &P1,
    to: &P2,
    opt: &mut O,
) {
    let from = ir::Parse::default()
        .translate(from)
        .expect("parse failed while parsing the output from implemented printer");
    let mut ir = from.clone();
    let to = ir::Parse::default()
        .translate(to)
        .expect("parse failed while parsing the output from implemented printer");
    let _ = opt.optimize(&mut ir);

    if !ir.is_equiv(&to) {
        let mut stderr = io::stderr().lock();
        stderr
            .write_fmt(format_args!(
                "[test_opt] actual outcome mismatches with the expected outcome.\n\n[before opt]"
            ))
            .unwrap();
        write(&from, &mut stderr).unwrap();
        stderr.write_fmt(format_args!("\n[after opt]")).unwrap();
        write(&ir, &mut stderr).unwrap();
        stderr
            .write_fmt(format_args!("\n[after opt (expected)]"))
            .unwrap();
        write(&to, &mut stderr).unwrap();
        drop(stderr);
        panic!("[test_opt]");
    }
}

/// Tests asmgen.
pub fn test_asmgen(path: &Path) {
    // Check if the file has .ir extension
    assert_eq!(path.extension(), Some(std::ffi::OsStr::new("ir")));
    let mut ir = ir::Parse::default()
        .translate(&path)
        .unwrap_or_else(|_| panic!("parse failed {}", path.display()));

    // Generate RISC-V assembly from IR
    let mut asm = Asmgen::default()
        .translate(&ir)
        .expect("fail to create riscv assembly code");

    let rand_num = rand::rng().random_range(1..100);
    modify_ir(&mut ir, rand_num);
    modify_asm(&mut asm, rand_num);

    // Execute IR
    let args = Vec::new();
    let result = ir::interp(&ir, args).unwrap_or_else(|interp_error| panic!("{}", interp_error));
    // We only allow main function whose return type is `int`
    let (value, width, is_signed) = result.get_int().expect("non-integer value occurs");
    assert_eq!(width, 32);
    assert!(is_signed);

    let temp_dir = tempdir().expect("temp dir creation failed");
    let asm_path = temp_dir.path().join("temp.S");
    let asm_path_str = asm_path.as_path().display().to_string();
    let bin_path_str = asm_path
        .with_extension("asmgen")
        .as_path()
        .display()
        .to_string();

    // Create the assembly code
    let mut buffer = File::create(asm_path.as_path()).expect("need to success creating file");
    write(&asm, &mut buffer).unwrap();

    // Compile the assembly code
    if !Command::new("riscv64-linux-gnu-gcc")
        .args(["-static", &asm_path_str, "-o", &bin_path_str])
        .stderr(Stdio::null())
        .status()
        .unwrap()
        .success()
    {
        ::std::process::exit(SKIP_TEST);
    }

    // Emulate the executable
    let mut child = Command::new("qemu-riscv64-static")
        .args([&bin_path_str])
        .stderr(Stdio::piped())
        .spawn()
        .expect("failed to execute the compiled executable");

    let Some(status) = child
        .wait_timeout(Duration::from_millis(1000))
        .expect("failed to obtain exit status from child process")
    else {
        println!("timeout occurs");
        child.kill().unwrap();
        let _ = child.wait().unwrap();
        ::std::process::exit(SKIP_TEST);
    };

    if child
        .stderr
        .expect("`stderr` of `child` must be `Some`")
        .bytes()
        .next()
        .is_some()
    {
        println!("error occurs");
        ::std::process::exit(SKIP_TEST);
    }

    let qemu_status = some_or_exit!(status.code(), SKIP_TEST);
    drop(buffer);
    temp_dir.close().expect("temp dir deletion failed");

    println!(
        "kecc interp (expected): {}, qemu: {}",
        value as u8, qemu_status as u8
    );
    assert_eq!(value as u8, qemu_status as u8);
}

/// Tests end-to-end translation.
pub fn test_end_to_end(path: &Path) {
    // Check if the file has .c extension
    assert_eq!(path.extension(), Some(std::ffi::OsStr::new("c")));

    // Test parse
    let unit = Parse
        .translate(&path)
        .unwrap_or_else(|_| panic!("parse failed {}", path.display()));

    let file_path = path.display().to_string();
    let bin_path = path
        .with_extension("endtoend")
        .as_path()
        .display()
        .to_string();

    // Compile c file: If fails, test is vacuously success
    if !Command::new("clang")
        .args([
            "-fsanitize=float-divide-by-zero",
            "-fsanitize=undefined",
            "-fno-sanitize-recover=all",
            &file_path,
            "-o",
            &bin_path,
        ])
        .stderr(Stdio::null())
        .status()
        .unwrap()
        .success()
    {
        ::std::process::exit(SKIP_TEST);
    }

    // Execute compiled executable
    let mut child = Command::new(fs::canonicalize(bin_path.clone()).unwrap())
        .stderr(Stdio::piped())
        .spawn()
        .expect("failed to execute the compiled executable");

    let _ = Command::new("rm")
        .arg(bin_path)
        .status()
        .expect("failed to remove compiled executable");

    let Some(status) = child
        .wait_timeout(Duration::from_millis(1000))
        .expect("failed to obtain exit status from child process")
    else {
        println!("timeout occurs");
        child.kill().unwrap();
        let _ = child.wait().unwrap();
        ::std::process::exit(SKIP_TEST);
    };

    if child
        .stderr
        .expect("`stderr` of `child` must be `Some`")
        .bytes()
        .next()
        .is_some()
    {
        println!("error occurs");
        ::std::process::exit(SKIP_TEST);
    }

    let clang_status = some_or_exit!(status.code(), SKIP_TEST);

    // Execute optimized IR
    let mut ir = Irgen::default()
        .translate(&unit)
        .unwrap_or_else(|irgen_error| panic!("{}", irgen_error));
    let _ = O1::default().optimize(&mut ir);
    let args = Vec::new();
    let result = ir::interp(&ir, args).unwrap_or_else(|interp_error| panic!("{}", interp_error));
    // We only allow a main function whose return type is `int`
    let (value, width, is_signed) = result.get_int().expect("non-integer value occurs");
    assert_eq!(width, 32);
    assert!(is_signed);

    // When obtaining status from `clang` executable process, the status value is truncated to byte
    // size. For this reason, we make `fuzzer` generate the C source code which returns values
    // typecasted to `unsigned char`. However, during `creduce` to reduce the code, typecasting may
    // be nullified. So, we truncate the result value to byte size one more time here.
    println!(
        "clang (expected): {}, kecc interp: {}",
        clang_status as u8, value as u8
    );
    assert_eq!(clang_status as u8, value as u8);

    // Generate RISC-V assembly from IR
    let asm = Asmgen::default()
        .translate(&ir)
        .expect("fail to create riscv assembly code");

    let temp_dir = tempdir().expect("temp dir creation failed");
    let asm_path = temp_dir.path().join("temp.S");
    let asm_path_str = asm_path.as_path().display().to_string();
    let bin_path_str = asm_path
        .with_extension("asmgen")
        .as_path()
        .display()
        .to_string();

    // Create the assembly code
    let mut buffer = File::create(asm_path.as_path()).expect("need to success creating file");
    write(&asm, &mut buffer).unwrap();

    // Compile the assembly code
    if !Command::new("riscv64-linux-gnu-gcc")
        .args(["-static", &asm_path_str, "-o", &bin_path_str])
        .stderr(Stdio::null())
        .status()
        .unwrap()
        .success()
    {
        ::std::process::exit(SKIP_TEST);
    }

    // Emulate the executable
    let mut child = Command::new("qemu-riscv64-static")
        .args([&bin_path_str])
        .stderr(Stdio::piped())
        .spawn()
        .expect("failed to execute the compiled executable");

    let Some(status) = child
        .wait_timeout(Duration::from_millis(1000))
        .expect("failed to obtain exit status from child process")
    else {
        println!("timeout occurs");
        child.kill().unwrap();
        let _ = child.wait().unwrap();
        ::std::process::exit(SKIP_TEST);
    };

    if child
        .stderr
        .expect("`stderr` of `child` must be `Some`")
        .bytes()
        .next()
        .is_some()
    {
        println!("error occurs");
        ::std::process::exit(SKIP_TEST);
    }

    let qemu_status = some_or_exit!(status.code(), SKIP_TEST);
    drop(buffer);
    temp_dir.close().expect("temp dir deletion failed");

    println!(
        "clang (expected): {}, qemu: {}",
        clang_status as u8, qemu_status as u8
    );
    assert_eq!(clang_status as u8, qemu_status as u8);
}