use of com.dat3m.dartagnan.program.Program in project Dat3M by hernanponcedeleon.
the class ProgramParser method parse.
public Program parse(File file) throws Exception {
if (file.getPath().endsWith("c")) {
compileWithClang(file);
compileWithSmack(file);
String name = file.getName().substring(0, file.getName().lastIndexOf('.'));
return new ProgramParser().parse(new File(System.getenv("DAT3M_HOME") + "/output/" + name + ".bpl"));
}
Program program;
try (FileInputStream stream = new FileInputStream(file)) {
ParserInterface parser = getConcreteParser(file);
CharStream charStream = CharStreams.fromStream(stream);
program = parser.parse(charStream);
}
program.setName(file.getName());
return program;
}
use of com.dat3m.dartagnan.program.Program in project Dat3M by hernanponcedeleon.
the class ProgramParser method parse.
public Program parse(String raw, String format) throws Exception {
switch(format) {
case "c":
case "i":
File CFile = File.createTempFile("dat3m", ".c");
CFile.deleteOnExit();
String name = CFile.getName().substring(0, CFile.getName().lastIndexOf('.'));
try (FileWriter writer = new FileWriter(CFile)) {
writer.write(raw);
}
compileWithClang(CFile);
compileWithSmack(CFile);
File BplFile = new File(System.getenv("DAT3M_HOME") + "/output/" + name + ".bpl");
BplFile.deleteOnExit();
Program p = new ProgramParser().parse(BplFile);
CFile.delete();
BplFile.delete();
return p;
case "bpl":
return new ParserBoogie().parse(CharStreams.fromString(raw));
case "litmus":
return getConcreteLitmusParser(raw.toUpperCase()).parse(CharStreams.fromString(raw));
}
throw new ParsingException("Unknown input file type");
}
use of com.dat3m.dartagnan.program.Program in project Dat3M by hernanponcedeleon.
the class Dartagnan method main.
public static void main(String[] args) throws Exception {
if (Arrays.asList(args).contains("--help")) {
collectOptions();
return;
}
CreateGitInfo();
String[] argKeyword = Arrays.stream(args).filter(s -> s.startsWith("-")).toArray(String[]::new);
// TODO: We don't parse configs yet
Configuration config = Configuration.fromCmdLineArguments(argKeyword);
Dartagnan o = new Dartagnan(config);
if (Arrays.stream(args).noneMatch(a -> supportedFormats.stream().anyMatch(a::endsWith))) {
throw new IllegalArgumentException("Input program not given or format not recognized");
}
// get() is guaranteed to success
File fileProgram = new File(Arrays.stream(args).filter(a -> supportedFormats.stream().anyMatch(a::endsWith)).findFirst().get());
logger.info("Program path: " + fileProgram);
if (Arrays.stream(args).noneMatch(a -> a.endsWith(".cat"))) {
throw new IllegalArgumentException("CAT model not given or format not recognized");
}
// get() is guaranteed to success
File fileModel = new File(Arrays.stream(args).filter(a -> a.endsWith(".cat")).findFirst().get());
logger.info("CAT file path: " + fileModel);
Wmm mcm = new ParserCat().parse(fileModel);
Program p = new ProgramParser().parse(fileProgram);
EnumSet<Property> properties = o.getProperty();
WitnessGraph witness = new WitnessGraph();
if (o.runValidator()) {
logger.info("Witness path: " + o.getWitnessPath());
witness = new ParserWitness().parse(new File(o.getWitnessPath()));
}
VerificationTask task = VerificationTask.builder().withConfig(config).withWitness(witness).build(p, mcm, properties);
ShutdownManager sdm = ShutdownManager.create();
Thread t = new Thread(() -> {
try {
if (o.hasTimeout()) {
// Converts timeout from secs to millisecs
Thread.sleep(1000L * o.getTimeout());
sdm.requestShutdown("Shutdown Request");
logger.warn("Shutdown Request");
}
} catch (InterruptedException e) {
// Verification ended, nothing to be done.
}
});
try {
t.start();
Configuration solverConfig = Configuration.builder().setOption(PHANTOM_REFERENCES, valueOf(o.usePhantomReferences())).build();
try (SolverContext ctx = SolverContextFactory.createSolverContext(solverConfig, BasicLogManager.create(solverConfig), sdm.getNotifier(), o.getSolver());
ProverEnvironment prover = ctx.newProverEnvironment(ProverOptions.GENERATE_MODELS)) {
Result result = UNKNOWN;
if (properties.contains(RACES)) {
if (properties.size() > 1) {
System.out.println("Data race detection cannot be combined with other properties");
System.exit(1);
}
result = DataRaceSolver.run(ctx, prover, task);
} else {
// Property is either LIVENESS and/or REACHABILITY
switch(o.getMethod()) {
case TWO:
try (ProverEnvironment prover2 = ctx.newProverEnvironment(ProverOptions.GENERATE_MODELS)) {
result = TwoSolvers.run(ctx, prover, prover2, task);
}
break;
case INCREMENTAL:
result = IncrementalSolver.run(ctx, prover, task);
break;
case ASSUME:
result = AssumeSolver.run(ctx, prover, task);
break;
case CAAT:
result = RefinementSolver.run(ctx, prover, RefinementTask.fromVerificationTaskWithDefaultBaselineWMM(task));
break;
}
}
// Verification ended, we can interrupt the timeout Thread
t.interrupt();
if (result.equals(FAIL) && o.generateGraphviz()) {
ExecutionModel m = new ExecutionModel(task);
m.initialize(prover.getModel(), ctx);
String name = task.getProgram().getName().substring(0, task.getProgram().getName().lastIndexOf('.'));
generateGraphvizFile(m, 1, (x, y) -> true, System.getenv("DAT3M_HOME") + "/output/", name);
}
if (p.getFormat().equals(SourceLanguage.LITMUS)) {
if (p.getAssFilter() != null) {
System.out.println("Filter " + (p.getAssFilter()));
}
System.out.println("Condition " + p.getAss().toStringWithType());
System.out.println(result == FAIL ? "Ok" : "No");
} else {
if (result == FAIL) {
if (TRUE.equals(prover.getModel().evaluate(REACHABILITY.getSMTVariable(ctx)))) {
System.out.println("Safety violation found");
}
if (TRUE.equals(prover.getModel().evaluate(LIVENESS.getSMTVariable(ctx)))) {
System.out.println("Liveness violation found");
}
}
System.out.println(result);
}
try {
WitnessBuilder w = new WitnessBuilder(task, ctx, prover, result);
// and if we are not doing witness validation
if (properties.contains(REACHABILITY) && w.canBeBuilt() && !o.runValidator()) {
w.build().write();
}
} catch (InvalidConfigurationException e) {
logger.warn(e.getMessage());
}
}
} catch (InterruptedException e) {
logger.warn("Timeout elapsed. The SMT solver was stopped");
System.out.println("TIMEOUT");
System.exit(0);
} catch (Exception e) {
logger.error(e.getMessage());
System.out.println("ERROR");
System.exit(1);
}
}
use of com.dat3m.dartagnan.program.Program in project Dat3M by hernanponcedeleon.
the class RefinementSolver method run.
// TODO: We do not yet use Witness information. The problem is that WitnessGraph.encode() generates
// constraints on hb, which is not encoded in Refinement.
public static Result run(SolverContext ctx, ProverEnvironment prover, RefinementTask task) throws InterruptedException, SolverException, InvalidConfigurationException {
task.preprocessProgram();
if (task.getProgram().getAss() instanceof AssertTrue) {
logger.info("Verification finished: assertion trivially holds");
return PASS;
}
task.performStaticProgramAnalyses();
task.performStaticWmmAnalyses();
task.initializeEncoders(ctx);
ProgramEncoder programEncoder = task.getProgramEncoder();
PropertyEncoder propertyEncoder = task.getPropertyEncoder();
WmmEncoder baselineEncoder = task.getBaselineWmmEncoder();
SymmetryEncoder symmEncoder = task.getSymmetryEncoder();
Program program = task.getProgram();
WMMSolver solver = new WMMSolver(task);
Refiner refiner = new Refiner(task);
CAATSolver.Status status = INCONSISTENT;
logger.info("Starting encoding using " + ctx.getVersion());
prover.addConstraint(programEncoder.encodeFullProgram(ctx));
prover.addConstraint(baselineEncoder.encodeFullMemoryModel(ctx));
prover.addConstraint(symmEncoder.encodeFullSymmetry(ctx));
prover.push();
prover.addConstraint(propertyEncoder.encodeSpecification(task.getProperty(), ctx));
// ------ Just for statistics ------
List<DNF<CoreLiteral>> foundCoreReasons = new ArrayList<>();
List<WMMSolver.Statistics> statList = new ArrayList<>();
int iterationCount = 0;
long lastTime = System.currentTimeMillis();
long curTime;
long totalNativeSolvingTime = 0;
long totalCaatTime = 0;
// ---------------------------------
logger.info("Refinement procedure started.");
while (!prover.isUnsat()) {
if (iterationCount == 0 && logger.isDebugEnabled()) {
String smtStatistics = "\n ===== SMT Statistics (after first iteration) ===== \n";
for (String key : prover.getStatistics().keySet()) {
smtStatistics += String.format("\t%s -> %s\n", key, prover.getStatistics().get(key));
}
logger.debug(smtStatistics);
}
iterationCount++;
curTime = System.currentTimeMillis();
totalNativeSolvingTime += (curTime - lastTime);
logger.debug("Solver iteration: \n" + " ===== Iteration: {} =====\n" + "Solving time(ms): {}", iterationCount, curTime - lastTime);
curTime = System.currentTimeMillis();
WMMSolver.Result solverResult;
try (Model model = prover.getModel()) {
solverResult = solver.check(model, ctx);
} catch (SolverException e) {
logger.error(e);
throw e;
}
WMMSolver.Statistics stats = solverResult.getStatistics();
statList.add(stats);
logger.debug("Refinement iteration:\n{}", stats);
status = solverResult.getStatus();
if (status == INCONSISTENT) {
DNF<CoreLiteral> reasons = solverResult.getCoreReasons();
foundCoreReasons.add(reasons);
prover.addConstraint(refiner.refine(reasons, ctx));
if (REFINEMENT_GENERATE_GRAPHVIZ_DEBUG_FILES) {
generateGraphvizFiles(task, solver.getExecution(), iterationCount, reasons);
}
if (logger.isTraceEnabled()) {
// Some statistics
StringBuilder message = new StringBuilder().append("Found inconsistency reasons:");
for (Conjunction<CoreLiteral> cube : reasons.getCubes()) {
message.append("\n").append(cube);
}
logger.trace(message);
}
} else {
// No violations found, we can't refine
break;
}
totalCaatTime += (System.currentTimeMillis() - curTime);
lastTime = System.currentTimeMillis();
}
iterationCount++;
curTime = System.currentTimeMillis();
totalNativeSolvingTime += (curTime - lastTime);
logger.debug("Final solver iteration:\n" + " ===== Final Iteration: {} =====\n" + "Native Solving/Proof time(ms): {}", iterationCount, curTime - lastTime);
if (logger.isInfoEnabled()) {
String message;
switch(status) {
case INCONCLUSIVE:
message = "CAAT Solver was inconclusive (bug?).";
break;
case CONSISTENT:
message = "Violation verified.";
break;
case INCONSISTENT:
message = "Bounded safety proven.";
break;
default:
throw new IllegalStateException("Unknown result type returned by CAAT Solver.");
}
logger.info(message);
}
if (status == INCONCLUSIVE) {
// CAATSolver got no result (should not be able to happen), so we cannot proceed further.
return UNKNOWN;
}
Result veriResult;
long boundCheckTime = 0;
if (prover.isUnsat()) {
// ------- CHECK BOUNDS -------
lastTime = System.currentTimeMillis();
prover.pop();
// Add bound check
prover.addConstraint(propertyEncoder.encodeBoundEventExec(ctx));
// Add back the constraints found during Refinement (TODO: We might need to perform a second refinement)
for (DNF<CoreLiteral> reason : foundCoreReasons) {
prover.addConstraint(refiner.refine(reason, ctx));
}
veriResult = !prover.isUnsat() ? UNKNOWN : PASS;
boundCheckTime = System.currentTimeMillis() - lastTime;
} else {
veriResult = FAIL;
}
if (logger.isInfoEnabled()) {
logger.info(generateSummary(statList, iterationCount, totalNativeSolvingTime, totalCaatTime, boundCheckTime));
}
if (logger.isDebugEnabled()) {
String smtStatistics = "\n ===== SMT Statistics (after final iteration) ===== \n";
for (String key : prover.getStatistics().keySet()) {
smtStatistics += String.format("\t%s -> %s\n", key, prover.getStatistics().get(key));
}
logger.debug(smtStatistics);
}
veriResult = program.getAss().getInvert() ? veriResult.invert() : veriResult;
logger.info("Verification finished with result " + veriResult);
return veriResult;
}
use of com.dat3m.dartagnan.program.Program in project Dat3M by hernanponcedeleon.
the class WitnessBuilder method reOrderBasedOnAtomicity.
private List<Event> reOrderBasedOnAtomicity(Program program, List<Event> order) {
List<Event> result = new ArrayList<>();
// Maintained for constant lookup time
Set<Event> processedEvents = new HashSet<>();
// All the atomic blocks in the code that have to stay together in any execution
List<List<Event>> atomicBlocks = program.getCache().getEvents(FilterBasic.get(Tag.SVCOMP.SVCOMPATOMIC)).stream().map(e -> ((EndAtomic) e).getBlock().stream().filter(order::contains).collect(Collectors.toList())).collect(Collectors.toList());
for (Event next : order) {
if (processedEvents.contains(next)) {
// next was added as part of a previous block
continue;
}
List<Event> block = atomicBlocks.stream().filter(b -> Collections.binarySearch(b, next) >= 0).findFirst().orElseGet(() -> Collections.singletonList(next));
result.addAll(block);
processedEvents.addAll(block);
}
return result;
}
Aggregations