Search in sources :

Example 61 with Model

use of com.microsoft.z3.Model in project Dat3M by hernanponcedeleon.

the class Encodings method getInitialHigh.

public static BoolExpr getInitialHigh(Program p, Model model, Context ctx, boolean var1, boolean val1) {
    Set<Event> highInits = p.getEvents().stream().filter(e -> e instanceof Init).filter(e -> e.getLoc() instanceof HighLocation).collect(Collectors.toSet());
    BoolExpr reachedState = ctx.mkTrue();
    for (Event e : highInits) {
        IntExpr var = var1 ? initValue(e, ctx) : initValue2(e, ctx);
        IntExpr val = val1 ? initValue(e, ctx) : initValue2(e, ctx);
        if (e.getLoc().getIValue() == null) {
            reachedState = ctx.mkAnd(reachedState, ctx.mkEq(var, model.getConstInterp(val)));
        }
    }
    return reachedState;
}
Also used : HighLocation(dartagnan.program.HighLocation) Utils.lastValueReg(dartagnan.utils.Utils.lastValueReg) Utils.uniqueValue(dartagnan.utils.Utils.uniqueValue) com.microsoft.z3(com.microsoft.z3) Event(dartagnan.program.Event) Set(java.util.Set) If(dartagnan.program.If) Collectors(java.util.stream.Collectors) Utils.initValue(dartagnan.utils.Utils.initValue) Init(dartagnan.program.Init) Register(dartagnan.program.Register) Utils.initValue2(dartagnan.utils.Utils.initValue2) Local(dartagnan.program.Local) Load(dartagnan.program.Load) MemEvent(dartagnan.program.MemEvent) Utils.ssaReg(dartagnan.utils.Utils.ssaReg) Program(dartagnan.program.Program) Utils.edge(dartagnan.utils.Utils.edge) Utils.lastValueLoc(dartagnan.utils.Utils.lastValueLoc) Store(dartagnan.program.Store) MapSSA(dartagnan.utils.MapSSA) Location(dartagnan.program.Location) HighLocation(dartagnan.program.HighLocation) Init(dartagnan.program.Init) Event(dartagnan.program.Event) MemEvent(dartagnan.program.MemEvent)

Example 62 with Model

use of com.microsoft.z3.Model in project Dat3M by hernanponcedeleon.

the class Encodings method encodeReachedState.

public static BoolExpr encodeReachedState(Program p, Model model, Context ctx) {
    Set<Location> locs = p.getEvents().stream().filter(e -> e instanceof MemEvent).map(e -> e.getLoc()).collect(Collectors.toSet());
    BoolExpr reachedState = ctx.mkTrue();
    for (Location loc : locs) {
        reachedState = ctx.mkAnd(reachedState, ctx.mkEq(lastValueLoc(loc, ctx), model.getConstInterp(lastValueLoc(loc, ctx))));
    }
    Set<Event> executedEvents = p.getEvents().stream().filter(e -> model.getConstInterp(e.executes(ctx)).isTrue()).collect(Collectors.toSet());
    Set<Register> regs = executedEvents.stream().filter(e -> e instanceof Local | e instanceof Load).map(e -> e.getReg()).collect(Collectors.toSet());
    for (Register reg : regs) {
        reachedState = ctx.mkAnd(reachedState, ctx.mkEq(lastValueReg(reg, ctx), model.getConstInterp(lastValueReg(reg, ctx))));
    }
    return reachedState;
}
Also used : HighLocation(dartagnan.program.HighLocation) Utils.lastValueReg(dartagnan.utils.Utils.lastValueReg) Utils.uniqueValue(dartagnan.utils.Utils.uniqueValue) com.microsoft.z3(com.microsoft.z3) Event(dartagnan.program.Event) Set(java.util.Set) If(dartagnan.program.If) Collectors(java.util.stream.Collectors) Utils.initValue(dartagnan.utils.Utils.initValue) Init(dartagnan.program.Init) Register(dartagnan.program.Register) Utils.initValue2(dartagnan.utils.Utils.initValue2) Local(dartagnan.program.Local) Load(dartagnan.program.Load) MemEvent(dartagnan.program.MemEvent) Utils.ssaReg(dartagnan.utils.Utils.ssaReg) Program(dartagnan.program.Program) Utils.edge(dartagnan.utils.Utils.edge) Utils.lastValueLoc(dartagnan.utils.Utils.lastValueLoc) Store(dartagnan.program.Store) MapSSA(dartagnan.utils.MapSSA) Location(dartagnan.program.Location) Load(dartagnan.program.Load) Register(dartagnan.program.Register) MemEvent(dartagnan.program.MemEvent) Event(dartagnan.program.Event) MemEvent(dartagnan.program.MemEvent) Local(dartagnan.program.Local) HighLocation(dartagnan.program.HighLocation) Location(dartagnan.program.Location)

