Logo AND Algorithmique Numérique Distribuée

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