Logo AND Algorithmique Numérique Distribuée

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