Logo AND Algorithmique Numérique Distribuée

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