Example 63 with Model

use of com.microsoft.z3.Model in project libSBOLj by SynBioDex.

the class SBOLDocumentTest method test_docModelMethods.

@Test
public void test_docModelMethods() throws SBOLValidationException {
    Model model = doc.createModel("pIKE_Toggle_1", "1.0", URI.create("http://virtualparts.org/part/pIKE_Toggle_1"), URI.create("http://identifiers.org/edam/format_2585"), SystemsBiologyOntology.CONTINUOUS_FRAMEWORK);
    assertTrue(doc.getModels().size() == 1);
    assertTrue(doc.getModel("pIKE_Toggle_1", "").equals(model));
    doc.clearModels();
    assertTrue(doc.getModels().size() == 0);
}
Also used : Model(org.sbolstandard.core2.Model) Test(org.junit.Test)

Example 64 with Model

use of com.microsoft.z3.Model in project batfish by batfish.

the class Encoder method buildCounterExample.

/*
   * Add the relevant variables in the counterexample to
   * display to the user in a human-readable fashion
   */
private void buildCounterExample(Encoder enc, Model m, SortedMap<String, String> model, SortedMap<String, String> packetModel, SortedSet<String> fwdModel, SortedMap<String, SortedMap<String, String>> envModel, SortedSet<String> failures) {
    SortedMap<Expr, String> valuation = new TreeMap<>();
    // If user asks for the full model
    for (Entry<String, Expr> entry : _allVariables.entrySet()) {
        String name = entry.getKey();
        Expr e = entry.getValue();
        Expr val = m.evaluate(e, true);
        if (!val.equals(e)) {
            String s = val.toString();
            if (_question.getFullModel()) {
                model.put(name, s);
            }
            valuation.put(e, s);
        }
    }
    // Packet model
    SymbolicPacket p = enc.getMainSlice().getSymbolicPacket();
    String dstIp = valuation.get(p.getDstIp());
    String srcIp = valuation.get(p.getSrcIp());
    String dstPt = valuation.get(p.getDstPort());
    String srcPt = valuation.get(p.getSrcPort());
    String icmpCode = valuation.get(p.getIcmpCode());
    String icmpType = valuation.get(p.getIcmpType());
    String ipProtocol = valuation.get(p.getIpProtocol());
    String tcpAck = valuation.get(p.getTcpAck());
    String tcpCwr = valuation.get(p.getTcpCwr());
    String tcpEce = valuation.get(p.getTcpEce());
    String tcpFin = valuation.get(p.getTcpFin());
    String tcpPsh = valuation.get(p.getTcpPsh());
    String tcpRst = valuation.get(p.getTcpRst());
    String tcpSyn = valuation.get(p.getTcpSyn());
    String tcpUrg = valuation.get(p.getTcpUrg());
    Ip dip = new Ip(Long.parseLong(dstIp));
    Ip sip = new Ip(Long.parseLong(srcIp));
    packetModel.put("dstIp", dip.toString());
    if (sip.asLong() != 0) {
        packetModel.put("srcIp", sip.toString());
    }
    if (dstPt != null && !dstPt.equals("0")) {
        packetModel.put("dstPort", dstPt);
    }
    if (srcPt != null && !srcPt.equals("0")) {
        packetModel.put("srcPort", srcPt);
    }
    if (icmpCode != null && !icmpCode.equals("0")) {
        packetModel.put("icmpCode", icmpCode);
    }
    if (icmpType != null && !icmpType.equals("0")) {
        packetModel.put("icmpType", icmpType);
    }
    if (ipProtocol != null && !ipProtocol.equals("0")) {
        Integer number = Integer.parseInt(ipProtocol);
        IpProtocol proto = IpProtocol.fromNumber(number);
        packetModel.put("protocol", proto.toString());
    }
    if ("true".equals(tcpAck)) {
        packetModel.put("tcpAck", "set");
    }
    if ("true".equals(tcpCwr)) {
        packetModel.put("tcpCwr", "set");
    }
    if ("true".equals(tcpEce)) {
        packetModel.put("tcpEce", "set");
    }
    if ("true".equals(tcpFin)) {
        packetModel.put("tcpFin", "set");
    }
    if ("true".equals(tcpPsh)) {
        packetModel.put("tcpPsh", "set");
    }
    if ("true".equals(tcpRst)) {
        packetModel.put("tcpRst", "set");
    }
    if ("true".equals(tcpSyn)) {
        packetModel.put("tcpSyn", "set");
    }
    if ("true".equals(tcpUrg)) {
        packetModel.put("tcpUrg", "set");
    }
    for (EncoderSlice slice : enc.getSlices().values()) {
        for (Entry<LogicalEdge, SymbolicRoute> entry2 : slice.getLogicalGraph().getEnvironmentVars().entrySet()) {
            LogicalEdge lge = entry2.getKey();
            SymbolicRoute r = entry2.getValue();
            if ("true".equals(valuation.get(r.getPermitted()))) {
                SortedMap<String, String> recordMap = new TreeMap<>();
                GraphEdge ge = lge.getEdge();
                String nodeIface = ge.getRouter() + "," + ge.getStart().getName() + " (BGP)";
                envModel.put(nodeIface, recordMap);
                if (r.getPrefixLength() != null) {
                    String x = valuation.get(r.getPrefixLength());
                    if (x != null) {
                        int len = Integer.parseInt(x);
                        Prefix p1 = new Prefix(dip, len);
                        recordMap.put("prefix", p1.toString());
                    }
                }
                if (r.getAdminDist() != null) {
                    String x = valuation.get(r.getAdminDist());
                    if (x != null) {
                        recordMap.put("admin distance", x);
                    }
                }
                if (r.getLocalPref() != null) {
                    String x = valuation.get(r.getLocalPref());
                    if (x != null) {
                        recordMap.put("local preference", x);
                    }
                }
                if (r.getMetric() != null) {
                    String x = valuation.get(r.getMetric());
                    if (x != null) {
                        recordMap.put("protocol metric", x);
                    }
                }
                if (r.getMed() != null) {
                    String x = valuation.get(r.getMed());
                    if (x != null) {
                        recordMap.put("multi-exit disc.", valuation.get(r.getMed()));
                    }
                }
                if (r.getOspfArea() != null && r.getOspfArea().getBitVec() != null) {
                    String x = valuation.get(r.getOspfArea().getBitVec());
                    if (x != null) {
                        Integer i = Integer.parseInt(x);
                        Long area = r.getOspfArea().value(i);
                        recordMap.put("OSPF Area", area.toString());
                    }
                }
                if (r.getOspfType() != null && r.getOspfType().getBitVec() != null) {
                    String x = valuation.get(r.getOspfType().getBitVec());
                    if (x != null) {
                        Integer i = Integer.parseInt(x);
                        OspfType type = r.getOspfType().value(i);
                        recordMap.put("OSPF Type", type.toString());
                    }
                }
                for (Entry<CommunityVar, BoolExpr> entry3 : r.getCommunities().entrySet()) {
                    CommunityVar cvar = entry3.getKey();
                    BoolExpr e = entry3.getValue();
                    String c = valuation.get(e);
                    // TODO: what about OTHER type?
                    if ("true".equals(c) && displayCommunity(cvar)) {
                        String s = cvar.getValue();
                        String t = slice.getNamedCommunities().get(cvar.getValue());
                        s = (t == null ? s : t);
                        recordMap.put("community " + s, "");
                    }
                }
            }
        }
    }
    // Forwarding Model
    enc.getMainSlice().getSymbolicDecisions().getDataForwarding().forEach((router, edge, e) -> {
        String s = valuation.get(e);
        if ("true".equals(s)) {
            SymbolicRoute r = enc.getMainSlice().getSymbolicDecisions().getBestNeighbor().get(router);
            if (r.getProtocolHistory() != null) {
                Protocol proto;
                List<Protocol> allProtocols = enc.getMainSlice().getProtocols().get(router);
                if (allProtocols.size() == 1) {
                    proto = allProtocols.get(0);
                } else {
                    s = valuation.get(r.getProtocolHistory().getBitVec());
                    int i = Integer.parseInt(s);
                    proto = r.getProtocolHistory().value(i);
                }
                fwdModel.add(edge + " (" + proto.name() + ")");
            } else {
                fwdModel.add(edge.toString());
            }
        }
    });
    _symbolicFailures.getFailedInternalLinks().forEach((x, y, e) -> {
        String s = valuation.get(e);
        if ("1".equals(s)) {
            String pair = (x.compareTo(y) < 0 ? x + "," + y : y + "," + x);
            failures.add("link(" + pair + ")");
        }
    });
    _symbolicFailures.getFailedEdgeLinks().forEach((ge, e) -> {
        String s = valuation.get(e);
        if ("1".equals(s)) {
            failures.add("link(" + ge.getRouter() + "," + ge.getStart().getName() + ")");
        }
    });
}
Also used : BoolExpr(com.microsoft.z3.BoolExpr) Ip(org.batfish.datamodel.Ip) Prefix(org.batfish.datamodel.Prefix) TreeMap(java.util.TreeMap) CommunityVar(org.batfish.symbolic.CommunityVar) BoolExpr(com.microsoft.z3.BoolExpr) ArithExpr(com.microsoft.z3.ArithExpr) BitVecExpr(com.microsoft.z3.BitVecExpr) Expr(com.microsoft.z3.Expr) IpProtocol(org.batfish.datamodel.IpProtocol) OspfType(org.batfish.symbolic.OspfType) IpProtocol(org.batfish.datamodel.IpProtocol) Protocol(org.batfish.symbolic.Protocol) GraphEdge(org.batfish.symbolic.GraphEdge)

