+#ifdef __linux__
+#define WAITPID_CHECKED_FLAGS __WALL
+#else
+#define WAITPID_CHECKED_FLAGS 0
+#endif
+
+XBT_LOG_NEW_DEFAULT_SUBCATEGORY(mc_checkerside, mc, "MC communication with the application");
+
+static simgrid::config::Flag<std::string> _sg_mc_setenv{
+ "model-check/setenv", "Extra environment variables to pass to the child process (ex: 'AZE=aze;QWE=qwe').", "",
+ [](std::string_view value) {
+ xbt_assert(value.empty() || value.find('=', 0) != std::string_view::npos,
+ "The 'model-check/setenv' parameter must be like 'AZE=aze', but it does not contain an equal sign.");
+ }};
+
+namespace simgrid::mc {
+
+XBT_ATTRIB_NORETURN static void run_child_process(int socket, const std::vector<char*>& args, bool need_ptrace)
+{
+ /* On startup, simix_global_init() calls simgrid::mc::Client::initialize(), which checks whether the MC_ENV_SOCKET_FD
+ * env variable is set. If so, MC mode is assumed, and the client is setup from its side
+ */
+
+#ifdef __linux__
+ // Make sure we do not outlive our parent
+ sigset_t mask;
+ sigemptyset(&mask);
+ xbt_assert(sigprocmask(SIG_SETMASK, &mask, nullptr) >= 0, "Could not unblock signals");
+ xbt_assert(prctl(PR_SET_PDEATHSIG, SIGHUP) == 0, "Could not PR_SET_PDEATHSIG");
+#endif
+
+ // Remove CLOEXEC to pass the socket to the application
+ int fdflags = fcntl(socket, F_GETFD, 0);
+ xbt_assert(fdflags != -1 && fcntl(socket, F_SETFD, fdflags & ~FD_CLOEXEC) != -1,
+ "Could not remove CLOEXEC for socket");
+
+ setenv(MC_ENV_SOCKET_FD, std::to_string(socket).c_str(), 1);
+ if (need_ptrace)
+ setenv("MC_NEED_PTRACE", "1", 1);
+
+ /* Setup the tokenizer that parses the cfg:model-check/setenv parameter */
+ using Tokenizer = boost::tokenizer<boost::char_separator<char>>;
+ boost::char_separator<char> semicol_sep(";");
+ boost::char_separator<char> equal_sep("=");
+ Tokenizer token_vars(_sg_mc_setenv.get(), semicol_sep); /* Iterate over all FOO=foo parts */
+ for (const auto& token : token_vars) {
+ std::vector<std::string> kv;
+ Tokenizer token_kv(token, equal_sep);
+ for (const auto& t : token_kv) /* Iterate over 'FOO' and then 'foo' in that 'FOO=foo' */
+ kv.push_back(t);
+ xbt_assert(kv.size() == 2, "Parse error on 'model-check/setenv' value %s. Does it contain an equal sign?",
+ token.c_str());
+ XBT_INFO("setenv '%s'='%s'", kv[0].c_str(), kv[1].c_str());
+ setenv(kv[0].c_str(), kv[1].c_str(), 1);
+ }
+
+ /* And now, exec the child process */
+ int i = 1;
+ while (args[i] != nullptr && args[i][0] == '-')
+ i++;
+
+ xbt_assert(args[i] != nullptr,
+ "Unable to find a binary to exec on the command line. Did you only pass config flags?");
+
+ execvp(args[i], args.data() + i);
+ XBT_CRITICAL("The model-checked process failed to exec(%s): %s.\n"
+ " Make sure that your binary exists on disk and is executable.",
+ args[i], strerror(errno));
+ if (strchr(args[i], '=') != nullptr)
+ XBT_CRITICAL("If you want to pass environment variables to the application, please use --cfg=model-check/setenv:%s",
+ args[i]);
+
+ xbt_die("Aborting now.");
+}
+
+static void wait_application_process(pid_t pid)
+{
+ XBT_DEBUG("Waiting for the model-checked process");
+ int status;
+
+ // The model-checked process SIGSTOP itself to signal it's ready:
+ xbt_assert(waitpid(pid, &status, WAITPID_CHECKED_FLAGS) == pid && WIFSTOPPED(status) && WSTOPSIG(status) == SIGSTOP,
+ "Could not wait model-checked process");
+
+ errno = 0;
+#ifdef __linux__
+ ptrace(PTRACE_SETOPTIONS, pid, nullptr, PTRACE_O_TRACEEXIT);
+ ptrace(PTRACE_CONT, pid, 0, 0);
+#elif defined BSD
+ ptrace(PT_CONTINUE, pid, (caddr_t)1, 0);
+#else
+#error "no ptrace equivalent coded for this platform"
+#endif
+ xbt_assert(errno == 0,
+ "Ptrace does not seem to be usable in your setup (errno: %d). "
+ "If you run from within a docker, adding `--cap-add SYS_PTRACE` to the docker line may help. "
+ "If it does not help, please report this bug.",
+ errno);
+}
+
+void CheckerSide::setup_events(bool socket_only)
+{
+ auto* base = event_base_new();
+ base_.reset(base);
+
+ socket_event_ = event_new(
+ base, get_channel().get_socket(), EV_READ | EV_PERSIST,
+ [](evutil_socket_t, short events, void* arg) {
+ auto checker = static_cast<simgrid::mc::CheckerSide*>(arg);
+ if (events == EV_READ) {
+ std::array<char, MC_MESSAGE_LENGTH> buffer;
+ ssize_t size = recv(checker->get_channel().get_socket(), buffer.data(), buffer.size(), MSG_DONTWAIT);
+ if (size == -1) {
+ XBT_ERROR("Channel::receive failure: %s", strerror(errno));
+ if (errno != EAGAIN)
+ throw simgrid::xbt::errno_error();
+ }
+
+ if (size == 0) // The app closed the socket. It must be dead by now.
+ checker->handle_waitpid();
+ else if (not checker->handle_message(buffer.data(), size))
+ checker->break_loop();
+ } else {
+ xbt_die("Unexpected event");
+ }
+ },
+ this);
+ event_add(socket_event_, nullptr);
+
+ if (socket_only) {
+ signal_event_ = nullptr;
+ } else {
+ signal_event_ = event_new(
+ base, SIGCHLD, EV_SIGNAL | EV_PERSIST,
+ [](evutil_socket_t sig, short events, void* arg) {
+ auto checker = static_cast<simgrid::mc::CheckerSide*>(arg);
+ if (events == EV_SIGNAL) {
+ if (sig == SIGCHLD)
+ checker->handle_waitpid();
+ else
+ xbt_die("Unexpected signal: %d", sig);
+ } else {
+ xbt_die("Unexpected event");
+ }
+ },
+ this);
+ event_add(signal_event_, nullptr);
+ }
+}
+
+/* When this constructor is called, no other checkerside exists */
+CheckerSide::CheckerSide(const std::vector<char*>& args, bool need_memory_info) : running_(true)
+{
+ // Create an AF_LOCAL socketpair used for exchanging messages between the model-checker process (ancestor)
+ // and the application process (child)
+ int sockets[2];
+ xbt_assert(socketpair(AF_LOCAL, SOCK_SEQPACKET | SOCK_CLOEXEC, 0, sockets) != -1, "Could not create socketpair: %s",
+ strerror(errno));
+
+ pid_ = fork();
+ xbt_assert(pid_ >= 0, "Could not fork application process");
+
+ if (pid_ == 0) { // Child
+ ::close(sockets[1]);
+ run_child_process(sockets[0], args, need_memory_info); // We need ptrace if we need the mem info
+ DIE_IMPOSSIBLE;
+ }
+
+ // Parent (model-checker):
+ ::close(sockets[0]);
+ channel_.reset_socket(sockets[1]);
+
+ setup_events(false); /* we need a signal handler too */
+ if (need_memory_info) {
+ // setup ptrace and sync with the app
+ wait_application_process(pid_);
+
+ // Request the initial memory on need
+ channel_.send(MessageType::NEED_MEMINFO);
+ s_mc_message_need_meminfo_reply_t answer;
+ ssize_t answer_size = channel_.receive(answer);
+ xbt_assert(answer_size != -1, "Could not receive message");
+ xbt_assert(answer.type == MessageType::NEED_MEMINFO_REPLY,
+ "The received message is not the NEED_MEMINFO_REPLY I was expecting but of type %s",
+ to_c_str(answer.type));
+ xbt_assert(answer_size == sizeof answer, "Broken message (size=%zd; expected %zu)", answer_size, sizeof answer);
+
+ /* We now have enough info to create the memory address space */
+ remote_memory_ = std::make_unique<simgrid::mc::RemoteProcessMemory>(pid_, answer.mmalloc_default_mdp);
+ }
+
+ wait_for_requests();
+}