Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Use simgrid::Host instead of xbt_dictelt_t for root main object
[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
23 #include "simgrid/sg_config.h"
24
25 #include "src/mc/ModelChecker.hpp"
26 #include "src/mc/PageStore.hpp"
27 #include "src/mc/ModelChecker.hpp"
28 #include "src/mc/mc_protocol.h"
29 #include "src/mc/mc_private.h"
30 #include "src/mc/mc_ignore.h"
31 #include "src/mc/mc_exit.h"
32 #include "src/mc/mc_liveness.h"
33
34 extern "C" {
35
36 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(mc_ModelChecker, mc, "ModelChecker");
37
38 }
39
40 ::simgrid::mc::ModelChecker* mc_model_checker = nullptr;
41
42 using simgrid::mc::remote;
43
44 // Hardcoded index for now:
45 #define SOCKET_FD_INDEX 0
46 #define SIGNAL_FD_INDEX 1
47
48 namespace simgrid {
49 namespace mc {
50
51 ModelChecker::ModelChecker(pid_t pid, int socket) :
52   pid_(pid), socket_(socket),
53   hostnames_(xbt_dict_new()),
54   page_store_(500),
55   parent_snapshot_(nullptr)
56 {
57 }
58
59 ModelChecker::~ModelChecker()
60 {
61   xbt_dict_free(&this->hostnames_);
62 }
63
64 const char* ModelChecker::get_host_name(const char* hostname)
65 {
66   // FIXME, simgrid::Host
67   // Lookup the host name in the dictionary (or create it):
68   xbt_dictelm_t elt = xbt_dict_get_elm_or_null(this->hostnames_, hostname);
69   if (!elt) {
70     xbt_dict_set(this->hostnames_, hostname, nullptr, nullptr);
71     elt = xbt_dict_get_elm_or_null(this->hostnames_, hostname);
72     assert(elt);
73   }
74   return elt->key;
75 }
76
77 void ModelChecker::start()
78 {
79   // Block SIGCHLD (this will be handled with accept/signalfd):
80   sigset_t set;
81   sigemptyset(&set);
82   sigaddset(&set, SIGCHLD);
83   if (sigprocmask(SIG_BLOCK, &set, nullptr) == -1)
84     throw std::system_error(errno, std::system_category());
85
86   sigset_t full_set;
87   sigfillset(&full_set);
88
89   // Prepare data for poll:
90
91   struct pollfd* socket_pollfd = &fds_[SOCKET_FD_INDEX];
92   socket_pollfd->fd = socket_;
93   socket_pollfd->events = POLLIN;
94   socket_pollfd->revents = 0;
95
96   int signal_fd = signalfd(-1, &set, 0);
97   if (signal_fd == -1)
98     throw std::system_error(errno, std::system_category());
99
100   struct pollfd* signalfd_pollfd = &fds_[SIGNAL_FD_INDEX];
101   signalfd_pollfd->fd = signal_fd;
102   signalfd_pollfd->events = POLLIN;
103   signalfd_pollfd->revents = 0;
104
105   XBT_DEBUG("Waiting for the model-checked process");
106   int status;
107
108   // The model-checked process SIGSTOP itself to signal it's ready:
109   pid_t res = waitpid(pid_, &status, __WALL);
110   if (res < 0 || !WIFSTOPPED(status) || WSTOPSIG(status) != SIGSTOP)
111     xbt_die("Could not wait model-checked process");
112
113   assert(process_ == nullptr);
114   process_ = std::unique_ptr<Process>(new Process(pid_, socket_));
115   // TODO, avoid direct dependency on sg_cfg
116   process_->privatized(sg_cfg_get_boolean("smpi/privatize_global_variables"));
117
118   /* Initialize statistics */
119   mc_stats = xbt_new0(s_mc_stats_t, 1);
120   mc_stats->state_size = 1;
121
122   if ((_sg_mc_dot_output_file != nullptr) && (_sg_mc_dot_output_file[0] != '\0'))
123     MC_init_dot_output();
124
125   /* Init parmap */
126   //parmap = xbt_parmap_mc_new(xbt_os_get_numcores(), XBT_PARMAP_DEFAULT);
127
128   setup_ignore();
129
130   ptrace(PTRACE_SETOPTIONS, pid_, nullptr, PTRACE_O_TRACEEXIT);
131   ptrace(PTRACE_CONT, pid_, 0, 0);
132 }
133
134 static const std::pair<const char*, const char*> ignored_local_variables[] = {
135   std::pair<const char*, const char*>{  "e", "*" },
136   std::pair<const char*, const char*>{ "__ex_cleanup", "*" },
137   std::pair<const char*, const char*>{ "__ex_mctx_en", "*" },
138   std::pair<const char*, const char*>{ "__ex_mctx_me", "*" },
139   std::pair<const char*, const char*>{ "__xbt_ex_ctx_ptr", "*" },
140   std::pair<const char*, const char*>{ "_log_ev", "*" },
141   std::pair<const char*, const char*>{ "_throw_ctx", "*" },
142   std::pair<const char*, const char*>{ "ctx", "*" },
143
144   std::pair<const char*, const char*>{ "self", "simcall_BODY_mc_snapshot" },
145   std::pair<const char*, const char*>{ "next_context", "smx_ctx_sysv_suspend_serial" },
146   std::pair<const char*, const char*>{ "i", "smx_ctx_sysv_suspend_serial" },
147
148   /* Ignore local variable about time used for tracing */
149   std::pair<const char*, const char*>{ "start_time", "*" },
150 };
151
152 void ModelChecker::setup_ignore()
153 {
154   Process& process = this->process();
155   for (std::pair<const char*, const char*> const& var :
156       ignored_local_variables)
157     process.ignore_local_variable(var.first, var.second);
158
159   /* Static variable used for tracing */
160   process.ignore_global_variable("counter");
161
162   /* SIMIX */
163   process.ignore_global_variable("smx_total_comms");
164 }
165
166 void ModelChecker::shutdown()
167 {
168   XBT_DEBUG("Shuting down model-checker");
169
170   simgrid::mc::Process* process = &this->process();
171   if (process->running()) {
172     XBT_DEBUG("Killing process");
173     kill(process->pid(), SIGTERM);
174     process->terminate();
175   }
176 }
177
178 void ModelChecker::resume(simgrid::mc::Process& process)
179 {
180   int res = process.send_message(MC_MESSAGE_CONTINUE);
181   if (res)
182     throw std::system_error(res, std::system_category());
183   process.cache_flags = (mc_process_cache_flags_t) 0;
184 }
185
186 static
187 void throw_socket_error(int fd)
188 {
189   int error = 0;
190   socklen_t errlen = sizeof(error);
191   if (getsockopt(fd, SOL_SOCKET, SO_ERROR, (void *)&error, &errlen) == -1)
192     error = errno;
193   throw std::system_error(error, std::system_category());
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_ignore_heap_message_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_ignore_memory_message_t message;
224       if (size != sizeof(message))
225         xbt_die("Broken messsage");
226       memcpy(&message, buffer, sizeof(message));
227       process().unignore_heap(
228         (void *)(std::uintptr_t) message.addr, message.size);
229       break;
230     }
231
232   case MC_MESSAGE_IGNORE_MEMORY:
233     {
234       s_mc_ignore_memory_message_t message;
235       if (size != sizeof(message))
236         xbt_die("Broken messsage");
237       memcpy(&message, buffer, sizeof(message));
238       this->process().ignore_region(message.addr, message.size);
239       break;
240     }
241
242   case MC_MESSAGE_STACK_REGION:
243     {
244       s_mc_stack_region_message_t message;
245       if (size != sizeof(message))
246         xbt_die("Broken messsage");
247       memcpy(&message, buffer, sizeof(message));
248       this->process().stack_areas().push_back(message.stack_region);
249     }
250     break;
251
252   case MC_MESSAGE_REGISTER_SYMBOL:
253     {
254       s_mc_register_symbol_message_t message;
255       if (size != sizeof(message))
256         xbt_die("Broken message");
257       memcpy(&message, buffer, sizeof(message));
258       if (message.callback)
259         xbt_die("Support for client-side function proposition is not implemented.");
260       XBT_DEBUG("Received symbol: %s", message.name);
261
262       if (_mc_property_automaton == nullptr)
263         _mc_property_automaton = xbt_automaton_new();
264
265       simgrid::mc::Process* process = &this->process();
266       simgrid::mc::remote_ptr<int> address
267         = simgrid::mc::remote((int*) message.data);
268       simgrid::xbt::add_proposition(_mc_property_automaton,
269         message.name,
270         [process, address]() { return process->read(address); }
271         );
272
273       break;
274     }
275
276   case MC_MESSAGE_WAITING:
277     return false;
278
279   case MC_MESSAGE_ASSERTION_FAILED:
280     MC_report_assertion_error();
281     ::exit(SIMGRID_MC_EXIT_SAFETY);
282     break;
283
284   default:
285     xbt_die("Unexpected message from model-checked application");
286
287   }
288   return true;
289 }
290
291 bool ModelChecker::handle_events()
292 {
293   char buffer[MC_MESSAGE_LENGTH];
294   struct pollfd* socket_pollfd = &fds_[SOCKET_FD_INDEX];
295   struct pollfd* signalfd_pollfd = &fds_[SIGNAL_FD_INDEX];
296
297   while(poll(fds_, 2, -1) == -1) {
298     switch(errno) {
299     case EINTR:
300       continue;
301     default:
302       throw std::system_error(errno, std::system_category());
303     }
304   }
305
306   if (socket_pollfd->revents) {
307     if (socket_pollfd->revents & POLLIN) {
308       ssize_t size = MC_receive_message(socket_pollfd->fd, buffer, sizeof(buffer), MSG_DONTWAIT);
309       if (size == -1 && errno != EAGAIN)
310         throw std::system_error(errno, std::system_category());
311       return handle_message(buffer, size);
312     }
313     if (socket_pollfd->revents & POLLERR) {
314       throw_socket_error(socket_pollfd->fd);
315     }
316     if (socket_pollfd->revents & POLLHUP)
317       xbt_die("Socket hang up?");
318   }
319
320   if (signalfd_pollfd->revents) {
321     if (signalfd_pollfd->revents & POLLIN) {
322       this->handle_signals();
323       return true;
324     }
325     if (signalfd_pollfd->revents & POLLERR) {
326       throw_socket_error(signalfd_pollfd->fd);
327     }
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 std::system_error(errno, std::system_category());
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 std::system_error(errno, std::system_category());
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, pid_, 0, &status) == -1)
385           xbt_die("Could not get exit status");
386         if (WIFSIGNALED(status)) {
387           MC_report_crash(status);
388           ::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, 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
427 void ModelChecker::simcall_handle(simgrid::mc::Process& process, unsigned long pid, int value)
428 {
429   s_mc_simcall_handle_message m;
430   memset(&m, 0, sizeof(m));
431   m.type  = MC_MESSAGE_SIMCALL_HANDLE;
432   m.pid   = pid;
433   m.value = value;
434   process.send_message(m);
435   process.cache_flags = (mc_process_cache_flags_t) 0;
436   while (process.running()) {
437     if (!this->handle_events())
438       return;
439   }
440 }
441
442 }
443 }