Logo AND Algorithmique Numérique Distribuée

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