Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Mark shared libraries private clean pages as non-writable on FreeBSD.
[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_record.h"
34 #include "src/mc/Transition.hpp"
35 #include "src/mc/Checker.hpp"
36
37 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(mc_ModelChecker, mc, "ModelChecker");
38
39 ::simgrid::mc::ModelChecker* mc_model_checker = nullptr;
40
41 using simgrid::mc::remote;
42
43 #ifdef __linux__
44 # define WAITPID_CHECKED_FLAGS __WALL
45 #else
46 # define WAITPID_CHECKED_FLAGS 0
47 #endif
48
49 // Hardcoded index for now:
50 #define SOCKET_FD_INDEX 0
51 #define SIGNAL_FD_INDEX 1
52
53 namespace simgrid {
54 namespace mc {
55
56 ModelChecker::ModelChecker(std::unique_ptr<Process> process) :
57   page_store_(500),
58   process_(std::move(process)),
59   parent_snapshot_(nullptr)
60 {
61
62 }
63
64 ModelChecker::~ModelChecker() {}
65
66 void ModelChecker::start()
67 {
68   const pid_t pid = process_->pid();
69
70   // Block SIGCHLD (this will be handled with accept/signalfd):
71   sigset_t set;
72   sigemptyset(&set);
73   sigaddset(&set, SIGCHLD);
74   if (sigprocmask(SIG_BLOCK, &set, nullptr) == -1)
75     throw simgrid::xbt::errno_error();
76
77   sigset_t full_set;
78   sigfillset(&full_set);
79
80   // Prepare data for poll:
81
82   struct pollfd* socket_pollfd = &fds_[SOCKET_FD_INDEX];
83   socket_pollfd->fd = process_->getChannel().getSocket();
84   socket_pollfd->events = POLLIN;
85   socket_pollfd->revents = 0;
86
87   int signal_fd = signalfd(-1, &set, 0);
88   if (signal_fd == -1)
89     throw simgrid::xbt::errno_error();
90
91   struct pollfd* signalfd_pollfd = &fds_[SIGNAL_FD_INDEX];
92   signalfd_pollfd->fd = signal_fd;
93   signalfd_pollfd->events = POLLIN;
94   signalfd_pollfd->revents = 0;
95
96   XBT_DEBUG("Waiting for the model-checked process");
97   int status;
98
99   // The model-checked process SIGSTOP itself to signal it's ready:
100   pid_t res = waitpid(pid, &status, WAITPID_CHECKED_FLAGS);
101   if (res < 0 || !WIFSTOPPED(status) || WSTOPSIG(status) != SIGSTOP)
102     xbt_die("Could not wait model-checked process");
103
104   process_->init();
105
106   if ((_sg_mc_dot_output_file != nullptr) && (_sg_mc_dot_output_file[0] != '\0'))
107     MC_init_dot_output();
108
109   setup_ignore();
110
111   ptrace(PTRACE_SETOPTIONS, pid, nullptr, PTRACE_O_TRACEEXIT);
112   ptrace(PTRACE_CONT, pid, 0, 0);
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 bool ModelChecker::handle_events()
313 {
314   char buffer[MC_MESSAGE_LENGTH];
315   struct pollfd* socket_pollfd = &fds_[SOCKET_FD_INDEX];
316   struct pollfd* signalfd_pollfd = &fds_[SIGNAL_FD_INDEX];
317
318   while(poll(fds_, 2, -1) == -1) {
319     switch(errno) {
320     case EINTR:
321       continue;
322     default:
323       throw simgrid::xbt::errno_error();
324     }
325   }
326
327   if (socket_pollfd->revents) {
328     if (socket_pollfd->revents & POLLIN) {
329       ssize_t size = process_->getChannel().receive(buffer, sizeof(buffer), false);
330       if (size == -1 && errno != EAGAIN)
331         throw simgrid::xbt::errno_error();
332       return handle_message(buffer, size);
333     }
334     if (socket_pollfd->revents & POLLERR)
335       throw_socket_error(socket_pollfd->fd);
336     if (socket_pollfd->revents & POLLHUP)
337       xbt_die("Socket hang up?");
338   }
339
340   if (signalfd_pollfd->revents) {
341     if (signalfd_pollfd->revents & POLLIN) {
342       this->handle_signals();
343       return true;
344     }
345     if (signalfd_pollfd->revents & POLLERR)
346       throw_socket_error(signalfd_pollfd->fd);
347     if (signalfd_pollfd->revents & POLLHUP)
348       xbt_die("Signalfd hang up?");
349   }
350
351   return true;
352 }
353
354 void ModelChecker::loop()
355 {
356   while (this->process().running())
357     this->handle_events();
358 }
359
360 void ModelChecker::handle_signals()
361 {
362   struct signalfd_siginfo info;
363   struct pollfd* signalfd_pollfd = &fds_[SIGNAL_FD_INDEX];
364   while (1) {
365     ssize_t size = read(signalfd_pollfd->fd, &info, sizeof(info));
366     if (size == -1) {
367       if (errno == EINTR)
368         continue;
369       else
370         throw simgrid::xbt::errno_error();
371     } else if (size != sizeof(info))
372         return throw std::runtime_error(
373           "Bad communication with model-checked application");
374     else
375       break;
376   }
377   this->on_signal(&info);
378 }
379
380 void ModelChecker::handle_waitpid()
381 {
382   XBT_DEBUG("Check for wait event");
383   int status;
384   pid_t pid;
385   while ((pid = waitpid(-1, &status, WNOHANG)) != 0) {
386     if (pid == -1) {
387       if (errno == ECHILD) {
388         // No more children:
389         if (this->process().running())
390           xbt_die("Inconsistent state");
391         else
392           break;
393       } else {
394         XBT_ERROR("Could not wait for pid");
395         throw simgrid::xbt::errno_error();
396       }
397     }
398
399     if (pid == this->process().pid()) {
400
401       // From PTRACE_O_TRACEEXIT:
402       if (status>>8 == (SIGTRAP | (PTRACE_EVENT_EXIT<<8))) {
403         if (ptrace(PTRACE_GETEVENTMSG, this->process().pid(), 0, &status) == -1)
404           xbt_die("Could not get exit status");
405         if (WIFSIGNALED(status)) {
406           MC_report_crash(status);
407           mc_model_checker->exit(SIMGRID_MC_EXIT_PROGRAM_CRASH);
408         }
409       }
410
411       // We don't care about signals, just reinject them:
412       if (WIFSTOPPED(status)) {
413         XBT_DEBUG("Stopped with signal %i", (int) WSTOPSIG(status));
414         if (ptrace(PTRACE_CONT, this->process().pid(), 0, WSTOPSIG(status)) == -1)
415           xbt_die("Could not PTRACE_CONT");
416       }
417
418       else if (WIFEXITED(status) || WIFSIGNALED(status)) {
419         XBT_DEBUG("Child process is over");
420         this->process().terminate();
421       }
422     }
423   }
424 }
425
426 void ModelChecker::on_signal(const struct signalfd_siginfo* info)
427 {
428   switch(info->ssi_signo) {
429   case SIGCHLD:
430     this->handle_waitpid();
431     break;
432   default:
433     break;
434   }
435 }
436
437 void ModelChecker::wait_client(simgrid::mc::Process& process)
438 {
439   this->resume(process);
440   while (this->process().running())
441     if (!this->handle_events())
442       return;
443 }
444
445 void ModelChecker::handle_simcall(Transition const& transition)
446 {
447   s_mc_simcall_handle_message m;
448   memset(&m, 0, sizeof(m));
449   m.type  = MC_MESSAGE_SIMCALL_HANDLE;
450   m.pid   = transition.pid;
451   m.value = transition.argument;
452   this->process_->getChannel().send(m);
453   this->process_->clear_cache();
454   while (this->process_->running())
455     if (!this->handle_events())
456       return;
457 }
458
459 bool ModelChecker::checkDeadlock()
460 {
461   int res;
462   if ((res = this->process().getChannel().send(MC_MESSAGE_DEADLOCK_CHECK)))
463     xbt_die("Could not check deadlock state");
464   s_mc_int_message_t message;
465   ssize_t s = mc_model_checker->process().getChannel().receive(message);
466   if (s == -1)
467     xbt_die("Could not receive message");
468   if (s != sizeof(message) || message.type != MC_MESSAGE_DEADLOCK_CHECK_REPLY)
469     xbt_die("Received unexpected message %s (%i, size=%i) "
470       "expected MC_MESSAGE_DEADLOCK_CHECK_REPLY (%i, size=%i)",
471       MC_message_type_name(message.type), (int) message.type, (int) s,
472       (int) MC_MESSAGE_DEADLOCK_CHECK_REPLY, (int) sizeof(message)
473       );
474   return message.value != 0;
475 }
476
477 }
478 }