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/sosp/RemoteProcessMemory.hpp"
16 #include "src/smpi/include/private.hpp"
18 #include "src/sthread/sthread.h"
19 #include "src/xbt/coverage.h"
21 #include <simgrid/modelchecker.h>
24 #include <cstdio> // setvbuf
28 #include <sys/ptrace.h>
29 #include <sys/socket.h>
30 #include <sys/types.h>
34 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(mc_client, mc, "MC client logic");
35 XBT_LOG_EXTERNAL_CATEGORY(mc_global);
37 namespace simgrid::mc {
39 std::unique_ptr<AppSide> AppSide::instance_;
41 AppSide* AppSide::initialize()
43 if (not std::getenv(MC_ENV_SOCKET_FD)) // We are not in MC mode: don't initialize the MC world
46 // Do not break if we are called multiple times:
48 return instance_.get();
50 simgrid::mc::model_checking_mode = ModelCheckingMode::APP_SIDE;
52 setvbuf(stdout, nullptr, _IOLBF, 0);
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);
59 // Check the socket type/validity:
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");
66 instance_ = std::make_unique<simgrid::mc::AppSide>(fd);
68 // Wait for the model-checker:
69 if (getenv("MC_NEED_PTRACE") != nullptr) {
72 ptrace(PTRACE_TRACEME, 0, nullptr, nullptr);
74 ptrace(PT_TRACE_ME, 0, nullptr, 0);
76 xbt_die("no ptrace equivalent coded for this platform, please don't use the liveness checker here.");
79 xbt_assert(errno == 0 && raise(SIGSTOP) == 0, "Could not wait for the model-checker (errno = %d: %s)", errno,
83 instance_->handle_messages();
84 return instance_.get();
87 void AppSide::handle_deadlock_check(const s_mc_message_t*) const
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);
96 XBT_CINFO(mc_global, "**************************");
97 XBT_CINFO(mc_global, "*** DEADLOCK DETECTED ***");
98 XBT_CINFO(mc_global, "**************************");
99 engine->display_all_actor_status();
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");
107 void AppSide::handle_simcall_execute(const s_mc_message_simcall_execute_t* message) const
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_);
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");
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);
124 stream << (short)mc::Transition::Type::UNKNOWN;
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';
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");
136 void AppSide::handle_finalize(const s_mc_message_int_t* msg) const
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();
144 XBT_DEBUG("Smpi_enabled: %d", SMPI_is_inited());
145 if (SMPI_is_inited())
149 coverage_checkpoint();
150 xbt_assert(channel_.send(MessageType::FINALIZE_REPLY) == 0, "Could not answer to FINALIZE");
155 void AppSide::handle_fork(const s_mc_message_int_t* msg)
158 xbt_assert(pid >= 0, "Could not fork application sub-process: %s.", strerror(errno));
160 if (pid == 0) { // Child
161 int sock = socket(AF_LOCAL, SOCK_SEQPACKET | SOCK_CLOEXEC, 0);
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);
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));
171 channel_.reset_socket(sock);
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));
179 void AppSide::handle_wait_child(const s_mc_message_int_t* msg)
183 waitpid(msg->value, &status, 0);
184 xbt_assert(errno == 0, "Cannot wait on behalf of the checker: %s.", strerror(errno));
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));
191 void AppSide::handle_need_meminfo()
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.");
199 void AppSide::handle_actors_status() const
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());
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;
209 one.enabled = mc::actor_is_enabled(actor);
210 one.max_considered = actor->simcall_.observer_->get_max_consider();
211 status.push_back(one);
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());
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");
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)
230 const auto& actor = actor_list.at(actor_status.aid);
231 const int max_considered = actor_status.max_considered;
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;
238 if (actor->simcall_.observer_ != nullptr) {
239 actor->simcall_.observer_->prepare(times_considered);
240 actor->simcall_.observer_->serialize(stream);
242 stream << (short)mc::Transition::Type::UNKNOWN;
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';
251 xbt_assert(channel_.send(probe) == 0, "Could not send ACTOR_TRANSITION_PROBE payload");
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.
260 void AppSide::handle_actors_maxpid() const
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");
268 #define assert_msg_size(_name_, _type_) \
269 xbt_assert(received_size == sizeof(_type_), "Unexpected size for " _name_ " (%zd != %zu)", received_size, \
272 void AppSide::handle_messages()
274 while (true) { // Until we get a CONTINUE message
275 XBT_DEBUG("Waiting messages from the model-checker");
277 std::array<char, MC_MESSAGE_LENGTH> message_buffer;
278 ssize_t received_size = channel_.receive(message_buffer.data(), message_buffer.size());
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.
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)",
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);
294 case MessageType::DEADLOCK_CHECK:
295 assert_msg_size("DEADLOCK_CHECK", s_mc_message_t);
296 handle_deadlock_check(message);
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());
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());
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());
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());
319 case MessageType::NEED_MEMINFO:
320 assert_msg_size("NEED_MEMINFO", s_mc_message_t);
321 handle_need_meminfo();
324 case MessageType::ACTORS_STATUS:
325 assert_msg_size("ACTORS_STATUS", s_mc_message_t);
326 handle_actors_status();
329 case MessageType::ACTORS_MAXPID:
330 assert_msg_size("ACTORS_MAXPID", s_mc_message_t);
331 handle_actors_maxpid();
335 xbt_die("Received unexpected message %s (%i)", to_c_str(message->type), static_cast<int>(message->type));
341 void AppSide::main_loop()
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]));
348 coverage_checkpoint();
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();
357 void AppSide::report_assertion_failure()
359 xbt_assert(channel_.send(MessageType::ASSERTION_FAILED) == 0, "Could not send assertion to model-checker");
360 this->handle_messages();
363 void AppSide::ignore_memory(void* addr, std::size_t size) const
365 if (not MC_is_active() || not need_memory_info_)
368 s_mc_message_ignore_memory_t message = {};
369 message.type = MessageType::IGNORE_MEMORY;
370 message.addr = (std::uintptr_t)addr;
372 xbt_assert(channel_.send(message) == 0, "Could not send IGNORE_MEMORY message to model-checker");
375 void AppSide::ignore_heap(void* address, std::size_t size) const
377 if (not MC_is_active() || not need_memory_info_)
380 const s_xbt_mheap_t* heap = mmalloc_get_current_heap();
382 s_mc_message_ignore_heap_t message = {};
383 message.type = MessageType::IGNORE_HEAP;
384 message.address = address;
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++;
391 message.fragment = (ADDR2UINT(address) % BLOCKSIZE) >> heap->heapinfo[message.block].type;
392 heap->heapinfo[message.block].busy_frag.ignore[message.fragment]++;
395 xbt_assert(channel_.send(message) == 0, "Could not send ignored region to MCer");
398 void AppSide::unignore_heap(void* address, std::size_t size) const
400 if (not MC_is_active() || not need_memory_info_)
403 s_mc_message_ignore_memory_t message = {};
404 message.type = MessageType::UNIGNORE_HEAP;
405 message.addr = (std::uintptr_t)address;
407 xbt_assert(channel_.send(message) == 0, "Could not send IGNORE_HEAP message to model-checker");
410 void AppSide::declare_symbol(const char* name, int* value) const
412 if (not MC_is_active() || not need_memory_info_) {
413 XBT_CRITICAL("Ignore AppSide::declare_symbol(%s)", name);
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");
426 /** Register a stack in the model checker
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.
432 void AppSide::declare_stack(void* stack, size_t size, ucontext_t* context) const
434 if (not MC_is_active() || not need_memory_info_)
437 const s_xbt_mheap_t* heap = mmalloc_get_current_heap();
439 s_stack_region_t region = {};
440 region.address = stack;
441 region.context = context;
443 region.block = ((char*)stack - (char*)heap->heapbase) / BLOCKSIZE + 1;
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");
450 } // namespace simgrid::mc