Logo AND Algorithmique Numérique Distribuée

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