1 /* Copyright (c) 2015-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/api/RemoteApp.hpp"
7 #include "src/mc/explo/Exploration.hpp"
8 #include "src/mc/mc_config.hpp"
9 #include "xbt/asserts.h"
10 #include "src/mc/api/State.hpp"
11 #include "src/mc/mc_config.hpp"
12 #include "src/mc/mc_exit.hpp"
13 #include "src/mc/mc_private.hpp"
15 #include "xbt/system_error.hpp"
20 #include <boost/tokenizer.hpp>
27 #include <sys/prctl.h>
29 #include <sys/ptrace.h>
33 #define WAITPID_CHECKED_FLAGS __WALL
35 #define WAITPID_CHECKED_FLAGS 0
38 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(mc_Session, mc, "Model-checker session");
39 XBT_LOG_EXTERNAL_CATEGORY(mc_global);
41 static simgrid::config::Flag<std::string> _sg_mc_setenv{
42 "model-check/setenv", "Extra environment variables to pass to the child process (ex: 'AZE=aze;QWE=qwe').", "",
43 [](std::string_view value) {
44 xbt_assert(value.empty() || value.find('=', 0) != std::string_view::npos,
45 "The 'model-check/setenv' parameter must be like 'AZE=aze', but it does not contain an equal sign.");
48 namespace simgrid::mc {
50 XBT_ATTRIB_NORETURN static void run_child_process(int socket, const std::vector<char*>& args)
52 /* On startup, simix_global_init() calls simgrid::mc::Client::initialize(), which checks whether the MC_ENV_SOCKET_FD
53 * env variable is set. If so, MC mode is assumed, and the client is setup from its side
57 // Make sure we do not outlive our parent
60 xbt_assert(sigprocmask(SIG_SETMASK, &mask, nullptr) >= 0, "Could not unblock signals");
61 xbt_assert(prctl(PR_SET_PDEATHSIG, SIGHUP) == 0, "Could not PR_SET_PDEATHSIG");
64 // Remove CLOEXEC to pass the socket to the application
65 int fdflags = fcntl(socket, F_GETFD, 0);
66 xbt_assert(fdflags != -1 && fcntl(socket, F_SETFD, fdflags & ~FD_CLOEXEC) != -1,
67 "Could not remove CLOEXEC for socket");
69 setenv(MC_ENV_SOCKET_FD, std::to_string(socket).c_str(), 1);
71 /* Setup the tokenizer that parses the cfg:model-check/setenv parameter */
72 using Tokenizer = boost::tokenizer<boost::char_separator<char>>;
73 boost::char_separator<char> semicol_sep(";");
74 boost::char_separator<char> equal_sep("=");
75 Tokenizer token_vars(_sg_mc_setenv.get(), semicol_sep); /* Iterate over all FOO=foo parts */
76 for (const auto& token : token_vars) {
77 std::vector<std::string> kv;
78 Tokenizer token_kv(token, equal_sep);
79 for (const auto& t : token_kv) /* Iterate over 'FOO' and then 'foo' in that 'FOO=foo' */
81 xbt_assert(kv.size() == 2, "Parse error on 'model-check/setenv' value %s. Does it contain an equal sign?",
83 XBT_INFO("setenv '%s'='%s'", kv[0].c_str(), kv[1].c_str());
84 setenv(kv[0].c_str(), kv[1].c_str(), 1);
87 /* And now, exec the child process */
89 while (args[i] != nullptr && args[i][0] == '-')
92 xbt_assert(args[i] != nullptr,
93 "Unable to find a binary to exec on the command line. Did you only pass config flags?");
95 execvp(args[i], args.data() + i);
96 XBT_CRITICAL("The model-checked process failed to exec(%s): %s.\n"
97 " Make sure that your binary exists on disk and is executable.",
98 args[i], strerror(errno));
99 if (strchr(args[i], '=') != nullptr)
100 XBT_CRITICAL("If you want to pass environment variables to the application, please use --cfg=model-check/setenv:%s",
103 xbt_die("Aborting now.");
106 RemoteApp::RemoteApp(const std::vector<char*>& args)
108 // Create an AF_LOCAL socketpair used for exchanging messages
109 // between the model-checker process (ourselves) and the model-checked
112 xbt_assert(socketpair(AF_LOCAL, SOCK_SEQPACKET | SOCK_CLOEXEC, 0, sockets) != -1, "Could not create socketpair");
115 xbt_assert(pid >= 0, "Could not fork model-checked process");
117 if (pid == 0) { // Child
119 run_child_process(sockets[0], args);
123 // Parent (model-checker):
126 xbt_assert(mc_model_checker == nullptr, "Did you manage to start the MC twice in this process?");
128 checker_side_ = std::make_unique<simgrid::mc::CheckerSide>(sockets[1]);
129 auto memory = std::make_unique<simgrid::mc::RemoteProcessMemory>(pid);
130 model_checker_ = std::make_unique<simgrid::mc::ModelChecker>(std::move(memory));
131 mc_model_checker = model_checker_.get();
135 /* Take the initial snapshot */
138 std::make_shared<simgrid::mc::Snapshot>(0, page_store_, model_checker_->get_remote_process_memory());
141 RemoteApp::~RemoteApp()
143 initial_snapshot_ = nullptr;
144 if (model_checker_) {
146 model_checker_ = nullptr;
147 mc_model_checker = nullptr;
150 void RemoteApp::start()
152 checker_side_->start(model_checker_.get());
154 XBT_DEBUG("Waiting for the model-checked process");
157 // The model-checked process SIGSTOP itself to signal it's ready:
158 const pid_t pid = get_remote_process_memory().pid();
160 xbt_assert(waitpid(pid, &status, WAITPID_CHECKED_FLAGS) == pid && WIFSTOPPED(status) && WSTOPSIG(status) == SIGSTOP,
161 "Could not wait model-checked process");
165 ptrace(PTRACE_SETOPTIONS, pid, nullptr, PTRACE_O_TRACEEXIT);
166 ptrace(PTRACE_CONT, pid, 0, 0);
168 ptrace(PT_CONTINUE, pid, (caddr_t)1, 0);
170 #error "no ptrace equivalent coded for this platform"
172 xbt_assert(errno == 0,
173 "Ptrace does not seem to be usable in your setup (errno: %d). "
174 "If you run from within a docker, adding `--cap-add SYS_PTRACE` to the docker line may help. "
175 "If it does not help, please report this bug.",
178 void RemoteApp::restore_initial_state() const
180 this->initial_snapshot_->restore(model_checker_->get_remote_process_memory());
183 unsigned long RemoteApp::get_maxpid() const
185 // note: we could maybe cache it and count the actor creation on checker side too.
186 // But counting correctly accross state checkpoint/restore would be annoying.
188 checker_side_->get_channel().send(MessageType::ACTORS_MAXPID);
189 s_mc_message_int_t answer;
190 ssize_t answer_size = checker_side_->get_channel().receive(answer);
191 xbt_assert(answer_size != -1, "Could not receive message");
192 xbt_assert(answer_size == sizeof answer, "Broken message (size=%zd; expected %zu)", answer_size, sizeof answer);
193 xbt_assert(answer.type == MessageType::ACTORS_MAXPID_REPLY,
194 "Received unexpected message %s (%i); expected MessageType::ACTORS_MAXPID_REPLY (%i)",
195 to_c_str(answer.type), (int)answer.type, (int)MessageType::ACTORS_MAXPID_REPLY);
200 void RemoteApp::get_actors_status(std::map<aid_t, ActorState>& whereto) const
202 // The messaging happens as follows:
204 // CheckerSide AppSide
205 // send ACTORS_STATUS ---->
206 // <----- send ACTORS_STATUS_REPLY
207 // <----- send `N` `s_mc_message_actors_status_one_t` structs
208 // <----- send `M` `s_mc_message_simcall_probe_one_t` structs
209 checker_side_->get_channel().send(MessageType::ACTORS_STATUS);
211 s_mc_message_actors_status_answer_t answer;
212 ssize_t answer_size = checker_side_->get_channel().receive(answer);
213 xbt_assert(answer_size != -1, "Could not receive message");
214 xbt_assert(answer_size == sizeof answer, "Broken message (size=%zd; expected %zu)", answer_size, sizeof answer);
215 xbt_assert(answer.type == MessageType::ACTORS_STATUS_REPLY,
216 "Received unexpected message %s (%i); expected MessageType::ACTORS_STATUS_REPLY (%i)",
217 to_c_str(answer.type), (int)answer.type, (int)MessageType::ACTORS_STATUS_REPLY);
219 // Message sanity checks
220 xbt_assert(answer.count >= 0, "Received an ACTOR_STATUS_REPLY message with an actor count of '%d' < 0", answer.count);
221 xbt_assert(answer.transition_count >= 0, "Received an ACTOR_STATUS_REPLY message with transition_count '%d' < 0",
222 answer.transition_count);
223 xbt_assert(answer.transition_count == 0 || answer.count >= 0,
224 "Received an ACTOR_STATUS_REPLY message with no actor data "
225 "but with transition data nonetheless");
227 std::vector<s_mc_message_actors_status_one_t> status(answer.count);
228 if (answer.count > 0) {
229 size_t size = status.size() * sizeof(s_mc_message_actors_status_one_t);
230 ssize_t received = checker_side_->get_channel().receive(status.data(), size);
231 xbt_assert(static_cast<size_t>(received) == size);
234 // Ensures that each actor sends precisely `answer.transition_count` transitions. While technically
235 // this doesn't catch the edge case where actor A sends 3 instead of 2 and actor B sends 2 instead
236 // of 3 transitions, that is ignored here since that invariant needs to be enforced on the AppSide
237 const auto expected_transitions = std::accumulate(
238 status.begin(), status.end(), 0, [](int total, const auto& actor) { return total + actor.n_transitions; });
239 xbt_assert(expected_transitions == answer.transition_count,
240 "Expected to receive %d transition(s) but was only notified of %d by the app side", expected_transitions,
241 answer.transition_count);
243 std::vector<s_mc_message_simcall_probe_one_t> probes(answer.transition_count);
244 if (answer.transition_count > 0) {
245 for (auto& probe : probes) {
246 ssize_t received = checker_side_->get_channel().receive(probe);
247 xbt_assert(received >= 0, "Could not receive response to ACTORS_PROBE message (%s)", strerror(errno));
248 xbt_assert(static_cast<size_t>(received) == sizeof probe,
249 "Could not receive response to ACTORS_PROBE message (%zd bytes received != %zu bytes expected",
250 received, sizeof probe);
255 std::move_iterator probes_iter(probes.begin());
257 for (const auto& actor : status) {
258 xbt_assert(actor.n_transitions == 0 || actor.n_transitions == actor.max_considered,
259 "If any transitions are serialized for an actor, it must match the "
260 "total number of transitions that can be considered for the actor "
261 "(currently %d), but only %d transition(s) was/were said to be encoded",
262 actor.max_considered, actor.n_transitions);
264 std::vector<std::shared_ptr<Transition>> actor_transitions;
265 for (int times_considered = 0; times_considered < actor.n_transitions; times_considered++, probes_iter++) {
266 std::stringstream stream((*probes_iter).buffer.data());
267 actor_transitions.emplace_back(deserialize_transition(actor.aid, times_considered, stream));
270 XBT_DEBUG("Received %zu transitions for actor %ld", actor_transitions.size(), actor.aid);
271 whereto.try_emplace(actor.aid, actor.aid, actor.enabled, actor.max_considered, std::move(actor_transitions));
275 void RemoteApp::check_deadlock() const
277 xbt_assert(checker_side_->get_channel().send(MessageType::DEADLOCK_CHECK) == 0, "Could not check deadlock state");
278 s_mc_message_int_t message;
279 ssize_t received = checker_side_->get_channel().receive(message);
280 xbt_assert(received != -1, "Could not receive message");
281 xbt_assert(received == sizeof message, "Broken message (size=%zd; expected %zu)", received, sizeof message);
282 xbt_assert(message.type == MessageType::DEADLOCK_CHECK_REPLY,
283 "Received unexpected message %s (%i); expected MessageType::DEADLOCK_CHECK_REPLY (%i)",
284 to_c_str(message.type), (int)message.type, (int)MessageType::DEADLOCK_CHECK_REPLY);
286 if (message.value != 0) {
287 XBT_CINFO(mc_global, "Counter-example execution trace:");
288 for (auto const& frame : model_checker_->get_exploration()->get_textual_trace())
289 XBT_CINFO(mc_global, " %s", frame.c_str());
290 XBT_INFO("You can debug the problem (and see the whole details) by rerunning out of simgrid-mc with "
291 "--cfg=model-check/replay:'%s'",
292 model_checker_->get_exploration()->get_record_trace().to_string().c_str());
293 model_checker_->get_exploration()->log_state();
294 throw DeadlockError();
298 void RemoteApp::wait_for_requests()
300 /* Resume the application */
301 if (checker_side_->get_channel().send(MessageType::CONTINUE) != 0)
302 throw xbt::errno_error();
303 get_remote_process_memory().clear_cache();
305 if (this->get_remote_process_memory().running())
306 checker_side_->dispatch();
309 void RemoteApp::shutdown()
311 XBT_DEBUG("Shutting down model-checker");
313 RemoteProcessMemory& process = get_remote_process_memory();
314 if (process.running()) {
315 XBT_DEBUG("Killing process");
317 kill(process.pid(), SIGKILL);
322 Transition* RemoteApp::handle_simcall(aid_t aid, int times_considered, bool new_transition)
324 s_mc_message_simcall_execute_t m = {};
325 m.type = MessageType::SIMCALL_EXECUTE;
327 m.times_considered_ = times_considered;
328 checker_side_->get_channel().send(m);
330 get_remote_process_memory().clear_cache();
331 if (this->get_remote_process_memory().running())
332 checker_side_->dispatch(); // The app may send messages while processing the transition
334 s_mc_message_simcall_execute_answer_t answer;
335 ssize_t s = checker_side_->get_channel().receive(answer);
336 xbt_assert(s != -1, "Could not receive message");
337 xbt_assert(s == sizeof answer, "Broken message (size=%zd; expected %zu)", s, sizeof answer);
338 xbt_assert(answer.type == MessageType::SIMCALL_EXECUTE_ANSWER,
339 "Received unexpected message %s (%i); expected MessageType::SIMCALL_EXECUTE_ANSWER (%i)",
340 to_c_str(answer.type), (int)answer.type, (int)MessageType::SIMCALL_EXECUTE_ANSWER);
342 if (new_transition) {
343 std::stringstream stream(answer.buffer.data());
344 return deserialize_transition(aid, times_considered, stream);
349 void RemoteApp::finalize_app(bool terminate_asap)
351 s_mc_message_int_t m = {};
352 m.type = MessageType::FINALIZE;
353 m.value = terminate_asap;
354 xbt_assert(checker_side_->get_channel().send(m) == 0, "Could not ask the app to finalize on need");
356 s_mc_message_t answer;
357 ssize_t s = checker_side_->get_channel().receive(answer);
358 xbt_assert(s != -1, "Could not receive answer to FINALIZE");
359 xbt_assert(s == sizeof answer, "Broken message (size=%zd; expected %zu)", s, sizeof answer);
360 xbt_assert(answer.type == MessageType::FINALIZE_REPLY,
361 "Received unexpected message %s (%i); expected MessageType::FINALIZE_REPLY (%i)", to_c_str(answer.type),
362 (int)answer.type, (int)MessageType::FINALIZE_REPLY);
365 } // namespace simgrid::mc