Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Update copyright lines.
[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/RemoteSimulation.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<RemoteSimulation> remote_simulation, int sockfd)
37     : checker_side_(sockfd), remote_simulation_(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_simulation_->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_simulation_->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 RemoteSimulation& process = this->get_remote_simulation();
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   RemoteSimulation* process = &this->get_remote_simulation();
111   if (process->running()) {
112     XBT_DEBUG("Killing process");
113     kill(process->pid(), SIGKILL);
114     process->terminate();
115   }
116 }
117
118 void ModelChecker::resume(RemoteSimulation& process)
119 {
120   int res = checker_side_.get_channel().send(MessageType::CONTINUE);
121   if (res)
122     throw xbt::errno_error();
123   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_simulation().dump_stack();
147   }
148 }
149
150 static void MC_report_assertion_error()
151 {
152   XBT_INFO("**************************");
153   XBT_INFO("*** PROPERTY NOT VALID ***");
154   XBT_INFO("**************************");
155   XBT_INFO("Counter-example execution trace:");
156   for (auto const& s : mc_model_checker->getChecker()->get_textual_trace())
157     XBT_INFO("  %s", s.c_str());
158   dumpRecordPath();
159   session->log_state();
160 }
161
162 bool ModelChecker::handle_message(const char* buffer, ssize_t size)
163 {
164   s_mc_message_t base_message;
165   xbt_assert(size >= (ssize_t)sizeof(base_message), "Broken message");
166   memcpy(&base_message, buffer, sizeof(base_message));
167
168   switch(base_message.type) {
169     case MessageType::IGNORE_HEAP: {
170       s_mc_message_ignore_heap_t message;
171       xbt_assert(size == sizeof(message), "Broken message");
172       memcpy(&message, buffer, sizeof(message));
173
174       IgnoredHeapRegion region;
175       region.block    = message.block;
176       region.fragment = message.fragment;
177       region.address  = message.address;
178       region.size     = message.size;
179       get_remote_simulation().ignore_heap(region);
180       break;
181     }
182
183     case MessageType::UNIGNORE_HEAP: {
184       s_mc_message_ignore_memory_t message;
185       xbt_assert(size == sizeof(message), "Broken message");
186       memcpy(&message, buffer, sizeof(message));
187       get_remote_simulation().unignore_heap((void*)(std::uintptr_t)message.addr, message.size);
188       break;
189     }
190
191     case MessageType::IGNORE_MEMORY: {
192       s_mc_message_ignore_memory_t message;
193       xbt_assert(size == sizeof(message), "Broken message");
194       memcpy(&message, buffer, sizeof(message));
195       this->get_remote_simulation().ignore_region(message.addr, message.size);
196       break;
197     }
198
199     case MessageType::STACK_REGION: {
200       s_mc_message_stack_region_t message;
201       xbt_assert(size == sizeof(message), "Broken message");
202       memcpy(&message, buffer, sizeof(message));
203       this->get_remote_simulation().stack_areas().push_back(message.stack_region);
204     } break;
205
206     case MessageType::REGISTER_SYMBOL: {
207       s_mc_message_register_symbol_t message;
208       xbt_assert(size == sizeof(message), "Broken message");
209       memcpy(&message, buffer, sizeof(message));
210       xbt_assert(not message.callback, "Support for client-side function proposition is not implemented.");
211       XBT_DEBUG("Received symbol: %s", message.name.data());
212
213       if (property_automaton == nullptr)
214         property_automaton = xbt_automaton_new();
215
216       const RemoteSimulation* process = &this->get_remote_simulation();
217       RemotePtr<int> address          = remote((int*)message.data);
218       xbt::add_proposition(property_automaton, message.name.data(),
219                            [process, address]() { return process->read(address); });
220
221       break;
222     }
223
224     case MessageType::WAITING:
225       return false;
226
227     case MessageType::ASSERTION_FAILED:
228       MC_report_assertion_error();
229       this->exit(SIMGRID_MC_EXIT_SAFETY);
230
231     default:
232       xbt_die("Unexpected message from model-checked application");
233   }
234   return true;
235 }
236
237 /** Terminate the model-checker application */
238 void ModelChecker::exit(int status)
239 {
240   // TODO, terminate the model checker politely instead of exiting rudely
241   if (get_remote_simulation().running())
242     kill(get_remote_simulation().pid(), SIGKILL);
243   ::exit(status);
244 }
245
246 void ModelChecker::handle_waitpid()
247 {
248   XBT_DEBUG("Check for wait event");
249   int status;
250   pid_t pid;
251   while ((pid = waitpid(-1, &status, WNOHANG)) != 0) {
252     if (pid == -1) {
253       if (errno == ECHILD) {
254         // No more children:
255         xbt_assert(not this->get_remote_simulation().running(), "Inconsistent state");
256         break;
257       } else {
258         XBT_ERROR("Could not wait for pid");
259         throw simgrid::xbt::errno_error();
260       }
261     }
262
263     if (pid == this->get_remote_simulation().pid()) {
264       // From PTRACE_O_TRACEEXIT:
265 #ifdef __linux__
266       if (status>>8 == (SIGTRAP | (PTRACE_EVENT_EXIT<<8))) {
267         xbt_assert(ptrace(PTRACE_GETEVENTMSG, remote_simulation_->pid(), 0, &status) != -1,
268                    "Could not get exit status");
269         if (WIFSIGNALED(status)) {
270           MC_report_crash(status);
271           mc_model_checker->exit(SIMGRID_MC_EXIT_PROGRAM_CRASH);
272         }
273       }
274 #endif
275
276       // We don't care about signals, just reinject them:
277       if (WIFSTOPPED(status)) {
278         XBT_DEBUG("Stopped with signal %i", (int) WSTOPSIG(status));
279         errno = 0;
280 #ifdef __linux__
281         ptrace(PTRACE_CONT, remote_simulation_->pid(), 0, WSTOPSIG(status));
282 #elif defined BSD
283         ptrace(PT_CONTINUE, remote_simulation_->pid(), (caddr_t)1, WSTOPSIG(status));
284 #endif
285         xbt_assert(errno == 0, "Could not PTRACE_CONT");
286       }
287
288       else if (WIFSIGNALED(status)) {
289         MC_report_crash(status);
290         mc_model_checker->exit(SIMGRID_MC_EXIT_PROGRAM_CRASH);
291       } else if (WIFEXITED(status)) {
292         XBT_DEBUG("Child process is over");
293         this->get_remote_simulation().terminate();
294       }
295     }
296   }
297 }
298
299 void ModelChecker::wait_for_requests()
300 {
301   this->resume(get_remote_simulation());
302   if (this->get_remote_simulation().running())
303     checker_side_.dispatch();
304 }
305
306 void ModelChecker::handle_simcall(Transition const& transition)
307 {
308   s_mc_message_simcall_handle_t m;
309   memset(&m, 0, sizeof(m));
310   m.type  = MessageType::SIMCALL_HANDLE;
311   m.pid   = transition.pid_;
312   m.value = transition.argument_;
313   checker_side_.get_channel().send(m);
314   this->remote_simulation_->clear_cache();
315   if (this->remote_simulation_->running())
316     checker_side_.dispatch();
317 }
318
319 bool ModelChecker::checkDeadlock()
320 {
321   int res = checker_side_.get_channel().send(MessageType::DEADLOCK_CHECK);
322   xbt_assert(res == 0, "Could not check deadlock state");
323   s_mc_message_int_t message;
324   ssize_t s = checker_side_.get_channel().receive(message);
325   xbt_assert(s != -1, "Could not receive message");
326   xbt_assert(s == sizeof(message) && message.type == MessageType::DEADLOCK_CHECK_REPLY,
327              "Received unexpected message %s (%i, size=%i) "
328              "expected MessageType::DEADLOCK_CHECK_REPLY (%i, size=%i)",
329              MC_message_type_name(message.type), (int)message.type, (int)s, (int)MessageType::DEADLOCK_CHECK_REPLY,
330              (int)sizeof(message));
331   return message.value != 0;
332 }
333
334 } // namespace mc
335 } // namespace simgrid