Logo AND Algorithmique Numérique Distribuée

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