Repository navigation
Expand file tree
/
Copy pathffi.rs
More file actions
3782 lines (3577 loc) · 131 KB
/
Copy pathffi.rs
File metadata and controls
3782 lines (3577 loc) · 131 KB
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
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// SPDX-License-Identifier: GPL-3.0-only
//
// FFI boundary: #[unsafe(no_mangle)] extern "C" functions that Map2Check's LLVM Pass calls.
// With `sys.rs` (the C library calls of the result channel) and `wasm.rs`,
// one of the only modules that contain unsafe code (test modules aside).
// Every unsafe block is annotated with a SAFETY comment.
//
// The C ABI (D6, 2.0.0): the `#[no_mangle]` functions here are exactly the
// names of the C runtime of Map2Check `develop` that the core modules own
// (`Map2CheckFunctions`, `TrackBBLog`, `NonDetLog`, `PropertyGenerator`)
// and the `__m2c_rt_*` entry points the generated IR modules forward to
// (scripts/check-export-set.sh). The `extern "C"` functions without
// `#[no_mangle]` are the old core API (`map2check_set_mode`,
// `map2check_map_malloc`, `print_all_containers_as_json`...): no longer
// exported, kept as Rust functions because the Rust tests drive the core
// through them.
use std::borrow::Cow;
use std::ffi::CStr;
// Importações desmembradas para evitar bugs do cbindgen
use crate::analysismode::assert::AssertChecker;
use crate::analysismode::memory::DerefChecker;
use crate::analysismode::memory::FreeChecker;
use crate::analysismode::memory::FreeResolvedChecker;
use crate::analysismode::memory::LoadChecker;
use crate::analysismode::mode;
use crate::analysismode::mode::AnalysisMode;
use crate::analysismode::mode::Check;
use crate::analysismode::overflow::AddI32;
use crate::analysismode::overflow::AddU32;
use crate::analysismode::overflow::DivI32;
use crate::analysismode::overflow::DivU32;
use crate::analysismode::overflow::MulI32;
use crate::analysismode::overflow::MulU32;
use crate::analysismode::overflow::NegI32;
use crate::analysismode::overflow::ShlI32;
use crate::analysismode::overflow::ShrI32;
use crate::analysismode::overflow::ShrU32;
use crate::analysismode::overflow::SignedBinop;
use crate::analysismode::overflow::SignedOp;
use crate::analysismode::overflow::SubI32;
use crate::analysismode::overflow::SubU32;
use crate::analysismode::VccChecker;
use crate::analysismode::VccContext;
use crate::bbtrack::BasicBlockEntry;
use crate::caller::ViolatedProperty;
use crate::error::Map2CheckError;
use crate::memtrack::c_mode::FreeOutcome;
use crate::memtrack::c_mode::MemMode;
use crate::memtrack::MemOrigin;
use crate::memtrack::MemTrackEntry;
use crate::nondet::NonDetEntry;
use crate::nondet::NonDetValue;
use crate::output;
use crate::output::termination;
use crate::state;
// — Helpers —————————————————————————————————————————————————————————————————
/// Convert a raw C string to text, `""` on null. Valid UTF-8 is borrowed
/// unchanged; invalid UTF-8 keeps its valid parts and has each invalid
/// sequence replaced by U+FFFD, so a name develop prints with `%s` is never
/// dropped (the memory paths keep the raw bytes with [`c_bytes`]).
///
/// # Safety
/// `ptr` must be null or point to a valid, null-terminated C string that
/// remains valid for the duration of the call.
unsafe fn c_str<'a>(ptr: *const std::os::raw::c_char) -> Cow<'a, str> {
if ptr.is_null() {
return Cow::Borrowed("");
}
// SAFETY: caller guarantees ptr is a valid null-terminated C string.
unsafe { CStr::from_ptr(ptr) }.to_string_lossy()
}
// A assinatura foi encurtada porque importamos o Map2CheckError ali em cima
fn log_error(e: &Map2CheckError) {
termination::log_error(e);
}
/// Records a violation (the first one is final, SD-03). When it is the
/// first and a Map2Check analysis mode is set, the run ends here as in
/// develop's `map2check_error()`: the result files are written and the
/// process aborts (`output::termination`). `end_of_program` marks the
/// end-of-program verdict.
fn record_violation(property: ViolatedProperty, line: u32, fname: &str, end_of_program: bool) {
match state::with_state(|s| {
let first = s.result.ok;
if first && end_of_program {
s.end_of_program = true;
}
s.set_false(property, line, fname);
Ok(first)
}) {
Ok(true) => termination::on_violation(),
Ok(false) => {}
Err(e) => log_error(&e),
}
}
/// Runs `checker`, records a violation if it finds one, and returns whether
/// the check passed (`false` on a violation or an internal error).
fn run_vcc_check(checker: impl VccChecker, ctx: &VccContext, line: u32, fname: &str) -> bool {
match checker.check(ctx) {
Ok(crate::analysismode::VccOutcome::Violated { property }) => {
record_violation(property, line, fname, false);
false
}
Ok(crate::analysismode::VccOutcome::Safe) => true,
Err(e) => {
log_error(&e);
false
}
}
}
/// Whether `check` reports violations in the selected analysis mode.
fn check_active(check: Check) -> bool {
mode::check_enabled(state::config().mode, check)
}
/// A C `enum ViolatedProperty` received by value as its `int`, so any value
/// a C caller passes is defined behaviour. `cbindgen.toml` excludes this
/// alias and renames it, so the header keeps the parameter type `enum
/// ViolatedProperty` of the C runtime.
pub type ViolatedPropertyRaw = std::os::raw::c_int;
/// The C value of `enum ViolatedProperty` (`Map2CheckTypes.h:80-91`), the
/// discriminant of [`ViolatedProperty`]; 10 is `Concurrency`.
fn violated_property_from_raw(raw: i32) -> Option<ViolatedProperty> {
[
ViolatedProperty::None,
ViolatedProperty::Unknown,
ViolatedProperty::MemsafetyFree,
ViolatedProperty::MemsafetyDeref,
ViolatedProperty::MemsafetyMemtrack,
ViolatedProperty::Reachability,
ViolatedProperty::Overflow,
ViolatedProperty::Assert,
ViolatedProperty::MemsafetyMemcleanup,
ViolatedProperty::DivByZero,
ViolatedProperty::Concurrency,
]
.into_iter()
.find(|p| *p as i32 == raw)
}
/// Failure policy at the `extern "C"` boundary (issue #8).
///
/// Every `#[no_mangle]` export runs its body through this function
/// (enforced by `tests/ffi_guard_coverage.rs`).
///
/// - Unwinding profiles (`dev`, `release`, `runtime`; `panic = "unwind"`):
/// a panic is caught here with `catch_unwind`, a diagnostic is written to
/// stderr and `default` is returned, so no unwind ever reaches C.
/// - `panic = "abort"` builds (the KLEE runtime, `klee/Cargo.toml`): `catch_unwind` cannot
/// intercept anything; a panic aborts the process immediately and there is
/// no recovery. Exports therefore must not rely on panics for control flow.
///
/// Deliberate process termination (`__VERIFIER_error`, `__VERIFIER_assume(0)`)
/// is not a failure and bypasses recovery by design.
pub(crate) fn ffi_guard<T>(f: impl FnOnce() -> T, default: T) -> T {
// The drop-in core is built with `panic = "abort"` (klee/Cargo.toml):
// there is nothing to catch, and the panic goes straight to the abort.
#[cfg(feature = "dropin")]
{
let _ = default;
f()
}
#[cfg(not(feature = "dropin"))]
match std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)) {
Ok(value) => value,
Err(_) => {
crate::sys::diagnostic(b"panic in FFI boundary; recovering safely");
default
}
}
}
// ── Initialisation ────────────────────────────────────────────────────────────
/// `map2check_init` of the C runtime (`Map2CheckFunctions.c:29-40`), which
/// the Map2Check passes call first: starts a fresh analysis through the
/// `analysis_init` of the selected mode (every container, counter, result and
/// flag is cleared) and keeps the configuration, mode included. Must be
/// called before any tracking function. `is_sv_comp` only sets develop's
/// `sv_comp`, which nothing reads, so it is accepted and ignored. Like
/// develop, it leaves the property files of an earlier run alone.
///
/// In the drop-in core (feature `dropin`, klee/Cargo.toml) it then calls the
/// external `analysis_init` and `nondet_init`, in that order, as
/// `Map2CheckFunctions.c:37-38` does: the linked mode module selects the
/// mode, the linked generator module starts the nondet log. Both are defined
/// only by those IR modules (D7), so builds that link the staticlib alone
/// (cargo test, `tests/ffi_harness.c`, the host link tests) do not have the
/// feature and call `analysis_init` themselves. The calls run outside the
/// state lock: both come back into the core.
#[no_mangle]
pub extern "C" fn map2check_init(is_sv_comp: std::os::raw::c_int) {
ffi_guard(
|| {
let _ = is_sv_comp;
state::init();
#[cfg(feature = "dropin")]
dropin::init_linked_modules();
},
(),
);
}
/// The calls of the drop-in core into the mode, generator and witness
/// modules it is linked with (D7 layout A-fwd). Not in
/// `include/map2check.h`: the IR modules define these names, the library
/// does not. Every call is made with the state lock released: the modules
/// call back into the core.
///
/// cbindgen:ignore
#[cfg(feature = "dropin")]
pub(crate) mod dropin {
extern "C" {
/// `analysis_init` of the linked `AnalysisMode*.bc`.
fn analysis_init();
/// `nondet_init` of the linked `NonDetGenerator*.bc`.
fn nondet_init();
/// `analysis_generate_aux_witness_files` of the linked
/// `AnalysisMode*.bc`.
fn analysis_generate_aux_witness_files();
/// `nondet_generate_aux_witness_files` of the linked
/// `NonDetGenerator*.bc`: `klee_log.csv` (AFL++, KLEE) or nothing
/// (none).
fn nondet_generate_aux_witness_files();
/// `generate_aux_files(MAP2CHECK_CONTAINER *, Bool)` of the linked
/// `WitnessGeneration.bc` (forwards to
/// `__m2c_rt_witness_generate_aux_files`) or `WitnessGenerationNone.bc`
/// (empty).
fn generate_aux_files(
trackbb_log: *mut std::os::raw::c_void,
violation: std::os::raw::c_char,
);
/// `generate_confirmation_file` of the linked witness module.
fn generate_confirmation_file();
}
/// `Map2CheckFunctions.c:37-38`.
pub(super) fn init_linked_modules() {
// SAFETY: both are `void (void)` C functions of the linked modules,
// which only call back into the core's exports.
unsafe {
analysis_init();
nondet_init();
}
}
/// `generate_aux_files(&trackbb_log, gotError)` of `map2check_exit`
/// (`Map2CheckFunctions.c:95`). The core keeps the basic-block log
/// itself, so the container pointer is null (D7, finding 6).
pub(crate) fn witness_generate_aux_files(violation: bool) {
// SAFETY: a C function of the linked witness module; the pointer is
// never dereferenced (`__m2c_rt_witness_generate_aux_files`).
unsafe { generate_aux_files(std::ptr::null_mut(), std::os::raw::c_char::from(violation)) }
}
/// `generate_confirmation_file()` of `map2check_exit`
/// (`Map2CheckFunctions.c:98`).
pub(crate) fn witness_generate_confirmation_file() {
// SAFETY: a `void (void)` C function of the linked witness module.
unsafe { generate_confirmation_file() }
}
/// `analysis_generate_aux_witness_files()` of `generate_aux_files`
/// (`WitnessGeneration.c:17`).
pub(crate) fn mode_generate_aux_witness_files() {
// SAFETY: a `void (void)` C function of the linked mode module.
unsafe { analysis_generate_aux_witness_files() }
}
/// `nondet_generate_aux_witness_files()` of `generate_aux_files`
/// (`WitnessGeneration.c:27`).
pub(crate) fn generator_generate_aux_witness_files() {
// SAFETY: a `void (void)` C function of the linked generator module.
unsafe { nondet_generate_aux_witness_files() }
}
}
/// Resets the global analysis state without aborting the caller.
pub extern "C" fn map2check_reset() {
ffi_guard(state::reset, ());
}
// ── Result management ─────────────────────────────────────────────────────────
/// End of the analysed program. With the mode unset, prints the JSON
/// report. With an analysis mode set it prints nothing and is develop's
/// `map2check_success()`
/// (`Map2CheckFunctions.c:67-70`, `:89-102`): writes `NONE` to
/// `map2check_property`, runs the end-of-program verdict of the mode, writes
/// the witness files when the witness is on (`__m2c_rt_witness_enable`), and
/// returns; when the verdict is a violation it writes that property instead
/// and aborts.
#[no_mangle]
pub extern "C" fn map2check_success() {
ffi_guard(
|| {
if !termination::on_success() {
output::print_report_unless_mode_set();
}
},
(),
);
}
/// Records a verification failure.
///
/// # Safety
/// `function_name` must be null or a valid null-terminated C string.
pub unsafe extern "C" fn set_false_result(
prp: i32,
line_number: i32,
function_name: *const std::os::raw::c_char,
) {
ffi_guard(
|| {
let Some(property) = violated_property_from_raw(prp) else {
eprintln!("[map2check] invalid violated-property value: {prp}");
return;
};
// SAFETY: caller guarantees function_name is a valid C string or null.
let fname: &str = &unsafe { c_str(function_name) };
record_violation(property, line_number as u32, fname, false);
},
(),
);
}
/// Returns the currently violated property.
pub extern "C" fn get_current_property() -> ViolatedProperty {
ffi_guard(
|| state::with_state(|s| Ok(s.result.property)).unwrap_or(ViolatedProperty::None),
ViolatedProperty::None,
)
}
/// Returns the current step counter value.
pub extern "C" fn get_current_step() -> u64 {
ffi_guard(
|| state::with_state(|s| Ok(s.current_step())).unwrap_or(0),
0,
)
}
/// Advances and returns the step counter. Unlike `get_current_step`, this
/// mutates the counter — analogous to `get_next_step`/`next_current_step` in
/// the C library.
pub extern "C" fn get_next_step() -> u64 {
ffi_guard(|| state::with_state(|s| Ok(s.next_step())).unwrap_or(0), 0)
}
/// Prints the full JSON report to stdout when no analysis mode is set. With
/// a mode set (a Map2Check run) it prints nothing: the result goes to the
/// files, and the analysed program's stdout stays clean.
pub extern "C" fn print_all_containers_as_json() {
ffi_guard(output::print_report_unless_mode_set, ());
}
/// Resets violation metadata without clearing tracking containers.
/// Host/test-only: the Map2Check passes never call it. It clears a recorded
/// violation by design, bypassing the first-violation rule (#36, SD-03).
pub extern "C" fn vcc_reset_meta_data() {
ffi_guard(
|| {
if let Err(e) = state::with_state(|s| {
s.result.property = ViolatedProperty::None;
s.result.ok = true;
s.result.line = 0;
s.result.function_name.clear();
s.failed_free = None;
s.got_error = false;
Ok(())
}) {
log_error(&e);
}
},
(),
);
}
/// Selects the memcleanup property for the end-of-program leak check.
/// Effect: `map2check_check_mem_endprog` reports a leak as
/// `MemsafetyMemcleanup` instead of `MemsafetyMemtrack`. The option is
/// configuration: `map2check_init()` and `map2check_reset()` keep it.
pub extern "C" fn map2check_set_memcleanup() {
ffi_guard(
|| {
state::update_config(|c| c.memcleanup = true);
},
(),
);
}
/// Marks NULL as valid for load checks.
/// Effect: `map2check_check_load` treats a NULL `ptr` as safe once this has
/// been called, instead of flagging it as `MemsafetyDeref`. Kept across
/// `map2check_init()` and `map2check_reset()`.
pub extern "C" fn map2check_set_null_is_valid() {
ffi_guard(
|| {
state::update_config(|c| c.null_is_valid = true);
},
(),
);
}
/// Turns on witness generation, as linking `WitnessGeneration.c` instead of
/// `WitnessGenerationNone.c` does in develop (`caller.cpp:624-640`). Effect:
/// when a Map2Check run ends (an analysis mode is set), the library also
/// writes `track_bb_log.st`, `heap_log.csv`, `allocation_log.csv` and
/// `list_log.csv` (memory modes), and on a violation `klee_log.csv` and
/// `map2check_checked_error`. Configuration: kept by `map2check_init()` and
/// `map2check_reset()`. Its C ABI is `__m2c_rt_witness_enable`.
pub extern "C" fn map2check_enable_witness() {
ffi_guard(
|| {
state::update_config(|c| c.witness = true);
},
(),
);
}
/// Selects the analysis mode, as the frontend of Map2Check `develop` does by
/// linking one `AnalysisMode*.c` per run (`caller.cpp:575-612`). The
/// instrumented program calls it before `map2check_init()` with one of the
/// `AnalysisMode` values (`AnalysisMode_None` 0 to `AnalysisMode_Target` 5).
/// Any other value is ignored with a diagnostic on stderr and leaves the mode
/// as it was. The mode is configuration: `map2check_init()` and
/// `map2check_reset()` keep it. Until a valid value is set the mode is unset
/// and every check is active. Per-mode effects are in
/// `rust/src/analysismode/mode.rs`.
pub extern "C" fn map2check_set_mode(mode: i32) {
ffi_guard(
|| {
let Some(mode) = analysis_mode_from_raw(mode) else {
eprintln!("[map2check] invalid analysis mode: {mode}");
return;
};
state::update_config(|c| c.mode = Some(mode));
},
(),
);
}
fn analysis_mode_from_raw(raw: i32) -> Option<AnalysisMode> {
match raw {
0 => Some(AnalysisMode::None),
1 => Some(AnalysisMode::Memtrack),
2 => Some(AnalysisMode::Memcleanup),
3 => Some(AnalysisMode::Overflow),
4 => Some(AnalysisMode::Assert),
5 => Some(AnalysisMode::Target),
_ => None,
}
}
/// Records that the target function was reached, without ending the process.
/// Same property as `map2check_target_function` of the `develop` C runtime
/// (`TARGET_REACHED`, `Map2CheckFunctions.c:61-65`), which then ends the run;
/// here the first violation stays final (SD-03) and the caller keeps running.
///
/// # Safety
/// `func` must be null or a valid null-terminated C string.
pub(crate) unsafe fn mark_target_reached(
func: *const std::os::raw::c_char,
_scope: i32,
line: i32,
) {
// SAFETY: caller guarantees func is a valid C string or null.
let fname: &str = &unsafe { c_str(func) };
record_violation(ViolatedProperty::Reachability, line as u32, fname, false);
}
/// Called by the target pass when the target function (e.g. `reach_error`)
/// is reached. Records `Reachability` (develop's `TARGET-REACHED`) at `line`
/// in `func`, in every mode, and returns: ending the run is Task 2.4 (SD-15).
/// `scope` is accepted for ABI compatibility and ignored, as in develop.
///
/// # Safety
/// `func` must be null or a valid null-terminated C string.
pub unsafe extern "C" fn map2check_reach_target(
func: *const std::os::raw::c_char,
scope: i32,
line: i32,
) {
ffi_guard(
|| {
// SAFETY: caller guarantees func is a valid C string or null.
unsafe { mark_target_reached(func, scope, line) }
},
(),
);
}
// ── C runtime ABI: Map2CheckFunctions, TrackBBLog, PropertyGenerator ────────
//
// `Map2CheckFunctions.c`, `TrackBBLog.c` and `PropertyGenerator.c` of
// Map2Check `develop`, with their C signatures. The C-only helpers of those
// files (`write_property_<x>`, `trackbb_new_row`, `is_in_tracked`,
// `trackbb_log_to_file`) are private to the Rust core (SD-22).
/// `map2check_get_current_step` (`Map2CheckFunctions.c:42`): develop's
/// `Map2CheckCurrentStep`, 0 after `map2check_init`.
#[no_mangle]
pub extern "C" fn map2check_get_current_step() -> std::os::raw::c_uint {
ffi_guard(|| state::with_state(|s| Ok(s.c_step)).unwrap_or(0), 0)
}
/// `map2check_next_current_step` (`Map2CheckFunctions.c:43`): adds 1 to the
/// counter `map2check_get_current_step` reads, wrapping as a C `unsigned`.
#[no_mangle]
pub extern "C" fn map2check_next_current_step() {
ffi_guard(
|| {
if let Err(e) = state::with_state(|s| {
s.c_step = s.c_step.wrapping_add(1);
Ok(())
}) {
log_error(&e);
}
},
(),
);
}
/// `map2check_track_bb` (`Map2CheckFunctions.c:49-55`): appends a row for
/// the basic block at `line` of `function_name` unless a row of that line
/// exists (`is_in_tracked`), so the first function name of a line stays.
/// The rows are `track_bb_log.st` of the witness.
///
/// # Safety
/// `function_name` must be null or a valid null-terminated C string.
#[no_mangle]
pub unsafe extern "C" fn map2check_track_bb(
line: std::os::raw::c_uint,
function_name: *const std::os::raw::c_char,
) {
ffi_guard(
|| {
// SAFETY: caller guarantees function_name is a valid C string or null.
let fname: &str = &unsafe { c_str(function_name) };
if let Err(e) = state::with_state(|s| {
if !crate::bbtrack::is_in_tracked(line, &s.bbtrack) {
let step = s.next_step();
s.bbtrack
.push(crate::bbtrack::trackbb_new_row(step, line, fname));
}
Ok(())
}) {
log_error(&e);
}
},
(),
);
}
/// `__VERIFIER_error` of the C core (`Map2CheckFunctions.c:57-59`): "DO
/// NOTHING". The passes carry the checks (the target through
/// `map2check_target_function`, asserts through `map2check_assert`), so a
/// program's own call has no effect and the run goes on, with a mode set
/// and without (SD-08).
#[no_mangle]
pub extern "C" fn __VERIFIER_error() {
ffi_guard(|| (), ());
}
/// `map2check_target_function` (`Map2CheckFunctions.c:61-65`), which the
/// target pass calls when the target function is reached: records
/// `TARGET_REACHED` at `line` in `func_name`; `scope` is not used. With a
/// mode set the run ends as develop's does (`map2check_property` has
/// `TARGET-REACHED`, abort); unset, it returns (SD-15).
///
/// # Safety
/// `func_name` must be null or a valid null-terminated C string.
#[no_mangle]
pub unsafe extern "C" fn map2check_target_function(
func_name: *const std::os::raw::c_char,
scope: std::os::raw::c_int,
line: std::os::raw::c_int,
) {
ffi_guard(
|| {
// SAFETY: caller guarantees func_name is a valid C string or null.
unsafe { mark_target_reached(func_name, scope, line) }
},
(),
);
}
/// `map2check_error` (`Map2CheckFunctions.c:72-75`): marks the run as
/// failed (`gotError`) and calls `map2check_exit`, which skips the
/// end-of-program verdict and, with a mode set, writes the witness files
/// (when enabled) and aborts. It writes no property file; develop's callers
/// write theirs first. Without a mode it returns (SD-03, SD-14).
#[no_mangle]
pub extern "C" fn map2check_error() {
ffi_guard(termination::map2check_error, ());
}
/// `map2check_exit` (`Map2CheckFunctions.c:89-102`): with no error yet, runs
/// the end-of-program verdict of the mode (a leak writes its property files);
/// then writes the witness files when enabled, runs `map2check_destroy`, and
/// on an error writes `map2check_checked_error` (witness on) and aborts.
/// Unlike `map2check_success` it writes no `NONE`. Without a mode nothing is
/// written and it returns (SD-03, SD-14).
#[no_mangle]
pub extern "C" fn map2check_exit() {
ffi_guard(termination::map2check_exit, ());
}
/// `map2check_destroy` (`Map2CheckFunctions.c:77-87`): releases the
/// basic-block log and the containers of the mode (`analysis_destroy`),
/// once per run; a second call does nothing until `map2check_init`.
#[no_mangle]
pub extern "C" fn map2check_destroy() {
ffi_guard(
|| {
let config = state::config();
if let Err(e) = state::with_state(|s| {
termination::destroy(config, s);
Ok(())
}) {
log_error(&e);
}
},
(),
);
}
/// `write_property` (`PropertyGenerator.c:50-106`): writes
/// `map2check_property` with the text of `violated` and, for FALSE-FREE,
/// FALSE-DEREF, FALSE-MEMTRACK, FALSE-MEMCLEANUP, OVERFLOW and ASSERT, its
/// `map2check_property_<prp>` file, into the current directory, whatever
/// the mode; `Line: %d` and `Function: %s` as develop prints them. It does
/// not record a violation or end the run. `Concurrency`, outside the C
/// switch, leaves `map2check_property` empty.
///
/// `violated` is taken as a C `int` ([`ViolatedPropertyRaw`], `enum
/// ViolatedProperty` in the header), so a value outside the enum is not
/// undefined behaviour: like a value with no case in the C switch, it leaves
/// `map2check_property` empty.
///
/// # Safety
/// `function_name` must be null or a valid null-terminated C string.
#[no_mangle]
pub unsafe extern "C" fn write_property(
violated: ViolatedPropertyRaw,
line: std::os::raw::c_int,
function_name: *const std::os::raw::c_char,
) {
ffi_guard(
|| {
// No case in the C switch: empty text, as for `Concurrency`.
let violated =
violated_property_from_raw(violated).unwrap_or(ViolatedProperty::Concurrency);
// SAFETY: caller guarantees function_name is a valid C string or null.
let fname: &str = &unsafe { c_str(function_name) };
termination::write_property(violated, line, fname);
},
(),
);
}
/// Core entry point of `generate_aux_files` (`WitnessGeneration.c:15-29`),
/// which the IR module `WitnessGeneration.bc` forwards to (D7): writes
/// `track_bb_log.st`, the logs of the memory modes and, when `violation` is
/// nonzero or `MAP2CHECK_SEED_REPLAY` is set, `klee_log.csv`, into the
/// current directory. `trackbb_log` is develop's container pointer; the core
/// reads its own state, so it is ignored and may be null.
///
/// # Safety
/// `trackbb_log` is never dereferenced.
#[no_mangle]
pub unsafe extern "C" fn __m2c_rt_witness_generate_aux_files(
trackbb_log: *mut std::os::raw::c_void,
violation: std::os::raw::c_char,
) {
ffi_guard(
|| {
let _ = trackbb_log;
termination::rt_generate_aux_files(violation != 0);
},
(),
);
}
/// Core entry point of `generate_confirmation_file`
/// (`WitnessGeneration.c:32-36`), which `WitnessGeneration.bc` forwards to
/// (D7): writes `END OF TIME` to `map2check_checked_error`.
#[no_mangle]
pub extern "C" fn __m2c_rt_witness_generate_confirmation_file() {
ffi_guard(termination::rt_generate_confirmation_file, ());
}
/// Turns on the witness files of a Map2Check run, the C ABI of the old
/// `map2check_enable_witness` (not exported since 2.0.0, Task 2.10), with
/// its behaviour: when a run with a mode ends, `map2check_exit` also writes
/// `track_bb_log.st`, the logs of the memory modes and, on a violation,
/// `klee_log.csv` and `map2check_checked_error`. Configuration, kept by
/// `map2check_init`. In develop the frontend selects the witness by linking
/// `WitnessGeneration.bc` instead of `WitnessGenerationNone.bc`
/// (`caller.cpp:624-640`); the host programs that link the staticlib
/// (`tests/ffi_harness.c`, the link tests of `scripts/runtime-ir/`) call
/// this instead. No IR module calls it, and the drop-in core (feature
/// `dropin`) ignores the option: it ends a run through the
/// `generate_aux_files`/`generate_confirmation_file` of the witness module it
/// is linked with, as the C does (Task 3.1). It stays for the staticlib,
/// which cannot reference those module functions (they would be undefined in
/// `cargo test` and in every program that links the staticlib alone).
#[no_mangle]
pub extern "C" fn __m2c_rt_witness_enable() {
ffi_guard(|| state::update_config(|c| c.witness = true), ());
}
// ── C runtime ABI: AnalysisModeOverflow (core entry points, D7) ─────────────
//
// `AnalysisModeOverflow.c` of Map2Check `develop`. The C names
// (`analysis_*`, `map2check_binop_*`, `overflowError`) are defined only by
// the generated IR module `AnalysisModeOverflow.bc`
// (`scripts/runtime-ir/gen_ll.py`), which forwards each one to the
// `__m2c_rt_overflow_<name>` below: every analysis mode defines
// `analysis_*`, so the core must not. `divisionByZeroError` and
// `unknown_not_supported` have no caller outside the C module and stay
// private (SD-22). The checks are `SignedBinop` (`analysismode::overflow`).
/// The signed binops of `AnalysisModeOverflow.c:197-276`: on a violation,
/// `overflowError` (FALSE_OVERFLOW, `:185-188`) or `divisionByZeroError`
/// (FALSE_DIVBYZERO, `:192-195`), which write the property files and call
/// `map2check_error`. No mode gate: linking the module is the mode. `scope`
/// is not used, as in C.
///
/// # Safety
/// `function_name` must be null or a valid null-terminated C string.
unsafe fn rt_overflow_signed(
op: SignedOp,
param1: i64,
param2: i64,
width: std::os::raw::c_uint,
line: std::os::raw::c_uint,
function_name: *const std::os::raw::c_char,
) {
let checker = SignedBinop {
op,
lhs: param1,
rhs: param2,
bits: width,
};
if let Some(property) = checker.violation() {
// SAFETY: caller guarantees function_name is valid or null.
let fname: &str = &unsafe { c_str(function_name) };
record_violation(property, line, fname, false);
}
}
/// `analysis_init` of the overflow mode (`AnalysisModeOverflow.c:279`). The C
/// body is empty: linking this module is what selects the overflow mode
/// (`caller.cpp:575-612`), so the core entry point selects
/// `AnalysisMode_Overflow`, which turns on the result files and the abort
/// of the first violation (SD-14). Nothing else changes.
#[no_mangle]
pub extern "C" fn __m2c_rt_overflow_analysis_init() {
ffi_guard(
|| state::update_config(|c| c.mode = Some(AnalysisMode::Overflow)),
(),
);
}
/// `analysis_destroy` of the overflow mode (`AnalysisModeOverflow.c:281`):
/// empty, the mode keeps no data.
#[no_mangle]
pub extern "C" fn __m2c_rt_overflow_analysis_destroy() {
ffi_guard(|| (), ());
}
/// `analysis_is_program_correct` of the overflow mode
/// (`AnalysisModeOverflow.c:283`): always TRUE (1).
#[no_mangle]
pub extern "C" fn __m2c_rt_overflow_analysis_is_program_correct() -> std::os::raw::c_char {
ffi_guard(|| 1, 1)
}
/// `analysis_generate_aux_witness_files` of the overflow mode
/// (`AnalysisModeOverflow.c:285`): empty.
#[no_mangle]
pub extern "C" fn __m2c_rt_overflow_analysis_generate_aux_witness_files() {
ffi_guard(|| (), ());
}
/// `overflowError` (`AnalysisModeOverflow.c:185-188`):
/// `write_property(FALSE_OVERFLOW, line, function_name)` and
/// `map2check_error()`. Here: records `OVERFLOW` at `line` in
/// `function_name` (the first violation stays final, SD-03); with a mode set
/// the property files are written and the process aborts. NULL reads as "".
///
/// # Safety
/// `function_name` must be null or a valid null-terminated C string.
#[allow(non_snake_case)]
#[no_mangle]
pub unsafe extern "C" fn __m2c_rt_overflow_overflowError(
line: std::os::raw::c_uint,
function_name: *const std::os::raw::c_char,
) {
ffi_guard(
|| {
// SAFETY: caller guarantees function_name is valid or null.
let fname: &str = &unsafe { c_str(function_name) };
record_violation(ViolatedProperty::Overflow, line, fname, false);
},
(),
);
}
/// `map2check_binop_add` (`AnalysisModeOverflow.c:197-206`): `OVERFLOW` when `param1 + param2` leaves the range of `width`.
/// Operands sign-extended to 64 bits, `width` the bit width of the result
/// type (0 or 64 and above mean 64). See `rt_overflow_signed`.
///
/// # Safety
/// `function_name` must be null or a valid null-terminated C string.
#[no_mangle]
pub unsafe extern "C" fn __m2c_rt_overflow_map2check_binop_add(
param1: i64,
param2: i64,
width: std::os::raw::c_uint,
line: std::os::raw::c_uint,
scope: std::os::raw::c_uint,
function_name: *const std::os::raw::c_char,
) {
ffi_guard(
|| {
let _ = scope;
// SAFETY: forwarded caller contract.
unsafe { rt_overflow_signed(SignedOp::Add, param1, param2, width, line, function_name) }
},
(),
);
}
/// `map2check_binop_sub` (`AnalysisModeOverflow.c:208-217`): `OVERFLOW` when `param1 - param2` leaves the range of `width`.
/// Operands sign-extended to 64 bits, `width` the bit width of the result
/// type (0 or 64 and above mean 64). See `rt_overflow_signed`.
///
/// # Safety
/// `function_name` must be null or a valid null-terminated C string.
#[no_mangle]
pub unsafe extern "C" fn __m2c_rt_overflow_map2check_binop_sub(
param1: i64,
param2: i64,
width: std::os::raw::c_uint,
line: std::os::raw::c_uint,
scope: std::os::raw::c_uint,
function_name: *const std::os::raw::c_char,
) {
ffi_guard(
|| {
let _ = scope;
// SAFETY: forwarded caller contract.
unsafe { rt_overflow_signed(SignedOp::Sub, param1, param2, width, line, function_name) }
},
(),
);
}
/// `map2check_binop_mul` (`AnalysisModeOverflow.c:234-243`): `OVERFLOW` when `param1 * param2` leaves the range of `width`.
/// Operands sign-extended to 64 bits, `width` the bit width of the result
/// type (0 or 64 and above mean 64). See `rt_overflow_signed`.
///
/// # Safety
/// `function_name` must be null or a valid null-terminated C string.
#[no_mangle]
pub unsafe extern "C" fn __m2c_rt_overflow_map2check_binop_mul(
param1: i64,
param2: i64,
width: std::os::raw::c_uint,
line: std::os::raw::c_uint,
scope: std::os::raw::c_uint,
function_name: *const std::os::raw::c_char,
) {
ffi_guard(
|| {
let _ = scope;
// SAFETY: forwarded caller contract.
unsafe { rt_overflow_signed(SignedOp::Mul, param1, param2, width, line, function_name) }
},
(),
);
}
/// `map2check_binop_sdiv` (`AnalysisModeOverflow.c:250-262`): `FALSE-DIVBYZERO` when `param2` is 0, `OVERFLOW` for MIN / -1 of `width`.
/// Operands sign-extended to 64 bits, `width` the bit width of the result
/// type (0 or 64 and above mean 64). See `rt_overflow_signed`.
///
/// # Safety
/// `function_name` must be null or a valid null-terminated C string.
#[no_mangle]
pub unsafe extern "C" fn __m2c_rt_overflow_map2check_binop_sdiv(
param1: i64,
param2: i64,
width: std::os::raw::c_uint,
line: std::os::raw::c_uint,
scope: std::os::raw::c_uint,
function_name: *const std::os::raw::c_char,
) {
ffi_guard(
|| {
let _ = scope;
// SAFETY: forwarded caller contract.
unsafe { rt_overflow_signed(SignedOp::Div, param1, param2, width, line, function_name) }
},
(),
);
}
/// `map2check_binop_srem` (`AnalysisModeOverflow.c:264-276`): `FALSE-DIVBYZERO` when `param2` is 0, `OVERFLOW` for MIN % -1 of `width` (undefined in C).
/// Operands sign-extended to 64 bits, `width` the bit width of the result
/// type (0 or 64 and above mean 64). See `rt_overflow_signed`.
///
/// # Safety
/// `function_name` must be null or a valid null-terminated C string.
#[no_mangle]
pub unsafe extern "C" fn __m2c_rt_overflow_map2check_binop_srem(
param1: i64,
param2: i64,
width: std::os::raw::c_uint,
line: std::os::raw::c_uint,
scope: std::os::raw::c_uint,
function_name: *const std::os::raw::c_char,
) {
ffi_guard(
|| {
let _ = scope;
// SAFETY: forwarded caller contract.
unsafe { rt_overflow_signed(SignedOp::Rem, param1, param2, width, line, function_name) }
},
(),
);
}
/// `map2check_binop_add_uint` (`AnalysisModeOverflow.c:224-227`): a deliberate
/// no-op, as in C (`:219-223`): unsigned wraparound is well-defined and is
/// not an overflow under SV-COMP's no-overflow property.
#[no_mangle]
pub extern "C" fn __m2c_rt_overflow_map2check_binop_add_uint(
param1: u64,
param2: u64,
width: std::os::raw::c_uint,
line: std::os::raw::c_uint,
scope: std::os::raw::c_uint,
function_name: *const std::os::raw::c_char,
) {
ffi_guard(
|| {
let _ = (param1, param2, width, line, scope, function_name);
},
(),
);
}
/// `map2check_binop_sub_uint` (`AnalysisModeOverflow.c:229-232`): a deliberate
/// no-op, as in C (`:219-223`): unsigned wraparound is well-defined and is
/// not an overflow under SV-COMP's no-overflow property.
#[no_mangle]
pub extern "C" fn __m2c_rt_overflow_map2check_binop_sub_uint(
param1: u64,
param2: u64,
width: std::os::raw::c_uint,
line: std::os::raw::c_uint,
scope: std::os::raw::c_uint,
function_name: *const std::os::raw::c_char,
) {
ffi_guard(
|| {
let _ = (param1, param2, width, line, scope, function_name);
},
(),
);
}
/// `map2check_binop_mul_uint` (`AnalysisModeOverflow.c:245-248`): a deliberate
/// no-op, as in C (`:219-223`): unsigned wraparound is well-defined and is
/// not an overflow under SV-COMP's no-overflow property.
#[no_mangle]
pub extern "C" fn __m2c_rt_overflow_map2check_binop_mul_uint(
param1: u64,
param2: u64,
width: std::os::raw::c_uint,
line: std::os::raw::c_uint,
scope: std::os::raw::c_uint,
function_name: *const std::os::raw::c_char,
) {
ffi_guard(
|| {
let _ = (param1, param2, width, line, scope, function_name);
},