Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Merge branch 'master' of https://framagit.org/simgrid/simgrid
[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)
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
67   /* Setup the tokenizer that parses the cfg:model-check/setenv parameter */
68   using Tokenizer = boost::tokenizer<boost::char_separator<char>>;
69   boost::char_separator<char> semicol_sep(";");
70   boost::char_separator<char> equal_sep("=");
71   Tokenizer token_vars(_sg_mc_setenv.get(), semicol_sep); /* Iterate over all FOO=foo parts */
72   for (const auto& token : token_vars) {
73     std::vector<std::string> kv;
74     Tokenizer token_kv(token, equal_sep);
75     for (const auto& t : token_kv) /* Iterate over 'FOO' and then 'foo' in that 'FOO=foo' */
76       kv.push_back(t);
77     xbt_assert(kv.size() == 2, "Parse error on 'model-check/setenv' value %s. Does it contain an equal sign?",
78                token.c_str());
79     XBT_INFO("setenv '%s'='%s'", kv[0].c_str(), kv[1].c_str());
80     setenv(kv[0].c_str(), kv[1].c_str(), 1);
81   }
82
83   /* And now, exec the child process */
84   int i = 1;
85   while (args[i] != nullptr && args[i][0] == '-')
86     i++;
87
88   xbt_assert(args[i] != nullptr,
89              "Unable to find a binary to exec on the command line. Did you only pass config flags?");
90
91   execvp(args[i], args.data() + i);
92   XBT_CRITICAL("The model-checked process failed to exec(%s): %s.\n"
93                "        Make sure that your binary exists on disk and is executable.",
94                args[i], strerror(errno));
95   if (strchr(args[i], '=') != nullptr)
96     XBT_CRITICAL("If you want to pass environment variables to the application, please use --cfg=model-check/setenv:%s",
97                  args[i]);
98
99   xbt_die("Aborting now.");
100 }
101
102 static void wait_application_process(pid_t pid)
103 {
104   XBT_DEBUG("Waiting for the model-checked process");
105   int status;
106
107   // The model-checked process SIGSTOP itself to signal it's ready:
108   xbt_assert(waitpid(pid, &status, WAITPID_CHECKED_FLAGS) == pid && WIFSTOPPED(status) && WSTOPSIG(status) == SIGSTOP,
109              "Could not wait model-checked process");
110
111   errno = 0;
112 #ifdef __linux__
113   ptrace(PTRACE_SETOPTIONS, pid, nullptr, PTRACE_O_TRACEEXIT);
114   ptrace(PTRACE_CONT, pid, 0, 0);
115 #elif defined BSD
116   ptrace(PT_CONTINUE, pid, (caddr_t)1, 0);
117 #else
118 #error "no ptrace equivalent coded for this platform"
119 #endif
120   xbt_assert(errno == 0,
121              "Ptrace does not seem to be usable in your setup (errno: %d). "
122              "If you run from within a docker, adding `--cap-add SYS_PTRACE` to the docker line may help. "
123              "If it does not help, please report this bug.",
124              errno);
125 }
126
127 void CheckerSide::setup_events()
128 {
129   auto* base = event_base_new();
130   base_.reset(base);
131
132   auto* socket_event = event_new(
133       base, get_channel().get_socket(), EV_READ | EV_PERSIST,
134       [](evutil_socket_t sig, short events, void* arg) {
135         auto checker = static_cast<simgrid::mc::CheckerSide*>(arg);
136         if (events == EV_READ) {
137           std::array<char, MC_MESSAGE_LENGTH> buffer;
138           ssize_t size = recv(checker->get_channel().get_socket(), buffer.data(), buffer.size(), MSG_DONTWAIT);
139           if (size == -1) {
140             XBT_ERROR("Channel::receive failure: %s", strerror(errno));
141             if (errno != EAGAIN)
142               throw simgrid::xbt::errno_error();
143           }
144
145           if (not checker->handle_message(buffer.data(), size))
146             checker->break_loop();
147         } else {
148           xbt_die("Unexpected event");
149         }
150       },
151       this);
152   event_add(socket_event, nullptr);
153   socket_event_.reset(socket_event);
154
155   auto* signal_event = event_new(
156       base, SIGCHLD, EV_SIGNAL | EV_PERSIST,
157       [](evutil_socket_t sig, short events, void* arg) {
158         auto checker = static_cast<simgrid::mc::CheckerSide*>(arg);
159         if (events == EV_SIGNAL) {
160           if (sig == SIGCHLD)
161             checker->handle_waitpid();
162           else
163             xbt_die("Unexpected signal: %d", sig);
164         } else {
165           xbt_die("Unexpected event");
166         }
167       },
168       this);
169   event_add(signal_event, nullptr);
170   signal_event_.reset(signal_event);
171 }
172
173 CheckerSide::CheckerSide(const std::vector<char*>& args) : 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");
179
180   pid_ = fork();
181   xbt_assert(pid_ >= 0, "Could not fork model-checked process");
182
183   if (pid_ == 0) { // Child
184     ::close(sockets[1]);
185     run_child_process(sockets[0], args);
186     DIE_IMPOSSIBLE;
187   }
188
189   // Parent (model-checker):
190   ::close(sockets[0]);
191   channel_.reset_socket(sockets[1]);
192
193   setup_events();
194   wait_application_process(pid_);
195
196   wait_for_requests();
197 }
198
199 void CheckerSide::dispatch_events() const
200 {
201   event_base_dispatch(base_.get());
202 }
203
204 void CheckerSide::break_loop() const
205 {
206   event_base_loopbreak(base_.get());
207 }
208
209 bool CheckerSide::handle_message(const char* buffer, ssize_t size)
210 {
211   s_mc_message_t base_message;
212   xbt_assert(size >= (ssize_t)sizeof(base_message), "Broken message");
213   memcpy(&base_message, buffer, sizeof(base_message));
214
215   switch (base_message.type) {
216     case MessageType::INITIAL_ADDRESSES: {
217       s_mc_message_initial_addresses_t message;
218       xbt_assert(size == sizeof(message), "Broken message. Got %d bytes instead of %d.", (int)size,
219                  (int)sizeof(message));
220       memcpy(&message, buffer, sizeof(message));
221       /* Create the memory address space, now that we have the mandatory information */
222       remote_memory_ = std::make_unique<simgrid::mc::RemoteProcessMemory>(pid_, message.mmalloc_default_mdp);
223       break;
224     }
225
226     case MessageType::IGNORE_HEAP: {
227       s_mc_message_ignore_heap_t message;
228       xbt_assert(size == sizeof(message), "Broken message");
229       memcpy(&message, buffer, sizeof(message));
230
231       IgnoredHeapRegion region;
232       region.block    = message.block;
233       region.fragment = message.fragment;
234       region.address  = message.address;
235       region.size     = message.size;
236       get_remote_memory().ignore_heap(region);
237       break;
238     }
239
240     case MessageType::UNIGNORE_HEAP: {
241       s_mc_message_ignore_memory_t message;
242       xbt_assert(size == sizeof(message), "Broken message");
243       memcpy(&message, buffer, sizeof(message));
244       get_remote_memory().unignore_heap((void*)(std::uintptr_t)message.addr, message.size);
245       break;
246     }
247
248     case MessageType::IGNORE_MEMORY: {
249       s_mc_message_ignore_memory_t message;
250       xbt_assert(size == sizeof(message), "Broken message");
251       memcpy(&message, buffer, sizeof(message));
252       get_remote_memory().ignore_region(message.addr, message.size);
253       break;
254     }
255
256     case MessageType::STACK_REGION: {
257       s_mc_message_stack_region_t message;
258       xbt_assert(size == sizeof(message), "Broken message");
259       memcpy(&message, buffer, sizeof(message));
260       get_remote_memory().stack_areas().push_back(message.stack_region);
261     } break;
262
263     case MessageType::REGISTER_SYMBOL: {
264       s_mc_message_register_symbol_t message;
265       xbt_assert(size == sizeof(message), "Broken message");
266       memcpy(&message, buffer, sizeof(message));
267       xbt_assert(not message.callback, "Support for client-side function proposition is not implemented.");
268       XBT_DEBUG("Received symbol: %s", message.name.data());
269
270       LivenessChecker::automaton_register_symbol(get_remote_memory(), message.name.data(), remote((int*)message.data));
271       break;
272     }
273
274     case MessageType::WAITING:
275       return false;
276
277     case MessageType::ASSERTION_FAILED:
278       Exploration::get_instance()->report_assertion_failure();
279       break;
280
281     default:
282       xbt_die("Unexpected message from model-checked application");
283   }
284   return true;
285 }
286
287 void CheckerSide::wait_for_requests()
288 {
289   /* Resume the application */
290   if (get_channel().send(MessageType::CONTINUE) != 0)
291     throw xbt::errno_error();
292   clear_memory_cache();
293
294   if (running())
295     dispatch_events();
296 }
297
298 void CheckerSide::clear_memory_cache()
299 {
300   if (remote_memory_)
301     remote_memory_->clear_cache();
302 }
303
304 void CheckerSide::handle_waitpid()
305 {
306   XBT_DEBUG("Check for wait event");
307   int status;
308   pid_t pid;
309   while ((pid = waitpid(-1, &status, WNOHANG)) != 0) {
310     if (pid == -1) {
311       if (errno == ECHILD) { // No more children:
312         xbt_assert(not this->running(), "Inconsistent state");
313         break;
314       } else {
315         XBT_ERROR("Could not wait for pid");
316         throw simgrid::xbt::errno_error();
317       }
318     }
319
320     if (pid == get_pid()) {
321       // From PTRACE_O_TRACEEXIT:
322 #ifdef __linux__
323       if (status >> 8 == (SIGTRAP | (PTRACE_EVENT_EXIT << 8))) {
324         unsigned long eventmsg;
325         xbt_assert(ptrace(PTRACE_GETEVENTMSG, pid, 0, &eventmsg) != -1, "Could not get exit status");
326         status = static_cast<int>(eventmsg);
327         if (WIFSIGNALED(status)) {
328           this->terminate();
329           Exploration::get_instance()->report_crash(status);
330         }
331       }
332 #endif
333
334       // We don't care about non-lethal signals, just reinject them:
335       if (WIFSTOPPED(status)) {
336         XBT_DEBUG("Stopped with signal %i", (int)WSTOPSIG(status));
337         errno = 0;
338 #ifdef __linux__
339         ptrace(PTRACE_CONT, pid, 0, WSTOPSIG(status));
340 #elif defined BSD
341         ptrace(PT_CONTINUE, pid, (caddr_t)1, WSTOPSIG(status));
342 #endif
343         xbt_assert(errno == 0, "Could not PTRACE_CONT");
344       }
345
346       else if (WIFSIGNALED(status)) {
347         this->terminate();
348         Exploration::get_instance()->report_crash(status);
349       } else if (WIFEXITED(status)) {
350         XBT_DEBUG("Child process is over");
351         this->terminate();
352       }
353     }
354   }
355 }
356
357 } // namespace simgrid::mc