Logo AND Algorithmique Numérique Distribuée

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