Logo AND Algorithmique Numérique Distribuée

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