Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Merge branch 'master' 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 = std::make_shared<simgrid::mc::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 std::shared_ptr<VisitedPair> LivenessChecker::insert_acceptance_pair(simgrid::mc::Pair* pair)
84 {
85   std::shared_ptr<VisitedPair> new_pair = std::make_shared<VisitedPair>(
86     pair->num, pair->automaton_state, pair->atomic_propositions,
87     pair->graph_state);
88
89   auto res = boost::range::equal_range(acceptance_pairs_, new_pair.get(),
90                                        simgrid::mc::DerefAndCompareByActorsCountAndUsedHeap());
91
92   if (pair->search_cycle) for (auto i = res.first; i != res.second; ++i) {
93     std::shared_ptr<simgrid::mc::VisitedPair> const& pair_test = *i;
94     if (xbt_automaton_state_compare(pair_test->automaton_state, new_pair->automaton_state) != 0 ||
95         *(pair_test->atomic_propositions) != *(new_pair->atomic_propositions) ||
96         not snapshot_equal(pair_test->graph_state->system_state.get(), new_pair->graph_state->system_state.get()))
97       continue;
98     XBT_INFO("Pair %d already reached (equal to pair %d) !", new_pair->num, pair_test->num);
99     exploration_stack_.pop_back();
100     if (dot_output != nullptr)
101       fprintf(dot_output, "\"%d\" -> \"%d\" [%s];\n", this->previous_pair_, pair_test->num,
102               this->previous_request_.c_str());
103     return nullptr;
104   }
105
106   acceptance_pairs_.insert(res.first, new_pair);
107   return new_pair;
108 }
109
110 void LivenessChecker::remove_acceptance_pair(int pair_num)
111 {
112   for (auto i = acceptance_pairs_.begin(); i != acceptance_pairs_.end(); ++i)
113     if ((*i)->num == pair_num) {
114       acceptance_pairs_.erase(i);
115       break;
116     }
117 }
118
119 void LivenessChecker::replay()
120 {
121   XBT_DEBUG("**** Begin Replay ****");
122
123   /* Intermediate backtracking */
124   if(_sg_mc_checkpoint > 0) {
125     simgrid::mc::Pair* pair = exploration_stack_.back().get();
126     if(pair->graph_state->system_state){
127       pair->graph_state->system_state->restore(&mc_model_checker->process());
128       return;
129     }
130   }
131
132   /* Restore the initial state */
133   simgrid::mc::session->restore_initial_state();
134
135   /* Traverse the stack from the initial state and re-execute the transitions */
136   int depth = 1;
137   for (std::shared_ptr<Pair> const& pair : exploration_stack_) {
138     if (pair == exploration_stack_.back())
139       break;
140
141     std::shared_ptr<State> state = pair->graph_state;
142
143     if (pair->exploration_started) {
144
145       int req_num             = state->transition_.argument_;
146       smx_simcall_t saved_req = &state->executed_req_;
147
148       smx_simcall_t req = nullptr;
149
150       if (saved_req != nullptr) {
151         /* because we got a copy of the executed request, we have to fetch the
152              real one, pointed by the request field of the issuer process */
153         const smx_actor_t issuer = MC_smx_simcall_get_issuer(saved_req);
154         req = &issuer->simcall;
155
156         /* Debug information */
157         XBT_DEBUG("Replay (depth = %d) : %s (%p)",
158           depth,
159           simgrid::mc::request_to_string(
160             req, req_num, simgrid::mc::RequestType::simix).c_str(),
161           state.get());
162       }
163
164       this->get_session().execute(state->transition_);
165     }
166
167     /* Update statistics */
168     visited_pairs_count_++;
169     mc_model_checker->executed_transitions++;
170
171     depth++;
172
173   }
174
175   XBT_DEBUG("**** End Replay ****");
176 }
177
178 /**
179  * @brief Checks whether a given pair has already been visited by the algorithm.
180  */
181 int LivenessChecker::insert_visited_pair(std::shared_ptr<VisitedPair> visited_pair, simgrid::mc::Pair* pair)
182 {
183   if (_sg_mc_max_visited_states == 0)
184     return -1;
185
186   if (visited_pair == nullptr)
187     visited_pair =
188         std::make_shared<VisitedPair>(pair->num, pair->automaton_state, pair->atomic_propositions, pair->graph_state);
189
190   auto range = boost::range::equal_range(visited_pairs_, visited_pair.get(),
191                                          simgrid::mc::DerefAndCompareByActorsCountAndUsedHeap());
192
193   for (auto i = range.first; i != range.second; ++i) {
194     VisitedPair* pair_test = i->get();
195     if (xbt_automaton_state_compare(pair_test->automaton_state, visited_pair->automaton_state) != 0 ||
196         *(pair_test->atomic_propositions) != *(visited_pair->atomic_propositions) ||
197         not snapshot_equal(pair_test->graph_state->system_state.get(), visited_pair->graph_state->system_state.get()))
198       continue;
199     if (pair_test->other_num == -1)
200       visited_pair->other_num = pair_test->num;
201     else
202       visited_pair->other_num = pair_test->other_num;
203     if (dot_output == nullptr)
204       XBT_DEBUG("Pair %d already visited ! (equal to pair %d)", visited_pair->num, pair_test->num);
205     else
206       XBT_DEBUG("Pair %d already visited ! (equal to pair %d (pair %d in dot_output))",
207         visited_pair->num, pair_test->num, visited_pair->other_num);
208     (*i) = std::move(visited_pair);
209     return (*i)->other_num;
210   }
211
212   visited_pairs_.insert(range.first, std::move(visited_pair));
213   this->purge_visited_pairs();
214   return -1;
215 }
216
217 void LivenessChecker::purge_visited_pairs()
218 {
219   if (_sg_mc_max_visited_states != 0 && visited_pairs_.size() > (std::size_t)_sg_mc_max_visited_states) {
220     // Remove the oldest entry with a linear search:
221     visited_pairs_.erase(
222         boost::min_element(visited_pairs_, [](std::shared_ptr<VisitedPair> const a,
223                                               std::shared_ptr<VisitedPair> const& b) { return a->num < b->num; }));
224   }
225 }
226
227 LivenessChecker::LivenessChecker(Session& s) : Checker(s)
228 {
229 }
230
231 RecordTrace LivenessChecker::get_record_trace() // override
232 {
233   RecordTrace res;
234   for (std::shared_ptr<Pair> const& pair : exploration_stack_)
235     res.push_back(pair->graph_state->get_transition());
236   return res;
237 }
238
239 void LivenessChecker::log_state() // override
240 {
241   XBT_INFO("Expanded pairs = %lu", expanded_pairs_count_);
242   XBT_INFO("Visited pairs = %lu", visited_pairs_count_);
243   XBT_INFO("Executed transitions = %lu", mc_model_checker->executed_transitions);
244 }
245
246 void LivenessChecker::show_acceptance_cycle(std::size_t depth)
247 {
248   XBT_INFO("*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*");
249   XBT_INFO("|             ACCEPTANCE CYCLE            |");
250   XBT_INFO("*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*");
251   XBT_INFO("Counter-example that violates formula:");
252   for (auto const& s : this->get_textual_trace())
253     XBT_INFO("  %s", s.c_str());
254   simgrid::mc::dumpRecordPath();
255   simgrid::mc::session->log_state();
256   XBT_INFO("Counter-example depth: %zu", depth);
257 }
258
259 std::vector<std::string> LivenessChecker::get_textual_trace() // override
260 {
261   std::vector<std::string> trace;
262   for (std::shared_ptr<Pair> const& pair : exploration_stack_) {
263     int req_num       = pair->graph_state->transition_.argument_;
264     smx_simcall_t req = &pair->graph_state->executed_req_;
265     if (req && req->call_ != SIMCALL_NONE)
266       trace.push_back(simgrid::mc::request_to_string(
267         req, req_num, simgrid::mc::RequestType::executed));
268   }
269   return trace;
270 }
271
272 std::shared_ptr<Pair> LivenessChecker::create_pair(Pair* current_pair, xbt_automaton_state_t state,
273                                                    std::shared_ptr<const std::vector<int>> propositions)
274 {
275   expanded_pairs_count_++;
276   std::shared_ptr<Pair> next_pair = std::make_shared<Pair>(expanded_pairs_count_);
277   next_pair->automaton_state      = state;
278   next_pair->graph_state = std::shared_ptr<simgrid::mc::State>(new simgrid::mc::State(++expanded_states_count_));
279   next_pair->atomic_propositions  = std::move(propositions);
280   if (current_pair)
281     next_pair->depth = current_pair->depth + 1;
282   else
283     next_pair->depth = 1;
284   /* Get enabled actors and insert them in the interleave set of the next graph_state */
285   for (auto& actor : mc_model_checker->process().actors())
286     if (simgrid::mc::actor_is_enabled(actor.copy.get_buffer()))
287       next_pair->graph_state->add_interleaving_set(actor.copy.get_buffer());
288   next_pair->requests = next_pair->graph_state->interleave_size();
289   /* FIXME : get search_cycle value for each accepting state */
290   if (next_pair->automaton_state->type == 1 || (current_pair && current_pair->search_cycle))
291     next_pair->search_cycle = true;
292   else
293     next_pair->search_cycle = false;
294   return next_pair;
295 }
296
297 void LivenessChecker::backtrack()
298 {
299   /* Traverse the stack backwards until a pair with a non empty interleave
300      set is found, deleting all the pairs that have it empty in the way. */
301   while (not exploration_stack_.empty()) {
302     std::shared_ptr<simgrid::mc::Pair> current_pair = exploration_stack_.back();
303     exploration_stack_.pop_back();
304     if (current_pair->requests > 0) {
305       /* We found a backtracking point */
306       XBT_DEBUG("Backtracking to depth %d", current_pair->depth);
307       exploration_stack_.push_back(std::move(current_pair));
308       this->replay();
309       XBT_DEBUG("Backtracking done");
310       break;
311     } else {
312       XBT_DEBUG("Delete pair %d at depth %d", current_pair->num, current_pair->depth);
313       if (current_pair->automaton_state->type == 1)
314         this->remove_acceptance_pair(current_pair->num);
315     }
316   }
317 }
318
319 void LivenessChecker::run()
320 {
321   XBT_INFO("Check the liveness property %s", _sg_mc_property_file.get().c_str());
322   MC_automaton_load(_sg_mc_property_file.get().c_str());
323
324   XBT_DEBUG("Starting the liveness algorithm");
325   simgrid::mc::session->initialize();
326
327   /* Initialize */
328   this->previous_pair_ = 0;
329
330   std::shared_ptr<const std::vector<int>> propos = this->get_proposition_values();
331
332   // For each initial state of the property automaton, push a
333   // (application_state, automaton_state) pair to the exploration stack:
334   unsigned int cursor = 0;
335   xbt_automaton_state_t automaton_state;
336   xbt_dynar_foreach (simgrid::mc::property_automaton->states, cursor, automaton_state)
337     if (automaton_state->type == -1)
338       exploration_stack_.push_back(this->create_pair(nullptr, automaton_state, propos));
339
340   /* Actually run the double DFS search for counter-examples */
341   while (not exploration_stack_.empty()) {
342     std::shared_ptr<Pair> current_pair = exploration_stack_.back();
343
344     /* Update current state in buchi automaton */
345     simgrid::mc::property_automaton->current_state = current_pair->automaton_state;
346
347     XBT_DEBUG(
348         "********************* ( Depth = %d, search_cycle = %d, interleave size = %zu, pair_num = %d, requests = %d)",
349         current_pair->depth, current_pair->search_cycle, current_pair->graph_state->interleave_size(),
350         current_pair->num, current_pair->requests);
351
352     if (current_pair->requests == 0) {
353       this->backtrack();
354       continue;
355     }
356
357     std::shared_ptr<VisitedPair> reached_pair;
358     if (current_pair->automaton_state->type == 1 && not current_pair->exploration_started) {
359       reached_pair = this->insert_acceptance_pair(current_pair.get());
360       if (reached_pair == nullptr) {
361         this->show_acceptance_cycle(current_pair->depth);
362         throw simgrid::mc::LivenessError();
363       }
364     }
365
366     /* Pair already visited ? stop the exploration on the current path */
367     if (not current_pair->exploration_started) {
368       int visited_num = this->insert_visited_pair(reached_pair, current_pair.get());
369       if (visited_num != -1) {
370         if (dot_output != nullptr) {
371           fprintf(dot_output, "\"%d\" -> \"%d\" [%s];\n", this->previous_pair_, visited_num,
372                   this->previous_request_.c_str());
373           fflush(dot_output);
374         }
375         XBT_DEBUG("Pair already visited (equal to pair %d), exploration on the current path stopped.", visited_num);
376         current_pair->requests = 0;
377         this->backtrack();
378         continue;
379       }
380     }
381
382     smx_simcall_t req = MC_state_choose_request(current_pair->graph_state.get());
383     int req_num       = current_pair->graph_state->transition_.argument_;
384
385     if (dot_output != nullptr) {
386       if (this->previous_pair_ != 0 && this->previous_pair_ != current_pair->num) {
387         fprintf(dot_output, "\"%d\" -> \"%d\" [%s];\n", this->previous_pair_, current_pair->num,
388                 this->previous_request_.c_str());
389         this->previous_request_.clear();
390       }
391       this->previous_pair_    = current_pair->num;
392       this->previous_request_ = simgrid::mc::request_get_dot_output(req, req_num);
393       if (current_pair->search_cycle)
394         fprintf(dot_output, "%d [shape=doublecircle];\n", current_pair->num);
395       fflush(dot_output);
396     }
397
398     XBT_DEBUG("Execute: %s",
399       simgrid::mc::request_to_string(
400         req, req_num, simgrid::mc::RequestType::simix).c_str());
401
402     /* Update stats */
403     mc_model_checker->executed_transitions++;
404     if (not current_pair->exploration_started)
405       visited_pairs_count_++;
406
407     /* Answer the request */
408     mc_model_checker->handle_simcall(current_pair->graph_state->transition_);
409
410     /* Wait for requests (schedules processes) */
411     mc_model_checker->wait_for_requests();
412
413     current_pair->requests--;
414     current_pair->exploration_started = true;
415
416     /* Get values of atomic propositions (variables used in the property formula) */
417     std::shared_ptr<const std::vector<int>> prop_values = this->get_proposition_values();
418
419     // For each enabled transition in the property automaton, push a
420     // (application_state, automaton_state) pair to the exploration stack:
421     for (int i = xbt_dynar_length(current_pair->automaton_state->out) - 1; i >= 0; i--) {
422       xbt_automaton_transition_t transition_succ = (xbt_automaton_transition_t)xbt_dynar_get_as(
423           current_pair->automaton_state->out, i, xbt_automaton_transition_t);
424       if (evaluate_label(transition_succ->label, *prop_values))
425         exploration_stack_.push_back(this->create_pair(current_pair.get(), transition_succ->dst, prop_values));
426      }
427
428   }
429
430   XBT_INFO("No property violation found.");
431   simgrid::mc::session->log_state();
432 }
433
434 Checker* createLivenessChecker(Session& s)
435 {
436   return new LivenessChecker(s);
437 }
438
439 }
440 }