Logo AND Algorithmique Numérique Distribuée

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