Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Fix builds with/without MC and with/without clang (hopefully)
[simgrid.git] / src / mc / ModelChecker.cpp
1 /* Copyright (c) 2008-2022. The SimGrid Team. All rights reserved.          */
2
3 /* This program is free software; you can redistribute it and/or modify it
4  * under the terms of the license (GNU LGPL) which comes with this package. */
5
6 #include "src/mc/ModelChecker.hpp"
7 #include "src/mc/Session.hpp"
8 #include "src/mc/Transition.hpp"
9 #include "src/mc/TransitionComm.hpp"
10 #include "src/mc/checker/Checker.hpp"
11 #include "src/mc/mc_config.hpp"
12 #include "src/mc/mc_exit.hpp"
13 #include "src/mc/mc_private.hpp"
14 #include "src/mc/remote/RemoteProcess.hpp"
15 #include "xbt/automaton.hpp"
16 #include "xbt/system_error.hpp"
17
18 #include <array>
19 #include <csignal>
20 #include <sys/ptrace.h>
21 #include <sys/wait.h>
22
23 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(mc_ModelChecker, mc, "ModelChecker");
24
25 ::simgrid::mc::ModelChecker* mc_model_checker = nullptr;
26
27 using simgrid::mc::remote;
28
29 #ifdef __linux__
30 # define WAITPID_CHECKED_FLAGS __WALL
31 #else
32 # define WAITPID_CHECKED_FLAGS 0
33 #endif
34
35 namespace simgrid {
36 namespace mc {
37
38 ModelChecker::ModelChecker(std::unique_ptr<RemoteProcess> remote_simulation, int sockfd)
39     : checker_side_(sockfd), remote_process_(std::move(remote_simulation))
40 {
41 }
42
43 void ModelChecker::start()
44 {
45   checker_side_.start(
46       [](evutil_socket_t sig, short events, void* arg) {
47         auto mc = static_cast<simgrid::mc::ModelChecker*>(arg);
48         if (events == EV_READ) {
49           std::array<char, MC_MESSAGE_LENGTH> buffer;
50           ssize_t size = mc->checker_side_.get_channel().receive(buffer.data(), buffer.size(), false);
51           if (size == -1 && errno != EAGAIN)
52             throw simgrid::xbt::errno_error();
53
54           if (not mc->handle_message(buffer.data(), size))
55             mc->checker_side_.break_loop();
56         } else if (events == EV_SIGNAL) {
57           if (sig == SIGCHLD)
58             mc->handle_waitpid();
59         } else {
60           xbt_die("Unexpected event");
61         }
62       },
63       this);
64
65   XBT_DEBUG("Waiting for the model-checked process");
66   int status;
67
68   // The model-checked process SIGSTOP itself to signal it's ready:
69   const pid_t pid = remote_process_->pid();
70
71   xbt_assert(waitpid(pid, &status, WAITPID_CHECKED_FLAGS) == pid && WIFSTOPPED(status) && WSTOPSIG(status) == SIGSTOP,
72              "Could not wait model-checked process");
73
74   if (not _sg_mc_dot_output_file.get().empty())
75     MC_init_dot_output();
76
77   setup_ignore();
78
79 #ifdef __linux__
80   ptrace(PTRACE_SETOPTIONS, pid, nullptr, PTRACE_O_TRACEEXIT);
81   ptrace(PTRACE_CONT, pid, 0, 0);
82 #elif defined BSD
83   ptrace(PT_CONTINUE, pid, (caddr_t)1, 0);
84 #else
85 # error "no ptrace equivalent coded for this platform"
86 #endif
87 }
88
89 static constexpr auto ignored_local_variables = {
90     std::make_pair("e", "*"),
91     std::make_pair("_log_ev", "*"),
92
93     /* Ignore local variable about time used for tracing */
94     std::make_pair("start_time", "*"),
95 };
96
97 void ModelChecker::setup_ignore()
98 {
99   const RemoteProcess& process = this->get_remote_process();
100   for (auto const& var : ignored_local_variables)
101     process.ignore_local_variable(var.first, var.second);
102
103   /* Static variable used for tracing */
104   process.ignore_global_variable("counter");
105 }
106
107 void ModelChecker::shutdown()
108 {
109   XBT_DEBUG("Shutting down model-checker");
110
111   RemoteProcess& process = get_remote_process();
112   if (process.running()) {
113     XBT_DEBUG("Killing process");
114     finalize_app(true);
115     kill(process.pid(), SIGKILL);
116     process.terminate();
117   }
118 }
119
120 void ModelChecker::resume()
121 {
122   int res = checker_side_.get_channel().send(MessageType::CONTINUE);
123   if (res)
124     throw xbt::errno_error();
125   remote_process_->clear_cache();
126 }
127
128 static void MC_report_crash(int status)
129 {
130   XBT_INFO("**************************");
131   XBT_INFO("** CRASH IN THE PROGRAM **");
132   XBT_INFO("**************************");
133   if (WIFSIGNALED(status))
134     XBT_INFO("From signal: %s", strsignal(WTERMSIG(status)));
135   else if (WIFEXITED(status))
136     XBT_INFO("From exit: %i", WEXITSTATUS(status));
137   if (not xbt_log_no_loc)
138     XBT_INFO("%s core dump was generated by the system.", WCOREDUMP(status) ? "A" : "No");
139   XBT_INFO("Counter-example execution trace:");
140   for (auto const& s : mc_model_checker->getChecker()->get_textual_trace())
141     XBT_INFO("  %s", s.c_str());
142   dumpRecordPath();
143   session_singleton->log_state();
144   if (xbt_log_no_loc) {
145     XBT_INFO("Stack trace not displayed because you passed --log=no_loc");
146   } else {
147     XBT_INFO("Stack trace:");
148     mc_model_checker->get_remote_process().dump_stack();
149   }
150 }
151
152 bool ModelChecker::handle_message(const char* buffer, ssize_t size)
153 {
154   s_mc_message_t base_message;
155   xbt_assert(size >= (ssize_t)sizeof(base_message), "Broken message");
156   memcpy(&base_message, buffer, sizeof(base_message));
157
158   switch(base_message.type) {
159     case MessageType::INITIAL_ADDRESSES: {
160       s_mc_message_initial_addresses_t message;
161       xbt_assert(size == sizeof(message), "Broken message. Got %d bytes instead of %d.", (int)size, (int)sizeof(message));
162       memcpy(&message, buffer, sizeof(message));
163
164       get_remote_process().init(message.mmalloc_default_mdp, message.maxpid, message.actors, message.dead_actors);
165       break;
166     }
167
168     case MessageType::IGNORE_HEAP: {
169       s_mc_message_ignore_heap_t message;
170       xbt_assert(size == sizeof(message), "Broken message");
171       memcpy(&message, buffer, sizeof(message));
172
173       IgnoredHeapRegion region;
174       region.block    = message.block;
175       region.fragment = message.fragment;
176       region.address  = message.address;
177       region.size     = message.size;
178       get_remote_process().ignore_heap(region);
179       break;
180     }
181
182     case MessageType::UNIGNORE_HEAP: {
183       s_mc_message_ignore_memory_t message;
184       xbt_assert(size == sizeof(message), "Broken message");
185       memcpy(&message, buffer, sizeof(message));
186       get_remote_process().unignore_heap((void*)(std::uintptr_t)message.addr, message.size);
187       break;
188     }
189
190     case MessageType::IGNORE_MEMORY: {
191       s_mc_message_ignore_memory_t message;
192       xbt_assert(size == sizeof(message), "Broken message");
193       memcpy(&message, buffer, sizeof(message));
194       this->get_remote_process().ignore_region(message.addr, message.size);
195       break;
196     }
197
198     case MessageType::STACK_REGION: {
199       s_mc_message_stack_region_t message;
200       xbt_assert(size == sizeof(message), "Broken message");
201       memcpy(&message, buffer, sizeof(message));
202       this->get_remote_process().stack_areas().push_back(message.stack_region);
203     } break;
204
205     case MessageType::REGISTER_SYMBOL: {
206       s_mc_message_register_symbol_t message;
207       xbt_assert(size == sizeof(message), "Broken message");
208       memcpy(&message, buffer, sizeof(message));
209       xbt_assert(not message.callback, "Support for client-side function proposition is not implemented.");
210       XBT_DEBUG("Received symbol: %s", message.name.data());
211
212       if (property_automaton == nullptr)
213         property_automaton = xbt_automaton_new();
214
215       const RemoteProcess* process    = &this->get_remote_process();
216       RemotePtr<int> address          = remote((int*)message.data);
217       xbt::add_proposition(property_automaton, message.name.data(),
218                            [process, address]() { return process->read(address); });
219
220       break;
221     }
222
223     case MessageType::WAITING:
224       return false;
225
226     case MessageType::ASSERTION_FAILED:
227       XBT_INFO("**************************");
228       XBT_INFO("*** PROPERTY NOT VALID ***");
229       XBT_INFO("**************************");
230       XBT_INFO("Counter-example execution trace:");
231       for (auto const& s : getChecker()->get_textual_trace())
232         XBT_INFO("  %s", s.c_str());
233       dumpRecordPath();
234       session_singleton->log_state();
235
236       this->exit(SIMGRID_MC_EXIT_SAFETY);
237
238     default:
239       xbt_die("Unexpected message from model-checked application");
240   }
241   return true;
242 }
243
244 /** Terminate the model-checker application */
245 void ModelChecker::exit(int status)
246 {
247   shutdown();
248   ::exit(status);
249 }
250
251 void ModelChecker::handle_waitpid()
252 {
253   XBT_DEBUG("Check for wait event");
254   int status;
255   pid_t pid;
256   while ((pid = waitpid(-1, &status, WNOHANG)) != 0) {
257     if (pid == -1) {
258       if (errno == ECHILD) {
259         // No more children:
260         xbt_assert(not this->get_remote_process().running(), "Inconsistent state");
261         break;
262       } else {
263         XBT_ERROR("Could not wait for pid");
264         throw simgrid::xbt::errno_error();
265       }
266     }
267
268     if (pid == this->get_remote_process().pid()) {
269       // From PTRACE_O_TRACEEXIT:
270 #ifdef __linux__
271       if (status>>8 == (SIGTRAP | (PTRACE_EVENT_EXIT<<8))) {
272         xbt_assert(ptrace(PTRACE_GETEVENTMSG, remote_process_->pid(), 0, &status) != -1, "Could not get exit status");
273         if (WIFSIGNALED(status)) {
274           MC_report_crash(status);
275           this->get_remote_process().terminate();
276           this->exit(SIMGRID_MC_EXIT_PROGRAM_CRASH);
277         }
278       }
279 #endif
280
281       // We don't care about signals, just reinject them:
282       if (WIFSTOPPED(status)) {
283         XBT_DEBUG("Stopped with signal %i", (int) WSTOPSIG(status));
284         errno = 0;
285 #ifdef __linux__
286         ptrace(PTRACE_CONT, remote_process_->pid(), 0, WSTOPSIG(status));
287 #elif defined BSD
288         ptrace(PT_CONTINUE, remote_process_->pid(), (caddr_t)1, WSTOPSIG(status));
289 #endif
290         xbt_assert(errno == 0, "Could not PTRACE_CONT");
291       }
292
293       else if (WIFSIGNALED(status)) {
294         MC_report_crash(status);
295         this->get_remote_process().terminate();
296         this->exit(SIMGRID_MC_EXIT_PROGRAM_CRASH);
297       } else if (WIFEXITED(status)) {
298         XBT_DEBUG("Child process is over");
299         this->get_remote_process().terminate();
300       }
301     }
302   }
303 }
304
305 void ModelChecker::wait_for_requests()
306 {
307   this->resume();
308   if (this->get_remote_process().running())
309     checker_side_.dispatch();
310 }
311
312 Transition* ModelChecker::handle_simcall(Transition const& transition, bool new_transition)
313 {
314   s_mc_message_simcall_execute_t m;
315   memset(&m, 0, sizeof(m));
316   m.type              = MessageType::SIMCALL_EXECUTE;
317   m.aid_              = transition.aid_;
318   m.times_considered_ = transition.times_considered_;
319   checker_side_.get_channel().send(m);
320
321   s_mc_message_simcall_execute_answer_t answer;
322   ssize_t s = checker_side_.get_channel().receive(answer);
323   xbt_assert(s != -1, "Could not receive message");
324   xbt_assert(s == sizeof(answer) && answer.type == MessageType::SIMCALL_EXECUTE_ANSWER,
325              "Received unexpected message %s (%i, size=%i) "
326              "expected MessageType::SIMCALL_EXECUTE_ANSWER (%i, size=%i)",
327              to_c_str(answer.type), (int)answer.type, (int)s, (int)MessageType::SIMCALL_EXECUTE_ANSWER,
328              (int)sizeof(answer));
329
330   this->remote_process_->clear_cache();
331   if (this->remote_process_->running())
332     checker_side_.dispatch(); // The app may send messages while processing the transition
333
334   if (new_transition)
335     return recv_transition(transition.aid_, transition.times_considered_, answer.simcall, answer.buffer);
336   else
337     return nullptr;
338 }
339 bool ModelChecker::simcall_is_visible(aid_t aid)
340 {
341   xbt_assert(mc_model_checker != nullptr, "This should be called from the checker side");
342
343   s_mc_message_simcall_is_visible_t m;
344   memset(&m, 0, sizeof(m));
345   m.type = MessageType::SIMCALL_IS_VISIBLE;
346   m.aid  = aid;
347   checker_side_.get_channel().send(m);
348
349   s_mc_message_simcall_is_visible_answer_t answer;
350   ssize_t s = checker_side_.get_channel().receive(answer);
351   xbt_assert(s != -1, "Could not receive message");
352   xbt_assert(s == sizeof(answer) && answer.type == MessageType::SIMCALL_IS_VISIBLE_ANSWER,
353              "Received unexpected message %s (%i, size=%i) "
354              "expected MessageType::SIMCALL_IS_VISIBLE_ANSWER (%i, size=%i)",
355              to_c_str(answer.type), (int)answer.type, (int)s, (int)MessageType::SIMCALL_IS_VISIBLE_ANSWER,
356              (int)sizeof(answer));
357
358   XBT_DEBUG("is_visible(%ld) is returning %s", aid, answer.value ? "true" : "false");
359
360   this->remote_process_->clear_cache();
361   return answer.value;
362 }
363
364 std::string ModelChecker::simcall_dot_label(aid_t aid, int times_considered)
365 {
366   xbt_assert(mc_model_checker != nullptr, "This should be called from the checker side");
367
368   s_mc_message_simcall_to_string_t m;
369   memset(&m, 0, sizeof(m));
370   m.type            = MessageType::SIMCALL_DOT_LABEL;
371   m.aid             = aid;
372   m.time_considered = times_considered;
373   checker_side_.get_channel().send(m);
374
375   s_mc_message_simcall_to_string_answer_t answer;
376   ssize_t s = checker_side_.get_channel().receive(answer);
377   xbt_assert(s != -1, "Could not receive message");
378   xbt_assert(s == sizeof(answer) && answer.type == MessageType::SIMCALL_DOT_LABEL_ANSWER,
379              "Received unexpected message %s (%i, size=%i) "
380              "expected MessageType::SIMCALL_TO_STRING_ANSWER (%i, size=%i)",
381              to_c_str(answer.type), (int)answer.type, (int)s, (int)MessageType::SIMCALL_DOT_LABEL_ANSWER,
382              (int)sizeof(answer));
383
384   XBT_DEBUG("dot_label(%ld) is returning %s", aid, answer.value);
385   return answer.value;
386 }
387
388 void ModelChecker::finalize_app(bool terminate_asap)
389 {
390   s_mc_message_int_t m;
391   memset(&m, 0, sizeof m);
392   m.type  = MessageType::FINALIZE;
393   m.value = terminate_asap;
394   xbt_assert(checker_side_.get_channel().send(m) == 0, "Could not ask the app to finalize on need");
395
396   s_mc_message_t answer;
397   xbt_assert(checker_side_.get_channel().receive(answer) != -1, "Could not receive answer to FINALIZE");
398 }
399
400 bool ModelChecker::checkDeadlock()
401 {
402   xbt_assert(checker_side_.get_channel().send(MessageType::DEADLOCK_CHECK) == 0, "Could not check deadlock state");
403   s_mc_message_int_t message;
404   ssize_t s = checker_side_.get_channel().receive(message);
405   xbt_assert(s != -1, "Could not receive message");
406   xbt_assert(s == sizeof(message) && message.type == MessageType::DEADLOCK_CHECK_REPLY,
407              "Received unexpected message %s (%i, size=%i) "
408              "expected MessageType::DEADLOCK_CHECK_REPLY (%i, size=%i)",
409              to_c_str(message.type), (int)message.type, (int)s, (int)MessageType::DEADLOCK_CHECK_REPLY,
410              (int)sizeof(message));
411   return message.value != 0;
412 }
413
414 } // namespace mc
415 } // namespace simgrid