Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
MC: stop reading maxpid in memory, but ask it over the network instead
[simgrid.git] / src / mc / ModelChecker.cpp
1 /* Copyright (c) 2008-2023. 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 signal: %d", sig);
57         } else {
58           xbt_die("Unexpected event");
59         }
60       },
61       this);
62
63   XBT_DEBUG("Waiting for the model-checked process");
64   int status;
65
66   // The model-checked process SIGSTOP itself to signal it's ready:
67   const pid_t pid = remote_process_->pid();
68
69   xbt_assert(waitpid(pid, &status, WAITPID_CHECKED_FLAGS) == pid && WIFSTOPPED(status) && WSTOPSIG(status) == SIGSTOP,
70              "Could not wait model-checked process");
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(Exploration* explorer, 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 (explorer) {
140     XBT_INFO("Counter-example execution trace:");
141     for (auto const& s : explorer->get_textual_trace())
142       XBT_INFO("  %s", s.c_str());
143     XBT_INFO("You can debug the problem (and see the whole details) by rerunning out of simgrid-mc with "
144              "--cfg=model-check/replay:'%s'",
145              explorer->get_record_trace().to_string().c_str());
146     explorer->log_state();
147     if (xbt_log_no_loc) {
148       XBT_INFO("Stack trace not displayed because you passed --log=no_loc");
149     } else {
150       XBT_INFO("Stack trace:");
151       explorer->get_remote_app().get_remote_process().dump_stack();
152     }
153   }
154 }
155
156 bool ModelChecker::handle_message(const char* buffer, ssize_t size)
157 {
158   s_mc_message_t base_message;
159   xbt_assert(size >= (ssize_t)sizeof(base_message), "Broken message");
160   memcpy(&base_message, buffer, sizeof(base_message));
161
162   switch(base_message.type) {
163     case MessageType::INITIAL_ADDRESSES: {
164       s_mc_message_initial_addresses_t message;
165       xbt_assert(size == sizeof(message), "Broken message. Got %d bytes instead of %d.", (int)size, (int)sizeof(message));
166       memcpy(&message, buffer, sizeof(message));
167
168       get_remote_process().init(message.mmalloc_default_mdp);
169       break;
170     }
171
172     case MessageType::IGNORE_HEAP: {
173       s_mc_message_ignore_heap_t message;
174       xbt_assert(size == sizeof(message), "Broken message");
175       memcpy(&message, buffer, sizeof(message));
176
177       IgnoredHeapRegion region;
178       region.block    = message.block;
179       region.fragment = message.fragment;
180       region.address  = message.address;
181       region.size     = message.size;
182       get_remote_process().ignore_heap(region);
183       break;
184     }
185
186     case MessageType::UNIGNORE_HEAP: {
187       s_mc_message_ignore_memory_t message;
188       xbt_assert(size == sizeof(message), "Broken message");
189       memcpy(&message, buffer, sizeof(message));
190       get_remote_process().unignore_heap((void*)(std::uintptr_t)message.addr, message.size);
191       break;
192     }
193
194     case MessageType::IGNORE_MEMORY: {
195       s_mc_message_ignore_memory_t message;
196       xbt_assert(size == sizeof(message), "Broken message");
197       memcpy(&message, buffer, sizeof(message));
198       this->get_remote_process().ignore_region(message.addr, message.size);
199       break;
200     }
201
202     case MessageType::STACK_REGION: {
203       s_mc_message_stack_region_t message;
204       xbt_assert(size == sizeof(message), "Broken message");
205       memcpy(&message, buffer, sizeof(message));
206       this->get_remote_process().stack_areas().push_back(message.stack_region);
207     } break;
208
209     case MessageType::REGISTER_SYMBOL: {
210       s_mc_message_register_symbol_t message;
211       xbt_assert(size == sizeof(message), "Broken message");
212       memcpy(&message, buffer, sizeof(message));
213       xbt_assert(not message.callback, "Support for client-side function proposition is not implemented.");
214       XBT_DEBUG("Received symbol: %s", message.name.data());
215
216       LivenessChecker::automaton_register_symbol(get_remote_process(), message.name.data(), remote((int*)message.data));
217       break;
218     }
219
220     case MessageType::WAITING:
221       return false;
222
223     case MessageType::ASSERTION_FAILED:
224       XBT_INFO("**************************");
225       XBT_INFO("*** PROPERTY NOT VALID ***");
226       XBT_INFO("**************************");
227       XBT_INFO("Counter-example execution trace:");
228       for (auto const& s : get_exploration()->get_textual_trace())
229         XBT_INFO("  %s", s.c_str());
230       XBT_INFO("You can debug the problem (and see the whole details) by rerunning out of simgrid-mc with "
231                "--cfg=model-check/replay:'%s'",
232                get_exploration()->get_record_trace().to_string().c_str());
233       exploration_->log_state();
234
235       this->exit(SIMGRID_MC_EXIT_SAFETY);
236
237     default:
238       xbt_die("Unexpected message from model-checked application");
239   }
240   return true;
241 }
242
243 /** Terminate the model-checker application */
244 void ModelChecker::exit(int status)
245 {
246   shutdown();
247   ::exit(status);
248 }
249
250 void ModelChecker::handle_waitpid()
251 {
252   XBT_DEBUG("Check for wait event");
253   int status;
254   pid_t pid;
255   while ((pid = waitpid(-1, &status, WNOHANG)) != 0) {
256     if (pid == -1) {
257       if (errno == ECHILD) {
258         // No more children:
259         xbt_assert(not this->get_remote_process().running(), "Inconsistent state");
260         break;
261       } else {
262         XBT_ERROR("Could not wait for pid");
263         throw simgrid::xbt::errno_error();
264       }
265     }
266
267     if (pid == this->get_remote_process().pid()) {
268       // From PTRACE_O_TRACEEXIT:
269 #ifdef __linux__
270       if (status>>8 == (SIGTRAP | (PTRACE_EVENT_EXIT<<8))) {
271         unsigned long eventmsg;
272         xbt_assert(ptrace(PTRACE_GETEVENTMSG, remote_process_->pid(), 0, &eventmsg) != -1, "Could not get exit status");
273         status = static_cast<int>(eventmsg);
274         if (WIFSIGNALED(status)) {
275           MC_report_crash(exploration_, status);
276           this->get_remote_process().terminate();
277           this->exit(SIMGRID_MC_EXIT_PROGRAM_CRASH);
278         }
279       }
280 #endif
281
282       // We don't care about signals, just reinject them:
283       if (WIFSTOPPED(status)) {
284         XBT_DEBUG("Stopped with signal %i", (int) WSTOPSIG(status));
285         errno = 0;
286 #ifdef __linux__
287         ptrace(PTRACE_CONT, remote_process_->pid(), 0, WSTOPSIG(status));
288 #elif defined BSD
289         ptrace(PT_CONTINUE, remote_process_->pid(), (caddr_t)1, WSTOPSIG(status));
290 #endif
291         xbt_assert(errno == 0, "Could not PTRACE_CONT");
292       }
293
294       else if (WIFSIGNALED(status)) {
295         MC_report_crash(exploration_, status);
296         this->get_remote_process().terminate();
297         this->exit(SIMGRID_MC_EXIT_PROGRAM_CRASH);
298       } else if (WIFEXITED(status)) {
299         XBT_DEBUG("Child process is over");
300         this->get_remote_process().terminate();
301       }
302     }
303   }
304 }
305
306 void ModelChecker::wait_for_requests()
307 {
308   this->resume();
309   if (this->get_remote_process().running())
310     checker_side_.dispatch();
311 }
312
313 Transition* ModelChecker::handle_simcall(aid_t aid, int times_considered, bool new_transition)
314 {
315   s_mc_message_simcall_execute_t m = {};
316   m.type              = MessageType::SIMCALL_EXECUTE;
317   m.aid_              = aid;
318   m.times_considered_ = times_considered;
319   checker_side_.get_channel().send(m);
320
321   this->remote_process_->clear_cache();
322   if (this->remote_process_->running())
323     checker_side_.dispatch(); // The app may send messages while processing the transition
324
325   s_mc_message_simcall_execute_answer_t answer;
326   ssize_t s = checker_side_.get_channel().receive(answer);
327   xbt_assert(s != -1, "Could not receive message");
328   xbt_assert(s == sizeof answer, "Broken message (size=%zd; expected %zu)", s, sizeof answer);
329   xbt_assert(answer.type == MessageType::SIMCALL_EXECUTE_ANSWER,
330              "Received unexpected message %s (%i); expected MessageType::SIMCALL_EXECUTE_ANSWER (%i)",
331              to_c_str(answer.type), (int)answer.type, (int)MessageType::SIMCALL_EXECUTE_ANSWER);
332
333   if (new_transition) {
334     std::stringstream stream(answer.buffer.data());
335     return deserialize_transition(aid, times_considered, stream);
336   } else
337     return nullptr;
338 }
339
340 void ModelChecker::finalize_app(bool terminate_asap)
341 {
342   s_mc_message_int_t m = {};
343   m.type  = MessageType::FINALIZE;
344   m.value = terminate_asap;
345   xbt_assert(checker_side_.get_channel().send(m) == 0, "Could not ask the app to finalize on need");
346
347   s_mc_message_t answer;
348   ssize_t s = checker_side_.get_channel().receive(answer);
349   xbt_assert(s != -1, "Could not receive answer to FINALIZE");
350   xbt_assert(s == sizeof answer, "Broken message (size=%zd; expected %zu)", s, sizeof answer);
351   xbt_assert(answer.type == MessageType::FINALIZE_REPLY,
352              "Received unexpected message %s (%i); expected MessageType::FINALIZE_REPLY (%i)", to_c_str(answer.type),
353              (int)answer.type, (int)MessageType::FINALIZE_REPLY);
354 }
355
356 } // namespace simgrid::mc