Logo AND Algorithmique Numérique Distribuée

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