Logo AND Algorithmique Numérique Distribuée

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