Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
fix MC + gcc builds
[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 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   setup_ignore();
71
72   errno = 0;
73 #ifdef __linux__
74   ptrace(PTRACE_SETOPTIONS, pid, nullptr, PTRACE_O_TRACEEXIT);
75   ptrace(PTRACE_CONT, pid, 0, 0);
76 #elif defined BSD
77   ptrace(PT_CONTINUE, pid, (caddr_t)1, 0);
78 #else
79 # error "no ptrace equivalent coded for this platform"
80 #endif
81   xbt_assert(errno == 0,
82              "Ptrace does not seem to be usable in your setup (errno: %d). "
83              "If you run from within a docker, adding `--cap-add SYS_PTRACE` to the docker line may help. "
84              "If it does not help, please report this bug.",
85              errno);
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, frame] : ignored_local_variables)
100     process.ignore_local_variable(var, frame);
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 = get_remote_process();
111   if (process.running()) {
112     XBT_DEBUG("Killing process");
113     finalize_app(true);
114     kill(process.pid(), SIGKILL);
115     process.terminate();
116   }
117 }
118
119 void ModelChecker::resume()
120 {
121   if (checker_side_.get_channel().send(MessageType::CONTINUE) != 0)
122     throw xbt::errno_error();
123   remote_process_->clear_cache();
124 }
125
126 static void MC_report_crash(Exploration* explorer, 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   if (explorer) {
138     XBT_INFO("Counter-example execution trace:");
139     for (auto const& s : explorer->get_textual_trace())
140       XBT_INFO("  %s", s.c_str());
141     XBT_INFO("You can debug the problem (and see the whole details) by rerunning out of simgrid-mc with "
142              "--cfg=model-check/replay:'%s'",
143              explorer->get_record_trace().to_string().c_str());
144     explorer->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);
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       LivenessChecker::automaton_register_symbol(get_remote_process(), message.name.data(), remote((int*)message.data));
215       break;
216     }
217
218     case MessageType::WAITING:
219       return false;
220
221     case MessageType::ASSERTION_FAILED:
222       XBT_INFO("**************************");
223       XBT_INFO("*** PROPERTY NOT VALID ***");
224       XBT_INFO("**************************");
225       XBT_INFO("Counter-example execution trace:");
226       for (auto const& s : get_exploration()->get_textual_trace())
227         XBT_INFO("  %s", s.c_str());
228       XBT_INFO("You can debug the problem (and see the whole details) by rerunning out of simgrid-mc with "
229                "--cfg=model-check/replay:'%s'",
230                get_exploration()->get_record_trace().to_string().c_str());
231       exploration_->log_state();
232
233       this->exit(SIMGRID_MC_EXIT_SAFETY);
234
235     default:
236       xbt_die("Unexpected message from model-checked application");
237   }
238   return true;
239 }
240
241 /** Terminate the model-checker application */
242 void ModelChecker::exit(int status)
243 {
244   shutdown();
245   ::exit(status);
246 }
247
248 void ModelChecker::handle_waitpid()
249 {
250   XBT_DEBUG("Check for wait event");
251   int status;
252   pid_t pid;
253   while ((pid = waitpid(-1, &status, WNOHANG)) != 0) {
254     if (pid == -1) {
255       if (errno == ECHILD) {
256         // No more children:
257         xbt_assert(not this->get_remote_process().running(), "Inconsistent state");
258         break;
259       } else {
260         XBT_ERROR("Could not wait for pid");
261         throw simgrid::xbt::errno_error();
262       }
263     }
264
265     if (pid == this->get_remote_process().pid()) {
266       // From PTRACE_O_TRACEEXIT:
267 #ifdef __linux__
268       if (status>>8 == (SIGTRAP | (PTRACE_EVENT_EXIT<<8))) {
269         unsigned long eventmsg;
270         xbt_assert(ptrace(PTRACE_GETEVENTMSG, remote_process_->pid(), 0, &eventmsg) != -1, "Could not get exit status");
271         status = static_cast<int>(eventmsg);
272         if (WIFSIGNALED(status)) {
273           MC_report_crash(exploration_, status);
274           this->get_remote_process().terminate();
275           this->exit(SIMGRID_MC_EXIT_PROGRAM_CRASH);
276         }
277       }
278 #endif
279
280       // We don't care about signals, just reinject them:
281       if (WIFSTOPPED(status)) {
282         XBT_DEBUG("Stopped with signal %i", (int) WSTOPSIG(status));
283         errno = 0;
284 #ifdef __linux__
285         ptrace(PTRACE_CONT, remote_process_->pid(), 0, WSTOPSIG(status));
286 #elif defined BSD
287         ptrace(PT_CONTINUE, remote_process_->pid(), (caddr_t)1, WSTOPSIG(status));
288 #endif
289         xbt_assert(errno == 0, "Could not PTRACE_CONT");
290       }
291
292       else if (WIFSIGNALED(status)) {
293         MC_report_crash(exploration_, status);
294         this->get_remote_process().terminate();
295         this->exit(SIMGRID_MC_EXIT_PROGRAM_CRASH);
296       } else if (WIFEXITED(status)) {
297         XBT_DEBUG("Child process is over");
298         this->get_remote_process().terminate();
299       }
300     }
301   }
302 }
303
304 void ModelChecker::wait_for_requests()
305 {
306   this->resume();
307   if (this->get_remote_process().running())
308     checker_side_.dispatch();
309 }
310
311 Transition* ModelChecker::handle_simcall(aid_t aid, int times_considered, bool new_transition)
312 {
313   s_mc_message_simcall_execute_t m = {};
314   m.type              = MessageType::SIMCALL_EXECUTE;
315   m.aid_              = aid;
316   m.times_considered_ = times_considered;
317   checker_side_.get_channel().send(m);
318
319   this->remote_process_->clear_cache();
320   if (this->remote_process_->running())
321     checker_side_.dispatch(); // The app may send messages while processing the transition
322
323   s_mc_message_simcall_execute_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_EXECUTE_ANSWER,
327              "Received unexpected message %s (%i, size=%i) "
328              "expected MessageType::SIMCALL_EXECUTE_ANSWER (%i, size=%i)",
329              to_c_str(answer.type), (int)answer.type, (int)s, (int)MessageType::SIMCALL_EXECUTE_ANSWER,
330              (int)sizeof(answer));
331
332   if (new_transition) {
333     std::stringstream stream(answer.buffer.data());
334     return deserialize_transition(aid, times_considered, stream);
335   } else
336     return nullptr;
337 }
338
339 void ModelChecker::finalize_app(bool terminate_asap)
340 {
341   s_mc_message_int_t m = {};
342   m.type  = MessageType::FINALIZE;
343   m.value = terminate_asap;
344   xbt_assert(checker_side_.get_channel().send(m) == 0, "Could not ask the app to finalize on need");
345
346   s_mc_message_t answer;
347   ssize_t s = checker_side_.get_channel().receive(answer);
348   xbt_assert(s != -1, "Could not receive answer to FINALIZE");
349   xbt_assert(s == sizeof(answer) && answer.type == MessageType::FINALIZE_REPLY,
350              "Received unexpected message %s (%i, size=%i) expected MessageType::FINALIZE_REPLY (%i, size=%i)",
351              to_c_str(answer.type), (int)answer.type, (int)s, (int)MessageType::FINALIZE_REPLY, (int)sizeof(answer));
352 }
353
354 } // namespace simgrid::mc