Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Compile the safe part of MC in default mode too
[simgrid.git] / src / mc / remote / AppSide.cpp
1 /* Copyright (c) 2015-2023. 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/remote/AppSide.hpp"
7 #include "simgrid/s4u/Host.hpp"
8 #include "src/internal_config.h"
9 #include "src/kernel/EngineImpl.hpp"
10 #include "src/kernel/actor/ActorImpl.hpp"
11 #include "src/kernel/actor/SimcallObserver.hpp"
12 #include "src/mc/mc_base.hpp"
13 #include "src/mc/mc_config.hpp"
14 #include "src/mc/sosp/RemoteProcessMemory.hpp"
15 #if HAVE_SMPI
16 #include "src/smpi/include/private.hpp"
17 #endif
18 #include "src/sthread/sthread.h"
19 #include "src/xbt/coverage.h"
20 #include "xbt/str.h"
21 #include <simgrid/modelchecker.h>
22
23 #include <cerrno>
24 #include <cstdio> // setvbuf
25 #include <cstdlib>
26 #include <memory>
27 #include <numeric>
28 #include <sys/ptrace.h>
29 #include <sys/socket.h>
30 #include <sys/types.h>
31 #include <sys/un.h>
32 #include <sys/wait.h>
33
34 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(mc_client, mc, "MC client logic");
35 XBT_LOG_EXTERNAL_CATEGORY(mc_global);
36
37 namespace simgrid::mc {
38
39 std::unique_ptr<AppSide> AppSide::instance_;
40
41 AppSide* AppSide::initialize()
42 {
43   if (not std::getenv(MC_ENV_SOCKET_FD)) // We are not in MC mode: don't initialize the MC world
44     return nullptr;
45
46   // Do not break if we are called multiple times:
47   if (instance_)
48     return instance_.get();
49
50   simgrid::mc::model_checking_mode = ModelCheckingMode::APP_SIDE;
51
52   setvbuf(stdout, nullptr, _IOLBF, 0);
53
54   // Fetch socket from MC_ENV_SOCKET_FD:
55   const char* fd_env = std::getenv(MC_ENV_SOCKET_FD);
56   int fd             = xbt_str_parse_int(fd_env, "Not a number in variable '" MC_ENV_SOCKET_FD "'");
57   XBT_DEBUG("Model-checked application found socket FD %i", fd);
58
59   // Check the socket type/validity:
60   int type;
61   socklen_t socklen = sizeof(type);
62   xbt_assert(getsockopt(fd, SOL_SOCKET, SO_TYPE, &type, &socklen) == 0, "Could not check socket type");
63   xbt_assert(type == SOCK_SEQPACKET, "Unexpected socket type %i", type);
64   XBT_DEBUG("Model-checked application found expected socket type");
65
66   instance_ = std::make_unique<simgrid::mc::AppSide>(fd);
67
68   // Wait for the model-checker:
69   if (getenv("MC_NEED_PTRACE") != nullptr) {
70     errno = 0;
71 #if defined __linux__
72     ptrace(PTRACE_TRACEME, 0, nullptr, nullptr);
73 #elif defined BSD
74     ptrace(PT_TRACE_ME, 0, nullptr, 0);
75 #else
76     xbt_die("no ptrace equivalent coded for this platform, please don't use the liveness checker here.");
77 #endif
78
79     xbt_assert(errno == 0 && raise(SIGSTOP) == 0, "Could not wait for the model-checker (errno = %d: %s)", errno,
80                strerror(errno));
81   }
82
83   instance_->handle_messages();
84   return instance_.get();
85 }
86
87 void AppSide::handle_deadlock_check(const s_mc_message_t*) const
88 {
89   const auto* engine     = kernel::EngineImpl::get_instance();
90   const auto& actor_list = engine->get_actor_list();
91   bool deadlock = not actor_list.empty() && std::none_of(begin(actor_list), end(actor_list), [](const auto& kv) {
92     return mc::actor_is_enabled(kv.second);
93   });
94
95   if (deadlock) {
96     XBT_CINFO(mc_global, "**************************");
97     XBT_CINFO(mc_global, "*** DEADLOCK DETECTED ***");
98     XBT_CINFO(mc_global, "**************************");
99     engine->display_all_actor_status();
100   }
101   // Send result:
102   s_mc_message_int_t answer = {};
103   answer.type  = MessageType::DEADLOCK_CHECK_REPLY;
104   answer.value = deadlock;
105   xbt_assert(channel_.send(answer) == 0, "Could not send response");
106 }
107 void AppSide::handle_simcall_execute(const s_mc_message_simcall_execute_t* message) const
108 {
109   kernel::actor::ActorImpl* actor = kernel::EngineImpl::get_instance()->get_actor_by_pid(message->aid_);
110   xbt_assert(actor != nullptr, "Invalid pid %ld", message->aid_);
111
112   // The client may send some messages to the server while processing the transition
113   actor->simcall_handle(message->times_considered_);
114   // Say the server that the transition is over and that it should proceed
115   xbt_assert(channel_.send(MessageType::WAITING) == 0, "Could not send MESSAGE_WAITING to model-checker");
116
117   // Finish the RPC from the server: return a serialized observer, to build a Transition on Checker side
118   s_mc_message_simcall_execute_answer_t answer = {};
119   answer.type                                  = MessageType::SIMCALL_EXECUTE_REPLY;
120   std::stringstream stream;
121   if (actor->simcall_.observer_ != nullptr) {
122     actor->simcall_.observer_->serialize(stream);
123   } else {
124     stream << (short)mc::Transition::Type::UNKNOWN;
125   }
126   std::string str = stream.str();
127   xbt_assert(str.size() + 1 <= answer.buffer.size(),
128              "The serialized simcall is too large for the buffer. Please fix the code.");
129   strncpy(answer.buffer.data(), str.c_str(), answer.buffer.size() - 1);
130   answer.buffer.back() = '\0';
131
132   XBT_DEBUG("send SIMCALL_EXECUTE_ANSWER(%s) ~> '%s'", actor->get_cname(), str.c_str());
133   xbt_assert(channel_.send(answer) == 0, "Could not send response");
134 }
135
136 void AppSide::handle_finalize(const s_mc_message_int_t* msg) const
137 {
138   bool terminate_asap = msg->value;
139   XBT_DEBUG("Finalize (terminate = %d)", (int)terminate_asap);
140   if (not terminate_asap) {
141     if (XBT_LOG_ISENABLED(mc_client, xbt_log_priority_debug))
142       kernel::EngineImpl::get_instance()->display_all_actor_status();
143 #if HAVE_SMPI
144     XBT_DEBUG("Smpi_enabled: %d", SMPI_is_inited());
145     if (SMPI_is_inited())
146       SMPI_finalize();
147 #endif
148   }
149   coverage_checkpoint();
150   xbt_assert(channel_.send(MessageType::FINALIZE_REPLY) == 0, "Could not answer to FINALIZE");
151   std::fflush(stdout);
152   if (terminate_asap)
153     ::_Exit(0);
154 }
155 void AppSide::handle_fork(const s_mc_message_int_t* msg)
156 {
157   int pid = fork();
158   xbt_assert(pid >= 0, "Could not fork application sub-process: %s.", strerror(errno));
159
160   if (pid == 0) { // Child
161     int sock = socket(AF_LOCAL, SOCK_SEQPACKET | SOCK_CLOEXEC, 0);
162
163     struct sockaddr_un addr = {};
164     addr.sun_family         = AF_LOCAL;
165     snprintf(addr.sun_path, 64, "/tmp/simgrid-mc-%lu", msg->value);
166     auto addr_size = offsetof(struct sockaddr_un, sun_path) + strlen(addr.sun_path);
167
168     xbt_assert(connect(sock, (struct sockaddr*)&addr, addr_size) >= 0,
169                "Cannot connect to Checker on /tmp/simgrid-mc-%lu: %s.", msg->value, strerror(errno));
170
171     channel_.reset_socket(sock);
172
173     s_mc_message_int_t answer = {};
174     answer.type               = MessageType::FORK_REPLY;
175     answer.value              = getpid();
176     xbt_assert(channel_.send(answer) == 0, "Could not send response to WAIT_CHILD_REPLY: %s", strerror(errno));
177   }
178 }
179 void AppSide::handle_wait_child(const s_mc_message_int_t* msg)
180 {
181   int status;
182   errno = 0;
183   waitpid(msg->value, &status, 0);
184   xbt_assert(errno == 0, "Cannot wait on behalf of the checker: %s.", strerror(errno));
185
186   s_mc_message_int_t answer = {};
187   answer.type               = MessageType::WAIT_CHILD_REPLY;
188   answer.value              = status;
189   xbt_assert(channel_.send(answer) == 0, "Could not send response to WAIT_CHILD: %s", strerror(errno));
190 }
191 void AppSide::handle_need_meminfo()
192 {
193 #if SIMGRID_HAVE_MC
194   this->need_memory_info_                  = true;
195   s_mc_message_need_meminfo_reply_t answer = {};
196   answer.type                              = MessageType::NEED_MEMINFO_REPLY;
197   answer.mmalloc_default_mdp               = mmalloc_get_current_heap();
198   xbt_assert(channel_.send(answer) == 0, "Could not send response to the request for meminfo.");
199 #else
200   xbt_die("SimGrid was compiled without MC suppport, so liveness and similar features are not available.");
201 #endif
202 }
203 void AppSide::handle_actors_status() const
204 {
205   auto const& actor_list = kernel::EngineImpl::get_instance()->get_actor_list();
206   XBT_DEBUG("Serialize the actors to answer ACTORS_STATUS from the checker. %zu actors to go.", actor_list.size());
207
208   std::vector<s_mc_message_actors_status_one_t> status;
209   for (auto const& [aid, actor] : actor_list) {
210     s_mc_message_actors_status_one_t one = {};
211     one.type                             = MessageType::ACTORS_STATUS_REPLY_TRANSITION;
212     one.aid                              = aid;
213     one.enabled                          = mc::actor_is_enabled(actor);
214     one.max_considered                   = actor->simcall_.observer_->get_max_consider();
215     status.push_back(one);
216   }
217
218   struct s_mc_message_actors_status_answer_t answer = {};
219   answer.type                                       = MessageType::ACTORS_STATUS_REPLY_COUNT;
220   answer.count                                      = static_cast<int>(status.size());
221
222   xbt_assert(channel_.send(answer) == 0, "Could not send ACTORS_STATUS_REPLY msg");
223   if (answer.count > 0) {
224     size_t size = status.size() * sizeof(s_mc_message_actors_status_one_t);
225     xbt_assert(channel_.send(status.data(), size) == 0, "Could not send ACTORS_STATUS_REPLY data");
226   }
227
228   // Serialize each transition to describe what each actor is doing
229   XBT_DEBUG("Deliver ACTOR_TRANSITION_PROBE payload");
230   for (const auto& actor_status : status) {
231     if (not actor_status.enabled)
232       continue;
233
234     const auto& actor        = actor_list.at(actor_status.aid);
235     const int max_considered = actor_status.max_considered;
236
237     for (int times_considered = 0; times_considered < max_considered; times_considered++) {
238       std::stringstream stream;
239       s_mc_message_simcall_probe_one_t probe;
240       probe.type = MessageType::ACTORS_STATUS_REPLY_SIMCALL;
241
242       if (actor->simcall_.observer_ != nullptr) {
243         actor->simcall_.observer_->prepare(times_considered);
244         actor->simcall_.observer_->serialize(stream);
245       } else {
246         stream << (short)mc::Transition::Type::UNKNOWN;
247       }
248
249       std::string str = stream.str();
250       xbt_assert(str.size() + 1 <= probe.buffer.size(),
251                  "The serialized transition is too large for the buffer. Please fix the code.");
252       strncpy(probe.buffer.data(), str.c_str(), probe.buffer.size() - 1);
253       probe.buffer.back() = '\0';
254
255       xbt_assert(channel_.send(probe) == 0, "Could not send ACTOR_TRANSITION_PROBE payload");
256     }
257     // NOTE: We do NOT need to reset `times_considered` for each actor's
258     // simcall observer here to the "original" value (i.e. the value BEFORE
259     // multiple prepare() calls were made for serialization purposes) since
260     // each SIMCALL_EXECUTE provides a `times_considered` to be used to prepare
261     // the transition before execution.
262   }
263 }
264 void AppSide::handle_actors_maxpid() const
265 {
266   s_mc_message_int_t answer = {};
267   answer.type               = MessageType::ACTORS_MAXPID_REPLY;
268   answer.value              = kernel::actor::ActorImpl::get_maxpid();
269   xbt_assert(channel_.send(answer) == 0, "Could not send response");
270 }
271
272 #define assert_msg_size(_name_, _type_)                                                                                \
273   xbt_assert(received_size == sizeof(_type_), "Unexpected size for " _name_ " (%zd != %zu)", received_size,            \
274              sizeof(_type_))
275
276 void AppSide::handle_messages()
277 {
278   while (true) { // Until we get a CONTINUE message
279     XBT_DEBUG("Waiting messages from the model-checker");
280
281     std::array<char, MC_MESSAGE_LENGTH> message_buffer;
282     ssize_t received_size = channel_.receive(message_buffer.data(), message_buffer.size());
283
284     if (received_size == 0) {
285       XBT_DEBUG("Socket closed on the Checker side, bailing out.");
286       ::_Exit(0); // Nobody's listening to that process anymore => exit as quickly as possible.
287     }
288     xbt_assert(received_size >= 0, "Could not receive commands from the model-checker");
289     xbt_assert(static_cast<size_t>(received_size) >= sizeof(s_mc_message_t), "Cannot handle short message (size=%zd)",
290                received_size);
291
292     const s_mc_message_t* message = (s_mc_message_t*)message_buffer.data();
293     switch (message->type) {
294       case MessageType::CONTINUE:
295         assert_msg_size("MESSAGE_CONTINUE", s_mc_message_t);
296         return;
297
298       case MessageType::DEADLOCK_CHECK:
299         assert_msg_size("DEADLOCK_CHECK", s_mc_message_t);
300         handle_deadlock_check(message);
301         break;
302
303       case MessageType::SIMCALL_EXECUTE:
304         assert_msg_size("SIMCALL_EXECUTE", s_mc_message_simcall_execute_t);
305         handle_simcall_execute((s_mc_message_simcall_execute_t*)message_buffer.data());
306         break;
307
308       case MessageType::FINALIZE:
309         assert_msg_size("FINALIZE", s_mc_message_int_t);
310         handle_finalize((s_mc_message_int_t*)message_buffer.data());
311         break;
312
313       case MessageType::FORK:
314         assert_msg_size("FORK", s_mc_message_int_t);
315         handle_fork((s_mc_message_int_t*)message_buffer.data());
316         break;
317
318       case MessageType::WAIT_CHILD:
319         assert_msg_size("WAIT_CHILD", s_mc_message_int_t);
320         handle_wait_child((s_mc_message_int_t*)message_buffer.data());
321         break;
322
323       case MessageType::NEED_MEMINFO:
324         assert_msg_size("NEED_MEMINFO", s_mc_message_t);
325         handle_need_meminfo();
326         break;
327
328       case MessageType::ACTORS_STATUS:
329         assert_msg_size("ACTORS_STATUS", s_mc_message_t);
330         handle_actors_status();
331         break;
332
333       case MessageType::ACTORS_MAXPID:
334         assert_msg_size("ACTORS_MAXPID", s_mc_message_t);
335         handle_actors_maxpid();
336         break;
337
338       default:
339         xbt_die("Received unexpected message %s (%i)", to_c_str(message->type), static_cast<int>(message->type));
340         break;
341     }
342   }
343 }
344
345 void AppSide::main_loop()
346 {
347   simgrid::mc::processes_time.resize(simgrid::kernel::actor::ActorImpl::get_maxpid());
348   MC_ignore_heap(simgrid::mc::processes_time.data(),
349                  simgrid::mc::processes_time.size() * sizeof(simgrid::mc::processes_time[0]));
350
351   sthread_disable();
352   coverage_checkpoint();
353   sthread_enable();
354   while (true) {
355     simgrid::mc::execute_actors();
356     xbt_assert(channel_.send(MessageType::WAITING) == 0, "Could not send WAITING message to model-checker");
357     this->handle_messages();
358   }
359 }
360
361 void AppSide::report_assertion_failure()
362 {
363   xbt_assert(channel_.send(MessageType::ASSERTION_FAILED) == 0, "Could not send assertion to model-checker");
364   this->handle_messages();
365 }
366
367 void AppSide::ignore_memory(void* addr, std::size_t size) const
368 {
369   if (not MC_is_active() || not need_memory_info_)
370     return;
371
372 #if SIMGRID_HAVE_MC
373   s_mc_message_ignore_memory_t message = {};
374   message.type = MessageType::IGNORE_MEMORY;
375   message.addr = (std::uintptr_t)addr;
376   message.size = size;
377   xbt_assert(channel_.send(message) == 0, "Could not send IGNORE_MEMORY message to model-checker");
378 #else
379   xbt_die("Cannot really call ignore_heap() in non-SIMGRID_MC mode.");
380 #endif
381 }
382
383 void AppSide::ignore_heap(void* address, std::size_t size) const
384 {
385   if (not MC_is_active() || not need_memory_info_)
386     return;
387
388 #if SIMGRID_HAVE_MC
389   const s_xbt_mheap_t* heap = mmalloc_get_current_heap();
390
391   s_mc_message_ignore_heap_t message = {};
392   message.type    = MessageType::IGNORE_HEAP;
393   message.address = address;
394   message.size    = size;
395   message.block   = ((char*)address - (char*)heap->heapbase) / BLOCKSIZE + 1;
396   if (heap->heapinfo[message.block].type == 0) {
397     message.fragment = -1;
398     heap->heapinfo[message.block].busy_block.ignore++;
399   } else {
400     message.fragment = (ADDR2UINT(address) % BLOCKSIZE) >> heap->heapinfo[message.block].type;
401     heap->heapinfo[message.block].busy_frag.ignore[message.fragment]++;
402   }
403
404   xbt_assert(channel_.send(message) == 0, "Could not send ignored region to MCer");
405 #else
406   xbt_die("Cannot really call ignore_heap() in non-SIMGRID_MC mode.");
407 #endif
408 }
409
410 void AppSide::unignore_heap(void* address, std::size_t size) const
411 {
412   if (not MC_is_active() || not need_memory_info_)
413     return;
414
415 #if SIMGRID_HAVE_MC
416   s_mc_message_ignore_memory_t message = {};
417   message.type = MessageType::UNIGNORE_HEAP;
418   message.addr = (std::uintptr_t)address;
419   message.size = size;
420   xbt_assert(channel_.send(message) == 0, "Could not send IGNORE_HEAP message to model-checker");
421 #else
422   xbt_die("Cannot really call unignore_heap() in non-SIMGRID_MC mode.");
423 #endif
424 }
425
426 void AppSide::declare_symbol(const char* name, int* value) const
427 {
428   if (not MC_is_active() || not need_memory_info_) {
429     XBT_CRITICAL("Ignore AppSide::declare_symbol(%s)", name);
430     return;
431   }
432
433 #if SIMGRID_HAVE_MC
434   s_mc_message_register_symbol_t message = {};
435   message.type = MessageType::REGISTER_SYMBOL;
436   xbt_assert(strlen(name) + 1 <= message.name.size(), "Symbol is too long");
437   strncpy(message.name.data(), name, message.name.size() - 1);
438   message.callback = nullptr;
439   message.data     = value;
440   xbt_assert(channel_.send(message) == 0, "Could send REGISTER_SYMBOL message to model-checker");
441 #else
442   xbt_die("Cannot really call declare_symbol() in non-SIMGRID_MC mode.");
443 #endif
444 }
445
446 /** Register a stack in the model checker
447  *
448  *  The stacks are allocated in the heap. The MC handle them specifically
449  *  when we analyze/compare the content of the heap so it must be told where
450  *  they are with this function.
451  */
452 void AppSide::declare_stack(void* stack, size_t size, ucontext_t* context) const
453 {
454   if (not MC_is_active() || not need_memory_info_)
455     return;
456
457 #if SIMGRID_HAVE_MC
458   const s_xbt_mheap_t* heap = mmalloc_get_current_heap();
459
460   s_stack_region_t region = {};
461   region.address = stack;
462   region.context = context;
463   region.size    = size;
464   region.block   = ((char*)stack - (char*)heap->heapbase) / BLOCKSIZE + 1;
465
466   s_mc_message_stack_region_t message = {};
467   message.type         = MessageType::STACK_REGION;
468   message.stack_region = region;
469   xbt_assert(channel_.send(message) == 0, "Could not send STACK_REGION to model-checker");
470 #else
471   xbt_die("Cannot really call declare_stack() in non-SIMGRID_MC mode.");
472 #endif
473 }
474 } // namespace simgrid::mc