Logo AND Algorithmique Numérique Distribuée

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