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()
194 this->need_memory_info_ = true;
195 s_mc_message_need_meminfo_reply_t answer = {};
196 answer.type = MessageType::NEED_MEMINFO_REPLY;
197 answer.mmalloc_default_mdp = mmalloc_get_current_heap();
198 xbt_assert(channel_.send(answer) == 0, "Could not send response to the request for meminfo.");
200 xbt_die("SimGrid was compiled without MC suppport, so liveness and similar features are not available.");
203 void AppSide::handle_actors_status() const
205 auto const& actor_list = kernel::EngineImpl::get_instance()->get_actor_list();
206 XBT_DEBUG("Serialize the actors to answer ACTORS_STATUS from the checker. %zu actors to go.", actor_list.size());
208 std::vector<s_mc_message_actors_status_one_t> status;
209 for (auto const& [aid, actor] : actor_list) {
210 s_mc_message_actors_status_one_t one = {};
211 one.type = MessageType::ACTORS_STATUS_REPLY_TRANSITION;
213 one.enabled = mc::actor_is_enabled(actor);
214 one.max_considered = actor->simcall_.observer_->get_max_consider();
215 status.push_back(one);
218 struct s_mc_message_actors_status_answer_t answer = {};
219 answer.type = MessageType::ACTORS_STATUS_REPLY_COUNT;
220 answer.count = static_cast<int>(status.size());
222 xbt_assert(channel_.send(answer) == 0, "Could not send ACTORS_STATUS_REPLY msg");
223 if (answer.count > 0) {
224 size_t size = status.size() * sizeof(s_mc_message_actors_status_one_t);
225 xbt_assert(channel_.send(status.data(), size) == 0, "Could not send ACTORS_STATUS_REPLY data");
228 // Serialize each transition to describe what each actor is doing
229 XBT_DEBUG("Deliver ACTOR_TRANSITION_PROBE payload");
230 for (const auto& actor_status : status) {
231 if (not actor_status.enabled)
234 const auto& actor = actor_list.at(actor_status.aid);
235 const int max_considered = actor_status.max_considered;
237 for (int times_considered = 0; times_considered < max_considered; times_considered++) {
238 std::stringstream stream;
239 s_mc_message_simcall_probe_one_t probe;
240 probe.type = MessageType::ACTORS_STATUS_REPLY_SIMCALL;
242 if (actor->simcall_.observer_ != nullptr) {
243 actor->simcall_.observer_->prepare(times_considered);
244 actor->simcall_.observer_->serialize(stream);
246 stream << (short)mc::Transition::Type::UNKNOWN;
249 std::string str = stream.str();
250 xbt_assert(str.size() + 1 <= probe.buffer.size(),
251 "The serialized transition is too large for the buffer. Please fix the code.");
252 strncpy(probe.buffer.data(), str.c_str(), probe.buffer.size() - 1);
253 probe.buffer.back() = '\0';
255 xbt_assert(channel_.send(probe) == 0, "Could not send ACTOR_TRANSITION_PROBE payload");
257 // NOTE: We do NOT need to reset `times_considered` for each actor's
258 // simcall observer here to the "original" value (i.e. the value BEFORE
259 // multiple prepare() calls were made for serialization purposes) since
260 // each SIMCALL_EXECUTE provides a `times_considered` to be used to prepare
261 // the transition before execution.
264 void AppSide::handle_actors_maxpid() const
266 s_mc_message_int_t answer = {};
267 answer.type = MessageType::ACTORS_MAXPID_REPLY;
268 answer.value = kernel::actor::ActorImpl::get_maxpid();
269 xbt_assert(channel_.send(answer) == 0, "Could not send response");
272 #define assert_msg_size(_name_, _type_) \
273 xbt_assert(received_size == sizeof(_type_), "Unexpected size for " _name_ " (%zd != %zu)", received_size, \
276 void AppSide::handle_messages()
278 while (true) { // Until we get a CONTINUE message
279 XBT_DEBUG("Waiting messages from the model-checker");
281 std::array<char, MC_MESSAGE_LENGTH> message_buffer;
282 ssize_t received_size = channel_.receive(message_buffer.data(), message_buffer.size());
284 if (received_size == 0) {
285 XBT_DEBUG("Socket closed on the Checker side, bailing out.");
286 ::_Exit(0); // Nobody's listening to that process anymore => exit as quickly as possible.
288 xbt_assert(received_size >= 0, "Could not receive commands from the model-checker");
289 xbt_assert(static_cast<size_t>(received_size) >= sizeof(s_mc_message_t), "Cannot handle short message (size=%zd)",
292 const s_mc_message_t* message = (s_mc_message_t*)message_buffer.data();
293 switch (message->type) {
294 case MessageType::CONTINUE:
295 assert_msg_size("MESSAGE_CONTINUE", s_mc_message_t);
298 case MessageType::DEADLOCK_CHECK:
299 assert_msg_size("DEADLOCK_CHECK", s_mc_message_t);
300 handle_deadlock_check(message);
303 case MessageType::SIMCALL_EXECUTE:
304 assert_msg_size("SIMCALL_EXECUTE", s_mc_message_simcall_execute_t);
305 handle_simcall_execute((s_mc_message_simcall_execute_t*)message_buffer.data());
308 case MessageType::FINALIZE:
309 assert_msg_size("FINALIZE", s_mc_message_int_t);
310 handle_finalize((s_mc_message_int_t*)message_buffer.data());
313 case MessageType::FORK:
314 assert_msg_size("FORK", s_mc_message_int_t);
315 handle_fork((s_mc_message_int_t*)message_buffer.data());
318 case MessageType::WAIT_CHILD:
319 assert_msg_size("WAIT_CHILD", s_mc_message_int_t);
320 handle_wait_child((s_mc_message_int_t*)message_buffer.data());
323 case MessageType::NEED_MEMINFO:
324 assert_msg_size("NEED_MEMINFO", s_mc_message_t);
325 handle_need_meminfo();
328 case MessageType::ACTORS_STATUS:
329 assert_msg_size("ACTORS_STATUS", s_mc_message_t);
330 handle_actors_status();
333 case MessageType::ACTORS_MAXPID:
334 assert_msg_size("ACTORS_MAXPID", s_mc_message_t);
335 handle_actors_maxpid();
339 xbt_die("Received unexpected message %s (%i)", to_c_str(message->type), static_cast<int>(message->type));
345 void AppSide::main_loop()
347 simgrid::mc::processes_time.resize(simgrid::kernel::actor::ActorImpl::get_maxpid());
348 MC_ignore_heap(simgrid::mc::processes_time.data(),
349 simgrid::mc::processes_time.size() * sizeof(simgrid::mc::processes_time[0]));
352 coverage_checkpoint();
355 simgrid::mc::execute_actors();
356 xbt_assert(channel_.send(MessageType::WAITING) == 0, "Could not send WAITING message to model-checker");
357 this->handle_messages();
361 void AppSide::report_assertion_failure()
363 xbt_assert(channel_.send(MessageType::ASSERTION_FAILED) == 0, "Could not send assertion to model-checker");
364 this->handle_messages();
367 void AppSide::ignore_memory(void* addr, std::size_t size) const
369 if (not MC_is_active() || not need_memory_info_)
373 s_mc_message_ignore_memory_t message = {};
374 message.type = MessageType::IGNORE_MEMORY;
375 message.addr = (std::uintptr_t)addr;
377 xbt_assert(channel_.send(message) == 0, "Could not send IGNORE_MEMORY message to model-checker");
379 xbt_die("Cannot really call ignore_heap() in non-SIMGRID_MC mode.");
383 void AppSide::ignore_heap(void* address, std::size_t size) const
385 if (not MC_is_active() || not need_memory_info_)
389 const s_xbt_mheap_t* heap = mmalloc_get_current_heap();
391 s_mc_message_ignore_heap_t message = {};
392 message.type = MessageType::IGNORE_HEAP;
393 message.address = address;
395 message.block = ((char*)address - (char*)heap->heapbase) / BLOCKSIZE + 1;
396 if (heap->heapinfo[message.block].type == 0) {
397 message.fragment = -1;
398 heap->heapinfo[message.block].busy_block.ignore++;
400 message.fragment = (ADDR2UINT(address) % BLOCKSIZE) >> heap->heapinfo[message.block].type;
401 heap->heapinfo[message.block].busy_frag.ignore[message.fragment]++;
404 xbt_assert(channel_.send(message) == 0, "Could not send ignored region to MCer");
406 xbt_die("Cannot really call ignore_heap() in non-SIMGRID_MC mode.");
410 void AppSide::unignore_heap(void* address, std::size_t size) const
412 if (not MC_is_active() || not need_memory_info_)
416 s_mc_message_ignore_memory_t message = {};
417 message.type = MessageType::UNIGNORE_HEAP;
418 message.addr = (std::uintptr_t)address;
420 xbt_assert(channel_.send(message) == 0, "Could not send IGNORE_HEAP message to model-checker");
422 xbt_die("Cannot really call unignore_heap() in non-SIMGRID_MC mode.");
426 void AppSide::declare_symbol(const char* name, int* value) const
428 if (not MC_is_active() || not need_memory_info_) {
429 XBT_CRITICAL("Ignore AppSide::declare_symbol(%s)", name);
434 s_mc_message_register_symbol_t message = {};
435 message.type = MessageType::REGISTER_SYMBOL;
436 xbt_assert(strlen(name) + 1 <= message.name.size(), "Symbol is too long");
437 strncpy(message.name.data(), name, message.name.size() - 1);
438 message.callback = nullptr;
439 message.data = value;
440 xbt_assert(channel_.send(message) == 0, "Could send REGISTER_SYMBOL message to model-checker");
442 xbt_die("Cannot really call declare_symbol() in non-SIMGRID_MC mode.");
446 /** Register a stack in the model checker
448 * The stacks are allocated in the heap. The MC handle them specifically
449 * when we analyze/compare the content of the heap so it must be told where
450 * they are with this function.
452 void AppSide::declare_stack(void* stack, size_t size, ucontext_t* context) const
454 if (not MC_is_active() || not need_memory_info_)
458 const s_xbt_mheap_t* heap = mmalloc_get_current_heap();
460 s_stack_region_t region = {};
461 region.address = stack;
462 region.context = context;
464 region.block = ((char*)stack - (char*)heap->heapbase) / BLOCKSIZE + 1;
466 s_mc_message_stack_region_t message = {};
467 message.type = MessageType::STACK_REGION;
468 message.stack_region = region;
469 xbt_assert(channel_.send(message) == 0, "Could not send STACK_REGION to model-checker");
471 xbt_die("Cannot really call declare_stack() in non-SIMGRID_MC mode.");
474 } // namespace simgrid::mc