Logo AND Algorithmique Numérique Distribuée

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