Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Avoid to send/receive zero-size messages.
[simgrid.git] / src / mc / api / RemoteApp.cpp
1 /* Copyright (c) 2015-2022. 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/internal_config.h" // HAVE_SMPI
8 #include "src/mc/explo/Exploration.hpp"
9 #include "src/mc/mc_config.hpp"
10 #if HAVE_SMPI
11 #include "smpi/smpi.h"
12 #include "src/smpi/include/private.hpp"
13 #endif
14 #include "signal.h"
15 #include "src/mc/api/State.hpp"
16 #include "src/mc/mc_config.hpp"
17 #include "src/mc/mc_exit.hpp"
18 #include "src/mc/mc_private.hpp"
19 #include "xbt/log.h"
20 #include "xbt/system_error.hpp"
21
22 #include <array>
23 #include <boost/tokenizer.hpp>
24 #include <memory>
25 #include <string>
26
27 #include <fcntl.h>
28 #ifdef __linux__
29 #include <sys/prctl.h>
30 #endif
31
32 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(mc_Session, mc, "Model-checker session");
33 XBT_LOG_EXTERNAL_CATEGORY(mc_global);
34
35 static simgrid::config::Flag<std::string> _sg_mc_setenv{
36     "model-check/setenv", "Extra environment variables to pass to the child process (ex: 'AZE=aze;QWE=qwe').", "",
37     [](std::string_view value) {
38       xbt_assert(value.empty() || value.find('=', 0) != std::string_view::npos,
39                  "The 'model-check/setenv' parameter must be like 'AZE=aze', but it does not contain an equal sign.");
40     }};
41
42 namespace simgrid::mc {
43
44 static void run_child_process(int socket, const std::vector<char*>& args)
45 {
46   /* On startup, simix_global_init() calls simgrid::mc::Client::initialize(), which checks whether the MC_ENV_SOCKET_FD
47    * env variable is set. If so, MC mode is assumed, and the client is setup from its side
48    */
49
50 #ifdef __linux__
51   // Make sure we do not outlive our parent
52   sigset_t mask;
53   sigemptyset(&mask);
54   xbt_assert(sigprocmask(SIG_SETMASK, &mask, nullptr) >= 0, "Could not unblock signals");
55   xbt_assert(prctl(PR_SET_PDEATHSIG, SIGHUP) == 0, "Could not PR_SET_PDEATHSIG");
56 #endif
57
58   // Remove CLOEXEC to pass the socket to the application
59   int fdflags = fcntl(socket, F_GETFD, 0);
60   xbt_assert(fdflags != -1 && fcntl(socket, F_SETFD, fdflags & ~FD_CLOEXEC) != -1,
61              "Could not remove CLOEXEC for socket");
62
63   setenv(MC_ENV_SOCKET_FD, std::to_string(socket).c_str(), 1);
64
65   /* Setup the tokenizer that parses the cfg:model-check/setenv parameter */
66   using Tokenizer = boost::tokenizer<boost::char_separator<char>>;
67   boost::char_separator<char> semicol_sep(";");
68   boost::char_separator<char> equal_sep("=");
69   Tokenizer token_vars(_sg_mc_setenv.get(), semicol_sep); /* Iterate over all FOO=foo parts */
70   for (const auto& token : token_vars) {
71     std::vector<std::string> kv;
72     Tokenizer token_kv(token, equal_sep);
73     for (const auto& t : token_kv) /* Iterate over 'FOO' and then 'foo' in that 'FOO=foo' */
74       kv.push_back(t);
75     xbt_assert(kv.size() == 2, "Parse error on 'model-check/setenv' value %s. Does it contain an equal sign?",
76                token.c_str());
77     XBT_INFO("setenv '%s'='%s'", kv[0].c_str(), kv[1].c_str());
78     setenv(kv[0].c_str(), kv[1].c_str(), 1);
79   }
80
81   /* And now, exec the child process */
82   int i = 1;
83   while (args[i] != nullptr && args[i][0] == '-')
84     i++;
85
86   xbt_assert(args[i] != nullptr,
87              "Unable to find a binary to exec on the command line. Did you only pass config flags?");
88
89   execvp(args[i], args.data() + i);
90   xbt_die("The model-checked process failed to exec(%s): %s", args[i], strerror(errno));
91 }
92
93 RemoteApp::RemoteApp(const std::vector<char*>& args)
94 {
95 #if HAVE_SMPI
96   smpi_init_options(); // only performed once
97   xbt_assert(smpi_cfg_privatization() != SmpiPrivStrategies::MMAP,
98              "Please use the dlopen privatization schema when model-checking SMPI code");
99 #endif
100
101   // Create an AF_LOCAL socketpair used for exchanging messages
102   // between the model-checker process (ourselves) and the model-checked
103   // process:
104   int sockets[2];
105   xbt_assert(socketpair(AF_LOCAL, SOCK_SEQPACKET | SOCK_CLOEXEC, 0, sockets) != -1, "Could not create socketpair");
106
107   pid_t pid = fork();
108   xbt_assert(pid >= 0, "Could not fork model-checked process");
109
110   if (pid == 0) { // Child
111     ::close(sockets[1]);
112     run_child_process(sockets[0], args);
113     DIE_IMPOSSIBLE;
114   }
115
116   // Parent (model-checker):
117   ::close(sockets[0]);
118
119   xbt_assert(mc_model_checker == nullptr, "Did you manage to start the MC twice in this process?");
120
121   auto process   = std::make_unique<simgrid::mc::RemoteProcess>(pid);
122   model_checker_ = std::make_unique<simgrid::mc::ModelChecker>(std::move(process), sockets[1]);
123
124   mc_model_checker = model_checker_.get();
125   model_checker_->start();
126
127   /* Take the initial snapshot */
128   model_checker_->wait_for_requests();
129   initial_snapshot_ = std::make_shared<simgrid::mc::Snapshot>(0);
130 }
131
132 RemoteApp::~RemoteApp()
133 {
134   initial_snapshot_ = nullptr;
135   if (model_checker_) {
136     model_checker_->shutdown();
137     model_checker_   = nullptr;
138     mc_model_checker = nullptr;
139   }
140 }
141
142 void RemoteApp::restore_initial_state() const
143 {
144   this->initial_snapshot_->restore(&model_checker_->get_remote_process());
145 }
146
147 unsigned long RemoteApp::get_maxpid() const
148 {
149   return model_checker_->get_remote_process().get_maxpid();
150 }
151
152 void RemoteApp::get_actors_status(std::map<aid_t, ActorState>& whereto) const
153 {
154   s_mc_message_t msg;
155   memset(&msg, 0, sizeof msg);
156   msg.type = simgrid::mc::MessageType::ACTORS_STATUS;
157   model_checker_->channel().send(msg);
158
159   s_mc_message_actors_status_answer_t answer;
160   ssize_t received = model_checker_->channel().receive(answer);
161   xbt_assert(received != -1, "Could not receive message");
162   xbt_assert(received == sizeof(answer) && answer.type == MessageType::ACTORS_STATUS_REPLY,
163              "Received unexpected message %s (%i, size=%i) "
164              "expected MessageType::ACTORS_STATUS_REPLY (%i, size=%i)",
165              to_c_str(answer.type), (int)answer.type, (int)received, (int)MessageType::ACTORS_STATUS_REPLY,
166              (int)sizeof(answer));
167
168   s_mc_message_actors_status_one_t status[answer.count];
169   if (answer.count > 0) {
170     received = model_checker_->channel().receive(&status, sizeof(status));
171     xbt_assert(static_cast<size_t>(received) == sizeof(status));
172   }
173
174   whereto.clear();
175   for (auto const& actor : status)
176     whereto.try_emplace(actor.aid, actor.aid, actor.enabled, actor.max_considered);
177 }
178
179 void RemoteApp::check_deadlock() const
180 {
181   xbt_assert(model_checker_->channel().send(MessageType::DEADLOCK_CHECK) == 0, "Could not check deadlock state");
182   s_mc_message_int_t message;
183   ssize_t s = model_checker_->channel().receive(message);
184   xbt_assert(s != -1, "Could not receive message");
185   xbt_assert(s == sizeof(message) && message.type == MessageType::DEADLOCK_CHECK_REPLY,
186              "Received unexpected message %s (%i, size=%i) "
187              "expected MessageType::DEADLOCK_CHECK_REPLY (%i, size=%i)",
188              to_c_str(message.type), (int)message.type, (int)s, (int)MessageType::DEADLOCK_CHECK_REPLY,
189              (int)sizeof(message));
190
191   if (message.value != 0) {
192     XBT_CINFO(mc_global, "**************************");
193     XBT_CINFO(mc_global, "*** DEADLOCK DETECTED ***");
194     XBT_CINFO(mc_global, "**************************");
195     XBT_CINFO(mc_global, "Counter-example execution trace:");
196     for (auto const& frame : model_checker_->get_exploration()->get_textual_trace())
197       XBT_CINFO(mc_global, "  %s", frame.c_str());
198     XBT_CINFO(mc_global, "Path = %s", model_checker_->get_exploration()->get_record_trace().to_string().c_str());
199     model_checker_->get_exploration()->log_state();
200     throw DeadlockError();
201   }
202 }
203 } // namespace simgrid::mc