Logo AND Algorithmique Numérique Distribuée

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