Logo AND Algorithmique Numérique Distribuée

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