1 /* Copyright (c) 2015-2023. The SimGrid Team. All rights reserved. */
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. */
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"
19 #include "src/smpi/include/private.hpp"
21 #include "src/sthread/sthread.h"
22 #include "src/xbt/coverage.h"
24 #include <simgrid/modelchecker.h>
27 #include <cstdio> // setvbuf
31 #include <sys/ptrace.h>
32 #include <sys/socket.h>
33 #include <sys/types.h>
37 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(mc_client, mc, "MC client logic");
38 XBT_LOG_EXTERNAL_CATEGORY(mc_global);
40 namespace simgrid::mc {
42 std::unique_ptr<AppSide> AppSide::instance_;
44 AppSide* AppSide::get()
46 // Only initialize the MC world once
47 if (instance_ != nullptr)
48 return instance_.get();
50 if (std::getenv(MC_ENV_SOCKET_FD) == nullptr) // We are not in MC mode: don't initialize the MC world
53 XBT_DEBUG("Initialize the MC world. %s=%s", MC_ENV_NEED_PTRACE, std::getenv(MC_ENV_NEED_PTRACE));
55 simgrid::mc::set_model_checking_mode(ModelCheckingMode::APP_SIDE);
57 setvbuf(stdout, nullptr, _IOLBF, 0);
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);
64 instance_ = std::make_unique<simgrid::mc::AppSide>(fd);
66 // Wait for the model-checker:
67 if (getenv(MC_ENV_NEED_PTRACE) != nullptr) {
70 ptrace(PTRACE_TRACEME, 0, nullptr, nullptr);
72 ptrace(PT_TRACE_ME, 0, nullptr, 0);
74 xbt_die("no ptrace equivalent coded for this platform, please don't use the liveness checker here.");
77 xbt_assert(errno == 0 && raise(SIGSTOP) == 0, "Could not wait for the model-checker (errno = %d: %s)", errno,
81 instance_->handle_messages();
82 return instance_.get();
85 void AppSide::handle_deadlock_check(const s_mc_message_t*) const
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);
94 XBT_CINFO(mc_global, "**************************");
95 XBT_CINFO(mc_global, "*** DEADLOCK DETECTED ***");
96 XBT_CINFO(mc_global, "**************************");
97 engine->display_all_actor_status();
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");
105 void AppSide::handle_simcall_execute(const s_mc_message_simcall_execute_t* message) const
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_);
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");
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);
122 stream << (short)mc::Transition::Type::UNKNOWN;
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';
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");
134 void AppSide::handle_finalize(const s_mc_message_int_t* msg) const
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();
142 XBT_DEBUG("Smpi_enabled: %d", SMPI_is_inited());
143 if (SMPI_is_inited())
147 coverage_checkpoint();
148 xbt_assert(channel_.send(MessageType::FINALIZE_REPLY) == 0, "Could not answer to FINALIZE");
153 void AppSide::handle_fork(const s_mc_message_int_t* msg)
157 /* Reap any zombie child, saving its status for later use in AppSide::handle_wait_child() */
158 while ((pid = waitpid(-1, &status, WNOHANG)) > 0)
159 child_statuses_[pid] = status;
162 xbt_assert(pid >= 0, "Could not fork application sub-process: %s.", strerror(errno));
164 if (pid == 0) { // Child
165 int sock = socket(AF_UNIX,
167 SOCK_STREAM, /* Mac OSX does not have AF_UNIX + SOCK_SEQPACKET, even if that's faster*/
173 struct sockaddr_un addr = {};
174 addr.sun_family = AF_UNIX;
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);
178 xbt_assert(connect(sock, (struct sockaddr*)&addr, addr_size) >= 0,
179 "Cannot connect to Checker on %s: %s.", addr.sun_path, strerror(errno));
181 channel_.reset_socket(sock);
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));
188 XBT_VERB("App %d forks subprocess %d.", getpid(), pid);
191 void AppSide::handle_wait_child(const s_mc_message_int_t* msg)
195 if (auto search = child_statuses_.find(msg->value); search != child_statuses_.end()) {
196 status = search->second;
197 child_statuses_.erase(search); // We only need this info once
199 waitpid(msg->value, &status, 0);
201 xbt_assert(errno == 0, "Cannot wait on behalf of the checker: %s.", strerror(errno));
203 s_mc_message_int_t answer = {};
204 answer.type = MessageType::WAIT_CHILD_REPLY;
205 answer.value = status;
206 xbt_assert(channel_.send(answer) == 0, "Could not send response to WAIT_CHILD: %s", strerror(errno));
208 void AppSide::handle_need_meminfo()
210 #if SIMGRID_HAVE_STATEFUL_MC
211 this->need_memory_info_ = true;
212 s_mc_message_need_meminfo_reply_t answer = {};
213 answer.type = MessageType::NEED_MEMINFO_REPLY;
214 answer.mmalloc_default_mdp = mmalloc_get_current_heap();
215 xbt_assert(channel_.send(answer) == 0, "Could not send response to the request for meminfo.");
217 xbt_die("SimGrid was compiled without MC suppport, so liveness and similar features are not available.");
220 void AppSide::handle_actors_status() const
222 auto const& actor_list = kernel::EngineImpl::get_instance()->get_actor_list();
223 XBT_DEBUG("Serialize the actors to answer ACTORS_STATUS from the checker. %zu actors to go.", actor_list.size());
225 std::vector<s_mc_message_actors_status_one_t> status;
226 for (auto const& [aid, actor] : actor_list) {
227 s_mc_message_actors_status_one_t one = {};
228 one.type = MessageType::ACTORS_STATUS_REPLY_TRANSITION;
230 one.enabled = mc::actor_is_enabled(actor);
231 one.max_considered = actor->simcall_.observer_->get_max_consider();
232 status.push_back(one);
235 struct s_mc_message_actors_status_answer_t answer = {};
236 answer.type = MessageType::ACTORS_STATUS_REPLY_COUNT;
237 answer.count = static_cast<int>(status.size());
239 xbt_assert(channel_.send(answer) == 0, "Could not send ACTORS_STATUS_REPLY msg");
240 if (answer.count > 0) {
241 size_t size = status.size() * sizeof(s_mc_message_actors_status_one_t);
242 xbt_assert(channel_.send(status.data(), size) == 0, "Could not send ACTORS_STATUS_REPLY data");
245 // Serialize each transition to describe what each actor is doing
246 XBT_DEBUG("Deliver ACTOR_TRANSITION_PROBE payload");
247 for (const auto& actor_status : status) {
248 if (not actor_status.enabled)
251 const auto& actor = actor_list.at(actor_status.aid);
252 const int max_considered = actor_status.max_considered;
254 for (int times_considered = 0; times_considered < max_considered; times_considered++) {
255 std::stringstream stream;
256 s_mc_message_simcall_probe_one_t probe;
257 probe.type = MessageType::ACTORS_STATUS_REPLY_SIMCALL;
259 if (actor->simcall_.observer_ != nullptr) {
260 actor->simcall_.observer_->prepare(times_considered);
261 actor->simcall_.observer_->serialize(stream);
263 stream << (short)mc::Transition::Type::UNKNOWN;
266 std::string str = stream.str();
267 xbt_assert(str.size() + 1 <= probe.buffer.size(),
268 "The serialized transition is too large for the buffer. Please fix the code.");
269 strncpy(probe.buffer.data(), str.c_str(), probe.buffer.size() - 1);
270 probe.buffer.back() = '\0';
272 xbt_assert(channel_.send(probe) == 0, "Could not send ACTOR_TRANSITION_PROBE payload");
274 // NOTE: We do NOT need to reset `times_considered` for each actor's
275 // simcall observer here to the "original" value (i.e. the value BEFORE
276 // multiple prepare() calls were made for serialization purposes) since
277 // each SIMCALL_EXECUTE provides a `times_considered` to be used to prepare
278 // the transition before execution.
281 void AppSide::handle_actors_maxpid() const
283 s_mc_message_int_t answer = {};
284 answer.type = MessageType::ACTORS_MAXPID_REPLY;
285 answer.value = kernel::actor::ActorImpl::get_maxpid();
286 xbt_assert(channel_.send(answer) == 0, "Could not send response");
289 #define assert_msg_size(_name_, _type_) \
290 xbt_assert(received_size == sizeof(_type_), "Unexpected size for " _name_ " (%zd != %zu)", received_size, \
293 void AppSide::handle_messages()
295 while (true) { // Until we get a CONTINUE message
296 XBT_DEBUG("Waiting messages from the model-checker");
298 std::array<char, MC_MESSAGE_LENGTH> message_buffer;
299 ssize_t received_size = channel_.receive(message_buffer.data(), message_buffer.size());
301 if (received_size == 0) {
302 XBT_DEBUG("Socket closed on the Checker side, bailing out.");
303 ::_Exit(0); // Nobody's listening to that process anymore => exit as quickly as possible.
305 xbt_assert(received_size >= 0, "Could not receive commands from the model-checker");
306 xbt_assert(static_cast<size_t>(received_size) >= sizeof(s_mc_message_t), "Cannot handle short message (size=%zd)",
309 const s_mc_message_t* message = (s_mc_message_t*)message_buffer.data();
310 switch (message->type) {
311 case MessageType::CONTINUE:
312 assert_msg_size("MESSAGE_CONTINUE", s_mc_message_t);
315 case MessageType::DEADLOCK_CHECK:
316 assert_msg_size("DEADLOCK_CHECK", s_mc_message_t);
317 handle_deadlock_check(message);
320 case MessageType::SIMCALL_EXECUTE:
321 assert_msg_size("SIMCALL_EXECUTE", s_mc_message_simcall_execute_t);
322 handle_simcall_execute((s_mc_message_simcall_execute_t*)message_buffer.data());
325 case MessageType::FINALIZE:
326 assert_msg_size("FINALIZE", s_mc_message_int_t);
327 handle_finalize((s_mc_message_int_t*)message_buffer.data());
330 case MessageType::FORK:
331 assert_msg_size("FORK", s_mc_message_int_t);
332 handle_fork((s_mc_message_int_t*)message_buffer.data());
335 case MessageType::WAIT_CHILD:
336 assert_msg_size("WAIT_CHILD", s_mc_message_int_t);
337 handle_wait_child((s_mc_message_int_t*)message_buffer.data());
340 case MessageType::NEED_MEMINFO:
341 assert_msg_size("NEED_MEMINFO", s_mc_message_t);
342 handle_need_meminfo();
345 case MessageType::ACTORS_STATUS:
346 assert_msg_size("ACTORS_STATUS", s_mc_message_t);
347 handle_actors_status();
350 case MessageType::ACTORS_MAXPID:
351 assert_msg_size("ACTORS_MAXPID", s_mc_message_t);
352 handle_actors_maxpid();
356 xbt_die("Received unexpected message %s (%i)", to_c_str(message->type), static_cast<int>(message->type));
362 void AppSide::main_loop()
364 simgrid::mc::processes_time.resize(simgrid::kernel::actor::ActorImpl::get_maxpid());
365 MC_ignore_heap(simgrid::mc::processes_time.data(),
366 simgrid::mc::processes_time.size() * sizeof(simgrid::mc::processes_time[0]));
369 coverage_checkpoint();
372 simgrid::mc::execute_actors();
373 xbt_assert(channel_.send(MessageType::WAITING) == 0, "Could not send WAITING message to model-checker");
374 this->handle_messages();
378 void AppSide::report_assertion_failure()
380 xbt_assert(channel_.send(MessageType::ASSERTION_FAILED) == 0, "Could not send assertion to model-checker");
381 this->handle_messages();
384 void AppSide::ignore_memory(void* addr, std::size_t size) const
386 if (not MC_is_active() || not need_memory_info_)
389 #if SIMGRID_HAVE_STATEFUL_MC
390 s_mc_message_ignore_memory_t message = {};
391 message.type = MessageType::IGNORE_MEMORY;
392 message.addr = (std::uintptr_t)addr;
394 xbt_assert(channel_.send(message) == 0, "Could not send IGNORE_MEMORY message to model-checker");
396 xbt_die("Cannot really call ignore_heap() in non-SIMGRID_MC mode.");
400 void AppSide::ignore_heap(void* address, std::size_t size) const
402 if (not MC_is_active() || not need_memory_info_)
405 #if SIMGRID_HAVE_STATEFUL_MC
406 const s_xbt_mheap_t* heap = mmalloc_get_current_heap();
408 s_mc_message_ignore_heap_t message = {};
409 message.type = MessageType::IGNORE_HEAP;
410 message.address = address;
412 message.block = ((char*)address - (char*)heap->heapbase) / BLOCKSIZE + 1;
413 if (heap->heapinfo[message.block].type == 0) {
414 message.fragment = -1;
415 heap->heapinfo[message.block].busy_block.ignore++;
417 message.fragment = (ADDR2UINT(address) % BLOCKSIZE) >> heap->heapinfo[message.block].type;
418 heap->heapinfo[message.block].busy_frag.ignore[message.fragment]++;
421 xbt_assert(channel_.send(message) == 0, "Could not send ignored region to MCer");
423 xbt_die("Cannot really call ignore_heap() in non-SIMGRID_MC mode.");
427 void AppSide::unignore_heap(void* address, std::size_t size) const
429 if (not MC_is_active() || not need_memory_info_)
432 #if SIMGRID_HAVE_STATEFUL_MC
433 s_mc_message_ignore_memory_t message = {};
434 message.type = MessageType::UNIGNORE_HEAP;
435 message.addr = (std::uintptr_t)address;
437 xbt_assert(channel_.send(message) == 0, "Could not send IGNORE_HEAP message to model-checker");
439 xbt_die("Cannot really call unignore_heap() in non-SIMGRID_MC mode.");
443 void AppSide::declare_symbol(const char* name, int* value) const
445 if (not MC_is_active() || not need_memory_info_) {
446 XBT_CRITICAL("Ignore AppSide::declare_symbol(%s)", name);
450 #if SIMGRID_HAVE_STATEFUL_MC
451 s_mc_message_register_symbol_t message = {};
452 message.type = MessageType::REGISTER_SYMBOL;
453 xbt_assert(strlen(name) + 1 <= message.name.size(), "Symbol is too long");
454 strncpy(message.name.data(), name, message.name.size() - 1);
455 message.callback = nullptr;
456 message.data = value;
457 xbt_assert(channel_.send(message) == 0, "Could send REGISTER_SYMBOL message to model-checker");
459 xbt_die("Cannot really call declare_symbol() in non-SIMGRID_MC mode.");
463 /** Register a stack in the model checker
465 * The stacks are allocated in the heap. The MC handle them specifically
466 * when we analyze/compare the content of the heap so it must be told where
467 * they are with this function.
469 #if HAVE_UCONTEXT_H /* Apple don't want us to use ucontexts */
470 void AppSide::declare_stack(void* stack, size_t size, ucontext_t* context) const
472 if (not MC_is_active() || not need_memory_info_)
475 #if SIMGRID_HAVE_STATEFUL_MC
476 const s_xbt_mheap_t* heap = mmalloc_get_current_heap();
478 s_stack_region_t region = {};
479 region.address = stack;
480 region.context = context;
482 region.block = ((char*)stack - (char*)heap->heapbase) / BLOCKSIZE + 1;
484 s_mc_message_stack_region_t message = {};
485 message.type = MessageType::STACK_REGION;
486 message.stack_region = region;
487 xbt_assert(channel_.send(message) == 0, "Could not send STACK_REGION to model-checker");
489 xbt_die("Cannot really call declare_stack() in non-SIMGRID_MC mode.");
494 } // namespace simgrid::mc