Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Inline a function
[simgrid.git] / src / mc / ModelChecker.cpp
1 /* Copyright (c) 2008-2021. The SimGrid Team. All rights reserved.          */
2
3 /* This program is free software; you can redistribute it and/or modify it
4  * under the terms of the license (GNU LGPL) which comes with this package. */
5
6 #include "src/mc/ModelChecker.hpp"
7 #include "src/mc/Session.hpp"
8 #include "src/mc/Transition.hpp"
9 #include "src/mc/checker/Checker.hpp"
10 #include "src/mc/mc_config.hpp"
11 #include "src/mc/mc_exit.hpp"
12 #include "src/mc/mc_private.hpp"
13 #include "src/mc/remote/RemoteProcess.hpp"
14 #include "xbt/automaton.hpp"
15 #include "xbt/system_error.hpp"
16
17 #include <array>
18 #include <sys/ptrace.h>
19 #include <sys/wait.h>
20
21 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(mc_ModelChecker, mc, "ModelChecker");
22
23 ::simgrid::mc::ModelChecker* mc_model_checker = nullptr;
24
25 using simgrid::mc::remote;
26
27 #ifdef __linux__
28 # define WAITPID_CHECKED_FLAGS __WALL
29 #else
30 # define WAITPID_CHECKED_FLAGS 0
31 #endif
32
33 namespace simgrid {
34 namespace mc {
35
36 ModelChecker::ModelChecker(std::unique_ptr<RemoteProcess> remote_simulation, int sockfd)
37     : checker_side_(sockfd), remote_process_(std::move(remote_simulation))
38 {
39 }
40
41 void ModelChecker::start()
42 {
43   checker_side_.start([](evutil_socket_t sig, short events, void* arg) {
44     auto mc = static_cast<simgrid::mc::ModelChecker*>(arg);
45     if (events == EV_READ) {
46       std::array<char, MC_MESSAGE_LENGTH> buffer;
47       ssize_t size = mc->checker_side_.get_channel().receive(buffer.data(), buffer.size(), false);
48       if (size == -1 && errno != EAGAIN)
49         throw simgrid::xbt::errno_error();
50
51       if (not mc->handle_message(buffer.data(), size))
52         mc->checker_side_.break_loop();
53     } else if (events == EV_SIGNAL) {
54       if (sig == SIGCHLD)
55         mc->handle_waitpid();
56     } else {
57       xbt_die("Unexpected event");
58     }
59   });
60
61   XBT_DEBUG("Waiting for the model-checked process");
62   int status;
63
64   // The model-checked process SIGSTOP itself to signal it's ready:
65   const pid_t pid = remote_process_->pid();
66
67   pid_t res = waitpid(pid, &status, WAITPID_CHECKED_FLAGS);
68   if (res < 0 || not WIFSTOPPED(status) || WSTOPSIG(status) != SIGSTOP)
69     xbt_die("Could not wait model-checked process");
70
71   remote_process_->init();
72
73   if (not _sg_mc_dot_output_file.get().empty())
74     MC_init_dot_output();
75
76   setup_ignore();
77
78 #ifdef __linux__
79   ptrace(PTRACE_SETOPTIONS, pid, nullptr, PTRACE_O_TRACEEXIT);
80   ptrace(PTRACE_CONT, pid, 0, 0);
81 #elif defined BSD
82   ptrace(PT_CONTINUE, pid, (caddr_t)1, 0);
83 #else
84 # error "no ptrace equivalent coded for this platform"
85 #endif
86 }
87
88 static constexpr auto ignored_local_variables = {
89     std::make_pair("e", "*"),
90     std::make_pair("_log_ev", "*"),
91
92     /* Ignore local variable about time used for tracing */
93     std::make_pair("start_time", "*"),
94 };
95
96 void ModelChecker::setup_ignore()
97 {
98   const RemoteProcess& process = this->get_remote_process();
99   for (auto const& var : ignored_local_variables)
100     process.ignore_local_variable(var.first, var.second);
101
102   /* Static variable used for tracing */
103   process.ignore_global_variable("counter");
104 }
105
106 void ModelChecker::shutdown()
107 {
108   XBT_DEBUG("Shutting down model-checker");
109
110   RemoteProcess* process = &this->get_remote_process();
111   if (process->running()) {
112     XBT_DEBUG("Killing process");
113     kill(process->pid(), SIGKILL);
114     process->terminate();
115   }
116 }
117
118 void ModelChecker::resume()
119 {
120   int res = checker_side_.get_channel().send(MessageType::CONTINUE);
121   if (res)
122     throw xbt::errno_error();
123   remote_process_->clear_cache();
124 }
125
126 static void MC_report_crash(int status)
127 {
128   XBT_INFO("**************************");
129   XBT_INFO("** CRASH IN THE PROGRAM **");
130   XBT_INFO("**************************");
131   if (WIFSIGNALED(status))
132     XBT_INFO("From signal: %s", strsignal(WTERMSIG(status)));
133   else if (WIFEXITED(status))
134     XBT_INFO("From exit: %i", WEXITSTATUS(status));
135   if (not xbt_log_no_loc)
136     XBT_INFO("%s core dump was generated by the system.", WCOREDUMP(status) ? "A" : "No");
137   XBT_INFO("Counter-example execution trace:");
138   for (auto const& s : mc_model_checker->getChecker()->get_textual_trace())
139     XBT_INFO("  %s", s.c_str());
140   dumpRecordPath();
141   session->log_state();
142   if (xbt_log_no_loc) {
143     XBT_INFO("Stack trace not displayed because you passed --log=no_loc");
144   } else {
145     XBT_INFO("Stack trace:");
146     mc_model_checker->get_remote_process().dump_stack();
147   }
148 }
149
150 bool ModelChecker::handle_message(const char* buffer, ssize_t size)
151 {
152   s_mc_message_t base_message;
153   xbt_assert(size >= (ssize_t)sizeof(base_message), "Broken message");
154   memcpy(&base_message, buffer, sizeof(base_message));
155
156   switch(base_message.type) {
157     case MessageType::IGNORE_HEAP: {
158       s_mc_message_ignore_heap_t message;
159       xbt_assert(size == sizeof(message), "Broken message");
160       memcpy(&message, buffer, sizeof(message));
161
162       IgnoredHeapRegion region;
163       region.block    = message.block;
164       region.fragment = message.fragment;
165       region.address  = message.address;
166       region.size     = message.size;
167       get_remote_process().ignore_heap(region);
168       break;
169     }
170
171     case MessageType::UNIGNORE_HEAP: {
172       s_mc_message_ignore_memory_t message;
173       xbt_assert(size == sizeof(message), "Broken message");
174       memcpy(&message, buffer, sizeof(message));
175       get_remote_process().unignore_heap((void*)(std::uintptr_t)message.addr, message.size);
176       break;
177     }
178
179     case MessageType::IGNORE_MEMORY: {
180       s_mc_message_ignore_memory_t message;
181       xbt_assert(size == sizeof(message), "Broken message");
182       memcpy(&message, buffer, sizeof(message));
183       this->get_remote_process().ignore_region(message.addr, message.size);
184       break;
185     }
186
187     case MessageType::STACK_REGION: {
188       s_mc_message_stack_region_t message;
189       xbt_assert(size == sizeof(message), "Broken message");
190       memcpy(&message, buffer, sizeof(message));
191       this->get_remote_process().stack_areas().push_back(message.stack_region);
192     } break;
193
194     case MessageType::REGISTER_SYMBOL: {
195       s_mc_message_register_symbol_t message;
196       xbt_assert(size == sizeof(message), "Broken message");
197       memcpy(&message, buffer, sizeof(message));
198       xbt_assert(not message.callback, "Support for client-side function proposition is not implemented.");
199       XBT_DEBUG("Received symbol: %s", message.name.data());
200
201       if (property_automaton == nullptr)
202         property_automaton = xbt_automaton_new();
203
204       const RemoteProcess* process    = &this->get_remote_process();
205       RemotePtr<int> address          = remote((int*)message.data);
206       xbt::add_proposition(property_automaton, message.name.data(),
207                            [process, address]() { return process->read(address); });
208
209       break;
210     }
211
212     case MessageType::WAITING:
213       return false;
214
215     case MessageType::ASSERTION_FAILED:
216       XBT_INFO("**************************");
217       XBT_INFO("*** PROPERTY NOT VALID ***");
218       XBT_INFO("**************************");
219       XBT_INFO("Counter-example execution trace:");
220       for (auto const& s : getChecker()->get_textual_trace())
221         XBT_INFO("  %s", s.c_str());
222       dumpRecordPath();
223       session->log_state();
224
225       this->exit(SIMGRID_MC_EXIT_SAFETY);
226
227     default:
228       xbt_die("Unexpected message from model-checked application");
229   }
230   return true;
231 }
232
233 /** Terminate the model-checker application */
234 void ModelChecker::exit(int status)
235 {
236   // TODO, terminate the model checker politely instead of exiting rudely
237   if (get_remote_process().running())
238     kill(get_remote_process().pid(), SIGKILL);
239   ::exit(status);
240 }
241
242 void ModelChecker::handle_waitpid()
243 {
244   XBT_DEBUG("Check for wait event");
245   int status;
246   pid_t pid;
247   while ((pid = waitpid(-1, &status, WNOHANG)) != 0) {
248     if (pid == -1) {
249       if (errno == ECHILD) {
250         // No more children:
251         xbt_assert(not this->get_remote_process().running(), "Inconsistent state");
252         break;
253       } else {
254         XBT_ERROR("Could not wait for pid");
255         throw simgrid::xbt::errno_error();
256       }
257     }
258
259     if (pid == this->get_remote_process().pid()) {
260       // From PTRACE_O_TRACEEXIT:
261 #ifdef __linux__
262       if (status>>8 == (SIGTRAP | (PTRACE_EVENT_EXIT<<8))) {
263         xbt_assert(ptrace(PTRACE_GETEVENTMSG, remote_process_->pid(), 0, &status) != -1, "Could not get exit status");
264         if (WIFSIGNALED(status)) {
265           MC_report_crash(status);
266           this->exit(SIMGRID_MC_EXIT_PROGRAM_CRASH);
267         }
268       }
269 #endif
270
271       // We don't care about signals, just reinject them:
272       if (WIFSTOPPED(status)) {
273         XBT_DEBUG("Stopped with signal %i", (int) WSTOPSIG(status));
274         errno = 0;
275 #ifdef __linux__
276         ptrace(PTRACE_CONT, remote_process_->pid(), 0, WSTOPSIG(status));
277 #elif defined BSD
278         ptrace(PT_CONTINUE, remote_process_->pid(), (caddr_t)1, WSTOPSIG(status));
279 #endif
280         xbt_assert(errno == 0, "Could not PTRACE_CONT");
281       }
282
283       else if (WIFSIGNALED(status)) {
284         MC_report_crash(status);
285         this->exit(SIMGRID_MC_EXIT_PROGRAM_CRASH);
286       } else if (WIFEXITED(status)) {
287         XBT_DEBUG("Child process is over");
288         this->get_remote_process().terminate();
289       }
290     }
291   }
292 }
293
294 void ModelChecker::wait_for_requests()
295 {
296   this->resume();
297   if (this->get_remote_process().running())
298     checker_side_.dispatch();
299 }
300
301 void ModelChecker::handle_simcall(Transition const& transition)
302 {
303   s_mc_message_simcall_handle_t m;
304   memset(&m, 0, sizeof(m));
305   m.type  = MessageType::SIMCALL_HANDLE;
306   m.pid_              = transition.pid_;
307   m.times_considered_ = transition.times_considered_;
308   checker_side_.get_channel().send(m);
309   this->remote_process_->clear_cache();
310   if (this->remote_process_->running())
311     checker_side_.dispatch();
312 }
313 bool ModelChecker::simcall_is_visible(int aid)
314 {
315   xbt_assert(mc_model_checker != nullptr, "This should be called from the checker side");
316
317   s_mc_message_simcall_is_visible_t m;
318   memset(&m, 0, sizeof(m));
319   m.type = MessageType::SIMCALL_IS_VISIBLE;
320   m.aid  = aid;
321   checker_side_.get_channel().send(m);
322
323   s_mc_message_simcall_is_visible_answer_t answer;
324   ssize_t s = checker_side_.get_channel().receive(answer);
325   xbt_assert(s != -1, "Could not receive message");
326   xbt_assert(s == sizeof(answer) && answer.type == MessageType::SIMCALL_IS_VISIBLE_ANSWER,
327              "Received unexpected message %s (%i, size=%i) "
328              "expected MessageType::SIMCALL_IS_VISIBLE_ANSWER (%i, size=%i)",
329              to_c_str(answer.type), (int)answer.type, (int)s, (int)MessageType::SIMCALL_IS_VISIBLE_ANSWER,
330              (int)sizeof(answer));
331
332   XBT_DEBUG("is_visible(%d) is returning %s", aid, answer.value ? "true" : "false");
333
334   this->remote_process_->clear_cache();
335   return answer.value;
336 }
337
338 std::string ModelChecker::simcall_to_string(MessageType type, int aid, int times_considered)
339 {
340   xbt_assert(mc_model_checker != nullptr, "This should be called from the checker side");
341
342   s_mc_message_simcall_to_string_t m;
343   memset(&m, 0, sizeof(m));
344   m.type            = type;
345   m.aid             = aid;
346   m.time_considered = times_considered;
347   checker_side_.get_channel().send(m);
348
349   s_mc_message_simcall_to_string_answer_t answer;
350   ssize_t s = checker_side_.get_channel().receive(answer);
351   xbt_assert(s != -1, "Could not receive message");
352   xbt_assert(s == sizeof(answer) && answer.type == MessageType::SIMCALL_TO_STRING_ANSWER,
353              "Received unexpected message %s (%i, size=%i) "
354              "expected MessageType::SIMCALL_TO_STRING_ANSWER (%i, size=%i)",
355              to_c_str(answer.type), (int)answer.type, (int)s, (int)MessageType::SIMCALL_TO_STRING_ANSWER,
356              (int)sizeof(answer));
357
358   return std::string(answer.value);
359 }
360
361 std::string ModelChecker::simcall_to_string(int aid, int times_considered)
362 {
363   std::string answer = simcall_to_string(MessageType::SIMCALL_TO_STRING, aid, times_considered);
364   XBT_DEBUG("to_string(%d) is returning %s", aid, answer.c_str());
365   return answer;
366 }
367
368 std::string ModelChecker::simcall_dot_label(int aid, int times_considered)
369 {
370   std::string answer = simcall_to_string(MessageType::SIMCALL_DOT_LABEL, aid, times_considered);
371   XBT_DEBUG("dot_label(%d) is returning %s", aid, answer.c_str());
372   return answer;
373 }
374
375 bool ModelChecker::checkDeadlock()
376 {
377   int res = checker_side_.get_channel().send(MessageType::DEADLOCK_CHECK);
378   xbt_assert(res == 0, "Could not check deadlock state");
379   s_mc_message_int_t message;
380   ssize_t s = checker_side_.get_channel().receive(message);
381   xbt_assert(s != -1, "Could not receive message");
382   xbt_assert(s == sizeof(message) && message.type == MessageType::DEADLOCK_CHECK_REPLY,
383              "Received unexpected message %s (%i, size=%i) "
384              "expected MessageType::DEADLOCK_CHECK_REPLY (%i, size=%i)",
385              to_c_str(message.type), (int)message.type, (int)s, (int)MessageType::DEADLOCK_CHECK_REPLY,
386              (int)sizeof(message));
387   return message.value != 0;
388 }
389
390 } // namespace mc
391 } // namespace simgrid