Logo AND Algorithmique Numérique Distribuée

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