Logo AND Algorithmique Numérique Distribuée

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