Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
16494c847630428f7aa0715d81869a537bf0956a
[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     livenessStack_.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
161   initial_global_state->snapshot = simgrid::mc::take_snapshot(0);
162   initial_global_state->prev_pair = 0;
163
164   unsigned int cursor = 0;
165   xbt_automaton_state_t automaton_state;
166
167   xbt_dynar_foreach(simgrid::mc::property_automaton->states, cursor, automaton_state) {
168     if (automaton_state->type == -1) {  /* Initial automaton state */
169
170       std::shared_ptr<Pair> initial_pair = std::make_shared<Pair>();
171       initial_pair->automaton_state = automaton_state;
172       initial_pair->graph_state = std::shared_ptr<simgrid::mc::State>(MC_state_new());
173       initial_pair->atomic_propositions = this->getPropositionValues();
174       initial_pair->depth = 1;
175
176       /* Get enabled processes and insert them in the interleave set of the graph_state */
177       for (auto& p : mc_model_checker->process().simix_processes())
178         if (simgrid::mc::process_is_enabled(&p.copy))
179           MC_state_interleave_process(initial_pair->graph_state.get(), &p.copy);
180
181       initial_pair->requests = MC_state_interleave_size(initial_pair->graph_state.get());
182       initial_pair->search_cycle = false;
183
184       livenessStack_.push_back(std::move(initial_pair));
185     }
186   }
187 }
188
189
190 void LivenessChecker::replay()
191 {
192   XBT_DEBUG("**** Begin Replay ****");
193
194   /* Intermediate backtracking */
195   if(_sg_mc_checkpoint > 0) {
196     simgrid::mc::Pair* pair = livenessStack_.back().get();
197     if(pair->graph_state->system_state){
198       simgrid::mc::restore_snapshot(pair->graph_state->system_state);
199       return;
200     }
201   }
202
203   /* Restore the initial state */
204   simgrid::mc::restore_snapshot(initial_global_state->snapshot);
205
206   /* Traverse the stack from the initial state and re-execute the transitions */
207   int depth = 1;
208   for (std::shared_ptr<Pair> const& pair : livenessStack_) {
209     if (pair == livenessStack_.back())
210       break;
211
212     std::shared_ptr<State> state = pair->graph_state;
213
214     if (pair->exploration_started) {
215
216       int value;
217       smx_simcall_t saved_req = MC_state_get_executed_request(state.get(), &value);
218
219       smx_simcall_t req = nullptr;
220
221       if (saved_req != nullptr) {
222         /* because we got a copy of the executed request, we have to fetch the
223              real one, pointed by the request field of the issuer process */
224         const smx_process_t issuer = MC_smx_simcall_get_issuer(saved_req);
225         req = &issuer->simcall;
226
227         /* Debug information */
228         if (XBT_LOG_ISENABLED(mc_liveness, xbt_log_priority_debug)) {
229           char* req_str = simgrid::mc::request_to_string(req, value, simgrid::mc::RequestType::simix);
230           XBT_DEBUG("Replay (depth = %d) : %s (%p)", depth, req_str, state.get());
231           xbt_free(req_str);
232         }
233
234       }
235
236       simgrid::mc::handle_simcall(req, value);
237       mc_model_checker->wait_for_requests();
238     }
239
240     /* Update statistics */
241     mc_stats->visited_pairs++;
242     mc_stats->executed_transitions++;
243
244     depth++;
245
246   }
247
248   XBT_DEBUG("**** End Replay ****");
249 }
250
251 /**
252  * \brief Checks whether a given pair has already been visited by the algorithm.
253  */
254 int LivenessChecker::insertVisitedPair(std::shared_ptr<VisitedPair> visited_pair, simgrid::mc::Pair* pair)
255 {
256   if (_sg_mc_visited == 0)
257     return -1;
258
259   if (visited_pair == nullptr)
260     visited_pair = std::make_shared<VisitedPair>(
261       pair->num, pair->automaton_state, pair->atomic_propositions,
262       pair->graph_state);
263
264   auto range = std::equal_range(visitedPairs_.begin(), visitedPairs_.end(),
265     visited_pair.get(), simgrid::mc::DerefAndCompareByNbProcessesAndUsedHeap());
266
267   for (auto i = range.first; i != range.second; ++i) {
268     VisitedPair* pair_test = i->get();
269     if (xbt_automaton_state_compare(
270           pair_test->automaton_state, visited_pair->automaton_state) != 0
271         || pair_test->atomic_propositions != visited_pair->atomic_propositions
272         || this->compare(pair_test, visited_pair.get()) != 0)
273         continue;
274     if (pair_test->other_num == -1)
275       visited_pair->other_num = pair_test->num;
276     else
277       visited_pair->other_num = pair_test->other_num;
278     if (dot_output == nullptr)
279       XBT_DEBUG("Pair %d already visited ! (equal to pair %d)", visited_pair->num, pair_test->num);
280     else
281       XBT_DEBUG("Pair %d already visited ! (equal to pair %d (pair %d in dot_output))",
282         visited_pair->num, pair_test->num, visited_pair->other_num);
283     (*i) = std::move(visited_pair);
284     return (*i)->other_num;
285   }
286
287   visitedPairs_.insert(range.first, std::move(visited_pair));
288   this->purgeVisitedPairs();
289   return -1;
290 }
291
292 void LivenessChecker::purgeVisitedPairs()
293 {
294   if (_sg_mc_visited != 0 && visitedPairs_.size() > (std::size_t) _sg_mc_visited) {
295     // Remove the oldest entry with a linear search:
296     visitedPairs_.erase(std::min_element(
297       visitedPairs_.begin(), visitedPairs_.end(),
298       [](std::shared_ptr<VisitedPair> const a, std::shared_ptr<VisitedPair> const& b) {
299         return a->num < b->num; } ));
300   }
301 }
302
303 LivenessChecker::LivenessChecker(Session& session) : Checker(session)
304 {
305 }
306
307 LivenessChecker::~LivenessChecker()
308 {
309 }
310
311 RecordTrace LivenessChecker::getRecordTrace() // override
312 {
313   RecordTrace res;
314   for (std::shared_ptr<Pair> const& pair : livenessStack_) {
315     int value;
316     smx_simcall_t req = MC_state_get_executed_request(pair->graph_state.get(), &value);
317     if (req && req->call != SIMCALL_NONE) {
318       smx_process_t issuer = MC_smx_simcall_get_issuer(req);
319       const int pid = issuer->pid;
320       res.push_back(RecordTraceElement(pid, value));
321     }
322   }
323   return res;
324 }
325
326 void LivenessChecker::showAcceptanceCycle(std::size_t depth)
327 {
328   XBT_INFO("*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*");
329   XBT_INFO("|             ACCEPTANCE CYCLE            |");
330   XBT_INFO("*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*");
331   XBT_INFO("Counter-example that violates formula :");
332   simgrid::mc::dumpRecordPath();
333   for (auto& s : this->getTextualTrace())
334     XBT_INFO("%s", s.c_str());
335   MC_print_statistics(mc_stats);
336   XBT_INFO("Counter-example depth : %zd", depth);
337 }
338
339 std::vector<std::string> LivenessChecker::getTextualTrace() // override
340 {
341   std::vector<std::string> trace;
342   for (std::shared_ptr<Pair> const& pair : livenessStack_) {
343     int value;
344     smx_simcall_t req = MC_state_get_executed_request(pair->graph_state.get(), &value);
345     if (req && req->call != SIMCALL_NONE) {
346       char* req_str = simgrid::mc::request_to_string(req, value, simgrid::mc::RequestType::executed);
347       trace.push_back(std::string(req_str));
348       xbt_free(req_str);
349     }
350   }
351   return trace;
352 }
353
354 int LivenessChecker::main(void)
355 {
356   while (!livenessStack_.empty()){
357     std::shared_ptr<Pair> current_pair = livenessStack_.back();
358
359     /* Update current state in buchi automaton */
360     simgrid::mc::property_automaton->current_state = current_pair->automaton_state;
361
362     XBT_DEBUG("********************* ( Depth = %d, search_cycle = %d, interleave size = %d, pair_num = %d, requests = %d)",
363        current_pair->depth, current_pair->search_cycle,
364        MC_state_interleave_size(current_pair->graph_state.get()), current_pair->num,
365        current_pair->requests);
366
367     if (current_pair->requests == 0) {
368       this->backtrack();
369       continue;
370     }
371
372     std::shared_ptr<VisitedPair> reached_pair;
373     if (current_pair->automaton_state->type == 1 && !current_pair->exploration_started
374         && (reached_pair = this->insertAcceptancePair(current_pair.get())) == nullptr) {
375       this->showAcceptanceCycle(current_pair->depth);
376       return SIMGRID_MC_EXIT_LIVENESS;
377     }
378
379     /* Pair already visited ? stop the exploration on the current path */
380     int visited_num = -1;
381     if ((!current_pair->exploration_started)
382       && (visited_num = this->insertVisitedPair(
383         reached_pair, current_pair.get())) != -1) {
384       if (dot_output != nullptr){
385         fprintf(dot_output, "\"%d\" -> \"%d\" [%s];\n", initial_global_state->prev_pair, visited_num, initial_global_state->prev_req);
386         fflush(dot_output);
387       }
388       XBT_DEBUG("Pair already visited (equal to pair %d), exploration on the current path stopped.", visited_num);
389       current_pair->requests = 0;
390       this->backtrack();
391       continue;
392     }
393
394     int value;
395     smx_simcall_t req = MC_state_get_request(current_pair->graph_state.get(), &value);
396
397     if (dot_output != nullptr) {
398       if (initial_global_state->prev_pair != 0 && initial_global_state->prev_pair != current_pair->num) {
399         fprintf(dot_output, "\"%d\" -> \"%d\" [%s];\n", initial_global_state->prev_pair, current_pair->num, initial_global_state->prev_req);
400         xbt_free(initial_global_state->prev_req);
401       }
402       initial_global_state->prev_pair = current_pair->num;
403       initial_global_state->prev_req = simgrid::mc::request_get_dot_output(req, value);
404       if (current_pair->search_cycle)
405         fprintf(dot_output, "%d [shape=doublecircle];\n", current_pair->num);
406       fflush(dot_output);
407     }
408
409     char* req_str = simgrid::mc::request_to_string(req, value, simgrid::mc::RequestType::simix);
410     XBT_DEBUG("Execute: %s", req_str);
411     xbt_free(req_str);
412
413     /* Set request as executed */
414     MC_state_set_executed_request(current_pair->graph_state.get(), req, value);
415
416     /* Update mc_stats */
417     mc_stats->executed_transitions++;
418     if (!current_pair->exploration_started)
419       mc_stats->visited_pairs++;
420
421     /* Answer the request */
422     simgrid::mc::handle_simcall(req, value);
423
424     /* Wait for requests (schedules processes) */
425     mc_model_checker->wait_for_requests();
426
427     current_pair->requests--;
428     current_pair->exploration_started = true;
429
430     /* Get values of atomic propositions (variables used in the property formula) */
431     std::vector<int> prop_values = this->getPropositionValues();
432
433     /* Evaluate enabled/true transitions in automaton according to atomic propositions values and create new pairs */
434     int cursor = xbt_dynar_length(current_pair->automaton_state->out) - 1;
435     while (cursor >= 0) {
436       xbt_automaton_transition_t transition_succ = (xbt_automaton_transition_t)xbt_dynar_get_as(current_pair->automaton_state->out, cursor, xbt_automaton_transition_t);
437       if (evaluate_label(transition_succ->label, prop_values)) {
438           std::shared_ptr<Pair> next_pair = std::make_shared<Pair>();
439           next_pair->graph_state = std::shared_ptr<simgrid::mc::State>(MC_state_new());
440           next_pair->automaton_state = transition_succ->dst;
441           next_pair->atomic_propositions = this->getPropositionValues();
442           next_pair->depth = current_pair->depth + 1;
443           /* Get enabled processes and insert them in the interleave set of the next graph_state */
444           for (auto& p : mc_model_checker->process().simix_processes())
445             if (simgrid::mc::process_is_enabled(&p.copy))
446               MC_state_interleave_process(next_pair->graph_state.get(), &p.copy);
447
448           next_pair->requests = MC_state_interleave_size(next_pair->graph_state.get());
449
450           /* FIXME : get search_cycle value for each acceptant state */
451           if (next_pair->automaton_state->type == 1 || current_pair->search_cycle)
452             next_pair->search_cycle = true;
453
454           /* Add new pair to the exploration stack */
455           livenessStack_.push_back(std::move(next_pair));
456
457        }
458        cursor--;
459      }
460
461   }
462
463   XBT_INFO("No property violation found.");
464   MC_print_statistics(mc_stats);
465   return SIMGRID_MC_EXIT_SUCCESS;
466 }
467
468 void LivenessChecker::backtrack()
469 {
470   /* Traverse the stack backwards until a pair with a non empty interleave
471      set is found, deleting all the pairs that have it empty in the way. */
472   while (!livenessStack_.empty()) {
473     std::shared_ptr<simgrid::mc::Pair> current_pair = livenessStack_.back();
474     livenessStack_.pop_back();
475     if (current_pair->requests > 0) {
476       /* We found a backtracking point */
477       XBT_DEBUG("Backtracking to depth %d", current_pair->depth);
478       livenessStack_.push_back(std::move(current_pair));
479       this->replay();
480       XBT_DEBUG("Backtracking done");
481       break;
482     } else {
483       XBT_DEBUG("Delete pair %d at depth %d", current_pair->num, current_pair->depth);
484       if (current_pair->automaton_state->type == 1)
485         this->removeAcceptancePair(current_pair->num);
486     }
487   }
488 }
489
490 int LivenessChecker::run()
491 {
492   XBT_INFO("Check the liveness property %s", _sg_mc_property_file);
493   MC_automaton_load(_sg_mc_property_file);
494   mc_model_checker->wait_for_requests();
495
496   XBT_DEBUG("Starting the liveness algorithm");
497
498   /* Create the initial state */
499   simgrid::mc::initial_global_state = std::unique_ptr<s_mc_global_t>(new s_mc_global_t());
500
501   this->prepare();
502   int res = this->main();
503   simgrid::mc::initial_global_state = nullptr;
504
505   return res;
506 }
507
508 Checker* createLivenessChecker(Session& session)
509 {
510   return new LivenessChecker(session);
511 }
512
513 }
514 }