1 /* Copyright (c) 2007-2023. The SimGrid Team. All rights reserved. */
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. */
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"
11 #if SIMGRID_HAVE_STATEFUL_MC
12 #include "src/mc/explo/LivenessChecker.hpp"
13 #include "src/mc/sosp/RemoteProcessMemory.hpp"
17 #include <sys/prctl.h>
20 #include <boost/tokenizer.hpp>
23 #include <sys/ptrace.h>
27 #define WAITPID_CHECKED_FLAGS __WALL
29 #define WAITPID_CHECKED_FLAGS 0
32 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(mc_checkerside, mc, "MC communication with the application");
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.");
41 namespace simgrid::mc {
43 XBT_ATTRIB_NORETURN static void run_child_process(int socket, const std::vector<char*>& args, bool need_ptrace)
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
50 // Make sure we do not outlive our parent
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");
57 setenv(MC_ENV_SOCKET_FD, std::to_string(socket).c_str(), 1);
59 setenv("MC_NEED_PTRACE", "1", 1);
61 /* Setup the tokenizer that parses the cfg:model-check/setenv parameter */
62 using Tokenizer = boost::tokenizer<boost::char_separator<char>>;
63 boost::char_separator<char> semicol_sep(";");
64 boost::char_separator<char> equal_sep("=");
65 Tokenizer token_vars(_sg_mc_setenv.get(), semicol_sep); /* Iterate over all FOO=foo parts */
66 for (const auto& token : token_vars) {
67 std::vector<std::string> kv;
68 Tokenizer token_kv(token, equal_sep);
69 for (const auto& t : token_kv) /* Iterate over 'FOO' and then 'foo' in that 'FOO=foo' */
71 xbt_assert(kv.size() == 2, "Parse error on 'model-check/setenv' value %s. Does it contain an equal sign?",
73 XBT_INFO("setenv '%s'='%s'", kv[0].c_str(), kv[1].c_str());
74 setenv(kv[0].c_str(), kv[1].c_str(), 1);
77 /* And now, exec the child process */
79 while (args[i] != nullptr && args[i][0] == '-')
82 xbt_assert(args[i] != nullptr,
83 "Unable to find a binary to exec on the command line. Did you only pass config flags?");
85 execvp(args[i], args.data() + i);
86 XBT_CRITICAL("The model-checked process failed to exec(%s): %s.\n"
87 " Make sure that your binary exists on disk and is executable.",
88 args[i], strerror(errno));
89 if (strchr(args[i], '=') != nullptr)
90 XBT_CRITICAL("If you want to pass environment variables to the application, please use --cfg=model-check/setenv:%s",
93 xbt_die("Aborting now.");
96 static void wait_application_process(pid_t pid)
98 XBT_DEBUG("Waiting for the model-checked process");
101 // The model-checked process SIGSTOP itself to signal it's ready:
102 xbt_assert(waitpid(pid, &status, WAITPID_CHECKED_FLAGS) == pid && WIFSTOPPED(status) && WSTOPSIG(status) == SIGSTOP,
103 "Could not wait model-checked process");
107 ptrace(PTRACE_SETOPTIONS, pid, nullptr, PTRACE_O_TRACEEXIT);
108 ptrace(PTRACE_CONT, pid, 0, 0);
110 ptrace(PT_CONTINUE, pid, (caddr_t)1, 0);
112 xbt_die("no ptrace equivalent coded for this platform, stateful model-checking is impossible.");
114 xbt_assert(errno == 0,
115 "Ptrace does not seem to be usable in your setup (errno: %d). "
116 "If you run from within a docker, adding `--cap-add SYS_PTRACE` to the docker line may help. "
117 "If it does not help, please report this bug.",
121 void CheckerSide::setup_events(bool socket_only)
123 auto* base = event_base_new();
126 socket_event_ = event_new(
127 base, get_channel().get_socket(), EV_READ | EV_PERSIST,
128 [](evutil_socket_t, short events, void* arg) {
129 auto checker = static_cast<simgrid::mc::CheckerSide*>(arg);
130 if (events == EV_READ) {
131 std::array<char, MC_MESSAGE_LENGTH> buffer;
132 ssize_t size = recv(checker->get_channel().get_socket(), buffer.data(), buffer.size(), MSG_DONTWAIT);
134 XBT_ERROR("Channel::receive failure: %s", strerror(errno));
136 throw simgrid::xbt::errno_error();
139 if (size == 0) // The app closed the socket. It must be dead by now.
140 checker->handle_waitpid();
141 else if (not checker->handle_message(buffer.data(), size))
142 checker->break_loop();
144 xbt_die("Unexpected event");
148 event_add(socket_event_, nullptr);
151 signal_event_ = nullptr;
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) {
159 checker->handle_waitpid();
161 xbt_die("Unexpected signal: %d", sig);
163 xbt_die("Unexpected event");
167 event_add(signal_event_, nullptr);
171 /* When this constructor is called, no other checkerside exists */
172 CheckerSide::CheckerSide(const std::vector<char*>& args, bool need_memory_info) : running_(true)
174 XBT_DEBUG("Create a CheckerSide. Needs_meminfo: %s", need_memory_info ? "YES" : "no");
176 // Create an AF_LOCAL socketpair used for exchanging messages between the model-checker process (ancestor)
177 // and the application process (child)
179 xbt_assert(socketpair(AF_LOCAL, SOCK_SEQPACKET, 0, sockets) != -1, "Could not create socketpair: %s",
183 xbt_assert(pid_ >= 0, "Could not fork application process");
185 if (pid_ == 0) { // Child
187 run_child_process(sockets[0], args, need_memory_info); // We need ptrace if we need the mem info
191 // Parent (model-checker):
193 channel_.reset_socket(sockets[1]);
195 setup_events(false); /* we need a signal handler too */
196 if (need_memory_info) {
197 #if SIMGRID_HAVE_STATEFUL_MC
198 // setup ptrace and sync with the app
199 wait_application_process(pid_);
201 // Request the initial memory on need
202 channel_.send(MessageType::NEED_MEMINFO);
203 s_mc_message_need_meminfo_reply_t answer;
204 ssize_t answer_size = channel_.receive(answer);
205 xbt_assert(answer_size != -1, "Could not receive message");
206 xbt_assert(answer.type == MessageType::NEED_MEMINFO_REPLY,
207 "The received message is not the NEED_MEMINFO_REPLY I was expecting but of type %s",
208 to_c_str(answer.type));
209 xbt_assert(answer_size == sizeof answer, "Broken message (size=%zd; expected %zu)", answer_size, sizeof answer);
211 /* We now have enough info to create the memory address space */
212 remote_memory_ = std::make_unique<simgrid::mc::RemoteProcessMemory>(pid_, answer.mmalloc_default_mdp);
214 xbt_die("Cannot introspect memory without MC support");
221 CheckerSide::~CheckerSide()
223 event_del(socket_event_);
224 event_free(socket_event_);
225 if (signal_event_ != nullptr) {
226 event_del(signal_event_);
227 event_free(signal_event_);
231 /* This constructor is called when cloning a checkerside to get its application to fork away */
232 CheckerSide::CheckerSide(int socket, CheckerSide* child_checker)
233 : channel_(socket), running_(true), child_checker_(child_checker)
235 setup_events(true); // We already have a signal handled in that case
237 s_mc_message_int_t answer;
238 ssize_t s = get_channel().receive(answer);
239 xbt_assert(s != -1, "Could not receive answer to FORK_REPLY");
240 xbt_assert(s == sizeof answer, "Broken message (size=%zd; expected %zu)", s, sizeof answer);
241 xbt_assert(answer.type == MessageType::FORK_REPLY,
242 "Received unexpected message %s (%i); expected MessageType::FORK_REPLY (%i)", to_c_str(answer.type),
243 (int)answer.type, (int)MessageType::FORK_REPLY);
249 std::unique_ptr<CheckerSide> CheckerSide::clone(int master_socket)
251 s_mc_message_int_t m = {};
252 m.type = MessageType::FORK;
254 xbt_assert(get_channel().send(m) == 0, "Could not ask the app to fork on need.");
256 int sock = accept(master_socket, nullptr /* I know who's connecting*/, nullptr);
257 xbt_assert(sock > 0, "Cannot accept the incomming connection of the forked app: %s.", strerror(errno));
259 return std::make_unique<CheckerSide>(sock, this);
262 void CheckerSide::finalize(bool terminate_asap)
264 s_mc_message_int_t m = {};
265 m.type = MessageType::FINALIZE;
266 m.value = terminate_asap;
267 xbt_assert(get_channel().send(m) == 0, "Could not ask the app to finalize on need");
269 s_mc_message_t answer;
270 ssize_t s = get_channel().receive(answer);
271 xbt_assert(s != -1, "Could not receive answer to FINALIZE");
272 xbt_assert(s == sizeof answer, "Broken message (size=%zd; expected %zu)", s, sizeof answer);
273 xbt_assert(answer.type == MessageType::FINALIZE_REPLY,
274 "Received unexpected message %s (%i); expected MessageType::FINALIZE_REPLY (%i)", to_c_str(answer.type),
275 (int)answer.type, (int)MessageType::FINALIZE_REPLY);
278 void CheckerSide::dispatch_events() const
280 event_base_dispatch(base_.get());
283 void CheckerSide::break_loop() const
285 event_base_loopbreak(base_.get());
288 bool CheckerSide::handle_message(const char* buffer, ssize_t size)
290 s_mc_message_t base_message;
291 xbt_assert(size >= (ssize_t)sizeof(base_message), "Broken message. Got only %ld bytes.", size);
292 memcpy(&base_message, buffer, sizeof(base_message));
294 switch (base_message.type) {
295 case MessageType::IGNORE_HEAP: {
296 #if SIMGRID_HAVE_STATEFUL_MC
297 if (remote_memory_ != nullptr) {
298 s_mc_message_ignore_heap_t message;
299 xbt_assert(size == sizeof(message), "Broken message");
300 memcpy(&message, buffer, sizeof(message));
302 IgnoredHeapRegion region;
303 region.block = message.block;
304 region.fragment = message.fragment;
305 region.address = message.address;
306 region.size = message.size;
307 get_remote_memory()->ignore_heap(region);
310 XBT_INFO("Ignoring a IGNORE_HEAP message because we don't need to introspect memory.");
314 case MessageType::UNIGNORE_HEAP: {
315 #if SIMGRID_HAVE_STATEFUL_MC
316 if (remote_memory_ != nullptr) {
317 s_mc_message_ignore_memory_t message;
318 xbt_assert(size == sizeof(message), "Broken message");
319 memcpy(&message, buffer, sizeof(message));
320 get_remote_memory()->unignore_heap((void*)message.addr, message.size);
323 XBT_INFO("Ignoring an UNIGNORE_HEAP message because we don't need to introspect memory.");
327 case MessageType::IGNORE_MEMORY: {
328 #if SIMGRID_HAVE_STATEFUL_MC
329 if (remote_memory_ != nullptr) {
330 s_mc_message_ignore_memory_t message;
331 xbt_assert(size == sizeof(message), "Broken message");
332 memcpy(&message, buffer, sizeof(message));
333 get_remote_memory()->ignore_region(message.addr, message.size);
336 XBT_INFO("Ignoring an IGNORE_MEMORY message because we don't need to introspect memory.");
340 case MessageType::STACK_REGION: {
341 #if SIMGRID_HAVE_STATEFUL_MC
342 if (remote_memory_ != nullptr) {
343 s_mc_message_stack_region_t message;
344 xbt_assert(size == sizeof(message), "Broken message");
345 memcpy(&message, buffer, sizeof(message));
346 get_remote_memory()->stack_areas().push_back(message.stack_region);
349 XBT_INFO("Ignoring an STACK_REGION message because we don't need to introspect memory.");
353 case MessageType::REGISTER_SYMBOL: {
354 #if SIMGRID_HAVE_STATEFUL_MC
355 s_mc_message_register_symbol_t message;
356 xbt_assert(size == sizeof(message), "Broken message");
357 memcpy(&message, buffer, sizeof(message));
358 xbt_assert(not message.callback, "Support for client-side function proposition is not implemented.");
359 XBT_DEBUG("Received symbol: %s", message.name.data());
361 LivenessChecker::automaton_register_symbol(*get_remote_memory(), message.name.data(), remote((int*)message.data));
363 xbt_die("Please don't use liveness properties when MC is compiled out.");
368 case MessageType::WAITING:
371 case MessageType::ASSERTION_FAILED:
372 Exploration::get_instance()->report_assertion_failure();
376 xbt_die("Unexpected message from the application");
381 void CheckerSide::wait_for_requests()
383 XBT_DEBUG("Resume the application");
384 if (get_channel().send(MessageType::CONTINUE) != 0)
385 throw xbt::errno_error();
386 clear_memory_cache();
392 void CheckerSide::clear_memory_cache()
394 #if SIMGRID_HAVE_STATEFUL_MC
396 remote_memory_->clear_cache();
400 void CheckerSide::handle_dead_child(int status)
402 // From PTRACE_O_TRACEEXIT:
404 if (status >> 8 == (SIGTRAP | (PTRACE_EVENT_EXIT << 8))) {
405 unsigned long eventmsg;
406 xbt_assert(ptrace(PTRACE_GETEVENTMSG, pid_, 0, &eventmsg) != -1, "Could not get exit status");
407 status = static_cast<int>(eventmsg);
408 if (WIFSIGNALED(status)) {
410 Exploration::get_instance()->report_crash(status);
415 // We don't care about non-lethal signals, just reinject them:
416 if (WIFSTOPPED(status)) {
417 XBT_DEBUG("Stopped with signal %i", (int)WSTOPSIG(status));
420 ptrace(PTRACE_CONT, pid_, 0, WSTOPSIG(status));
422 ptrace(PT_CONTINUE, pid_, (caddr_t)1, WSTOPSIG(status));
424 xbt_assert(errno == 0, "Could not PTRACE_CONT: %s", strerror(errno));
427 else if (WIFSIGNALED(status)) {
429 Exploration::get_instance()->report_crash(status);
430 } else if (WIFEXITED(status)) {
431 XBT_DEBUG("Child process is over");
436 void CheckerSide::handle_waitpid()
438 XBT_DEBUG("%d checks for wait event. %s", getpid(),
439 child_checker_ == nullptr ? "Wait directly." : "Ask our proxy to wait for its child.");
441 if (child_checker_ == nullptr) { // Wait directly
444 while ((pid = waitpid(-1, &status, WNOHANG)) != 0) {
446 if (errno == ECHILD) { // No more children:
447 xbt_assert(not this->running(), "Inconsistent state");
450 xbt_die("Could not wait for pid: %s", strerror(errno));
454 if (pid == get_pid())
455 handle_dead_child(status);
458 } else { // Ask our proxy to wait for us
460 s_mc_message_int_t request = {};
461 request.type = MessageType::WAIT_CHILD;
462 request.value = pid_;
463 xbt_assert(child_checker_->get_channel().send(request) == 0,
464 "Could not ask my child to waitpid its child for me: %s", strerror(errno));
466 s_mc_message_int_t answer;
467 ssize_t answer_size = child_checker_->get_channel().receive(answer);
468 xbt_assert(answer_size != -1, "Could not receive message");
469 xbt_assert(answer.type == MessageType::WAIT_CHILD_REPLY,
470 "The received message is not the WAIT_CHILD_REPLY I was expecting but of type %s",
471 to_c_str(answer.type));
472 xbt_assert(answer_size == sizeof answer, "Broken message (size=%zd; expected %zu)", answer_size, sizeof answer);
473 handle_dead_child(answer.value);
476 } // namespace simgrid::mc