Example 65 with Model

use of com.microsoft.z3.Model in project batfish by batfish.

the class PropertyChecker method checkProperty.

/*
   * General purpose logic for checking a property that holds that
   * handles the various flags and parameters for a query with endpoints
   *
   * q is the question from the user.
   * instrument instruments each router in the graph as needed to check the property.
   * answer takes the result from Z3 and produces the answer for the user.
   *
   */
private AnswerElement checkProperty(HeaderLocationQuestion q, TriFunction<Encoder, Set<String>, Set<GraphEdge>, Map<String, BoolExpr>> instrument, Function<VerifyParam, AnswerElement> answer) {
    long totalTime = System.currentTimeMillis();
    PathRegexes p = new PathRegexes(q);
    Graph graph = new Graph(_batfish);
    Set<GraphEdge> destPorts = findFinalInterfaces(graph, p);
    List<String> sourceRouters = PatternUtils.findMatchingSourceNodes(graph, p);
    if (destPorts.isEmpty()) {
        throw new BatfishException("Set of valid destination interfaces is empty");
    }
    if (sourceRouters.isEmpty()) {
        throw new BatfishException("Set of valid ingress nodes is empty");
    }
    inferDestinationHeaderSpace(graph, destPorts, q);
    Set<GraphEdge> failOptions = failLinkSet(graph, q);
    Tuple<Stream<Supplier<NetworkSlice>>, Long> ecs = findAllNetworkSlices(q, graph, true);
    Stream<Supplier<NetworkSlice>> stream = ecs.getFirst();
    Long timeAbstraction = ecs.getSecond();
    AnswerElement[] answerElement = new AnswerElement[1];
    VerificationResult[] result = new VerificationResult[2];
    List<VerificationStats> ecStats = new ArrayList<>();
    // Checks ECs in parallel, but short circuits when a counterexample is found
    boolean hasCounterExample = stream.anyMatch(lazyEc -> {
        long timeEc = System.currentTimeMillis();
        NetworkSlice slice = lazyEc.get();
        timeEc = System.currentTimeMillis() - timeEc;
        synchronized (_lock) {
            // Make sure the headerspace is correct
            HeaderLocationQuestion question = new HeaderLocationQuestion(q);
            question.setHeaderSpace(slice.getHeaderSpace());
            // Get the EC graph and mapping
            Graph g = slice.getGraph();
            Set<String> srcRouters = mapConcreteToAbstract(slice, sourceRouters);
            long timeEncoding = System.currentTimeMillis();
            Encoder enc = new Encoder(_settings, g, question);
            enc.computeEncoding();
            timeEncoding = System.currentTimeMillis() - timeEncoding;
            // Add environment constraints for base case
            if (question.getDiffType() != null) {
                if (question.getEnvDiff()) {
                    addEnvironmentConstraints(enc, question.getDeltaEnvironmentType());
                }
            } else {
                addEnvironmentConstraints(enc, question.getBaseEnvironmentType());
            }
            Map<String, BoolExpr> prop = instrument.apply(enc, srcRouters, destPorts);
            // If this is a equivalence query, we create a second copy of the network
            Encoder enc2 = null;
            Map<String, BoolExpr> prop2 = null;
            if (question.getDiffType() != null) {
                HeaderLocationQuestion q2 = new HeaderLocationQuestion(question);
                q2.setFailures(0);
                long timeDiffEncoding = System.currentTimeMillis();
                enc2 = new Encoder(enc, g, q2);
                enc2.computeEncoding();
                timeDiffEncoding = System.currentTimeMillis() - timeDiffEncoding;
                timeEncoding += timeDiffEncoding;
            }
            if (question.getDiffType() != null) {
                assert (enc2 != null);
                // create a map for enc2 to lookup a related environment variable from enc
                Table2<GraphEdge, EdgeType, SymbolicRoute> relatedEnv = new Table2<>();
                enc2.getMainSlice().getLogicalGraph().getEnvironmentVars().forEach((lge, r) -> relatedEnv.put(lge.getEdge(), lge.getEdgeType(), r));
                BoolExpr related = enc.mkTrue();
                addEnvironmentConstraints(enc2, question.getBaseEnvironmentType());
                if (!question.getEnvDiff()) {
                    related = relateEnvironments(enc, enc2);
                }
                prop2 = instrument.apply(enc2, srcRouters, destPorts);
                // Add diff constraints
                BoolExpr required = enc.mkTrue();
                for (String source : srcRouters) {
                    BoolExpr sourceProp1 = prop.get(source);
                    BoolExpr sourceProp2 = prop2.get(source);
                    BoolExpr val;
                    switch(q.getDiffType()) {
                        case INCREASED:
                            val = enc.mkImplies(sourceProp1, sourceProp2);
                            break;
                        case REDUCED:
                            val = enc.mkImplies(sourceProp2, sourceProp1);
                            break;
                        case ANY:
                            val = enc.mkEq(sourceProp1, sourceProp2);
                            break;
                        default:
                            throw new BatfishException("Missing case: " + q.getDiffType());
                    }
                    required = enc.mkAnd(required, val);
                }
                related = enc.mkAnd(related, relatePackets(enc, enc2));
                enc.add(related);
                enc.add(enc.mkNot(required));
            } else {
                // Not a differential query; just a query on a single version of the network.
                BoolExpr allProp = enc.mkTrue();
                for (String router : srcRouters) {
                    BoolExpr r = prop.get(router);
                    if (q.getNegate()) {
                        r = enc.mkNot(r);
                    }
                    allProp = enc.mkAnd(allProp, r);
                }
                enc.add(enc.mkNot(allProp));
            }
            addFailureConstraints(enc, destPorts, failOptions);
            Tuple<VerificationResult, Model> tup = enc.verify();
            VerificationResult res = tup.getFirst();
            Model model = tup.getSecond();
            if (q.getBenchmark()) {
                VerificationStats stats = res.getStats();
                stats.setAvgComputeEcTime(timeEc);
                stats.setMaxComputeEcTime(timeEc);
                stats.setMinComputeEcTime(timeEc);
                stats.setAvgEncodingTime(timeEncoding);
                stats.setMaxEncodingTime(timeEncoding);
                stats.setMinEncodingTime(timeEncoding);
                stats.setTimeCreateBdds((double) timeAbstraction);
                synchronized (_lock) {
                    ecStats.add(stats);
                }
            }
            if (!res.isVerified()) {
                VerifyParam vp = new VerifyParam(res, model, srcRouters, enc, enc2, prop, prop2);
                AnswerElement ae = answer.apply(vp);
                synchronized (_lock) {
                    answerElement[0] = ae;
                    result[0] = res;
                }
                return true;
            }
            synchronized (_lock) {
                result[1] = res;
            }
            return false;
        }
    });
    totalTime = (System.currentTimeMillis() - totalTime);
    VerificationResult res;
    AnswerElement ae;
    if (hasCounterExample) {
        res = result[0];
        ae = answerElement[0];
    } else {
        res = result[1];
        VerifyParam vp = new VerifyParam(res, null, null, null, null, null, null);
        ae = answer.apply(vp);
    }
    if (q.getBenchmark()) {
        VerificationStats stats = VerificationStats.combineAll(ecStats, totalTime);
        res.setStats(stats);
    }
    return ae;
}
Also used : BoolExpr(com.microsoft.z3.BoolExpr) HeaderLocationQuestion(org.batfish.datamodel.questions.smt.HeaderLocationQuestion) ArrayList(java.util.ArrayList) PathRegexes(org.batfish.symbolic.utils.PathRegexes) NetworkSlice(org.batfish.symbolic.abstraction.NetworkSlice) Table2(org.batfish.symbolic.collections.Table2) Stream(java.util.stream.Stream) Supplier(java.util.function.Supplier) BatfishException(org.batfish.common.BatfishException) SmtOneAnswerElement(org.batfish.symbolic.answers.SmtOneAnswerElement) SmtDeterminismAnswerElement(org.batfish.symbolic.answers.SmtDeterminismAnswerElement) SmtReachabilityAnswerElement(org.batfish.symbolic.answers.SmtReachabilityAnswerElement) AnswerElement(org.batfish.datamodel.answers.AnswerElement) SmtManyAnswerElement(org.batfish.symbolic.answers.SmtManyAnswerElement) Graph(org.batfish.symbolic.Graph) Model(com.microsoft.z3.Model) GraphEdge(org.batfish.symbolic.GraphEdge)

Aggregations

Test (org.junit.Test)45 Model (org.eclipse.xtext.valueconverter.bug250313.Model)30 ICompositeNode (org.eclipse.xtext.nodemodel.ICompositeNode)16 BoolExpr (com.microsoft.z3.BoolExpr)11 ILeafNode (org.eclipse.xtext.nodemodel.ILeafNode)11 Model (org.eclipse.xtext.parsetree.reconstr.bug299395.Model)9 SubModel (org.eclipse.xtext.parsetree.reconstr.bug299395.SubModel)9 Model (com.microsoft.z3.Model)7 Init (dartagnan.program.Init)7 Program (dartagnan.program.Program)7 Set (java.util.Set)7 Collectors (java.util.stream.Collectors)7 com.microsoft.z3 (com.microsoft.z3)6 Event (dartagnan.program.Event)6 Load (dartagnan.program.Load)6 Location (dartagnan.program.Location)6 MemEvent (dartagnan.program.MemEvent)6 Register (dartagnan.program.Register)6 Store (dartagnan.program.Store)6 EPackage (org.eclipse.emf.ecore.EPackage)6