Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Merge branch 'master' into actor-priority
[simgrid.git] / src / mc / checker / LivenessChecker.cpp
1 /* Copyright (c) 2011-2017. The SimGrid Team.
2  * All rights reserved.                                                     */
3
4 /* This program is free software; you can redistribute it and/or modify it
5  * under the terms of the license (GNU LGPL) which comes with this package. */
6
7 #include <cstring>
8
9 #include <memory>
10 #include <list>
11
12 #include <boost/range/algorithm.hpp>
13
14 #include <unistd.h>
15 #include <sys/wait.h>
16
17 #include <xbt/automaton.h>
18 #include <xbt/dynar.h>
19 #include <xbt/dynar.hpp>
20 #include <xbt/log.h>
21 #include <xbt/sysdep.h>
22
23 #include "src/mc/Session.hpp"
24 #include "src/mc/Transition.hpp"
25 #include "src/mc/checker/LivenessChecker.hpp"
26 #include "src/mc/mc_exit.hpp"
27 #include "src/mc/mc_private.hpp"
28 #include "src/mc/mc_private.hpp"
29 #include "src/mc/mc_record.hpp"
30 #include "src/mc/mc_replay.h"
31 #include "src/mc/mc_request.hpp"
32 #include "src/mc/mc_smx.hpp"
33 #include "src/mc/remote/Client.hpp"
34
35 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(mc_liveness, mc, "Logging specific to algorithms for liveness properties verification");
36
37 /********* Static functions *********/
38
39 namespace simgrid {
40 namespace mc {
41
42 VisitedPair::VisitedPair(int pair_num, xbt_automaton_state_t automaton_state,
43                          std::shared_ptr<const std::vector<int>> atomic_propositions,
44                          std::shared_ptr<simgrid::mc::State> graph_state)
45     : num(pair_num), automaton_state(automaton_state)
46 {
47   simgrid::mc::RemoteClient* process = &(mc_model_checker->process());
48
49   this->graph_state = std::move(graph_state);
50   if(this->graph_state->system_state == nullptr)
51     this->graph_state->system_state = simgrid::mc::take_snapshot(pair_num);
52   this->heap_bytes_used = mmalloc_get_bytes_used_remote(process->get_heap()->heaplimit, process->get_malloc_info());
53
54   this->actors_count = mc_model_checker->process().actors().size();
55
56   this->other_num = -1;
57   this->atomic_propositions = std::move(atomic_propositions);
58 }
59
60 static bool evaluate_label(xbt_automaton_exp_label_t l, std::vector<int> const& values)
61 {
62   switch (l->type) {
63   case xbt_automaton_exp_label::AUT_OR:
64     return evaluate_label(l->u.or_and.left_exp, values)
65       || evaluate_label(l->u.or_and.right_exp, values);
66   case xbt_automaton_exp_label::AUT_AND:
67     return evaluate_label(l->u.or_and.left_exp, values)
68       && evaluate_label(l->u.or_and.right_exp, values);
69   case xbt_automaton_exp_label::AUT_NOT:
70     return not evaluate_label(l->u.exp_not, values);
71   case xbt_automaton_exp_label::AUT_PREDICAT:{
72       unsigned int cursor = 0;
73       xbt_automaton_propositional_symbol_t p = nullptr;
74       xbt_dynar_foreach(simgrid::mc::property_automaton->propositional_symbols, cursor, p) {
75         if (std::strcmp(xbt_automaton_propositional_symbol_get_name(p), l->u.predicat) == 0)
76           return values[cursor] != 0;
77       }
78       xbt_die("Missing predicate");
79       break;
80     }
81   case xbt_automaton_exp_label::AUT_ONE:
82     return true;
83   default:
84     xbt_die("Unexpected vaue for automaton");
85   }
86 }
87
88 Pair::Pair(unsigned long expanded_pairs) : num(expanded_pairs)
89 {}
90
91 std::shared_ptr<const std::vector<int>> LivenessChecker::getPropositionValues()
92 {
93   std::vector<int> values;
94   unsigned int cursor = 0;
95   xbt_automaton_propositional_symbol_t ps = nullptr;
96   xbt_dynar_foreach(simgrid::mc::property_automaton->propositional_symbols, cursor, ps)
97     values.push_back(xbt_automaton_propositional_symbol_evaluate(ps));
98   return std::make_shared<const std::vector<int>>(std::move(values));
99 }
100
101 int LivenessChecker::compare(simgrid::mc::VisitedPair* state1, simgrid::mc::VisitedPair* state2)
102 {
103   simgrid::mc::Snapshot* s1 = state1->graph_state->system_state.get();
104   simgrid::mc::Snapshot* s2 = state2->graph_state->system_state.get();
105   int num1 = state1->num;
106   int num2 = state2->num;
107   return simgrid::mc::snapshot_compare(num1, s1, num2, s2);
108 }
109
110 std::shared_ptr<VisitedPair> LivenessChecker::insertAcceptancePair(simgrid::mc::Pair* pair)
111 {
112   std::shared_ptr<VisitedPair> new_pair = std::make_shared<VisitedPair>(
113     pair->num, pair->automaton_state, pair->atomic_propositions,
114     pair->graph_state);
115
116   auto res = boost::range::equal_range(acceptancePairs_, new_pair.get(),
117                                        simgrid::mc::DerefAndCompareByActorsCountAndUsedHeap());
118
119   if (pair->search_cycle) for (auto i = res.first; i != res.second; ++i) {
120     std::shared_ptr<simgrid::mc::VisitedPair> const& pair_test = *i;
121     if (xbt_automaton_state_compare(
122           pair_test->automaton_state, new_pair->automaton_state) != 0
123         || *(pair_test->atomic_propositions) != *(new_pair->atomic_propositions)
124         || this->compare(pair_test.get(), new_pair.get()) != 0)
125       continue;
126     XBT_INFO("Pair %d already reached (equal to pair %d) !", new_pair->num, pair_test->num);
127     explorationStack_.pop_back();
128     if (dot_output != nullptr)
129       fprintf(dot_output, "\"%d\" -> \"%d\" [%s];\n", this->previousPair_, pair_test->num,
130               this->previousRequest_.c_str());
131     return nullptr;
132   }
133
134   acceptancePairs_.insert(res.first, new_pair);
135   return new_pair;
136 }
137
138 void LivenessChecker::removeAcceptancePair(int pair_num)
139 {
140   for (auto i = acceptancePairs_.begin(); i != acceptancePairs_.end(); ++i)
141     if ((*i)->num == pair_num) {
142       acceptancePairs_.erase(i);
143       break;
144     }
145 }
146
147 void LivenessChecker::replay()
148 {
149   XBT_DEBUG("**** Begin Replay ****");
150
151   /* Intermediate backtracking */
152   if(_sg_mc_checkpoint > 0) {
153     simgrid::mc::Pair* pair = explorationStack_.back().get();
154     if(pair->graph_state->system_state){
155       simgrid::mc::restore_snapshot(pair->graph_state->system_state);
156       return;
157     }
158   }
159
160   /* Restore the initial state */
161   simgrid::mc::session->restoreInitialState();
162
163   /* Traverse the stack from the initial state and re-execute the transitions */
164   int depth = 1;
165   for (std::shared_ptr<Pair> const& pair : explorationStack_) {
166     if (pair == explorationStack_.back())
167       break;
168
169     std::shared_ptr<State> state = pair->graph_state;
170
171     if (pair->exploration_started) {
172
173       int req_num = state->transition.argument;
174       smx_simcall_t saved_req = &state->executed_req;
175
176       smx_simcall_t req = nullptr;
177
178       if (saved_req != nullptr) {
179         /* because we got a copy of the executed request, we have to fetch the
180              real one, pointed by the request field of the issuer process */
181         const smx_actor_t issuer = MC_smx_simcall_get_issuer(saved_req);
182         req = &issuer->simcall;
183
184         /* Debug information */
185         XBT_DEBUG("Replay (depth = %d) : %s (%p)",
186           depth,
187           simgrid::mc::request_to_string(
188             req, req_num, simgrid::mc::RequestType::simix).c_str(),
189           state.get());
190       }
191
192       this->getSession().execute(state->transition);
193     }
194
195     /* Update statistics */
196     visitedPairsCount_++;
197     mc_model_checker->executed_transitions++;
198
199     depth++;
200
201   }
202
203   XBT_DEBUG("**** End Replay ****");
204 }
205
206 /**
207  * \brief Checks whether a given pair has already been visited by the algorithm.
208  */
209 int LivenessChecker::insertVisitedPair(std::shared_ptr<VisitedPair> visited_pair, simgrid::mc::Pair* pair)
210 {
211   if (_sg_mc_max_visited_states == 0)
212     return -1;
213
214   if (visited_pair == nullptr)
215     visited_pair =
216         std::make_shared<VisitedPair>(pair->num, pair->automaton_state, pair->atomic_propositions, pair->graph_state);
217
218   auto range = boost::range::equal_range(visitedPairs_, visited_pair.get(),
219                                          simgrid::mc::DerefAndCompareByActorsCountAndUsedHeap());
220
221   for (auto i = range.first; i != range.second; ++i) {
222     VisitedPair* pair_test = i->get();
223     if (xbt_automaton_state_compare(
224           pair_test->automaton_state, visited_pair->automaton_state) != 0
225         || *(pair_test->atomic_propositions) != *(visited_pair->atomic_propositions)
226         || this->compare(pair_test, visited_pair.get()) != 0)
227         continue;
228     if (pair_test->other_num == -1)
229       visited_pair->other_num = pair_test->num;
230     else
231       visited_pair->other_num = pair_test->other_num;
232     if (dot_output == nullptr)
233       XBT_DEBUG("Pair %d already visited ! (equal to pair %d)", visited_pair->num, pair_test->num);
234     else
235       XBT_DEBUG("Pair %d already visited ! (equal to pair %d (pair %d in dot_output))",
236         visited_pair->num, pair_test->num, visited_pair->other_num);
237     (*i) = std::move(visited_pair);
238     return (*i)->other_num;
239   }
240
241   visitedPairs_.insert(range.first, std::move(visited_pair));
242   this->purgeVisitedPairs();
243   return -1;
244 }
245
246 void LivenessChecker::purgeVisitedPairs()
247 {
248   if (_sg_mc_max_visited_states != 0 && visitedPairs_.size() > (std::size_t)_sg_mc_max_visited_states) {
249     // Remove the oldest entry with a linear search:
250     visitedPairs_.erase(boost::min_element(visitedPairs_,
251       [](std::shared_ptr<VisitedPair> const a, std::shared_ptr<VisitedPair> const& b) {
252         return a->num < b->num; } ));
253   }
254 }
255
256 LivenessChecker::LivenessChecker(Session& session) : Checker(session)
257 {
258 }
259
260 RecordTrace LivenessChecker::getRecordTrace() // override
261 {
262   RecordTrace res;
263   for (std::shared_ptr<Pair> const& pair : explorationStack_)
264     res.push_back(pair->graph_state->getTransition());
265   return res;
266 }
267
268 void LivenessChecker::logState() // override
269 {
270   XBT_INFO("Expanded pairs = %lu", expandedPairsCount_);
271   XBT_INFO("Visited pairs = %lu", visitedPairsCount_);
272   XBT_INFO("Executed transitions = %lu", mc_model_checker->executed_transitions);
273 }
274
275 void LivenessChecker::showAcceptanceCycle(std::size_t depth)
276 {
277   XBT_INFO("*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*");
278   XBT_INFO("|             ACCEPTANCE CYCLE            |");
279   XBT_INFO("*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*");
280   XBT_INFO("Counter-example that violates formula :");
281   simgrid::mc::dumpRecordPath();
282   for (auto const& s : this->getTextualTrace())
283     XBT_INFO("%s", s.c_str());
284   simgrid::mc::session->logState();
285   XBT_INFO("Counter-example depth : %zu", depth);
286 }
287
288 std::vector<std::string> LivenessChecker::getTextualTrace() // override
289 {
290   std::vector<std::string> trace;
291   for (std::shared_ptr<Pair> const& pair : explorationStack_) {
292     int req_num = pair->graph_state->transition.argument;
293     smx_simcall_t req = &pair->graph_state->executed_req;
294     if (req && req->call != SIMCALL_NONE)
295       trace.push_back(simgrid::mc::request_to_string(
296         req, req_num, simgrid::mc::RequestType::executed));
297   }
298   return trace;
299 }
300
301 std::shared_ptr<Pair> LivenessChecker::newPair(Pair* current_pair, xbt_automaton_state_t state,
302                                                std::shared_ptr<const std::vector<int>> propositions)
303 {
304   std::shared_ptr<Pair> next_pair = std::make_shared<Pair>(++expandedPairsCount_);
305   next_pair->automaton_state      = state;
306   next_pair->graph_state          = std::shared_ptr<simgrid::mc::State>(new simgrid::mc::State(++expandedStatesCount_));
307   next_pair->atomic_propositions  = std::move(propositions);
308   if (current_pair)
309     next_pair->depth = current_pair->depth + 1;
310   else
311     next_pair->depth = 1;
312   /* Get enabled actors and insert them in the interleave set of the next graph_state */
313   for (auto& actor : mc_model_checker->process().actors())
314     if (simgrid::mc::actor_is_enabled(actor.copy.getBuffer()))
315       next_pair->graph_state->addInterleavingSet(actor.copy.getBuffer());
316   next_pair->requests = next_pair->graph_state->interleaveSize();
317   /* FIXME : get search_cycle value for each accepting state */
318   if (next_pair->automaton_state->type == 1 || (current_pair && current_pair->search_cycle))
319     next_pair->search_cycle = true;
320   else
321     next_pair->search_cycle = false;
322   return next_pair;
323 }
324
325 void LivenessChecker::backtrack()
326 {
327   /* Traverse the stack backwards until a pair with a non empty interleave
328      set is found, deleting all the pairs that have it empty in the way. */
329   while (not explorationStack_.empty()) {
330     std::shared_ptr<simgrid::mc::Pair> current_pair = explorationStack_.back();
331     explorationStack_.pop_back();
332     if (current_pair->requests > 0) {
333       /* We found a backtracking point */
334       XBT_DEBUG("Backtracking to depth %d", current_pair->depth);
335       explorationStack_.push_back(std::move(current_pair));
336       this->replay();
337       XBT_DEBUG("Backtracking done");
338       break;
339     } else {
340       XBT_DEBUG("Delete pair %d at depth %d", current_pair->num, current_pair->depth);
341       if (current_pair->automaton_state->type == 1)
342         this->removeAcceptancePair(current_pair->num);
343     }
344   }
345 }
346
347 void LivenessChecker::run()
348 {
349   XBT_INFO("Check the liveness property %s", _sg_mc_property_file);
350   MC_automaton_load(_sg_mc_property_file);
351
352   XBT_DEBUG("Starting the liveness algorithm");
353   simgrid::mc::session->initialize();
354
355   /* Initialize */
356   this->previousPair_ = 0;
357
358   std::shared_ptr<const std::vector<int>> propos = this->getPropositionValues();
359
360   // For each initial state of the property automaton, push a
361   // (application_state, automaton_state) pair to the exploration stack:
362   unsigned int cursor = 0;
363   xbt_automaton_state_t automaton_state;
364   xbt_dynar_foreach (simgrid::mc::property_automaton->states, cursor, automaton_state)
365     if (automaton_state->type == -1)
366       explorationStack_.push_back(this->newPair(nullptr, automaton_state, propos));
367
368   /* Actually run the double DFS search for counter-examples */
369   while (not explorationStack_.empty()) {
370     std::shared_ptr<Pair> current_pair = explorationStack_.back();
371
372     /* Update current state in buchi automaton */
373     simgrid::mc::property_automaton->current_state = current_pair->automaton_state;
374
375     XBT_DEBUG(
376         "********************* ( Depth = %d, search_cycle = %d, interleave size = %zu, pair_num = %d, requests = %d)",
377         current_pair->depth, current_pair->search_cycle, current_pair->graph_state->interleaveSize(), current_pair->num,
378         current_pair->requests);
379
380     if (current_pair->requests == 0) {
381       this->backtrack();
382       continue;
383     }
384
385     std::shared_ptr<VisitedPair> reached_pair;
386     if (current_pair->automaton_state->type == 1 && not current_pair->exploration_started) {
387       reached_pair = this->insertAcceptancePair(current_pair.get());
388       if (reached_pair == nullptr) {
389         this->showAcceptanceCycle(current_pair->depth);
390         throw simgrid::mc::LivenessError();
391       }
392     }
393
394     /* Pair already visited ? stop the exploration on the current path */
395     if (not current_pair->exploration_started) {
396       int visited_num = this->insertVisitedPair(reached_pair, current_pair.get());
397       if (visited_num != -1) {
398         if (dot_output != nullptr) {
399           fprintf(dot_output, "\"%d\" -> \"%d\" [%s];\n", this->previousPair_, visited_num,
400                   this->previousRequest_.c_str());
401           fflush(dot_output);
402         }
403         XBT_DEBUG("Pair already visited (equal to pair %d), exploration on the current path stopped.", visited_num);
404         current_pair->requests = 0;
405         this->backtrack();
406         continue;
407       }
408     }
409
410     smx_simcall_t req = MC_state_get_request(current_pair->graph_state.get());
411     int req_num = current_pair->graph_state->transition.argument;
412
413     if (dot_output != nullptr) {
414       if (this->previousPair_ != 0 && this->previousPair_ != current_pair->num) {
415         fprintf(dot_output, "\"%d\" -> \"%d\" [%s];\n",
416           this->previousPair_, current_pair->num,
417           this->previousRequest_.c_str());
418         this->previousRequest_.clear();
419       }
420       this->previousPair_ = current_pair->num;
421       this->previousRequest_ = simgrid::mc::request_get_dot_output(req, req_num);
422       if (current_pair->search_cycle)
423         fprintf(dot_output, "%d [shape=doublecircle];\n", current_pair->num);
424       fflush(dot_output);
425     }
426
427     XBT_DEBUG("Execute: %s",
428       simgrid::mc::request_to_string(
429         req, req_num, simgrid::mc::RequestType::simix).c_str());
430
431     /* Update stats */
432     mc_model_checker->executed_transitions++;
433     if (not current_pair->exploration_started)
434       visitedPairsCount_++;
435
436     /* Answer the request */
437     mc_model_checker->handle_simcall(current_pair->graph_state->transition);
438
439     /* Wait for requests (schedules processes) */
440     mc_model_checker->wait_for_requests();
441
442     current_pair->requests--;
443     current_pair->exploration_started = true;
444
445     /* Get values of atomic propositions (variables used in the property formula) */
446     std::shared_ptr<const std::vector<int>> prop_values = this->getPropositionValues();
447
448     // For each enabled transition in the property automaton, push a
449     // (application_state, automaton_state) pair to the exploration stack:
450     for (int cursor = xbt_dynar_length(current_pair->automaton_state->out) - 1; cursor >= 0; cursor--) {
451       xbt_automaton_transition_t transition_succ = (xbt_automaton_transition_t)xbt_dynar_get_as(current_pair->automaton_state->out, cursor, xbt_automaton_transition_t);
452       if (evaluate_label(transition_succ->label, *prop_values))
453           explorationStack_.push_back(this->newPair(
454             current_pair.get(), transition_succ->dst, prop_values));
455      }
456
457   }
458
459   XBT_INFO("No property violation found.");
460   simgrid::mc::session->logState();
461 }
462
463 Checker* createLivenessChecker(Session& session)
464 {
465   return new LivenessChecker(session);
466 }
467
468 }
469 }