Logo AND Algorithmique Numérique Distribuée

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