Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Free xbt_automaton on Api::s_close.
[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   if (mc_model_checker->get_exploration()) {
139     XBT_INFO("Counter-example execution trace:");
140     for (auto const& s : mc_model_checker->get_exploration()->get_textual_trace())
141       XBT_INFO("  %s", s.c_str());
142     XBT_INFO("Path = %s", mc_model_checker->get_exploration()->get_record_trace().to_string().c_str());
143     session_singleton->log_state();
144     if (xbt_log_no_loc) {
145       XBT_INFO("Stack trace not displayed because you passed --log=no_loc");
146     } else {
147       XBT_INFO("Stack trace:");
148       mc_model_checker->get_remote_process().dump_stack();
149     }
150   }
151 }
152
153 bool ModelChecker::handle_message(const char* buffer, ssize_t size)
154 {
155   s_mc_message_t base_message;
156   xbt_assert(size >= (ssize_t)sizeof(base_message), "Broken message");
157   memcpy(&base_message, buffer, sizeof(base_message));
158
159   switch(base_message.type) {
160     case MessageType::INITIAL_ADDRESSES: {
161       s_mc_message_initial_addresses_t message;
162       xbt_assert(size == sizeof(message), "Broken message. Got %d bytes instead of %d.", (int)size, (int)sizeof(message));
163       memcpy(&message, buffer, sizeof(message));
164
165       get_remote_process().init(message.mmalloc_default_mdp, message.maxpid, message.actors, message.dead_actors);
166       break;
167     }
168
169     case MessageType::IGNORE_HEAP: {
170       s_mc_message_ignore_heap_t message;
171       xbt_assert(size == sizeof(message), "Broken message");
172       memcpy(&message, buffer, sizeof(message));
173
174       IgnoredHeapRegion region;
175       region.block    = message.block;
176       region.fragment = message.fragment;
177       region.address  = message.address;
178       region.size     = message.size;
179       get_remote_process().ignore_heap(region);
180       break;
181     }
182
183     case MessageType::UNIGNORE_HEAP: {
184       s_mc_message_ignore_memory_t message;
185       xbt_assert(size == sizeof(message), "Broken message");
186       memcpy(&message, buffer, sizeof(message));
187       get_remote_process().unignore_heap((void*)(std::uintptr_t)message.addr, message.size);
188       break;
189     }
190
191     case MessageType::IGNORE_MEMORY: {
192       s_mc_message_ignore_memory_t message;
193       xbt_assert(size == sizeof(message), "Broken message");
194       memcpy(&message, buffer, sizeof(message));
195       this->get_remote_process().ignore_region(message.addr, message.size);
196       break;
197     }
198
199     case MessageType::STACK_REGION: {
200       s_mc_message_stack_region_t message;
201       xbt_assert(size == sizeof(message), "Broken message");
202       memcpy(&message, buffer, sizeof(message));
203       this->get_remote_process().stack_areas().push_back(message.stack_region);
204     } break;
205
206     case MessageType::REGISTER_SYMBOL: {
207       s_mc_message_register_symbol_t message;
208       xbt_assert(size == sizeof(message), "Broken message");
209       memcpy(&message, buffer, sizeof(message));
210       xbt_assert(not message.callback, "Support for client-side function proposition is not implemented.");
211       XBT_DEBUG("Received symbol: %s", message.name.data());
212
213       if (property_automaton == nullptr)
214         property_automaton = xbt_automaton_new();
215
216       const RemoteProcess* process    = &this->get_remote_process();
217       RemotePtr<int> address          = remote((int*)message.data);
218       xbt::add_proposition(property_automaton, message.name.data(),
219                            [process, address]() { return process->read(address); });
220
221       break;
222     }
223
224     case MessageType::WAITING:
225       return false;
226
227     case MessageType::ASSERTION_FAILED:
228       XBT_INFO("**************************");
229       XBT_INFO("*** PROPERTY NOT VALID ***");
230       XBT_INFO("**************************");
231       XBT_INFO("Counter-example execution trace:");
232       for (auto const& s : get_exploration()->get_textual_trace())
233         XBT_INFO("  %s", s.c_str());
234       XBT_INFO("Path = %s", get_exploration()->get_record_trace().to_string().c_str());
235       session_singleton->log_state();
236
237       this->exit(SIMGRID_MC_EXIT_SAFETY);
238
239     default:
240       xbt_die("Unexpected message from model-checked application");
241   }
242   return true;
243 }
244
245 /** Terminate the model-checker application */
246 void ModelChecker::exit(int status)
247 {
248   shutdown();
249   ::exit(status);
250 }
251
252 void ModelChecker::handle_waitpid()
253 {
254   XBT_DEBUG("Check for wait event");
255   int status;
256   pid_t pid;
257   while ((pid = waitpid(-1, &status, WNOHANG)) != 0) {
258     if (pid == -1) {
259       if (errno == ECHILD) {
260         // No more children:
261         xbt_assert(not this->get_remote_process().running(), "Inconsistent state");
262         break;
263       } else {
264         XBT_ERROR("Could not wait for pid");
265         throw simgrid::xbt::errno_error();
266       }
267     }
268
269     if (pid == this->get_remote_process().pid()) {
270       // From PTRACE_O_TRACEEXIT:
271 #ifdef __linux__
272       if (status>>8 == (SIGTRAP | (PTRACE_EVENT_EXIT<<8))) {
273         xbt_assert(ptrace(PTRACE_GETEVENTMSG, remote_process_->pid(), 0, &status) != -1, "Could not get exit status");
274         if (WIFSIGNALED(status)) {
275           MC_report_crash(status);
276           this->get_remote_process().terminate();
277           this->exit(SIMGRID_MC_EXIT_PROGRAM_CRASH);
278         }
279       }
280 #endif
281
282       // We don't care about signals, just reinject them:
283       if (WIFSTOPPED(status)) {
284         XBT_DEBUG("Stopped with signal %i", (int) WSTOPSIG(status));
285         errno = 0;
286 #ifdef __linux__
287         ptrace(PTRACE_CONT, remote_process_->pid(), 0, WSTOPSIG(status));
288 #elif defined BSD
289         ptrace(PT_CONTINUE, remote_process_->pid(), (caddr_t)1, WSTOPSIG(status));
290 #endif
291         xbt_assert(errno == 0, "Could not PTRACE_CONT");
292       }
293
294       else if (WIFSIGNALED(status)) {
295         MC_report_crash(status);
296         this->get_remote_process().terminate();
297         this->exit(SIMGRID_MC_EXIT_PROGRAM_CRASH);
298       } else if (WIFEXITED(status)) {
299         XBT_DEBUG("Child process is over");
300         this->get_remote_process().terminate();
301       }
302     }
303   }
304 }
305
306 void ModelChecker::wait_for_requests()
307 {
308   this->resume();
309   if (this->get_remote_process().running())
310     checker_side_.dispatch();
311 }
312
313 Transition* ModelChecker::handle_simcall(aid_t aid, int times_considered, bool new_transition)
314 {
315   s_mc_message_simcall_execute_t m;
316   memset(&m, 0, sizeof(m));
317   m.type              = MessageType::SIMCALL_EXECUTE;
318   m.aid_              = aid;
319   m.times_considered_ = times_considered;
320   checker_side_.get_channel().send(m);
321
322   this->remote_process_->clear_cache();
323   if (this->remote_process_->running())
324     checker_side_.dispatch(); // The app may send messages while processing the transition
325
326   s_mc_message_simcall_execute_answer_t answer;
327   ssize_t s = checker_side_.get_channel().receive(answer);
328   xbt_assert(s != -1, "Could not receive message");
329   xbt_assert(s == sizeof(answer) && answer.type == MessageType::SIMCALL_EXECUTE_ANSWER,
330              "Received unexpected message %s (%i, size=%i) "
331              "expected MessageType::SIMCALL_EXECUTE_ANSWER (%i, size=%i)",
332              to_c_str(answer.type), (int)answer.type, (int)s, (int)MessageType::SIMCALL_EXECUTE_ANSWER,
333              (int)sizeof(answer));
334
335   if (new_transition) {
336     std::stringstream stream(answer.buffer.data());
337     return deserialize_transition(aid, times_considered, stream);
338   } else
339     return nullptr;
340 }
341
342 void ModelChecker::finalize_app(bool terminate_asap)
343 {
344   s_mc_message_int_t m;
345   memset(&m, 0, sizeof m);
346   m.type  = MessageType::FINALIZE;
347   m.value = terminate_asap;
348   xbt_assert(checker_side_.get_channel().send(m) == 0, "Could not ask the app to finalize on need");
349
350   s_mc_message_t answer;
351   xbt_assert(checker_side_.get_channel().receive(answer) != -1, "Could not receive answer to FINALIZE");
352 }
353
354 } // namespace mc
355 } // namespace simgrid