Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
fe9c2650c4dfffddd68f7ec6a2854c1c32d1caa7
[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()
123 {
124   if (base_ != nullptr)
125     event_base_free(base_.get());
126   auto* base = event_base_new();
127   base_.reset(base);
128
129   socket_event_ = event_new(
130       base, get_channel().get_socket(), EV_READ | EV_PERSIST,
131       [](evutil_socket_t, short events, void* arg) {
132         auto checker = static_cast<simgrid::mc::CheckerSide*>(arg);
133         if (events == EV_READ) {
134           std::array<char, MC_MESSAGE_LENGTH> buffer;
135           ssize_t size = recv(checker->get_channel().get_socket(), 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         } else {
147           xbt_die("Unexpected event");
148         }
149       },
150       this);
151   event_add(socket_event_, nullptr);
152
153   signal_event_ = event_new(
154       base, SIGCHLD, EV_SIGNAL | EV_PERSIST,
155       [](evutil_socket_t sig, short events, void* arg) {
156         auto checker = static_cast<simgrid::mc::CheckerSide*>(arg);
157         if (events == EV_SIGNAL) {
158           if (sig == SIGCHLD)
159             checker->handle_waitpid();
160           else
161             xbt_die("Unexpected signal: %d", sig);
162         } else {
163           xbt_die("Unexpected event");
164         }
165       },
166       this);
167   event_add(signal_event_, nullptr);
168 }
169
170 CheckerSide::CheckerSide(const std::vector<char*>& args, bool need_memory_info) : running_(true)
171 {
172   bool need_ptrace = not need_memory_info;
173
174   // Create an AF_LOCAL socketpair used for exchanging messages between the model-checker process (ancestor)
175   // and the application process (child)
176   int sockets[2];
177   xbt_assert(socketpair(AF_LOCAL, SOCK_SEQPACKET | SOCK_CLOEXEC, 0, sockets) != -1, "Could not create socketpair");
178
179   pid_ = fork();
180   xbt_assert(pid_ >= 0, "Could not fork model-checked process");
181
182   if (pid_ == 0) { // Child
183     ::close(sockets[1]);
184     run_child_process(sockets[0], args, need_ptrace);
185     DIE_IMPOSSIBLE;
186   }
187
188   // Parent (model-checker):
189   ::close(sockets[0]);
190   channel_.reset_socket(sockets[1]);
191
192   setup_events();
193   if (need_ptrace)
194     wait_application_process(pid_);
195
196   // Request the initial memory on need
197   if (need_memory_info) {
198     channel_.send(MessageType::INITIAL_ADDRESSES);
199     s_mc_message_initial_addresses_reply_t answer;
200     ssize_t answer_size = channel_.receive(answer);
201     xbt_assert(answer_size != -1, "Could not receive message");
202     xbt_assert(answer.type == MessageType::INITIAL_ADDRESSES_REPLY,
203                "The received message is not the INITIAL_ADDRESS_REPLY I was expecting but of type %s",
204                to_c_str(answer.type));
205     xbt_assert(answer_size == sizeof answer, "Broken message (size=%zd; expected %zu)", answer_size, sizeof answer);
206
207     /* We now have enough info to create the memory address space */
208     remote_memory_ = std::make_unique<simgrid::mc::RemoteProcessMemory>(pid_, answer.mmalloc_default_mdp);
209   }
210
211   wait_for_requests();
212 }
213
214 CheckerSide::~CheckerSide()
215 {
216   event_del(socket_event_);
217   event_free(socket_event_);
218   event_del(signal_event_);
219   event_free(signal_event_);
220
221   if (running()) {
222     errno = 0;
223     xbt_assert(kill(get_pid(), SIGKILL) == 0);
224     errno = 0;
225     waitpid(get_pid(), nullptr, 0);
226     xbt_assert(errno == 0);
227   }
228 }
229
230 void CheckerSide::finalize(bool terminate_asap)
231 {
232   s_mc_message_int_t m = {};
233   m.type               = MessageType::FINALIZE;
234   m.value              = terminate_asap;
235   xbt_assert(get_channel().send(m) == 0, "Could not ask the app to finalize on need");
236
237   s_mc_message_t answer;
238   ssize_t s = get_channel().receive(answer);
239   xbt_assert(s != -1, "Could not receive answer to FINALIZE");
240   xbt_assert(s == sizeof answer, "Broken message (size=%zd; expected %zu)", s, sizeof answer);
241   xbt_assert(answer.type == MessageType::FINALIZE_REPLY,
242              "Received unexpected message %s (%i); expected MessageType::FINALIZE_REPLY (%i)", to_c_str(answer.type),
243              (int)answer.type, (int)MessageType::FINALIZE_REPLY);
244 }
245
246 void CheckerSide::dispatch_events() const
247 {
248   event_base_dispatch(base_.get());
249 }
250
251 void CheckerSide::break_loop() const
252 {
253   event_base_loopbreak(base_.get());
254 }
255
256 bool CheckerSide::handle_message(const char* buffer, ssize_t size)
257 {
258   s_mc_message_t base_message;
259   xbt_assert(size >= (ssize_t)sizeof(base_message), "Broken message. Got only %ld bytes.", size);
260   memcpy(&base_message, buffer, sizeof(base_message));
261
262   switch (base_message.type) {
263     case MessageType::IGNORE_HEAP: {
264       if (remote_memory_ != nullptr) {
265         s_mc_message_ignore_heap_t message;
266         xbt_assert(size == sizeof(message), "Broken message");
267         memcpy(&message, buffer, sizeof(message));
268
269         IgnoredHeapRegion region;
270         region.block    = message.block;
271         region.fragment = message.fragment;
272         region.address  = message.address;
273         region.size     = message.size;
274         get_remote_memory()->ignore_heap(region);
275       } else {
276         XBT_INFO("Ignoring a IGNORE_HEAP message because we don't need to introspect memory.");
277       }
278       break;
279     }
280
281     case MessageType::UNIGNORE_HEAP: {
282       if (remote_memory_ != nullptr) {
283         s_mc_message_ignore_memory_t message;
284         xbt_assert(size == sizeof(message), "Broken message");
285         memcpy(&message, buffer, sizeof(message));
286         get_remote_memory()->unignore_heap((void*)message.addr, message.size);
287       } else {
288         XBT_INFO("Ignoring an UNIGNORE_HEAP message because we don't need to introspect memory.");
289       }
290       break;
291     }
292
293     case MessageType::IGNORE_MEMORY: {
294       if (remote_memory_ != nullptr) {
295         s_mc_message_ignore_memory_t message;
296         xbt_assert(size == sizeof(message), "Broken message");
297         memcpy(&message, buffer, sizeof(message));
298         get_remote_memory()->ignore_region(message.addr, message.size);
299       } else {
300         XBT_INFO("Ignoring an IGNORE_MEMORY message because we don't need to introspect memory.");
301       }
302       break;
303     }
304
305     case MessageType::STACK_REGION: {
306       if (remote_memory_ != nullptr) {
307         s_mc_message_stack_region_t message;
308         xbt_assert(size == sizeof(message), "Broken message");
309         memcpy(&message, buffer, sizeof(message));
310         get_remote_memory()->stack_areas().push_back(message.stack_region);
311       } else {
312         XBT_INFO("Ignoring an STACK_REGION message because we don't need to introspect memory.");
313       }
314       break;
315     }
316
317     case MessageType::REGISTER_SYMBOL: {
318       s_mc_message_register_symbol_t message;
319       xbt_assert(size == sizeof(message), "Broken message");
320       memcpy(&message, buffer, sizeof(message));
321       xbt_assert(not message.callback, "Support for client-side function proposition is not implemented.");
322       XBT_DEBUG("Received symbol: %s", message.name.data());
323
324       LivenessChecker::automaton_register_symbol(*get_remote_memory(), message.name.data(), remote((int*)message.data));
325       break;
326     }
327
328     case MessageType::WAITING:
329       return false;
330
331     case MessageType::ASSERTION_FAILED:
332       Exploration::get_instance()->report_assertion_failure();
333       break;
334
335     default:
336       xbt_die("Unexpected message from model-checked application");
337   }
338   return true;
339 }
340
341 void CheckerSide::wait_for_requests()
342 {
343   /* Resume the application */
344   if (get_channel().send(MessageType::CONTINUE) != 0)
345     throw xbt::errno_error();
346   clear_memory_cache();
347
348   if (running())
349     dispatch_events();
350 }
351
352 void CheckerSide::clear_memory_cache()
353 {
354   if (remote_memory_)
355     remote_memory_->clear_cache();
356 }
357
358 void CheckerSide::handle_waitpid()
359 {
360   XBT_DEBUG("Check for wait event");
361   int status;
362   pid_t pid;
363   while ((pid = waitpid(-1, &status, WNOHANG)) != 0) {
364     if (pid == -1) {
365       if (errno == ECHILD) { // No more children:
366         xbt_assert(not this->running(), "Inconsistent state");
367         break;
368       } else {
369         xbt_die("Could not wait for pid: %s", strerror(errno));
370       }
371     }
372
373     if (pid == get_pid()) {
374       // From PTRACE_O_TRACEEXIT:
375 #ifdef __linux__
376       if (status >> 8 == (SIGTRAP | (PTRACE_EVENT_EXIT << 8))) {
377         unsigned long eventmsg;
378         xbt_assert(ptrace(PTRACE_GETEVENTMSG, pid, 0, &eventmsg) != -1, "Could not get exit status");
379         status = static_cast<int>(eventmsg);
380         if (WIFSIGNALED(status)) {
381           this->terminate();
382           Exploration::get_instance()->report_crash(status);
383         }
384       }
385 #endif
386
387       // We don't care about non-lethal signals, just reinject them:
388       if (WIFSTOPPED(status)) {
389         XBT_DEBUG("Stopped with signal %i", (int)WSTOPSIG(status));
390         errno = 0;
391 #ifdef __linux__
392         ptrace(PTRACE_CONT, pid, 0, WSTOPSIG(status));
393 #elif defined BSD
394         ptrace(PT_CONTINUE, pid, (caddr_t)1, WSTOPSIG(status));
395 #endif
396         xbt_assert(errno == 0, "Could not PTRACE_CONT");
397       }
398
399       else if (WIFSIGNALED(status)) {
400         this->terminate();
401         Exploration::get_instance()->report_crash(status);
402       } else if (WIFEXITED(status)) {
403         XBT_DEBUG("Child process is over");
404         this->terminate();
405       }
406     }
407   }
408 }
409
410 } // namespace simgrid::mc