Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
deprecate Engine::shutdown()
[simgrid.git] / src / mc / ModelChecker.cpp
1 /* Copyright (c) 2008-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/ModelChecker.hpp"
7 #include "src/mc/Session.hpp"
8 #include "src/mc/explo/Exploration.hpp"
9 #include "src/mc/mc_config.hpp"
10 #include "src/mc/mc_exit.hpp"
11 #include "src/mc/mc_private.hpp"
12 #include "src/mc/remote/RemoteProcess.hpp"
13 #include "src/mc/transition/TransitionComm.hpp"
14 #include "xbt/automaton.hpp"
15 #include "xbt/system_error.hpp"
16
17 #include <array>
18 #include <csignal>
19 #include <sys/ptrace.h>
20 #include <sys/wait.h>
21
22 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(mc_ModelChecker, mc, "ModelChecker");
23
24 ::simgrid::mc::ModelChecker* mc_model_checker = nullptr;
25
26 using simgrid::mc::remote;
27
28 #ifdef __linux__
29 # define WAITPID_CHECKED_FLAGS __WALL
30 #else
31 # define WAITPID_CHECKED_FLAGS 0
32 #endif
33
34 namespace simgrid {
35 namespace mc {
36
37 ModelChecker::ModelChecker(std::unique_ptr<RemoteProcess> remote_simulation, int sockfd)
38     : checker_side_(sockfd), remote_process_(std::move(remote_simulation))
39 {
40 }
41
42 void ModelChecker::start()
43 {
44   checker_side_.start(
45       [](evutil_socket_t sig, short events, void* arg) {
46         auto mc = static_cast<simgrid::mc::ModelChecker*>(arg);
47         if (events == EV_READ) {
48           std::array<char, MC_MESSAGE_LENGTH> buffer;
49           ssize_t size = mc->checker_side_.get_channel().receive(buffer.data(), buffer.size(), false);
50           if (size == -1 && errno != EAGAIN)
51             throw simgrid::xbt::errno_error();
52
53           if (not mc->handle_message(buffer.data(), size))
54             mc->checker_side_.break_loop();
55         } else if (events == EV_SIGNAL) {
56           if (sig == SIGCHLD)
57             mc->handle_waitpid();
58         } else {
59           xbt_die("Unexpected event");
60         }
61       },
62       this);
63
64   XBT_DEBUG("Waiting for the model-checked process");
65   int status;
66
67   // The model-checked process SIGSTOP itself to signal it's ready:
68   const pid_t pid = remote_process_->pid();
69
70   xbt_assert(waitpid(pid, &status, WAITPID_CHECKED_FLAGS) == pid && WIFSTOPPED(status) && WSTOPSIG(status) == SIGSTOP,
71              "Could not wait model-checked process");
72
73   if (not _sg_mc_dot_output_file.get().empty())
74     MC_init_dot_output();
75
76   setup_ignore();
77
78 #ifdef __linux__
79   ptrace(PTRACE_SETOPTIONS, pid, nullptr, PTRACE_O_TRACEEXIT);
80   ptrace(PTRACE_CONT, pid, 0, 0);
81 #elif defined BSD
82   ptrace(PT_CONTINUE, pid, (caddr_t)1, 0);
83 #else
84 # error "no ptrace equivalent coded for this platform"
85 #endif
86 }
87
88 static constexpr auto ignored_local_variables = {
89     std::make_pair("e", "*"),
90     std::make_pair("_log_ev", "*"),
91
92     /* Ignore local variable about time used for tracing */
93     std::make_pair("start_time", "*"),
94 };
95
96 void ModelChecker::setup_ignore()
97 {
98   const RemoteProcess& process = this->get_remote_process();
99   for (auto const& var : ignored_local_variables)
100     process.ignore_local_variable(var.first, var.second);
101
102   /* Static variable used for tracing */
103   process.ignore_global_variable("counter");
104 }
105
106 void ModelChecker::shutdown()
107 {
108   XBT_DEBUG("Shutting down model-checker");
109
110   RemoteProcess& process = get_remote_process();
111   if (process.running()) {
112     XBT_DEBUG("Killing process");
113     finalize_app(true);
114     kill(process.pid(), SIGKILL);
115     process.terminate();
116   }
117 }
118
119 void ModelChecker::resume()
120 {
121   int res = checker_side_.get_channel().send(MessageType::CONTINUE);
122   if (res)
123     throw xbt::errno_error();
124   remote_process_->clear_cache();
125 }
126
127 static void MC_report_crash(int status)
128 {
129   XBT_INFO("**************************");
130   XBT_INFO("** CRASH IN THE PROGRAM **");
131   XBT_INFO("**************************");
132   if (WIFSIGNALED(status))
133     XBT_INFO("From signal: %s", strsignal(WTERMSIG(status)));
134   else if (WIFEXITED(status))
135     XBT_INFO("From exit: %i", WEXITSTATUS(status));
136   if (not xbt_log_no_loc)
137     XBT_INFO("%s core dump was generated by the system.", WCOREDUMP(status) ? "A" : "No");
138   XBT_INFO("Counter-example execution trace:");
139   for (auto const& s : mc_model_checker->get_exploration()->get_textual_trace())
140     XBT_INFO("  %s", s.c_str());
141   XBT_INFO("Path = %s", mc_model_checker->get_exploration()->get_record_trace().to_string().c_str());
142   session_singleton->log_state();
143   if (xbt_log_no_loc) {
144     XBT_INFO("Stack trace not displayed because you passed --log=no_loc");
145   } else {
146     XBT_INFO("Stack trace:");
147     mc_model_checker->get_remote_process().dump_stack();
148   }
149 }
150
151 bool ModelChecker::handle_message(const char* buffer, ssize_t size)
152 {
153   s_mc_message_t base_message;
154   xbt_assert(size >= (ssize_t)sizeof(base_message), "Broken message");
155   memcpy(&base_message, buffer, sizeof(base_message));
156
157   switch(base_message.type) {
158     case MessageType::INITIAL_ADDRESSES: {
159       s_mc_message_initial_addresses_t message;
160       xbt_assert(size == sizeof(message), "Broken message. Got %d bytes instead of %d.", (int)size, (int)sizeof(message));
161       memcpy(&message, buffer, sizeof(message));
162
163       get_remote_process().init(message.mmalloc_default_mdp, message.maxpid, message.actors, message.dead_actors);
164       break;
165     }
166
167     case MessageType::IGNORE_HEAP: {
168       s_mc_message_ignore_heap_t message;
169       xbt_assert(size == sizeof(message), "Broken message");
170       memcpy(&message, buffer, sizeof(message));
171
172       IgnoredHeapRegion region;
173       region.block    = message.block;
174       region.fragment = message.fragment;
175       region.address  = message.address;
176       region.size     = message.size;
177       get_remote_process().ignore_heap(region);
178       break;
179     }
180
181     case MessageType::UNIGNORE_HEAP: {
182       s_mc_message_ignore_memory_t message;
183       xbt_assert(size == sizeof(message), "Broken message");
184       memcpy(&message, buffer, sizeof(message));
185       get_remote_process().unignore_heap((void*)(std::uintptr_t)message.addr, message.size);
186       break;
187     }
188
189     case MessageType::IGNORE_MEMORY: {
190       s_mc_message_ignore_memory_t message;
191       xbt_assert(size == sizeof(message), "Broken message");
192       memcpy(&message, buffer, sizeof(message));
193       this->get_remote_process().ignore_region(message.addr, message.size);
194       break;
195     }
196
197     case MessageType::STACK_REGION: {
198       s_mc_message_stack_region_t message;
199       xbt_assert(size == sizeof(message), "Broken message");
200       memcpy(&message, buffer, sizeof(message));
201       this->get_remote_process().stack_areas().push_back(message.stack_region);
202     } break;
203
204     case MessageType::REGISTER_SYMBOL: {
205       s_mc_message_register_symbol_t message;
206       xbt_assert(size == sizeof(message), "Broken message");
207       memcpy(&message, buffer, sizeof(message));
208       xbt_assert(not message.callback, "Support for client-side function proposition is not implemented.");
209       XBT_DEBUG("Received symbol: %s", message.name.data());
210
211       if (property_automaton == nullptr)
212         property_automaton = xbt_automaton_new();
213
214       const RemoteProcess* process    = &this->get_remote_process();
215       RemotePtr<int> address          = remote((int*)message.data);
216       xbt::add_proposition(property_automaton, message.name.data(),
217                            [process, address]() { return process->read(address); });
218
219       break;
220     }
221
222     case MessageType::WAITING:
223       return false;
224
225     case MessageType::ASSERTION_FAILED:
226       XBT_INFO("**************************");
227       XBT_INFO("*** PROPERTY NOT VALID ***");
228       XBT_INFO("**************************");
229       XBT_INFO("Counter-example execution trace:");
230       for (auto const& s : get_exploration()->get_textual_trace())
231         XBT_INFO("  %s", s.c_str());
232       XBT_INFO("Path = %s", get_exploration()->get_record_trace().to_string().c_str());
233       session_singleton->log_state();
234
235       this->exit(SIMGRID_MC_EXIT_SAFETY);
236
237     default:
238       xbt_die("Unexpected message from model-checked application");
239   }
240   return true;
241 }
242
243 /** Terminate the model-checker application */
244 void ModelChecker::exit(int status)
245 {
246   shutdown();
247   ::exit(status);
248 }
249
250 void ModelChecker::handle_waitpid()
251 {
252   XBT_DEBUG("Check for wait event");
253   int status;
254   pid_t pid;
255   while ((pid = waitpid(-1, &status, WNOHANG)) != 0) {
256     if (pid == -1) {
257       if (errno == ECHILD) {
258         // No more children:
259         xbt_assert(not this->get_remote_process().running(), "Inconsistent state");
260         break;
261       } else {
262         XBT_ERROR("Could not wait for pid");
263         throw simgrid::xbt::errno_error();
264       }
265     }
266
267     if (pid == this->get_remote_process().pid()) {
268       // From PTRACE_O_TRACEEXIT:
269 #ifdef __linux__
270       if (status>>8 == (SIGTRAP | (PTRACE_EVENT_EXIT<<8))) {
271         xbt_assert(ptrace(PTRACE_GETEVENTMSG, remote_process_->pid(), 0, &status) != -1, "Could not get exit status");
272         if (WIFSIGNALED(status)) {
273           MC_report_crash(status);
274           this->get_remote_process().terminate();
275           this->exit(SIMGRID_MC_EXIT_PROGRAM_CRASH);
276         }
277       }
278 #endif
279
280       // We don't care about signals, just reinject them:
281       if (WIFSTOPPED(status)) {
282         XBT_DEBUG("Stopped with signal %i", (int) WSTOPSIG(status));
283         errno = 0;
284 #ifdef __linux__
285         ptrace(PTRACE_CONT, remote_process_->pid(), 0, WSTOPSIG(status));
286 #elif defined BSD
287         ptrace(PT_CONTINUE, remote_process_->pid(), (caddr_t)1, WSTOPSIG(status));
288 #endif
289         xbt_assert(errno == 0, "Could not PTRACE_CONT");
290       }
291
292       else if (WIFSIGNALED(status)) {
293         MC_report_crash(status);
294         this->get_remote_process().terminate();
295         this->exit(SIMGRID_MC_EXIT_PROGRAM_CRASH);
296       } else if (WIFEXITED(status)) {
297         XBT_DEBUG("Child process is over");
298         this->get_remote_process().terminate();
299       }
300     }
301   }
302 }
303
304 void ModelChecker::wait_for_requests()
305 {
306   this->resume();
307   if (this->get_remote_process().running())
308     checker_side_.dispatch();
309 }
310
311 Transition* ModelChecker::handle_simcall(aid_t aid, int times_considered, bool new_transition)
312 {
313   s_mc_message_simcall_execute_t m;
314   memset(&m, 0, sizeof(m));
315   m.type              = MessageType::SIMCALL_EXECUTE;
316   m.aid_              = aid;
317   m.times_considered_ = times_considered;
318   checker_side_.get_channel().send(m);
319
320   this->remote_process_->clear_cache();
321   if (this->remote_process_->running())
322     checker_side_.dispatch(); // The app may send messages while processing the transition
323
324   s_mc_message_simcall_execute_answer_t answer;
325   ssize_t s = checker_side_.get_channel().receive(answer);
326   xbt_assert(s != -1, "Could not receive message");
327   xbt_assert(s == sizeof(answer) && answer.type == MessageType::SIMCALL_EXECUTE_ANSWER,
328              "Received unexpected message %s (%i, size=%i) "
329              "expected MessageType::SIMCALL_EXECUTE_ANSWER (%i, size=%i)",
330              to_c_str(answer.type), (int)answer.type, (int)s, (int)MessageType::SIMCALL_EXECUTE_ANSWER,
331              (int)sizeof(answer));
332
333   if (new_transition) {
334     std::stringstream stream(answer.buffer.data());
335     return deserialize_transition(aid, times_considered, stream);
336   } else
337     return nullptr;
338 }
339
340 void ModelChecker::finalize_app(bool terminate_asap)
341 {
342   s_mc_message_int_t m;
343   memset(&m, 0, sizeof m);
344   m.type  = MessageType::FINALIZE;
345   m.value = terminate_asap;
346   xbt_assert(checker_side_.get_channel().send(m) == 0, "Could not ask the app to finalize on need");
347
348   s_mc_message_t answer;
349   xbt_assert(checker_side_.get_channel().receive(answer) != -1, "Could not receive answer to FINALIZE");
350 }
351
352 } // namespace mc
353 } // namespace simgrid