Logo AND Algorithmique Numérique Distribuée

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