Logo AND Algorithmique Numérique Distribuée

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