Logo AND Algorithmique Numérique Distribuée

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