Logo AND Algorithmique Numérique Distribuée

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