Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
remove useless parameters in header generation
[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.h"
27 #include "src/mc/mc_private.h"
28 #include "src/mc/mc_private.h"
29 #include "src/mc/mc_record.h"
30 #include "src/mc/mc_replay.h"
31 #include "src/mc/mc_request.h"
32 #include "src/mc/mc_smx.h"
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     }
80   case xbt_automaton_exp_label::AUT_ONE:
81     return true;
82   default:
83     xbt_die("Unexpected vaue for automaton");
84   }
85 }
86
87 Pair::Pair(unsigned long expanded_pairs) : num(expanded_pairs)
88 {}
89
90 std::shared_ptr<const std::vector<int>> LivenessChecker::getPropositionValues()
91 {
92   std::vector<int> values;
93   unsigned int cursor = 0;
94   xbt_automaton_propositional_symbol_t ps = nullptr;
95   xbt_dynar_foreach(simgrid::mc::property_automaton->propositional_symbols, cursor, ps)
96     values.push_back(xbt_automaton_propositional_symbol_evaluate(ps));
97   return std::make_shared<const std::vector<int>>(std::move(values));
98 }
99
100 int LivenessChecker::compare(simgrid::mc::VisitedPair* state1, simgrid::mc::VisitedPair* state2)
101 {
102   simgrid::mc::Snapshot* s1 = state1->graph_state->system_state.get();
103   simgrid::mc::Snapshot* s2 = state2->graph_state->system_state.get();
104   int num1 = state1->num;
105   int num2 = state2->num;
106   return simgrid::mc::snapshot_compare(num1, s1, num2, s2);
107 }
108
109 std::shared_ptr<VisitedPair> LivenessChecker::insertAcceptancePair(simgrid::mc::Pair* pair)
110 {
111   std::shared_ptr<VisitedPair> new_pair = std::make_shared<VisitedPair>(
112     pair->num, pair->automaton_state, pair->atomic_propositions,
113     pair->graph_state);
114
115   auto res = boost::range::equal_range(acceptancePairs_, new_pair.get(),
116                                        simgrid::mc::DerefAndCompareByActorsCountAndUsedHeap());
117
118   if (pair->search_cycle) for (auto i = res.first; i != res.second; ++i) {
119     std::shared_ptr<simgrid::mc::VisitedPair> const& pair_test = *i;
120     if (xbt_automaton_state_compare(
121           pair_test->automaton_state, new_pair->automaton_state) != 0
122         || *(pair_test->atomic_propositions) != *(new_pair->atomic_propositions)
123         || this->compare(pair_test.get(), new_pair.get()) != 0)
124       continue;
125     XBT_INFO("Pair %d already reached (equal to pair %d) !", new_pair->num, pair_test->num);
126     explorationStack_.pop_back();
127     if (dot_output != nullptr)
128       fprintf(dot_output, "\"%d\" -> \"%d\" [%s];\n", this->previousPair_, pair_test->num,
129               this->previousRequest_.c_str());
130     return nullptr;
131   }
132
133   acceptancePairs_.insert(res.first, new_pair);
134   return new_pair;
135 }
136
137 void LivenessChecker::removeAcceptancePair(int pair_num)
138 {
139   for (auto i = acceptancePairs_.begin(); i != acceptancePairs_.end(); ++i)
140     if ((*i)->num == pair_num) {
141       acceptancePairs_.erase(i);
142       break;
143     }
144 }
145
146 void LivenessChecker::replay()
147 {
148   XBT_DEBUG("**** Begin Replay ****");
149
150   /* Intermediate backtracking */
151   if(_sg_mc_checkpoint > 0) {
152     simgrid::mc::Pair* pair = explorationStack_.back().get();
153     if(pair->graph_state->system_state){
154       simgrid::mc::restore_snapshot(pair->graph_state->system_state);
155       return;
156     }
157   }
158
159   /* Restore the initial state */
160   simgrid::mc::session->restoreInitialState();
161
162   /* Traverse the stack from the initial state and re-execute the transitions */
163   int depth = 1;
164   for (std::shared_ptr<Pair> const& pair : explorationStack_) {
165     if (pair == explorationStack_.back())
166       break;
167
168     std::shared_ptr<State> state = pair->graph_state;
169
170     if (pair->exploration_started) {
171
172       int req_num = state->transition.argument;
173       smx_simcall_t saved_req = &state->executed_req;
174
175       smx_simcall_t req = nullptr;
176
177       if (saved_req != nullptr) {
178         /* because we got a copy of the executed request, we have to fetch the
179              real one, pointed by the request field of the issuer process */
180         const smx_actor_t issuer = MC_smx_simcall_get_issuer(saved_req);
181         req = &issuer->simcall;
182
183         /* Debug information */
184         XBT_DEBUG("Replay (depth = %d) : %s (%p)",
185           depth,
186           simgrid::mc::request_to_string(
187             req, req_num, simgrid::mc::RequestType::simix).c_str(),
188           state.get());
189       }
190
191       this->getSession().execute(state->transition);
192     }
193
194     /* Update statistics */
195     visitedPairsCount_++;
196     mc_model_checker->executed_transitions++;
197
198     depth++;
199
200   }
201
202   XBT_DEBUG("**** End Replay ****");
203 }
204
205 /**
206  * \brief Checks whether a given pair has already been visited by the algorithm.
207  */
208 int LivenessChecker::insertVisitedPair(std::shared_ptr<VisitedPair> visited_pair, simgrid::mc::Pair* pair)
209 {
210   if (_sg_mc_max_visited_states == 0)
211     return -1;
212
213   if (visited_pair == nullptr)
214     visited_pair =
215         std::make_shared<VisitedPair>(pair->num, pair->automaton_state, pair->atomic_propositions, pair->graph_state);
216
217   auto range = boost::range::equal_range(visitedPairs_, visited_pair.get(),
218                                          simgrid::mc::DerefAndCompareByActorsCountAndUsedHeap());
219
220   for (auto i = range.first; i != range.second; ++i) {
221     VisitedPair* pair_test = i->get();
222     if (xbt_automaton_state_compare(
223           pair_test->automaton_state, visited_pair->automaton_state) != 0
224         || *(pair_test->atomic_propositions) != *(visited_pair->atomic_propositions)
225         || this->compare(pair_test, visited_pair.get()) != 0)
226         continue;
227     if (pair_test->other_num == -1)
228       visited_pair->other_num = pair_test->num;
229     else
230       visited_pair->other_num = pair_test->other_num;
231     if (dot_output == nullptr)
232       XBT_DEBUG("Pair %d already visited ! (equal to pair %d)", visited_pair->num, pair_test->num);
233     else
234       XBT_DEBUG("Pair %d already visited ! (equal to pair %d (pair %d in dot_output))",
235         visited_pair->num, pair_test->num, visited_pair->other_num);
236     (*i) = std::move(visited_pair);
237     return (*i)->other_num;
238   }
239
240   visitedPairs_.insert(range.first, std::move(visited_pair));
241   this->purgeVisitedPairs();
242   return -1;
243 }
244
245 void LivenessChecker::purgeVisitedPairs()
246 {
247   if (_sg_mc_max_visited_states != 0 && visitedPairs_.size() > (std::size_t)_sg_mc_max_visited_states) {
248     // Remove the oldest entry with a linear search:
249     visitedPairs_.erase(boost::min_element(visitedPairs_,
250       [](std::shared_ptr<VisitedPair> const a, std::shared_ptr<VisitedPair> const& b) {
251         return a->num < b->num; } ));
252   }
253 }
254
255 LivenessChecker::LivenessChecker(Session& session) : Checker(session)
256 {
257 }
258
259 RecordTrace LivenessChecker::getRecordTrace() // override
260 {
261   RecordTrace res;
262   for (std::shared_ptr<Pair> const& pair : explorationStack_)
263     res.push_back(pair->graph_state->getTransition());
264   return res;
265 }
266
267 void LivenessChecker::logState() // override
268 {
269   Checker::logState();
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 }