Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
4489b8473eaa5bd0844e9dfecf14b3c027acd80a
[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 <poll.h>
10 #include <sys/types.h>
11 #include <sys/wait.h>
12 #include <sys/socket.h>
13 #include <sys/signalfd.h>
14 #include <sys/ptrace.h>
15
16 #include <memory>
17 #include <system_error>
18
19 #include <xbt/log.h>
20 #include <xbt/automaton.h>
21 #include <xbt/automaton.hpp>
22 #include <xbt/system_error.hpp>
23
24 #include "simgrid/sg_config.h"
25
26 #include "src/mc/ModelChecker.hpp"
27 #include "src/mc/PageStore.hpp"
28 #include "src/mc/ModelChecker.hpp"
29 #include "src/mc/mc_protocol.h"
30 #include "src/mc/mc_private.h"
31 #include "src/mc/mc_ignore.h"
32 #include "src/mc/mc_exit.h"
33 #include "src/mc/mc_liveness.h"
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 // Hardcoded index for now:
42 #define SOCKET_FD_INDEX 0
43 #define SIGNAL_FD_INDEX 1
44
45 namespace simgrid {
46 namespace mc {
47
48 ModelChecker::ModelChecker(std::unique_ptr<Process> process) :
49   hostnames_(xbt_dict_new()),
50   page_store_(500),
51   process_(std::move(process)),
52   parent_snapshot_(nullptr)
53 {
54
55 }
56
57 ModelChecker::~ModelChecker()
58 {
59   xbt_dict_free(&this->hostnames_);
60 }
61
62 const char* ModelChecker::get_host_name(const char* hostname)
63 {
64   // Lookup the host name in the dictionary (or create it):
65   xbt_dictelm_t elt = xbt_dict_get_elm_or_null(this->hostnames_, hostname);
66   if (!elt) {
67     xbt_dict_set(this->hostnames_, hostname, nullptr, nullptr);
68     elt = xbt_dict_get_elm_or_null(this->hostnames_, hostname);
69     assert(elt);
70   }
71   return elt->key;
72 }
73
74 void ModelChecker::start()
75 {
76   const pid_t pid = process_->pid();
77
78   // Block SIGCHLD (this will be handled with accept/signalfd):
79   sigset_t set;
80   sigemptyset(&set);
81   sigaddset(&set, SIGCHLD);
82   if (sigprocmask(SIG_BLOCK, &set, nullptr) == -1)
83     throw simgrid::xbt::errno_error(errno);
84
85   sigset_t full_set;
86   sigfillset(&full_set);
87
88   // Prepare data for poll:
89
90   struct pollfd* socket_pollfd = &fds_[SOCKET_FD_INDEX];
91   socket_pollfd->fd = process_->getChannel().getSocket();
92   socket_pollfd->events = POLLIN;
93   socket_pollfd->revents = 0;
94
95   int signal_fd = signalfd(-1, &set, 0);
96   if (signal_fd == -1)
97     throw simgrid::xbt::errno_error(errno);
98
99   struct pollfd* signalfd_pollfd = &fds_[SIGNAL_FD_INDEX];
100   signalfd_pollfd->fd = signal_fd;
101   signalfd_pollfd->events = POLLIN;
102   signalfd_pollfd->revents = 0;
103
104   XBT_DEBUG("Waiting for the model-checked process");
105   int status;
106
107   // The model-checked process SIGSTOP itself to signal it's ready:
108   pid_t res = waitpid(pid, &status, __WALL);
109   if (res < 0 || !WIFSTOPPED(status) || WSTOPSIG(status) != SIGSTOP)
110     xbt_die("Could not wait model-checked process");
111
112   process_->init();
113
114   /* Initialize statistics */
115   mc_stats = xbt_new0(s_mc_stats_t, 1);
116   mc_stats->state_size = 1;
117
118   if ((_sg_mc_dot_output_file != nullptr) && (_sg_mc_dot_output_file[0] != '\0'))
119     MC_init_dot_output();
120
121   setup_ignore();
122
123   ptrace(PTRACE_SETOPTIONS, pid, nullptr, PTRACE_O_TRACEEXIT);
124   ptrace(PTRACE_CONT, pid, 0, 0);
125 }
126
127 static const std::pair<const char*, const char*> ignored_local_variables[] = {
128   std::pair<const char*, const char*>{  "e", "*" },
129   std::pair<const char*, const char*>{ "__ex_cleanup", "*" },
130   std::pair<const char*, const char*>{ "__ex_mctx_en", "*" },
131   std::pair<const char*, const char*>{ "__ex_mctx_me", "*" },
132   std::pair<const char*, const char*>{ "__xbt_ex_ctx_ptr", "*" },
133   std::pair<const char*, const char*>{ "_log_ev", "*" },
134   std::pair<const char*, const char*>{ "_throw_ctx", "*" },
135   std::pair<const char*, const char*>{ "ctx", "*" },
136
137   std::pair<const char*, const char*>{ "self", "simcall_BODY_mc_snapshot" },
138   std::pair<const char*, const char*>{ "next_context", "smx_ctx_sysv_suspend_serial" },
139   std::pair<const char*, const char*>{ "i", "smx_ctx_sysv_suspend_serial" },
140
141   /* Ignore local variable about time used for tracing */
142   std::pair<const char*, const char*>{ "start_time", "*" },
143 };
144
145 void ModelChecker::setup_ignore()
146 {
147   Process& process = this->process();
148   for (std::pair<const char*, const char*> const& var :
149       ignored_local_variables)
150     process.ignore_local_variable(var.first, var.second);
151
152   /* Static variable used for tracing */
153   process.ignore_global_variable("counter");
154
155   /* SIMIX */
156   process.ignore_global_variable("smx_total_comms");
157 }
158
159 void ModelChecker::shutdown()
160 {
161   XBT_DEBUG("Shuting down model-checker");
162
163   simgrid::mc::Process* process = &this->process();
164   if (process->running()) {
165     XBT_DEBUG("Killing process");
166     kill(process->pid(), SIGTERM);
167     process->terminate();
168   }
169 }
170
171 void ModelChecker::resume(simgrid::mc::Process& process)
172 {
173   int res = process.getChannel().send(MC_MESSAGE_CONTINUE);
174   if (res)
175     throw simgrid::xbt::errno_error(res);
176   process.clear_cache();
177 }
178
179 static
180 void throw_socket_error(int fd)
181 {
182   int error = 0;
183   socklen_t errlen = sizeof(error);
184   if (getsockopt(fd, SOL_SOCKET, SO_ERROR, (void *)&error, &errlen) == -1)
185     error = errno;
186   throw simgrid::xbt::errno_error(errno);
187 }
188
189 bool ModelChecker::handle_message(char* buffer, ssize_t size)
190 {
191   s_mc_message_t base_message;
192   if (size < (ssize_t) sizeof(base_message))
193     xbt_die("Broken message");
194   memcpy(&base_message, buffer, sizeof(base_message));
195
196   switch(base_message.type) {
197
198   case MC_MESSAGE_IGNORE_HEAP:
199     {
200       s_mc_ignore_heap_message_t message;
201       if (size != sizeof(message))
202         xbt_die("Broken messsage");
203       memcpy(&message, buffer, sizeof(message));
204
205       IgnoredHeapRegion region;
206       region.block = message.block;
207       region.fragment = message.fragment;
208       region.address = message.address;
209       region.size = message.size;
210       process().ignore_heap(region);
211       break;
212     }
213
214   case MC_MESSAGE_UNIGNORE_HEAP:
215     {
216       s_mc_ignore_memory_message_t message;
217       if (size != sizeof(message))
218         xbt_die("Broken messsage");
219       memcpy(&message, buffer, sizeof(message));
220       process().unignore_heap(
221         (void *)(std::uintptr_t) message.addr, message.size);
222       break;
223     }
224
225   case MC_MESSAGE_IGNORE_MEMORY:
226     {
227       s_mc_ignore_memory_message_t message;
228       if (size != sizeof(message))
229         xbt_die("Broken messsage");
230       memcpy(&message, buffer, sizeof(message));
231       this->process().ignore_region(message.addr, message.size);
232       break;
233     }
234
235   case MC_MESSAGE_STACK_REGION:
236     {
237       s_mc_stack_region_message_t message;
238       if (size != sizeof(message))
239         xbt_die("Broken messsage");
240       memcpy(&message, buffer, sizeof(message));
241       this->process().stack_areas().push_back(message.stack_region);
242     }
243     break;
244
245   case MC_MESSAGE_REGISTER_SYMBOL:
246     {
247       s_mc_register_symbol_message_t message;
248       if (size != sizeof(message))
249         xbt_die("Broken message");
250       memcpy(&message, buffer, sizeof(message));
251       if (message.callback)
252         xbt_die("Support for client-side function proposition is not implemented.");
253       XBT_DEBUG("Received symbol: %s", message.name);
254
255       if (simgrid::mc::property_automaton == nullptr)
256         simgrid::mc::property_automaton = xbt_automaton_new();
257
258       simgrid::mc::Process* process = &this->process();
259       simgrid::mc::RemotePtr<int> address
260         = simgrid::mc::remote((int*) message.data);
261       simgrid::xbt::add_proposition(simgrid::mc::property_automaton,
262         message.name,
263         [process, address]() { return process->read(address); }
264         );
265
266       break;
267     }
268
269   case MC_MESSAGE_WAITING:
270     return false;
271
272   case MC_MESSAGE_ASSERTION_FAILED:
273     MC_report_assertion_error();
274     this->exit(SIMGRID_MC_EXIT_SAFETY);
275     break;
276
277   default:
278     xbt_die("Unexpected message from model-checked application");
279
280   }
281   return true;
282 }
283
284 /** Terminate the model-checker aplication */
285 void ModelChecker::exit(int status)
286 {
287   // TODO, terminate the model checker politely instead of exiting rudel
288   if (process().running())
289     kill(process().pid(), SIGKILL);
290   ::exit(status);
291 }
292
293 bool ModelChecker::handle_events()
294 {
295   char buffer[MC_MESSAGE_LENGTH];
296   struct pollfd* socket_pollfd = &fds_[SOCKET_FD_INDEX];
297   struct pollfd* signalfd_pollfd = &fds_[SIGNAL_FD_INDEX];
298
299   while(poll(fds_, 2, -1) == -1) {
300     switch(errno) {
301     case EINTR:
302       continue;
303     default:
304       throw simgrid::xbt::errno_error(errno);
305     }
306   }
307
308   if (socket_pollfd->revents) {
309     if (socket_pollfd->revents & POLLIN) {
310       ssize_t size = process_->getChannel().receive(buffer, sizeof(buffer), false);
311       if (size == -1 && errno != EAGAIN)
312         throw simgrid::xbt::errno_error(errno);
313       return handle_message(buffer, size);
314     }
315     if (socket_pollfd->revents & POLLERR)
316       throw_socket_error(socket_pollfd->fd);
317     if (socket_pollfd->revents & POLLHUP)
318       xbt_die("Socket hang up?");
319   }
320
321   if (signalfd_pollfd->revents) {
322     if (signalfd_pollfd->revents & POLLIN) {
323       this->handle_signals();
324       return true;
325     }
326     if (signalfd_pollfd->revents & POLLERR)
327       throw_socket_error(signalfd_pollfd->fd);
328     if (signalfd_pollfd->revents & POLLHUP)
329       xbt_die("Signalfd hang up?");
330   }
331
332   return true;
333 }
334
335 void ModelChecker::loop()
336 {
337   while (this->process().running())
338     this->handle_events();
339 }
340
341 void ModelChecker::handle_signals()
342 {
343   struct signalfd_siginfo info;
344   struct pollfd* signalfd_pollfd = &fds_[SIGNAL_FD_INDEX];
345   while (1) {
346     ssize_t size = read(signalfd_pollfd->fd, &info, sizeof(info));
347     if (size == -1) {
348       if (errno == EINTR)
349         continue;
350       else
351         throw simgrid::xbt::errno_error(errno);
352     } else if (size != sizeof(info))
353         return throw std::runtime_error(
354           "Bad communication with model-checked application");
355     else
356       break;
357   }
358   this->on_signal(&info);
359 }
360
361 void ModelChecker::handle_waitpid()
362 {
363   XBT_DEBUG("Check for wait event");
364   int status;
365   pid_t pid;
366   while ((pid = waitpid(-1, &status, WNOHANG)) != 0) {
367     if (pid == -1) {
368       if (errno == ECHILD) {
369         // No more children:
370         if (this->process().running())
371           xbt_die("Inconsistent state");
372         else
373           break;
374       } else {
375         XBT_ERROR("Could not wait for pid");
376         throw simgrid::xbt::errno_error(errno);
377       }
378     }
379
380     if (pid == this->process().pid()) {
381
382       // From PTRACE_O_TRACEEXIT:
383       if (status>>8 == (SIGTRAP | (PTRACE_EVENT_EXIT<<8))) {
384         if (ptrace(PTRACE_GETEVENTMSG, this->process().pid(), 0, &status) == -1)
385           xbt_die("Could not get exit status");
386         if (WIFSIGNALED(status)) {
387           MC_report_crash(status);
388           mc_model_checker->exit(SIMGRID_MC_EXIT_PROGRAM_CRASH);
389         }
390       }
391
392       // We don't care about signals, just reinject them:
393       if (WIFSTOPPED(status)) {
394         XBT_DEBUG("Stopped with signal %i", (int) WSTOPSIG(status));
395         if (ptrace(PTRACE_CONT, this->process().pid(), 0, WSTOPSIG(status)) == -1)
396           xbt_die("Could not PTRACE_CONT");
397       }
398
399       else if (WIFEXITED(status) || WIFSIGNALED(status)) {
400         XBT_DEBUG("Child process is over");
401         this->process().terminate();
402       }
403     }
404   }
405 }
406
407 void ModelChecker::on_signal(const struct signalfd_siginfo* info)
408 {
409   switch(info->ssi_signo) {
410   case SIGCHLD:
411     this->handle_waitpid();
412     break;
413   default:
414     break;
415   }
416 }
417
418 void ModelChecker::wait_client(simgrid::mc::Process& process)
419 {
420   this->resume(process);
421   while (this->process().running())
422     if (!this->handle_events())
423       return;
424 }
425
426 void ModelChecker::simcall_handle(simgrid::mc::Process& process, unsigned long pid, int value)
427 {
428   s_mc_simcall_handle_message m;
429   memset(&m, 0, sizeof(m));
430   m.type  = MC_MESSAGE_SIMCALL_HANDLE;
431   m.pid   = pid;
432   m.value = value;
433   process.getChannel().send(m);
434   process.clear_cache();
435   while (process.running())
436     if (!this->handle_events())
437       return;
438 }
439
440 }
441 }