Logo AND Algorithmique Numérique Distribuée

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