Logo AND Algorithmique Numérique Distribuée

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