Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
eac05cd7d4f6e56d9110802ea5b3683c22235328
[simgrid.git] / src / mc / ModelChecker.cpp
1 /* Copyright (c) 2008-2022. 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/explo/Exploration.hpp"
8 #include "src/mc/explo/LivenessChecker.hpp"
9 #include "src/mc/mc_config.hpp"
10 #include "src/mc/mc_exit.hpp"
11 #include "src/mc/mc_private.hpp"
12 #include "src/mc/remote/RemoteProcess.hpp"
13 #include "src/mc/transition/TransitionComm.hpp"
14 #include "xbt/automaton.hpp"
15 #include "xbt/system_error.hpp"
16
17 #include <array>
18 #include <csignal>
19 #include <sys/ptrace.h>
20 #include <sys/wait.h>
21
22 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(mc_ModelChecker, mc, "ModelChecker");
23
24 ::simgrid::mc::ModelChecker* mc_model_checker = nullptr;
25
26 #ifdef __linux__
27 # define WAITPID_CHECKED_FLAGS __WALL
28 #else
29 # define WAITPID_CHECKED_FLAGS 0
30 #endif
31
32 namespace simgrid::mc {
33
34 ModelChecker::ModelChecker(std::unique_ptr<RemoteProcess> remote_simulation, int sockfd)
35     : checker_side_(sockfd), remote_process_(std::move(remote_simulation))
36 {
37 }
38
39 void ModelChecker::start()
40 {
41   checker_side_.start(
42       [](evutil_socket_t sig, short events, void* arg) {
43         auto mc = static_cast<simgrid::mc::ModelChecker*>(arg);
44         if (events == EV_READ) {
45           std::array<char, MC_MESSAGE_LENGTH> buffer;
46           ssize_t size = mc->checker_side_.get_channel().receive(buffer.data(), buffer.size(), false);
47           if (size == -1 && errno != EAGAIN)
48             throw simgrid::xbt::errno_error();
49
50           if (not mc->handle_message(buffer.data(), size))
51             mc->checker_side_.break_loop();
52         } else if (events == EV_SIGNAL) {
53           if (sig == SIGCHLD)
54             mc->handle_waitpid();
55         } else {
56           xbt_die("Unexpected event");
57         }
58       },
59       this);
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   xbt_assert(waitpid(pid, &status, WAITPID_CHECKED_FLAGS) == pid && WIFSTOPPED(status) && WSTOPSIG(status) == SIGSTOP,
68              "Could not wait model-checked process");
69
70   if (not _sg_mc_dot_output_file.get().empty()) {
71     dot_output_ = fopen(_sg_mc_dot_output_file.get().c_str(), "w");
72     xbt_assert(dot_output_ != nullptr, "Error open dot output file: %s", strerror(errno));
73
74     fprintf(dot_output_, "digraph graphname{\n fixedsize=true; rankdir=TB; ranksep=.25; edge [fontsize=12]; node "
75                          "[fontsize=10, shape=circle,width=.5 ]; graph [resolution=20, fontsize=10];\n");
76   }
77
78   setup_ignore();
79
80   errno = 0;
81 #ifdef __linux__
82   ptrace(PTRACE_SETOPTIONS, pid, nullptr, PTRACE_O_TRACEEXIT);
83   ptrace(PTRACE_CONT, pid, 0, 0);
84 #elif defined BSD
85   ptrace(PT_CONTINUE, pid, (caddr_t)1, 0);
86 #else
87 # error "no ptrace equivalent coded for this platform"
88 #endif
89   xbt_assert(errno == 0,
90              "Ptrace does not seem to be usable in your setup (errno: %d). "
91              "If you run from within a docker, adding `--cap-add SYS_PTRACE` to the docker line may help. "
92              "If it does not help, please report this bug.",
93              errno);
94 }
95
96 void ModelChecker::dot_output(const char* fmt, ...)
97 {
98   if (dot_output_ != nullptr) {
99     va_list ap;
100     va_start(ap, fmt);
101     vfprintf(dot_output_, fmt, ap);
102     va_end(ap);
103   }
104 }
105
106 static constexpr auto ignored_local_variables = {
107     std::make_pair("e", "*"),
108     std::make_pair("_log_ev", "*"),
109
110     /* Ignore local variable about time used for tracing */
111     std::make_pair("start_time", "*"),
112 };
113
114 void ModelChecker::setup_ignore()
115 {
116   const RemoteProcess& process = this->get_remote_process();
117   for (auto const& [var, frame] : ignored_local_variables)
118     process.ignore_local_variable(var, frame);
119
120   /* Static variable used for tracing */
121   process.ignore_global_variable("counter");
122 }
123
124 void ModelChecker::shutdown()
125 {
126   XBT_DEBUG("Shutting down model-checker");
127
128   RemoteProcess& process = get_remote_process();
129   if (process.running()) {
130     XBT_DEBUG("Killing process");
131     finalize_app(true);
132     kill(process.pid(), SIGKILL);
133     process.terminate();
134   }
135 }
136
137 void ModelChecker::resume()
138 {
139   if (checker_side_.get_channel().send(MessageType::CONTINUE) != 0)
140     throw xbt::errno_error();
141   remote_process_->clear_cache();
142 }
143
144 static void MC_report_crash(Exploration* explorer, int status)
145 {
146   XBT_INFO("**************************");
147   XBT_INFO("** CRASH IN THE PROGRAM **");
148   XBT_INFO("**************************");
149   if (WIFSIGNALED(status))
150     XBT_INFO("From signal: %s", strsignal(WTERMSIG(status)));
151   else if (WIFEXITED(status))
152     XBT_INFO("From exit: %i", WEXITSTATUS(status));
153   if (not xbt_log_no_loc)
154     XBT_INFO("%s core dump was generated by the system.", WCOREDUMP(status) ? "A" : "No");
155   if (explorer) {
156     XBT_INFO("Counter-example execution trace:");
157     for (auto const& s : explorer->get_textual_trace())
158       XBT_INFO("  %s", s.c_str());
159     XBT_INFO("You can debug the problem (and see the whole details) by rerunning out of simgrid-mc with "
160              "--cfg=model-check/replay:'%s'",
161              explorer->get_record_trace().to_string().c_str());
162     explorer->log_state();
163     if (xbt_log_no_loc) {
164       XBT_INFO("Stack trace not displayed because you passed --log=no_loc");
165     } else {
166       XBT_INFO("Stack trace:");
167       mc_model_checker->get_remote_process().dump_stack();
168     }
169   }
170 }
171
172 bool ModelChecker::handle_message(const char* buffer, ssize_t size)
173 {
174   s_mc_message_t base_message;
175   xbt_assert(size >= (ssize_t)sizeof(base_message), "Broken message");
176   memcpy(&base_message, buffer, sizeof(base_message));
177
178   switch(base_message.type) {
179     case MessageType::INITIAL_ADDRESSES: {
180       s_mc_message_initial_addresses_t message;
181       xbt_assert(size == sizeof(message), "Broken message. Got %d bytes instead of %d.", (int)size, (int)sizeof(message));
182       memcpy(&message, buffer, sizeof(message));
183
184       get_remote_process().init(message.mmalloc_default_mdp, message.maxpid);
185       break;
186     }
187
188     case MessageType::IGNORE_HEAP: {
189       s_mc_message_ignore_heap_t message;
190       xbt_assert(size == sizeof(message), "Broken message");
191       memcpy(&message, buffer, sizeof(message));
192
193       IgnoredHeapRegion region;
194       region.block    = message.block;
195       region.fragment = message.fragment;
196       region.address  = message.address;
197       region.size     = message.size;
198       get_remote_process().ignore_heap(region);
199       break;
200     }
201
202     case MessageType::UNIGNORE_HEAP: {
203       s_mc_message_ignore_memory_t message;
204       xbt_assert(size == sizeof(message), "Broken message");
205       memcpy(&message, buffer, sizeof(message));
206       get_remote_process().unignore_heap((void*)(std::uintptr_t)message.addr, message.size);
207       break;
208     }
209
210     case MessageType::IGNORE_MEMORY: {
211       s_mc_message_ignore_memory_t message;
212       xbt_assert(size == sizeof(message), "Broken message");
213       memcpy(&message, buffer, sizeof(message));
214       this->get_remote_process().ignore_region(message.addr, message.size);
215       break;
216     }
217
218     case MessageType::STACK_REGION: {
219       s_mc_message_stack_region_t message;
220       xbt_assert(size == sizeof(message), "Broken message");
221       memcpy(&message, buffer, sizeof(message));
222       this->get_remote_process().stack_areas().push_back(message.stack_region);
223     } break;
224
225     case MessageType::REGISTER_SYMBOL: {
226       s_mc_message_register_symbol_t message;
227       xbt_assert(size == sizeof(message), "Broken message");
228       memcpy(&message, buffer, sizeof(message));
229       xbt_assert(not message.callback, "Support for client-side function proposition is not implemented.");
230       XBT_DEBUG("Received symbol: %s", message.name.data());
231
232       LivenessChecker::automaton_register_symbol(get_remote_process(), message.name.data(), remote((int*)message.data));
233       break;
234     }
235
236     case MessageType::WAITING:
237       return false;
238
239     case MessageType::ASSERTION_FAILED:
240       XBT_INFO("**************************");
241       XBT_INFO("*** PROPERTY NOT VALID ***");
242       XBT_INFO("**************************");
243       XBT_INFO("Counter-example execution trace:");
244       for (auto const& s : get_exploration()->get_textual_trace())
245         XBT_INFO("  %s", s.c_str());
246       XBT_INFO("You can debug the problem (and see the whole details) by rerunning out of simgrid-mc with "
247                "--cfg=model-check/replay:'%s'",
248                get_exploration()->get_record_trace().to_string().c_str());
249       exploration_->log_state();
250
251       this->exit(SIMGRID_MC_EXIT_SAFETY);
252
253     default:
254       xbt_die("Unexpected message from model-checked application");
255   }
256   return true;
257 }
258
259 /** Terminate the model-checker application */
260 void ModelChecker::exit(int status)
261 {
262   shutdown();
263   ::exit(status);
264 }
265
266 void ModelChecker::handle_waitpid()
267 {
268   XBT_DEBUG("Check for wait event");
269   int status;
270   pid_t pid;
271   while ((pid = waitpid(-1, &status, WNOHANG)) != 0) {
272     if (pid == -1) {
273       if (errno == ECHILD) {
274         // No more children:
275         xbt_assert(not this->get_remote_process().running(), "Inconsistent state");
276         break;
277       } else {
278         XBT_ERROR("Could not wait for pid");
279         throw simgrid::xbt::errno_error();
280       }
281     }
282
283     if (pid == this->get_remote_process().pid()) {
284       // From PTRACE_O_TRACEEXIT:
285 #ifdef __linux__
286       if (status>>8 == (SIGTRAP | (PTRACE_EVENT_EXIT<<8))) {
287         xbt_assert(ptrace(PTRACE_GETEVENTMSG, remote_process_->pid(), 0, &status) != -1, "Could not get exit status");
288         if (WIFSIGNALED(status)) {
289           MC_report_crash(exploration_, status);
290           this->get_remote_process().terminate();
291           this->exit(SIMGRID_MC_EXIT_PROGRAM_CRASH);
292         }
293       }
294 #endif
295
296       // We don't care about signals, just reinject them:
297       if (WIFSTOPPED(status)) {
298         XBT_DEBUG("Stopped with signal %i", (int) WSTOPSIG(status));
299         errno = 0;
300 #ifdef __linux__
301         ptrace(PTRACE_CONT, remote_process_->pid(), 0, WSTOPSIG(status));
302 #elif defined BSD
303         ptrace(PT_CONTINUE, remote_process_->pid(), (caddr_t)1, WSTOPSIG(status));
304 #endif
305         xbt_assert(errno == 0, "Could not PTRACE_CONT");
306       }
307
308       else if (WIFSIGNALED(status)) {
309         MC_report_crash(exploration_, status);
310         this->get_remote_process().terminate();
311         this->exit(SIMGRID_MC_EXIT_PROGRAM_CRASH);
312       } else if (WIFEXITED(status)) {
313         XBT_DEBUG("Child process is over");
314         this->get_remote_process().terminate();
315       }
316     }
317   }
318 }
319
320 void ModelChecker::wait_for_requests()
321 {
322   this->resume();
323   if (this->get_remote_process().running())
324     checker_side_.dispatch();
325 }
326
327 Transition* ModelChecker::handle_simcall(aid_t aid, int times_considered, bool new_transition)
328 {
329   s_mc_message_simcall_execute_t m;
330   memset(&m, 0, sizeof(m));
331   m.type              = MessageType::SIMCALL_EXECUTE;
332   m.aid_              = aid;
333   m.times_considered_ = times_considered;
334   checker_side_.get_channel().send(m);
335
336   this->remote_process_->clear_cache();
337   if (this->remote_process_->running())
338     checker_side_.dispatch(); // The app may send messages while processing the transition
339
340   s_mc_message_simcall_execute_answer_t answer;
341   ssize_t s = checker_side_.get_channel().receive(answer);
342   xbt_assert(s != -1, "Could not receive message");
343   xbt_assert(s == sizeof(answer) && answer.type == MessageType::SIMCALL_EXECUTE_ANSWER,
344              "Received unexpected message %s (%i, size=%i) "
345              "expected MessageType::SIMCALL_EXECUTE_ANSWER (%i, size=%i)",
346              to_c_str(answer.type), (int)answer.type, (int)s, (int)MessageType::SIMCALL_EXECUTE_ANSWER,
347              (int)sizeof(answer));
348
349   if (new_transition) {
350     std::stringstream stream(answer.buffer.data());
351     return deserialize_transition(aid, times_considered, stream);
352   } else
353     return nullptr;
354 }
355
356 void ModelChecker::finalize_app(bool terminate_asap)
357 {
358   s_mc_message_int_t m;
359   memset(&m, 0, sizeof m);
360   m.type  = MessageType::FINALIZE;
361   m.value = terminate_asap;
362   xbt_assert(checker_side_.get_channel().send(m) == 0, "Could not ask the app to finalize on need");
363
364   s_mc_message_t answer;
365   ssize_t s = checker_side_.get_channel().receive(answer);
366   xbt_assert(s != -1, "Could not receive answer to FINALIZE");
367   xbt_assert(s == sizeof(answer) && answer.type == MessageType::FINALIZE_REPLY,
368              "Received unexpected message %s (%i, size=%i) expected MessageType::FINALIZE_REPLY (%i, size=%i)",
369              to_c_str(answer.type), (int)answer.type, (int)s, (int)MessageType::FINALIZE_REPLY, (int)sizeof(answer));
370 }
371
372 } // namespace simgrid::mc