Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
MC: disable Address Space Layout Randomization in the application
[simgrid.git] / src / mc / api / RemoteApp.cpp
1 /* Copyright (c) 2015-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/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"
14 #include "xbt/log.h"
15 #include "xbt/system_error.hpp"
16 #include <signal.h>
17
18 #include <algorithm>
19 #include <array>
20 #include <boost/tokenizer.hpp>
21 #include <memory>
22 #include <numeric>
23 #include <string>
24
25 #include <fcntl.h>
26 #ifdef __linux__
27 #include <sys/personality.h>
28 #include <sys/prctl.h>
29 #endif
30 #include <sys/ptrace.h>
31 #include <sys/wait.h>
32
33 #ifdef __linux__
34 #define WAITPID_CHECKED_FLAGS __WALL
35 #else
36 #define WAITPID_CHECKED_FLAGS 0
37 #endif
38
39 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(mc_Session, mc, "Model-checker session");
40 XBT_LOG_EXTERNAL_CATEGORY(mc_global);
41
42 static simgrid::config::Flag<std::string> _sg_mc_setenv{
43     "model-check/setenv", "Extra environment variables to pass to the child process (ex: 'AZE=aze;QWE=qwe').", "",
44     [](std::string_view value) {
45       xbt_assert(value.empty() || value.find('=', 0) != std::string_view::npos,
46                  "The 'model-check/setenv' parameter must be like 'AZE=aze', but it does not contain an equal sign.");
47     }};
48
49 namespace simgrid::mc {
50
51 XBT_ATTRIB_NORETURN static void run_child_process(int socket, const std::vector<char*>& args)
52 {
53   /* On startup, simix_global_init() calls simgrid::mc::Client::initialize(), which checks whether the MC_ENV_SOCKET_FD
54    * env variable is set. If so, MC mode is assumed, and the client is setup from its side
55    */
56
57 #ifdef __linux__
58   // Make sure we do not outlive our parent
59   sigset_t mask;
60   sigemptyset(&mask);
61   xbt_assert(sigprocmask(SIG_SETMASK, &mask, nullptr) >= 0, "Could not unblock signals");
62   xbt_assert(prctl(PR_SET_PDEATHSIG, SIGHUP) == 0, "Could not PR_SET_PDEATHSIG");
63
64   // Make sure that the application process layout is not randomized, so that the info we gather is stable over re-execs
65   if (personality(ADDR_NO_RANDOMIZE) == -1) {
66     XBT_ERROR("Could not set the NO_RANDOMIZE personality");
67     throw xbt::errno_error();
68   }
69 #endif
70
71   // Remove CLOEXEC to pass the socket to the application
72   int fdflags = fcntl(socket, F_GETFD, 0);
73   xbt_assert(fdflags != -1 && fcntl(socket, F_SETFD, fdflags & ~FD_CLOEXEC) != -1,
74              "Could not remove CLOEXEC for socket");
75
76   setenv(MC_ENV_SOCKET_FD, std::to_string(socket).c_str(), 1);
77
78   /* Setup the tokenizer that parses the cfg:model-check/setenv parameter */
79   using Tokenizer = boost::tokenizer<boost::char_separator<char>>;
80   boost::char_separator<char> semicol_sep(";");
81   boost::char_separator<char> equal_sep("=");
82   Tokenizer token_vars(_sg_mc_setenv.get(), semicol_sep); /* Iterate over all FOO=foo parts */
83   for (const auto& token : token_vars) {
84     std::vector<std::string> kv;
85     Tokenizer token_kv(token, equal_sep);
86     for (const auto& t : token_kv) /* Iterate over 'FOO' and then 'foo' in that 'FOO=foo' */
87       kv.push_back(t);
88     xbt_assert(kv.size() == 2, "Parse error on 'model-check/setenv' value %s. Does it contain an equal sign?",
89                token.c_str());
90     XBT_INFO("setenv '%s'='%s'", kv[0].c_str(), kv[1].c_str());
91     setenv(kv[0].c_str(), kv[1].c_str(), 1);
92   }
93
94   /* And now, exec the child process */
95   int i = 1;
96   while (args[i] != nullptr && args[i][0] == '-')
97     i++;
98
99   xbt_assert(args[i] != nullptr,
100              "Unable to find a binary to exec on the command line. Did you only pass config flags?");
101
102   execvp(args[i], args.data() + i);
103   XBT_CRITICAL("The model-checked process failed to exec(%s): %s.\n"
104                "        Make sure that your binary exists on disk and is executable.",
105                args[i], strerror(errno));
106   if (strchr(args[i], '=') != nullptr)
107     XBT_CRITICAL("If you want to pass environment variables to the application, please use --cfg=model-check/setenv:%s",
108                  args[i]);
109
110   xbt_die("Aborting now.");
111 }
112
113 RemoteApp::RemoteApp(const std::vector<char*>& args)
114 {
115   // Create an AF_LOCAL socketpair used for exchanging messages
116   // between the model-checker process (ourselves) and the model-checked
117   // process:
118   int sockets[2];
119   xbt_assert(socketpair(AF_LOCAL, SOCK_SEQPACKET | SOCK_CLOEXEC, 0, sockets) != -1, "Could not create socketpair");
120
121   pid_t pid = fork();
122   xbt_assert(pid >= 0, "Could not fork model-checked process");
123
124   if (pid == 0) { // Child
125     ::close(sockets[1]);
126     run_child_process(sockets[0], args);
127     DIE_IMPOSSIBLE;
128   }
129
130   // Parent (model-checker):
131   ::close(sockets[0]);
132
133   checker_side_ = std::make_unique<simgrid::mc::CheckerSide>(sockets[1], pid);
134
135   start();
136
137   /* Take the initial snapshot */
138   wait_for_requests();
139   initial_snapshot_ = std::make_shared<simgrid::mc::Snapshot>(0, page_store_, checker_side_->get_remote_memory());
140 }
141
142 RemoteApp::~RemoteApp()
143 {
144   initial_snapshot_ = nullptr;
145   shutdown();
146 }
147 void RemoteApp::start()
148 {
149   XBT_DEBUG("Waiting for the model-checked process");
150   int status;
151
152   // The model-checked process SIGSTOP itself to signal it's ready:
153   const pid_t pid = checker_side_->get_pid();
154
155   xbt_assert(waitpid(pid, &status, WAITPID_CHECKED_FLAGS) == pid && WIFSTOPPED(status) && WSTOPSIG(status) == SIGSTOP,
156              "Could not wait model-checked process");
157
158   errno = 0;
159 #ifdef __linux__
160   ptrace(PTRACE_SETOPTIONS, pid, nullptr, PTRACE_O_TRACEEXIT);
161   ptrace(PTRACE_CONT, pid, 0, 0);
162 #elif defined BSD
163   ptrace(PT_CONTINUE, pid, (caddr_t)1, 0);
164 #else
165 #error "no ptrace equivalent coded for this platform"
166 #endif
167   xbt_assert(errno == 0,
168              "Ptrace does not seem to be usable in your setup (errno: %d). "
169              "If you run from within a docker, adding `--cap-add SYS_PTRACE` to the docker line may help. "
170              "If it does not help, please report this bug.",
171              errno);
172 }
173 void RemoteApp::restore_initial_state() const
174 {
175   this->initial_snapshot_->restore(checker_side_->get_remote_memory());
176 }
177
178 unsigned long RemoteApp::get_maxpid() const
179 {
180   // note: we could maybe cache it and count the actor creation on checker side too.
181   // But counting correctly accross state checkpoint/restore would be annoying.
182
183   checker_side_->get_channel().send(MessageType::ACTORS_MAXPID);
184   s_mc_message_int_t answer;
185   ssize_t answer_size = checker_side_->get_channel().receive(answer);
186   xbt_assert(answer_size != -1, "Could not receive message");
187   xbt_assert(answer_size == sizeof answer, "Broken message (size=%zd; expected %zu)", answer_size, sizeof answer);
188   xbt_assert(answer.type == MessageType::ACTORS_MAXPID_REPLY,
189              "Received unexpected message %s (%i); expected MessageType::ACTORS_MAXPID_REPLY (%i)",
190              to_c_str(answer.type), (int)answer.type, (int)MessageType::ACTORS_MAXPID_REPLY);
191
192   return answer.value;
193 }
194
195 void RemoteApp::get_actors_status(std::map<aid_t, ActorState>& whereto) const
196 {
197   // The messaging happens as follows:
198   //
199   // CheckerSide                  AppSide
200   // send ACTORS_STATUS ---->
201   //                    <----- send ACTORS_STATUS_REPLY
202   //                    <----- send `N` `s_mc_message_actors_status_one_t` structs
203   //                    <----- send `M` `s_mc_message_simcall_probe_one_t` structs
204   checker_side_->get_channel().send(MessageType::ACTORS_STATUS);
205
206   s_mc_message_actors_status_answer_t answer;
207   ssize_t answer_size = checker_side_->get_channel().receive(answer);
208   xbt_assert(answer_size != -1, "Could not receive message");
209   xbt_assert(answer_size == sizeof answer, "Broken message (size=%zd; expected %zu)", answer_size, sizeof answer);
210   xbt_assert(answer.type == MessageType::ACTORS_STATUS_REPLY,
211              "Received unexpected message %s (%i); expected MessageType::ACTORS_STATUS_REPLY (%i)",
212              to_c_str(answer.type), (int)answer.type, (int)MessageType::ACTORS_STATUS_REPLY);
213
214   // Message sanity checks
215   xbt_assert(answer.count >= 0, "Received an ACTOR_STATUS_REPLY message with an actor count of '%d' < 0", answer.count);
216   xbt_assert(answer.transition_count >= 0, "Received an ACTOR_STATUS_REPLY message with transition_count '%d' < 0",
217              answer.transition_count);
218   xbt_assert(answer.transition_count == 0 || answer.count >= 0,
219              "Received an ACTOR_STATUS_REPLY message with no actor data "
220              "but with transition data nonetheless");
221
222   std::vector<s_mc_message_actors_status_one_t> status(answer.count);
223   if (answer.count > 0) {
224     size_t size      = status.size() * sizeof(s_mc_message_actors_status_one_t);
225     ssize_t received = checker_side_->get_channel().receive(status.data(), size);
226     xbt_assert(static_cast<size_t>(received) == size);
227   }
228
229   // Ensures that each actor sends precisely `answer.transition_count` transitions. While technically
230   // this doesn't catch the edge case where actor A sends 3 instead of 2 and actor B sends 2 instead
231   // of 3 transitions, that is ignored here since that invariant needs to be enforced on the AppSide
232   const auto expected_transitions = std::accumulate(
233       status.begin(), status.end(), 0, [](int total, const auto& actor) { return total + actor.n_transitions; });
234   xbt_assert(expected_transitions == answer.transition_count,
235              "Expected to receive %d transition(s) but was only notified of %d by the app side", expected_transitions,
236              answer.transition_count);
237
238   std::vector<s_mc_message_simcall_probe_one_t> probes(answer.transition_count);
239   if (answer.transition_count > 0) {
240     for (auto& probe : probes) {
241       ssize_t received = checker_side_->get_channel().receive(probe);
242       xbt_assert(received >= 0, "Could not receive response to ACTORS_PROBE message (%s)", strerror(errno));
243       xbt_assert(static_cast<size_t>(received) == sizeof probe,
244                  "Could not receive response to ACTORS_PROBE message (%zd bytes received != %zu bytes expected",
245                  received, sizeof probe);
246     }
247   }
248
249   whereto.clear();
250   std::move_iterator probes_iter(probes.begin());
251
252   for (const auto& actor : status) {
253     xbt_assert(actor.n_transitions == 0 || actor.n_transitions == actor.max_considered,
254                "If any transitions are serialized for an actor, it must match the "
255                "total number of transitions that can be considered for the actor "
256                "(currently %d), but only %d transition(s) was/were said to be encoded",
257                actor.max_considered, actor.n_transitions);
258
259     std::vector<std::shared_ptr<Transition>> actor_transitions;
260     for (int times_considered = 0; times_considered < actor.n_transitions; times_considered++, probes_iter++) {
261       std::stringstream stream((*probes_iter).buffer.data());
262       actor_transitions.emplace_back(deserialize_transition(actor.aid, times_considered, stream));
263     }
264
265     XBT_DEBUG("Received %zu transitions for actor %ld", actor_transitions.size(), actor.aid);
266     whereto.try_emplace(actor.aid, actor.aid, actor.enabled, actor.max_considered, std::move(actor_transitions));
267   }
268 }
269
270 void RemoteApp::check_deadlock() const
271 {
272   xbt_assert(checker_side_->get_channel().send(MessageType::DEADLOCK_CHECK) == 0, "Could not check deadlock state");
273   s_mc_message_int_t message;
274   ssize_t received = checker_side_->get_channel().receive(message);
275   xbt_assert(received != -1, "Could not receive message");
276   xbt_assert(received == sizeof message, "Broken message (size=%zd; expected %zu)", received, sizeof message);
277   xbt_assert(message.type == MessageType::DEADLOCK_CHECK_REPLY,
278              "Received unexpected message %s (%i); expected MessageType::DEADLOCK_CHECK_REPLY (%i)",
279              to_c_str(message.type), (int)message.type, (int)MessageType::DEADLOCK_CHECK_REPLY);
280
281   if (message.value != 0) {
282     auto* explo = Exploration::get_instance();
283     XBT_CINFO(mc_global, "Counter-example execution trace:");
284     for (auto const& frame : explo->get_textual_trace())
285       XBT_CINFO(mc_global, "  %s", frame.c_str());
286     XBT_INFO("You can debug the problem (and see the whole details) by rerunning out of simgrid-mc with "
287              "--cfg=model-check/replay:'%s'",
288              explo->get_record_trace().to_string().c_str());
289     explo->log_state();
290     throw DeadlockError();
291   }
292 }
293
294 void RemoteApp::wait_for_requests()
295 {
296   /* Resume the application */
297   if (checker_side_->get_channel().send(MessageType::CONTINUE) != 0)
298     throw xbt::errno_error();
299   checker_side_->clear_memory_cache();
300
301   if (checker_side_->running())
302     checker_side_->dispatch_events();
303 }
304
305 void RemoteApp::shutdown()
306 {
307   XBT_DEBUG("Shutting down model-checker");
308
309   if (checker_side_->running()) {
310     XBT_DEBUG("Killing process");
311     finalize_app(true);
312     kill(checker_side_->get_pid(), SIGKILL);
313     checker_side_->terminate();
314   }
315 }
316
317 Transition* RemoteApp::handle_simcall(aid_t aid, int times_considered, bool new_transition)
318 {
319   s_mc_message_simcall_execute_t m = {};
320   m.type                           = MessageType::SIMCALL_EXECUTE;
321   m.aid_                           = aid;
322   m.times_considered_              = times_considered;
323   checker_side_->get_channel().send(m);
324
325   get_remote_process_memory().clear_cache();
326   if (checker_side_->running())
327     checker_side_->dispatch_events(); // The app may send messages while processing the transition
328
329   s_mc_message_simcall_execute_answer_t answer;
330   ssize_t s = checker_side_->get_channel().receive(answer);
331   xbt_assert(s != -1, "Could not receive message");
332   xbt_assert(s == sizeof answer, "Broken message (size=%zd; expected %zu)", s, sizeof answer);
333   xbt_assert(answer.type == MessageType::SIMCALL_EXECUTE_ANSWER,
334              "Received unexpected message %s (%i); expected MessageType::SIMCALL_EXECUTE_ANSWER (%i)",
335              to_c_str(answer.type), (int)answer.type, (int)MessageType::SIMCALL_EXECUTE_ANSWER);
336
337   if (new_transition) {
338     std::stringstream stream(answer.buffer.data());
339     return deserialize_transition(aid, times_considered, stream);
340   } else
341     return nullptr;
342 }
343
344 void RemoteApp::finalize_app(bool terminate_asap)
345 {
346   s_mc_message_int_t m = {};
347   m.type               = MessageType::FINALIZE;
348   m.value              = terminate_asap;
349   xbt_assert(checker_side_->get_channel().send(m) == 0, "Could not ask the app to finalize on need");
350
351   s_mc_message_t answer;
352   ssize_t s = checker_side_->get_channel().receive(answer);
353   xbt_assert(s != -1, "Could not receive answer to FINALIZE");
354   xbt_assert(s == sizeof answer, "Broken message (size=%zd; expected %zu)", s, sizeof answer);
355   xbt_assert(answer.type == MessageType::FINALIZE_REPLY,
356              "Received unexpected message %s (%i); expected MessageType::FINALIZE_REPLY (%i)", to_c_str(answer.type),
357              (int)answer.type, (int)MessageType::FINALIZE_REPLY);
358 }
359
360 } // namespace simgrid::mc