Logo AND Algorithmique Numérique Distribuée

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