Logo AND Algorithmique Numérique Distribuée

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