Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
211995b856f07d1ff1b986543493ea72d9001c9d
[simgrid.git] / src / mc / remote / CheckerSide.cpp
1 /* Copyright (c) 2007-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/remote/CheckerSide.hpp"
7 #include "src/mc/explo/Exploration.hpp"
8 #include "src/mc/mc_environ.h"
9 #include "xbt/config.hpp"
10 #include "xbt/system_error.hpp"
11
12 #if SIMGRID_HAVE_STATEFUL_MC
13 #include "src/mc/explo/LivenessChecker.hpp"
14 #include "src/mc/sosp/RemoteProcessMemory.hpp"
15 #endif
16
17 #ifdef __linux__
18 #include <sys/prctl.h>
19 #endif
20
21 #include <boost/tokenizer.hpp>
22 #include <csignal>
23 #include <fcntl.h>
24 #include <sys/ptrace.h>
25 #include <sys/wait.h>
26
27 #ifdef __linux__
28 #define WAITPID_CHECKED_FLAGS __WALL
29 #else
30 #define WAITPID_CHECKED_FLAGS 0
31 #endif
32
33 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(mc_checkerside, mc, "MC communication with the application");
34
35 static simgrid::config::Flag<std::string> _sg_mc_setenv{
36     "model-check/setenv", "Extra environment variables to pass to the child process (ex: 'AZE=aze;QWE=qwe').", "",
37     [](std::string_view value) {
38       xbt_assert(value.empty() || value.find('=', 0) != std::string_view::npos,
39                  "The 'model-check/setenv' parameter must be like 'AZE=aze', but it does not contain an equal sign.");
40     }};
41
42 namespace simgrid::mc {
43
44 XBT_ATTRIB_NORETURN static void run_child_process(int socket, const std::vector<char*>& args, bool need_ptrace)
45 {
46   /* On startup, simix_global_init() calls simgrid::mc::Client::initialize(), which checks whether the MC_ENV_SOCKET_FD
47    * env variable is set. If so, MC mode is assumed, and the client is setup from its side
48    */
49
50 #ifdef __linux__
51   // Make sure we do not outlive our parent
52   sigset_t mask;
53   sigemptyset(&mask);
54   xbt_assert(sigprocmask(SIG_SETMASK, &mask, nullptr) >= 0, "Could not unblock signals");
55   xbt_assert(prctl(PR_SET_PDEATHSIG, SIGHUP) == 0, "Could not PR_SET_PDEATHSIG");
56 #endif
57
58   setenv(MC_ENV_SOCKET_FD, std::to_string(socket).c_str(), 1);
59   if (need_ptrace)
60     setenv(MC_ENV_NEED_PTRACE, "1", 1);
61
62   /* Setup the tokenizer that parses the cfg:model-check/setenv parameter */
63   using Tokenizer = boost::tokenizer<boost::char_separator<char>>;
64   boost::char_separator<char> semicol_sep(";");
65   boost::char_separator<char> equal_sep("=");
66   Tokenizer token_vars(_sg_mc_setenv.get(), semicol_sep); /* Iterate over all FOO=foo parts */
67   for (const auto& token : token_vars) {
68     std::vector<std::string> kv;
69     Tokenizer token_kv(token, equal_sep);
70     for (const auto& t : token_kv) /* Iterate over 'FOO' and then 'foo' in that 'FOO=foo' */
71       kv.push_back(t);
72     xbt_assert(kv.size() == 2, "Parse error on 'model-check/setenv' value %s. Does it contain an equal sign?",
73                token.c_str());
74     XBT_INFO("setenv '%s'='%s'", kv[0].c_str(), kv[1].c_str());
75     setenv(kv[0].c_str(), kv[1].c_str(), 1);
76   }
77
78   /* And now, exec the child process */
79   int i = 1;
80   while (args[i] != nullptr && args[i][0] == '-')
81     i++;
82
83   xbt_assert(args[i] != nullptr,
84              "Unable to find a binary to exec on the command line. Did you only pass config flags?");
85
86   execvp(args[i], args.data() + i);
87   XBT_CRITICAL("The model-checked process failed to exec(%s): %s.\n"
88                "        Make sure that your binary exists on disk and is executable.",
89                args[i], strerror(errno));
90   if (strchr(args[i], '=') != nullptr)
91     XBT_CRITICAL("If you want to pass environment variables to the application, please use --cfg=model-check/setenv:%s",
92                  args[i]);
93
94   xbt_die("Aborting now.");
95 }
96
97 static void wait_application_process(pid_t pid)
98 {
99   XBT_DEBUG("Waiting for the model-checked process");
100   int status;
101
102   // The model-checked process SIGSTOP itself to signal it's ready:
103   xbt_assert(waitpid(pid, &status, WAITPID_CHECKED_FLAGS) == pid && WIFSTOPPED(status) && WSTOPSIG(status) == SIGSTOP,
104              "Could not wait model-checked process");
105
106   errno = 0;
107 #ifdef __linux__
108   ptrace(PTRACE_SETOPTIONS, pid, nullptr, PTRACE_O_TRACEEXIT);
109   ptrace(PTRACE_CONT, pid, 0, 0);
110 #elif defined BSD
111   ptrace(PT_CONTINUE, pid, (caddr_t)1, 0);
112 #else
113   xbt_die("no ptrace equivalent coded for this platform, stateful model-checking is impossible.");
114 #endif
115   xbt_assert(errno == 0,
116              "Ptrace does not seem to be usable in your setup (errno: %d). "
117              "If you run from within a docker, adding `--cap-add SYS_PTRACE` to the docker line may help. "
118              "If it does not help, please report this bug.",
119              errno);
120   XBT_DEBUG("%d ptrace correctly setup.", getpid());
121 }
122
123 void CheckerSide::setup_events(bool socket_only)
124 {
125   auto* base = event_base_new();
126   base_.reset(base);
127
128   socket_event_ = event_new(
129       base, get_channel().get_socket(), EV_READ | EV_PERSIST,
130       [](evutil_socket_t, short events, void* arg) {
131         auto checker = static_cast<simgrid::mc::CheckerSide*>(arg);
132         if (events == EV_READ) {
133           do {
134             std::array<char, MC_MESSAGE_LENGTH> buffer;
135             ssize_t size = checker->get_channel().receive(buffer.data(), buffer.size(), MSG_DONTWAIT);
136             if (size == -1) {
137               XBT_ERROR("Channel::receive failure: %s", strerror(errno));
138               if (errno != EAGAIN)
139                 throw simgrid::xbt::errno_error();
140             }
141
142             if (size == 0) // The app closed the socket. It must be dead by now.
143               checker->handle_waitpid();
144             else if (not checker->handle_message(buffer.data(), size)) {
145               checker->break_loop();
146               break;
147             }
148           } while (checker->get_channel().has_pending_data());
149         } else {
150           xbt_die("Unexpected event");
151         }
152       },
153       this);
154   event_add(socket_event_, nullptr);
155
156   if (socket_only) {
157     signal_event_ = nullptr;
158   } else {
159     signal_event_ = event_new(
160         base, SIGCHLD, EV_SIGNAL | EV_PERSIST,
161         [](evutil_socket_t sig, short events, void* arg) {
162           auto checker = static_cast<simgrid::mc::CheckerSide*>(arg);
163           if (events == EV_SIGNAL) {
164             if (sig == SIGCHLD)
165               checker->handle_waitpid();
166             else
167               xbt_die("Unexpected signal: %d", sig);
168           } else {
169             xbt_die("Unexpected event");
170           }
171         },
172         this);
173     event_add(signal_event_, nullptr);
174   }
175 }
176
177 /* When this constructor is called, no other checkerside exists */
178 CheckerSide::CheckerSide(const std::vector<char*>& args, bool need_memory_info) : running_(true)
179 {
180   XBT_DEBUG("Create a CheckerSide. Needs_meminfo: %s", need_memory_info ? "YES" : "no");
181
182   // Create an AF_UNIX socketpair used for exchanging messages between the model-checker process (ancestor)
183   // and the application process (child)
184   int sockets[2];
185   xbt_assert(socketpair(AF_UNIX,
186 #ifdef __APPLE__
187                         SOCK_STREAM, /* Mac OSX does not have AF_UNIX + SOCK_SEQPACKET, even if that's faster */
188 #else
189                         SOCK_SEQPACKET,
190 #endif
191                         0, sockets) != -1,
192              "Could not create socketpair: %s", strerror(errno));
193
194   pid_ = fork();
195   xbt_assert(pid_ >= 0, "Could not fork application process");
196
197   if (pid_ == 0) { // Child
198     ::close(sockets[1]);
199     run_child_process(sockets[0], args, need_memory_info); // We need ptrace if we need the mem info
200     DIE_IMPOSSIBLE;
201   }
202
203   // Parent (model-checker):
204   ::close(sockets[0]);
205   channel_.reset_socket(sockets[1]);
206
207   setup_events(false); /* we need a signal handler too */
208   if (need_memory_info) {
209 #if SIMGRID_HAVE_STATEFUL_MC
210     // setup ptrace and sync with the app
211     wait_application_process(pid_);
212
213     // Request the initial memory on need
214     channel_.send(MessageType::NEED_MEMINFO);
215     s_mc_message_need_meminfo_reply_t answer;
216     ssize_t answer_size = channel_.receive(answer);
217     xbt_assert(answer_size != -1, "Could not receive message");
218     xbt_assert(answer.type == MessageType::NEED_MEMINFO_REPLY,
219                "The received message is not the NEED_MEMINFO_REPLY I was expecting but of type %s",
220                to_c_str(answer.type));
221     xbt_assert(answer_size == sizeof answer, "Broken message (size=%zd; expected %zu)", answer_size, sizeof answer);
222
223     /* We now have enough info to create the memory address space */
224     remote_memory_ = std::make_unique<simgrid::mc::RemoteProcessMemory>(pid_, answer.mmalloc_default_mdp);
225 #else
226     xbt_die("Cannot introspect memory without MC support");
227 #endif
228   }
229
230   wait_for_requests();
231 }
232
233 CheckerSide::~CheckerSide()
234 {
235   event_del(socket_event_);
236   event_free(socket_event_);
237   if (signal_event_ != nullptr) {
238     event_del(signal_event_);
239     event_free(signal_event_);
240   }
241 }
242
243 /* This constructor is called when cloning a checkerside to get its application to fork away */
244 CheckerSide::CheckerSide(int socket, CheckerSide* child_checker)
245     : channel_(socket, child_checker->channel_), running_(true), child_checker_(child_checker)
246 {
247   setup_events(true); // We already have a signal handled in that case
248
249   s_mc_message_int_t answer;
250   ssize_t s = get_channel().receive(answer);
251   xbt_assert(s != -1, "Could not receive answer to FORK_REPLY");
252   xbt_assert(s == sizeof answer, "Broken message (size=%zd; expected %zu)", s, sizeof answer);
253   xbt_assert(answer.type == MessageType::FORK_REPLY,
254              "Received unexpected message %s (%i); expected MessageType::FORK_REPLY (%i)", to_c_str(answer.type),
255              (int)answer.type, (int)MessageType::FORK_REPLY);
256   pid_ = answer.value;
257
258   wait_for_requests();
259 }
260
261 std::unique_ptr<CheckerSide> CheckerSide::clone(int master_socket, const std::string& master_socket_name)
262 {
263   s_mc_message_fork_t m = {};
264   m.type                = MessageType::FORK;
265   xbt_assert(master_socket_name.size() == MC_SOCKET_NAME_LEN);
266   std::copy_n(begin(master_socket_name), MC_SOCKET_NAME_LEN, begin(m.socket_name));
267   xbt_assert(get_channel().send(m) == 0, "Could not ask the app to fork on need.");
268
269   int sock = accept(master_socket, nullptr /* I know who's connecting*/, nullptr);
270   xbt_assert(sock > 0, "Cannot accept the incomming connection of the forked app: %s.", strerror(errno));
271
272   return std::make_unique<CheckerSide>(sock, this);
273 }
274
275 void CheckerSide::finalize(bool terminate_asap)
276 {
277   s_mc_message_int_t m = {};
278   m.type               = MessageType::FINALIZE;
279   m.value              = terminate_asap;
280   xbt_assert(get_channel().send(m) == 0, "Could not ask the app to finalize on need");
281
282   s_mc_message_t answer;
283   ssize_t s = get_channel().receive(answer);
284   xbt_assert(s != -1, "Could not receive answer to FINALIZE");
285   xbt_assert(s == sizeof answer, "Broken message (size=%zd; expected %zu)", s, sizeof answer);
286   xbt_assert(answer.type == MessageType::FINALIZE_REPLY,
287              "Received unexpected message %s (%i); expected MessageType::FINALIZE_REPLY (%i)", to_c_str(answer.type),
288              (int)answer.type, (int)MessageType::FINALIZE_REPLY);
289 }
290
291 void CheckerSide::dispatch_events() const
292 {
293   event_base_dispatch(base_.get());
294 }
295
296 void CheckerSide::break_loop() const
297 {
298   event_base_loopbreak(base_.get());
299 }
300
301 bool CheckerSide::handle_message(const char* buffer, ssize_t size)
302 {
303   s_mc_message_t base_message;
304   ssize_t consumed;
305   xbt_assert(size >= (ssize_t)sizeof(base_message), "Broken message. Got only %ld bytes.", size);
306   memcpy(&base_message, buffer, sizeof(base_message));
307
308   switch (base_message.type) {
309     case MessageType::IGNORE_HEAP: {
310       consumed = sizeof(s_mc_message_ignore_heap_t);
311 #if SIMGRID_HAVE_STATEFUL_MC
312       if (remote_memory_ != nullptr) {
313         s_mc_message_ignore_heap_t message;
314         xbt_assert(size >= static_cast<ssize_t>(sizeof(message)), "Broken message");
315         memcpy(&message, buffer, sizeof(message));
316
317         IgnoredHeapRegion region;
318         region.block    = message.block;
319         region.fragment = message.fragment;
320         region.address  = message.address;
321         region.size     = message.size;
322         get_remote_memory()->ignore_heap(region);
323       } else
324 #endif
325         XBT_INFO("Ignoring a IGNORE_HEAP message because we don't need to introspect memory.");
326       break;
327     }
328
329     case MessageType::UNIGNORE_HEAP: {
330       consumed = sizeof(s_mc_message_ignore_memory_t);
331 #if SIMGRID_HAVE_STATEFUL_MC
332       if (remote_memory_ != nullptr) {
333         s_mc_message_ignore_memory_t message;
334         xbt_assert(size == static_cast<ssize_t>(sizeof(message)), "Broken message");
335         memcpy(&message, buffer, sizeof(message));
336         get_remote_memory()->unignore_heap((void*)message.addr, message.size);
337       } else
338 #endif
339         XBT_INFO("Ignoring an UNIGNORE_HEAP message because we don't need to introspect memory.");
340       break;
341     }
342
343     case MessageType::IGNORE_MEMORY: {
344       consumed = sizeof(s_mc_message_ignore_memory_t);
345 #if SIMGRID_HAVE_STATEFUL_MC
346       if (remote_memory_ != nullptr) {
347         s_mc_message_ignore_memory_t message;
348         xbt_assert(size >= static_cast<ssize_t>(sizeof(message)), "Broken message");
349         memcpy(&message, buffer, sizeof(message));
350         get_remote_memory()->ignore_region(message.addr, message.size);
351       } else
352 #endif
353         XBT_INFO("Ignoring an IGNORE_MEMORY message because we don't need to introspect memory.");
354       break;
355     }
356
357     case MessageType::STACK_REGION: {
358       consumed = sizeof(s_mc_message_stack_region_t);
359 #if SIMGRID_HAVE_STATEFUL_MC
360       if (remote_memory_ != nullptr) {
361         s_mc_message_stack_region_t message;
362         xbt_assert(size >= static_cast<ssize_t>(sizeof(message)), "Broken message");
363         memcpy(&message, buffer, sizeof(message));
364         get_remote_memory()->stack_areas().push_back(message.stack_region);
365       } else
366 #endif
367         XBT_INFO("Ignoring an STACK_REGION message because we don't need to introspect memory.");
368       break;
369     }
370
371     case MessageType::REGISTER_SYMBOL: {
372       consumed = sizeof(s_mc_message_register_symbol_t);
373 #if SIMGRID_HAVE_STATEFUL_MC
374       s_mc_message_register_symbol_t message;
375       xbt_assert(size >= static_cast<ssize_t>(sizeof(message)), "Broken message");
376       memcpy(&message, buffer, sizeof(message));
377       xbt_assert(not message.callback, "Support for client-side function proposition is not implemented.");
378       XBT_DEBUG("Received symbol: %s", message.name.data());
379
380       LivenessChecker::automaton_register_symbol(*get_remote_memory(), message.name.data(), remote((int*)message.data));
381 #else
382       xbt_die("Please don't use liveness properties when MC is compiled out.");
383 #endif
384       break;
385     }
386
387     case MessageType::WAITING:
388       consumed = sizeof(s_mc_message_t);
389       if (size > consumed) {
390         XBT_DEBUG("%d reinject %d bytes after a %s message", getpid(), (int)(size - consumed),
391                   to_c_str(base_message.type));
392         channel_.reinject(&buffer[consumed], size - consumed);
393       }
394
395       return false;
396
397     case MessageType::ASSERTION_FAILED:
398       // report_assertion_failure() is NORETURN, but it may change when we report more than one error per run,
399       // so please keep the consumed computation even if clang-static detects it as a dead affectation.
400       consumed = sizeof(s_mc_message_t);
401       Exploration::get_instance()->report_assertion_failure();
402       break;
403
404     default:
405       xbt_die("Unexpected message from the application");
406   }
407   if (size > consumed) {
408     XBT_DEBUG("%d reinject %d bytes after a %s message", getpid(), (int)(size - consumed), to_c_str(base_message.type));
409     channel_.reinject(&buffer[consumed], size - consumed);
410   }
411   return true;
412 }
413
414 void CheckerSide::wait_for_requests()
415 {
416   XBT_DEBUG("Resume the application");
417   if (get_channel().send(MessageType::CONTINUE) != 0)
418     throw xbt::errno_error();
419   clear_memory_cache();
420
421   if (running())
422     dispatch_events();
423 }
424
425 void CheckerSide::clear_memory_cache()
426 {
427 #if SIMGRID_HAVE_STATEFUL_MC
428   if (remote_memory_)
429     remote_memory_->clear_cache();
430 #endif
431 }
432
433 void CheckerSide::handle_dead_child(int status)
434 {
435   // From PTRACE_O_TRACEEXIT:
436 #ifdef __linux__
437   if (status >> 8 == (SIGTRAP | (PTRACE_EVENT_EXIT << 8))) {
438     unsigned long eventmsg;
439     xbt_assert(ptrace(PTRACE_GETEVENTMSG, pid_, 0, &eventmsg) != -1, "Could not get exit status");
440     status = static_cast<int>(eventmsg);
441     if (WIFSIGNALED(status)) {
442       this->terminate();
443       Exploration::get_instance()->report_crash(status);
444     }
445   }
446 #endif
447
448   // We don't care about non-lethal signals, just reinject them:
449   if (WIFSTOPPED(status)) {
450     XBT_DEBUG("Stopped with signal %i", (int)WSTOPSIG(status));
451     errno = 0;
452 #ifdef __linux__
453     ptrace(PTRACE_CONT, pid_, 0, WSTOPSIG(status));
454 #elif defined BSD
455     ptrace(PT_CONTINUE, pid_, (caddr_t)1, WSTOPSIG(status));
456 #endif
457     xbt_assert(errno == 0, "Could not PTRACE_CONT: %s", strerror(errno));
458   }
459
460   else if (WIFSIGNALED(status)) {
461     this->terminate();
462     Exploration::get_instance()->report_crash(status);
463   } else if (WIFEXITED(status)) {
464     XBT_DEBUG("Child process is over");
465     this->terminate();
466   }
467 }
468
469 void CheckerSide::handle_waitpid()
470 {
471   XBT_DEBUG("%d checks for wait event. %s", getpid(),
472             child_checker_ == nullptr ? "Wait directly." : "Ask our proxy to wait for its child.");
473
474   if (child_checker_ == nullptr) { // Wait directly
475     int status;
476     pid_t pid;
477     while ((pid = waitpid(-1, &status, WNOHANG)) != 0) {
478       if (pid == -1) {
479         if (errno == ECHILD) { // No more children:
480           xbt_assert(not this->running(), "Inconsistent state");
481           break;
482         } else {
483           xbt_die("Could not wait for pid: %s", strerror(errno));
484         }
485       }
486
487       if (pid == get_pid())
488         handle_dead_child(status);
489     }
490
491   } else { // Ask our proxy to wait for us
492     s_mc_message_int_t request = {};
493     request.type               = MessageType::WAIT_CHILD;
494     request.value              = pid_;
495     xbt_assert(child_checker_->get_channel().send(request) == 0,
496                "Could not ask my child to waitpid its child for me: %s", strerror(errno));
497
498     s_mc_message_int_t answer;
499     ssize_t answer_size = child_checker_->get_channel().receive(answer);
500     xbt_assert(answer_size != -1, "Could not receive message");
501     xbt_assert(answer.type == MessageType::WAIT_CHILD_REPLY,
502                "The received message is not the WAIT_CHILD_REPLY I was expecting but of type %s",
503                to_c_str(answer.type));
504     xbt_assert(answer_size == sizeof answer, "Broken message (size=%zd; expected %zu)", answer_size, sizeof answer);
505     handle_dead_child(answer.value);
506   }
507 }
508 } // namespace simgrid::mc