Logo AND Algorithmique Numérique Distribuée

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