Logo AND Algorithmique Numérique Distribuée

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