Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
b5baea4270e1aab24b3aa0a45c5c812a4e2042cf
[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/Transition.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 // 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   if ((_sg_mc_dot_output_file != nullptr) && (_sg_mc_dot_output_file[0] != '\0'))
115     MC_init_dot_output();
116
117   setup_ignore();
118
119   ptrace(PTRACE_SETOPTIONS, pid, nullptr, PTRACE_O_TRACEEXIT);
120   ptrace(PTRACE_CONT, pid, 0, 0);
121 }
122
123 static const std::pair<const char*, const char*> ignored_local_variables[] = {
124   std::pair<const char*, const char*>{  "e", "*" },
125   std::pair<const char*, const char*>{ "__ex_cleanup", "*" },
126   std::pair<const char*, const char*>{ "__ex_mctx_en", "*" },
127   std::pair<const char*, const char*>{ "__ex_mctx_me", "*" },
128   std::pair<const char*, const char*>{ "__xbt_ex_ctx_ptr", "*" },
129   std::pair<const char*, const char*>{ "_log_ev", "*" },
130   std::pair<const char*, const char*>{ "_throw_ctx", "*" },
131   std::pair<const char*, const char*>{ "ctx", "*" },
132
133   std::pair<const char*, const char*>{ "self", "simcall_BODY_mc_snapshot" },
134   std::pair<const char*, const char*>{ "next_context", "smx_ctx_sysv_suspend_serial" },
135   std::pair<const char*, const char*>{ "i", "smx_ctx_sysv_suspend_serial" },
136
137   /* Ignore local variable about time used for tracing */
138   std::pair<const char*, const char*>{ "start_time", "*" },
139 };
140
141 void ModelChecker::setup_ignore()
142 {
143   Process& process = this->process();
144   for (std::pair<const char*, const char*> const& var :
145       ignored_local_variables)
146     process.ignore_local_variable(var.first, var.second);
147
148   /* Static variable used for tracing */
149   process.ignore_global_variable("counter");
150
151   /* SIMIX */
152   process.ignore_global_variable("smx_total_comms");
153 }
154
155 void ModelChecker::shutdown()
156 {
157   XBT_DEBUG("Shuting down model-checker");
158
159   simgrid::mc::Process* process = &this->process();
160   if (process->running()) {
161     XBT_DEBUG("Killing process");
162     kill(process->pid(), SIGTERM);
163     process->terminate();
164   }
165 }
166
167 void ModelChecker::resume(simgrid::mc::Process& process)
168 {
169   int res = process.getChannel().send(MC_MESSAGE_CONTINUE);
170   if (res)
171     throw simgrid::xbt::errno_error(res);
172   process.clear_cache();
173 }
174
175 static
176 void throw_socket_error(int fd)
177 {
178   int error = 0;
179   socklen_t errlen = sizeof(error);
180   if (getsockopt(fd, SOL_SOCKET, SO_ERROR, (void *)&error, &errlen) == -1)
181     error = errno;
182   throw simgrid::xbt::errno_error(errno);
183 }
184
185 bool ModelChecker::handle_message(char* buffer, ssize_t size)
186 {
187   s_mc_message_t base_message;
188   if (size < (ssize_t) sizeof(base_message))
189     xbt_die("Broken message");
190   memcpy(&base_message, buffer, sizeof(base_message));
191
192   switch(base_message.type) {
193
194   case MC_MESSAGE_IGNORE_HEAP:
195     {
196       s_mc_ignore_heap_message_t message;
197       if (size != sizeof(message))
198         xbt_die("Broken messsage");
199       memcpy(&message, buffer, sizeof(message));
200
201       IgnoredHeapRegion region;
202       region.block = message.block;
203       region.fragment = message.fragment;
204       region.address = message.address;
205       region.size = message.size;
206       process().ignore_heap(region);
207       break;
208     }
209
210   case MC_MESSAGE_UNIGNORE_HEAP:
211     {
212       s_mc_ignore_memory_message_t message;
213       if (size != sizeof(message))
214         xbt_die("Broken messsage");
215       memcpy(&message, buffer, sizeof(message));
216       process().unignore_heap(
217         (void *)(std::uintptr_t) message.addr, message.size);
218       break;
219     }
220
221   case MC_MESSAGE_IGNORE_MEMORY:
222     {
223       s_mc_ignore_memory_message_t message;
224       if (size != sizeof(message))
225         xbt_die("Broken messsage");
226       memcpy(&message, buffer, sizeof(message));
227       this->process().ignore_region(message.addr, message.size);
228       break;
229     }
230
231   case MC_MESSAGE_STACK_REGION:
232     {
233       s_mc_stack_region_message_t message;
234       if (size != sizeof(message))
235         xbt_die("Broken messsage");
236       memcpy(&message, buffer, sizeof(message));
237       this->process().stack_areas().push_back(message.stack_region);
238     }
239     break;
240
241   case MC_MESSAGE_REGISTER_SYMBOL:
242     {
243       s_mc_register_symbol_message_t message;
244       if (size != sizeof(message))
245         xbt_die("Broken message");
246       memcpy(&message, buffer, sizeof(message));
247       if (message.callback)
248         xbt_die("Support for client-side function proposition is not implemented.");
249       XBT_DEBUG("Received symbol: %s", message.name);
250
251       if (simgrid::mc::property_automaton == nullptr)
252         simgrid::mc::property_automaton = xbt_automaton_new();
253
254       simgrid::mc::Process* process = &this->process();
255       simgrid::mc::RemotePtr<int> address
256         = simgrid::mc::remote((int*) message.data);
257       simgrid::xbt::add_proposition(simgrid::mc::property_automaton,
258         message.name,
259         [process, address]() { return process->read(address); }
260         );
261
262       break;
263     }
264
265   case MC_MESSAGE_WAITING:
266     return false;
267
268   case MC_MESSAGE_ASSERTION_FAILED:
269     MC_report_assertion_error();
270     this->exit(SIMGRID_MC_EXIT_SAFETY);
271     break;
272
273   default:
274     xbt_die("Unexpected message from model-checked application");
275
276   }
277   return true;
278 }
279
280 /** Terminate the model-checker aplication */
281 void ModelChecker::exit(int status)
282 {
283   // TODO, terminate the model checker politely instead of exiting rudel
284   if (process().running())
285     kill(process().pid(), SIGKILL);
286   ::exit(status);
287 }
288
289 bool ModelChecker::handle_events()
290 {
291   char buffer[MC_MESSAGE_LENGTH];
292   struct pollfd* socket_pollfd = &fds_[SOCKET_FD_INDEX];
293   struct pollfd* signalfd_pollfd = &fds_[SIGNAL_FD_INDEX];
294
295   while(poll(fds_, 2, -1) == -1) {
296     switch(errno) {
297     case EINTR:
298       continue;
299     default:
300       throw simgrid::xbt::errno_error(errno);
301     }
302   }
303
304   if (socket_pollfd->revents) {
305     if (socket_pollfd->revents & POLLIN) {
306       ssize_t size = process_->getChannel().receive(buffer, sizeof(buffer), false);
307       if (size == -1 && errno != EAGAIN)
308         throw simgrid::xbt::errno_error(errno);
309       return handle_message(buffer, size);
310     }
311     if (socket_pollfd->revents & POLLERR)
312       throw_socket_error(socket_pollfd->fd);
313     if (socket_pollfd->revents & POLLHUP)
314       xbt_die("Socket hang up?");
315   }
316
317   if (signalfd_pollfd->revents) {
318     if (signalfd_pollfd->revents & POLLIN) {
319       this->handle_signals();
320       return true;
321     }
322     if (signalfd_pollfd->revents & POLLERR)
323       throw_socket_error(signalfd_pollfd->fd);
324     if (signalfd_pollfd->revents & POLLHUP)
325       xbt_die("Signalfd hang up?");
326   }
327
328   return true;
329 }
330
331 void ModelChecker::loop()
332 {
333   while (this->process().running())
334     this->handle_events();
335 }
336
337 void ModelChecker::handle_signals()
338 {
339   struct signalfd_siginfo info;
340   struct pollfd* signalfd_pollfd = &fds_[SIGNAL_FD_INDEX];
341   while (1) {
342     ssize_t size = read(signalfd_pollfd->fd, &info, sizeof(info));
343     if (size == -1) {
344       if (errno == EINTR)
345         continue;
346       else
347         throw simgrid::xbt::errno_error(errno);
348     } else if (size != sizeof(info))
349         return throw std::runtime_error(
350           "Bad communication with model-checked application");
351     else
352       break;
353   }
354   this->on_signal(&info);
355 }
356
357 void ModelChecker::handle_waitpid()
358 {
359   XBT_DEBUG("Check for wait event");
360   int status;
361   pid_t pid;
362   while ((pid = waitpid(-1, &status, WNOHANG)) != 0) {
363     if (pid == -1) {
364       if (errno == ECHILD) {
365         // No more children:
366         if (this->process().running())
367           xbt_die("Inconsistent state");
368         else
369           break;
370       } else {
371         XBT_ERROR("Could not wait for pid");
372         throw simgrid::xbt::errno_error(errno);
373       }
374     }
375
376     if (pid == this->process().pid()) {
377
378       // From PTRACE_O_TRACEEXIT:
379       if (status>>8 == (SIGTRAP | (PTRACE_EVENT_EXIT<<8))) {
380         if (ptrace(PTRACE_GETEVENTMSG, this->process().pid(), 0, &status) == -1)
381           xbt_die("Could not get exit status");
382         if (WIFSIGNALED(status)) {
383           MC_report_crash(status);
384           mc_model_checker->exit(SIMGRID_MC_EXIT_PROGRAM_CRASH);
385         }
386       }
387
388       // We don't care about signals, just reinject them:
389       if (WIFSTOPPED(status)) {
390         XBT_DEBUG("Stopped with signal %i", (int) WSTOPSIG(status));
391         if (ptrace(PTRACE_CONT, this->process().pid(), 0, WSTOPSIG(status)) == -1)
392           xbt_die("Could not PTRACE_CONT");
393       }
394
395       else if (WIFEXITED(status) || WIFSIGNALED(status)) {
396         XBT_DEBUG("Child process is over");
397         this->process().terminate();
398       }
399     }
400   }
401 }
402
403 void ModelChecker::on_signal(const struct signalfd_siginfo* info)
404 {
405   switch(info->ssi_signo) {
406   case SIGCHLD:
407     this->handle_waitpid();
408     break;
409   default:
410     break;
411   }
412 }
413
414 void ModelChecker::wait_client(simgrid::mc::Process& process)
415 {
416   this->resume(process);
417   while (this->process().running())
418     if (!this->handle_events())
419       return;
420 }
421
422 void ModelChecker::handle_simcall(Transition const& transition)
423 {
424   s_mc_simcall_handle_message m;
425   memset(&m, 0, sizeof(m));
426   m.type  = MC_MESSAGE_SIMCALL_HANDLE;
427   m.pid   = transition.pid;
428   m.value = transition.argument;
429   this->process_->getChannel().send(m);
430   this->process_->clear_cache();
431   while (this->process_->running())
432     if (!this->handle_events())
433       return;
434 }
435
436 bool ModelChecker::checkDeadlock()
437 {
438   int res;
439   if ((res = this->process().getChannel().send(MC_MESSAGE_DEADLOCK_CHECK)))
440     xbt_die("Could not check deadlock state");
441   s_mc_int_message_t message;
442   ssize_t s = mc_model_checker->process().getChannel().receive(message);
443   if (s == -1)
444     xbt_die("Could not receive message");
445   if (s != sizeof(message) || message.type != MC_MESSAGE_DEADLOCK_CHECK_REPLY)
446     xbt_die("%s received unexpected message %s (%i, size=%i) "
447       "expected MC_MESSAGE_DEADLOCK_CHECK_REPLY (%i, size=%i)",
448       MC_mode_name(mc_mode),
449       MC_message_type_name(message.type), (int) message.type, (int) s,
450       (int) MC_MESSAGE_DEADLOCK_CHECK_REPLY, (int) sizeof(message)
451       );
452   return message.value != 0;
453 }
454
455 }
456 }