Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 9 additions & 22 deletions kani-driver/src/call_cbmc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ use std::process::Command;
use std::time::Instant;

use crate::args::KaniArgs;
use crate::cbmc_output_parser::process_cbmc_output;
use crate::cbmc_output_parser::{process_cbmc_output, VerificationOutput};
use crate::session::KaniSession;

#[derive(PartialEq, Eq)]
Expand All @@ -21,12 +21,6 @@ pub enum VerificationStatus {
impl KaniSession {
/// Verify a goto binary that's been prepared with goto-instrument
pub fn run_cbmc(&self, file: &Path, harness: &HarnessMetadata) -> Result<VerificationStatus> {
let output_filename = crate::util::append_path(file, "cbmc_output");
{
let mut temps = self.temporaries.borrow_mut();
temps.push(output_filename.clone());
}

let args: Vec<OsString> = self.cbmc_flags(file, harness)?;

// TODO get cbmc path from self
Expand All @@ -35,11 +29,11 @@ impl KaniSession {

let now = Instant::now();

let verification_result = if self.args.output_format == crate::args::OutputFormat::Old {
let verification_output = if self.args.output_format == crate::args::OutputFormat::Old {
if self.run_terminal(cmd).is_err() {
Ok(VerificationStatus::Failure)
VerificationOutput { status: VerificationStatus::Failure, processed_items: None }
} else {
Ok(VerificationStatus::Success)
VerificationOutput { status: VerificationStatus::Success, processed_items: None }
}
} else {
// Add extra argument to receive the output in JSON format.
Expand All @@ -51,17 +45,13 @@ impl KaniSession {
if let Some(cbmc_process) = cbmc_process_opt {
// The introduction of reachability checks forces us to decide
// the verification result based on the postprocessing of CBMC results.
let output_filename_opt: Option<&Path> =
self.args.concrete_playback.as_ref().map(|_| output_filename.as_path());
let processed_result = process_cbmc_output(
process_cbmc_output(
cbmc_process,
self.args.extra_pointer_checks,
&self.args.output_format,
output_filename_opt,
);
Ok(processed_result)
)
} else {
Ok(VerificationStatus::Failure)
VerificationOutput { status: VerificationStatus::Failure, processed_items: None }
}
};
// TODO: We should print this even the verification fails but not if it crashes.
Expand All @@ -70,11 +60,8 @@ impl KaniSession {
println!("Verification Time: {}s", elapsed);
}

if let Ok(VerificationStatus::Failure) = verification_result {
self.gen_and_add_concrete_playback(&output_filename, harness);
}

verification_result
self.gen_and_add_concrete_playback(harness, &verification_output)?;
Comment thread
sanjit-bhat marked this conversation as resolved.
Resolved
Ok(verification_output.status)
}

/// used by call_cbmc_viewer, invokes different variants of CBMC.
Expand Down
134 changes: 68 additions & 66 deletions kani-driver/src/cbmc_output_parser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,9 +30,8 @@ use serde::Deserialize;
use std::{
collections::HashMap,
env,
fs::File,
io::{BufRead, BufReader, BufWriter, Write},
path::{Path, PathBuf},
io::{BufRead, BufReader},
path::PathBuf,
process::{Child, ChildStdout},
};

Expand Down Expand Up @@ -184,7 +183,7 @@ const REACH_CHECK_DESC: &str = "[KANI_REACHABILITY_CHECK]";
/// See the parser for more information on how they are processed.
#[derive(Debug, Deserialize)]
#[serde(untagged)]
enum ParserItem {
pub enum ParserItem {
Program {
program: String,
},
Expand Down Expand Up @@ -297,6 +296,7 @@ fn filepath(file: String) -> String {
file
}
}

/// Struct that represents traces.
///
/// In general, traces may include more information than this, but this is not
Expand All @@ -307,7 +307,39 @@ pub struct TraceItem {
pub thread: u32,
pub step_type: String,
pub hidden: bool,
pub lhs: Option<String>,
pub source_location: Option<SourceLocation>,
pub value: Option<TraceValue>,
}

/// Struct that represents a trace value.
///
/// Note: this struct can have a lot of different fields depending on the value type.
/// The fields included right now are relevant to primitive types.
#[derive(Clone, Debug, Deserialize)]
pub struct TraceValue {
pub name: String,
pub binary: Option<String>,
pub data: Option<TraceData>,
pub width: Option<u8>,
}

/// Enum that represents a trace data item.
#[derive(Clone, Debug, Deserialize)]
#[serde(untagged)]
pub enum TraceData {
NonBool(String),
Bool(bool),
}

impl std::fmt::Display for TraceData {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let trace_data_str = match self {
Self::NonBool(trace_data) => trace_data.to_string(),
Self::Bool(trace_data) => trace_data.to_string(),
};
write! {f, "{}", trace_data_str}
}
}

#[derive(Copy, Clone, Debug, Deserialize, PartialEq, Eq)]
Expand Down Expand Up @@ -353,26 +385,11 @@ enum Action {
struct Parser<'a, 'b> {
pub input_so_far: String,
pub buffer: &'a mut BufReader<&'b mut ChildStdout>,
/// Buffered writer over the CBMC output file.
/// This is needed for old parsers (e.g., like the one in the concrete playback code) that require the actual CBMC output file.
/// TODO: This can be removed once we overhaul the concrete playback parser.
/// See this tracking issue: <https://github.com/model-checking/kani/issues/1477>.
cbmc_out_buf_writer: Option<BufWriter<File>>,
}

impl<'a, 'b> Parser<'a, 'b> {
pub fn new(
buffer: &'a mut BufReader<&'b mut ChildStdout>,
output_filename_opt: Option<&Path>,
) -> Self {
let cbmc_out_buf_writer = output_filename_opt.map(|output_filename| {
let cbmc_out_file = File::create(output_filename).expect(&format!(
"In CBMC output parser, couldn't create CBMC output file `{}`",
output_filename.display()
));
BufWriter::new(cbmc_out_file)
});
Parser { input_so_far: String::new(), buffer, cbmc_out_buf_writer }
pub fn new(buffer: &'a mut BufReader<&'b mut ChildStdout>) -> Self {
Parser { input_so_far: String::new(), buffer }
}

/// Triggers an action based on the input:
Expand Down Expand Up @@ -440,7 +457,6 @@ impl<'a, 'b> Parser<'a, 'b> {
/// Processes a line to determine if an action must be triggered.
/// The action may result in a `ParserItem`, which is then returned.
pub fn process_line(&mut self, input: String) -> Option<ParserItem> {
self.add_line_to_buf_writer(&input);
self.add_to_input(input.clone());
let action_required = self.triggers_action(input);
if let Some(action) = action_required {
Expand All @@ -449,26 +465,6 @@ impl<'a, 'b> Parser<'a, 'b> {
}
None
}

/// Adds a single line to the CBMC output buffered writer.
pub fn add_line_to_buf_writer(&mut self, line: &str) {
if let Some(buf_writer) = self.cbmc_out_buf_writer.as_mut() {
write!(buf_writer, "{}", line).expect(&format!(
"In CBMC output parser, couldn't write `{}` to CBMC output buffered writer",
line
));
}
}

/// Flushes the CBMC output buffered writer.
/// This should be called after the parser has processed the entire CBMC output.
pub fn flush_buf_writer(&mut self) {
if let Some(buf_writer) = self.cbmc_out_buf_writer.as_mut() {
buf_writer.flush().expect(
"In CBMC output parser, couldn't flush buffered writer to CBMC output file",
);
}
}
}

/// The iterator implementation for `Parser` reads the buffer line by line,
Expand All @@ -481,7 +477,6 @@ impl<'a, 'b> Iterator for Parser<'a, 'b> {
match self.buffer.read_line(&mut input) {
Ok(len) => {
if len == 0 {
self.flush_buf_writer();
return None;
}
let item = self.process_line(input);
Expand Down Expand Up @@ -537,6 +532,12 @@ fn postprocess_error_message(message: ParserItem) -> ParserItem {
}
}

/// The verification output, as extracted by the CBMC output parser.
pub struct VerificationOutput {
pub status: VerificationStatus,
pub processed_items: Option<Vec<ParserItem>>,
}

/// The main function to process CBMC's output.
///
/// First, we create a reader on CBMC's `stdout`, which is required for the
Expand All @@ -549,31 +550,32 @@ pub fn process_cbmc_output(
mut process: Child,
extra_ptr_checks: bool,
output_format: &OutputFormat,
output_filename_opt: Option<&Path>,
) -> VerificationStatus {
) -> VerificationOutput {
let stdout = process.stdout.as_mut().unwrap();
let mut stdout_reader = BufReader::new(stdout);
let parser = Parser::new(&mut stdout_reader, output_filename_opt);
let parser = Parser::new(&mut stdout_reader);
let mut result = false;

for item in parser {
Comment thread
sanjit-bhat marked this conversation as resolved.
Resolved
// Some items (e.g., messages) are skipped.
// We could also process them and decide to skip later.
if item.must_be_skipped() {
continue;
}
let processed_item = process_item(item, extra_ptr_checks, &mut result);
// Both formatting and printing could be handled by objects which
// implement a trait `Printer`.
let formatted_item = format_item(&processed_item, output_format);
if let Some(fmt_item) = formatted_item {
println!("{}", fmt_item);
}
// TODO: Record processed items and dump them into a JSON file
// <https://github.com/model-checking/kani/issues/942>
}

if result { VerificationStatus::Success } else { VerificationStatus::Failure }
let processed_items: Vec<_> = parser
.filter_map(|item| {
// Some items (e.g., messages) are skipped.
// We could also process them and decide to skip later.
if item.must_be_skipped() {
return None;
}
let processed_item = process_item(item, extra_ptr_checks, &mut result);
// Both formatting and printing could be handled by objects which
// implement a trait `Printer`.
let formatted_item = format_item(&processed_item, output_format);
if let Some(fmt_item) = formatted_item {
println!("{}", fmt_item);
}
// TODO: Record processed items and dump them into a JSON file
// <https://github.com/model-checking/kani/issues/942>
Some(processed_item)
})
.collect();
let status = if result { VerificationStatus::Success } else { VerificationStatus::Failure };
VerificationOutput { status, processed_items: Some(processed_items) }
}

/// Returns an optional formatted item based on the output format
Expand Down Expand Up @@ -915,7 +917,7 @@ fn remove_check_ids_from_description(mut properties: Vec<Property>) -> Vec<Prope
/// Extracts the property class from the property string.
///
/// Property strings have the format `([<function>.]<property_class_id>.<counter>)`
fn extract_property_class(property: &Property) -> Option<&str> {
pub fn extract_property_class(property: &Property) -> Option<&str> {
let property_class: Vec<&str> = property.property.rsplitn(3, '.').collect();
if property_class.len() > 1 { Some(property_class[1]) } else { None }
}
Expand Down
Loading