Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Merge branch 'tracemgrsplit' into 'master'
[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::get_proposition_values()
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::insert_acceptance_pair(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(acceptance_pairs_, 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     exploration_stack_.pop_back();
108     if (dot_output != nullptr)
109       fprintf(dot_output, "\"%d\" -> \"%d\" [%s];\n", this->previous_pair_, pair_test->num,
110               this->previous_request_.c_str());
111     return nullptr;
112   }
113
114   acceptance_pairs_.insert(res.first, new_pair);
115   return new_pair;
116 }
117
118 void LivenessChecker::remove_acceptance_pair(int pair_num)
119 {
120   for (auto i = acceptance_pairs_.begin(); i != acceptance_pairs_.end(); ++i)
121     if ((*i)->num == pair_num) {
122       acceptance_pairs_.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 = exploration_stack_.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->restore_initial_state();
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 : exploration_stack_) {
146     if (pair == exploration_stack_.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->get_session().execute(state->transition);
173     }
174
175     /* Update statistics */
176     visited_pairs_count_++;
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::insert_visited_pair(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(visited_pairs_, 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   visited_pairs_.insert(range.first, std::move(visited_pair));
222   this->purge_visited_pairs();
223   return -1;
224 }
225
226 void LivenessChecker::purge_visited_pairs()
227 {
228   if (_sg_mc_max_visited_states != 0 && visited_pairs_.size() > (std::size_t)_sg_mc_max_visited_states) {
229     // Remove the oldest entry with a linear search:
230     visited_pairs_.erase(
231         boost::min_element(visited_pairs_, [](std::shared_ptr<VisitedPair> const a,
232                                               std::shared_ptr<VisitedPair> const& b) { return a->num < b->num; }));
233   }
234 }
235
236 LivenessChecker::LivenessChecker(Session& s) : Checker(s)
237 {
238 }
239
240 RecordTrace LivenessChecker::get_record_trace() // override
241 {
242   RecordTrace res;
243   for (std::shared_ptr<Pair> const& pair : exploration_stack_)
244     res.push_back(pair->graph_state->getTransition());
245   return res;
246 }
247
248 void LivenessChecker::log_state() // override
249 {
250   XBT_INFO("Expanded pairs = %lu", expanded_pairs_count_);
251   XBT_INFO("Visited pairs = %lu", visited_pairs_count_);
252   XBT_INFO("Executed transitions = %lu", mc_model_checker->executed_transitions);
253 }
254
255 void LivenessChecker::show_acceptance_cycle(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->get_textual_trace())
262     XBT_INFO("  %s", s.c_str());
263   simgrid::mc::dumpRecordPath();
264   simgrid::mc::session->log_state();
265   XBT_INFO("Counter-example depth: %zu", depth);
266 }
267
268 std::vector<std::string> LivenessChecker::get_textual_trace() // override
269 {
270   std::vector<std::string> trace;
271   for (std::shared_ptr<Pair> const& pair : exploration_stack_) {
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::create_pair(Pair* current_pair, xbt_automaton_state_t state,
282                                                    std::shared_ptr<const std::vector<int>> propositions)
283 {
284   expanded_pairs_count_++;
285   std::shared_ptr<Pair> next_pair = std::make_shared<Pair>(expanded_pairs_count_);
286   next_pair->automaton_state      = state;
287   next_pair->graph_state = std::shared_ptr<simgrid::mc::State>(new simgrid::mc::State(++expanded_states_count_));
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.get_buffer()))
296       next_pair->graph_state->addInterleavingSet(actor.copy.get_buffer());
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 exploration_stack_.empty()) {
311     std::shared_ptr<simgrid::mc::Pair> current_pair = exploration_stack_.back();
312     exploration_stack_.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       exploration_stack_.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->remove_acceptance_pair(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->previous_pair_ = 0;
338
339   std::shared_ptr<const std::vector<int>> propos = this->get_proposition_values();
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       exploration_stack_.push_back(this->create_pair(nullptr, automaton_state, propos));
348
349   /* Actually run the double DFS search for counter-examples */
350   while (not exploration_stack_.empty()) {
351     std::shared_ptr<Pair> current_pair = exploration_stack_.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->insert_acceptance_pair(current_pair.get());
369       if (reached_pair == nullptr) {
370         this->show_acceptance_cycle(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->insert_visited_pair(reached_pair, current_pair.get());
378       if (visited_num != -1) {
379         if (dot_output != nullptr) {
380           fprintf(dot_output, "\"%d\" -> \"%d\" [%s];\n", this->previous_pair_, visited_num,
381                   this->previous_request_.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->previous_pair_ != 0 && this->previous_pair_ != current_pair->num) {
396         fprintf(dot_output, "\"%d\" -> \"%d\" [%s];\n", this->previous_pair_, current_pair->num,
397                 this->previous_request_.c_str());
398         this->previous_request_.clear();
399       }
400       this->previous_pair_    = current_pair->num;
401       this->previous_request_ = simgrid::mc::request_get_dot_output(req, req_num);
402       if (current_pair->search_cycle)
403         fprintf(dot_output, "%d [shape=doublecircle];\n", current_pair->num);
404       fflush(dot_output);
405     }
406
407     XBT_DEBUG("Execute: %s",
408       simgrid::mc::request_to_string(
409         req, req_num, simgrid::mc::RequestType::simix).c_str());
410
411     /* Update stats */
412     mc_model_checker->executed_transitions++;
413     if (not current_pair->exploration_started)
414       visited_pairs_count_++;
415
416     /* Answer the request */
417     mc_model_checker->handle_simcall(current_pair->graph_state->transition);
418
419     /* Wait for requests (schedules processes) */
420     mc_model_checker->wait_for_requests();
421
422     current_pair->requests--;
423     current_pair->exploration_started = true;
424
425     /* Get values of atomic propositions (variables used in the property formula) */
426     std::shared_ptr<const std::vector<int>> prop_values = this->get_proposition_values();
427
428     // For each enabled transition in the property automaton, push a
429     // (application_state, automaton_state) pair to the exploration stack:
430     for (int i = xbt_dynar_length(current_pair->automaton_state->out) - 1; i >= 0; i--) {
431       xbt_automaton_transition_t transition_succ = (xbt_automaton_transition_t)xbt_dynar_get_as(
432           current_pair->automaton_state->out, i, xbt_automaton_transition_t);
433       if (evaluate_label(transition_succ->label, *prop_values))
434         exploration_stack_.push_back(this->create_pair(current_pair.get(), transition_succ->dst, prop_values));
435      }
436
437   }
438
439   XBT_INFO("No property violation found.");
440   simgrid::mc::session->log_state();
441 }
442
443 Checker* createLivenessChecker(Session& s)
444 {
445   return new LivenessChecker(s);
446 }
447
448 }
449 }