Logo AND Algorithmique Numérique Distribuée

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