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/remote/RemoteProcess.hpp"
16 #include "src/smpi/include/private.hpp"
18 #include "src/sthread/sthread.h"
19 #include "xbt/coverage.h"
21 #include "xbt/xbt_modinter.h" /* mmalloc_preinit to get the default mmalloc arena address */
22 #include <simgrid/modelchecker.h>
25 #include <cstdio> // setvbuf
30 #include <sys/ptrace.h>
31 #include <sys/socket.h>
32 #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::cfg_do_model_check = true;
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:
71 ptrace(PTRACE_TRACEME, 0, nullptr, nullptr);
73 ptrace(PT_TRACE_ME, 0, nullptr, 0);
75 #error "no ptrace equivalent coded for this platform"
77 xbt_assert(errno == 0 && raise(SIGSTOP) == 0, "Could not wait for the model-checker (errno = %d: %s)", errno,
80 s_mc_message_initial_addresses_t message{MessageType::INITIAL_ADDRESSES, mmalloc_get_current_heap(),
81 kernel::actor::ActorImpl::get_maxpid_addr()};
82 xbt_assert(instance_->channel_.send(message) == 0, "Could not send the initial message with addresses.");
84 instance_->handle_messages();
85 return instance_.get();
88 void AppSide::handle_deadlock_check(const s_mc_message_t*) const
90 const auto* engine = kernel::EngineImpl::get_instance();
91 const auto& actor_list = engine->get_actor_list();
92 bool deadlock = not actor_list.empty() && std::none_of(begin(actor_list), end(actor_list), [](const auto& kv) {
93 return mc::actor_is_enabled(kv.second);
97 XBT_CINFO(mc_global, "**************************");
98 XBT_CINFO(mc_global, "*** DEADLOCK DETECTED ***");
99 XBT_CINFO(mc_global, "**************************");
100 engine->display_all_actor_status();
103 s_mc_message_int_t answer{MessageType::DEADLOCK_CHECK_REPLY, deadlock};
104 xbt_assert(channel_.send(answer) == 0, "Could not send response");
106 void AppSide::handle_simcall_execute(const s_mc_message_simcall_execute_t* message) const
108 kernel::actor::ActorImpl* actor = kernel::EngineImpl::get_instance()->get_actor_by_pid(message->aid_);
109 xbt_assert(actor != nullptr, "Invalid pid %ld", message->aid_);
111 // The client may send some messages to the server while processing the transition
112 actor->simcall_handle(message->times_considered_);
113 // Say the server that the transition is over and that it should proceed
114 xbt_assert(channel_.send(MessageType::WAITING) == 0, "Could not send MESSAGE_WAITING to model-checker");
116 // Finish the RPC from the server: return a serialized observer, to build a Transition on Checker side
117 s_mc_message_simcall_execute_answer_t answer;
118 memset(&answer, 0, sizeof(answer));
119 answer.type = MessageType::SIMCALL_EXECUTE_ANSWER;
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_actors_status() const
157 auto const& actor_list = kernel::EngineImpl::get_instance()->get_actor_list();
158 const int num_actors = actor_list.size();
159 XBT_DEBUG("Serialize the actors to answer ACTORS_STATUS from the checker. %d actors to go.", num_actors);
161 std::vector<s_mc_message_actors_status_one_t> status(num_actors);
163 int total_transitions = 0;
165 for (auto const& [aid, actor] : actor_list) {
167 status[i].enabled = mc::actor_is_enabled(actor);
168 status[i].max_considered = actor->simcall_.observer_->get_max_consider();
169 status[i].n_transitions = mc::actor_is_enabled(actor) ? status[i].max_considered : 0;
170 total_transitions += status[i].n_transitions;
174 struct s_mc_message_actors_status_answer_t answer {
175 MessageType::ACTORS_STATUS_REPLY, num_actors, total_transitions
178 xbt_assert(channel_.send(answer) == 0, "Could not send ACTORS_STATUS_REPLY msg");
179 if (answer.count > 0) {
180 size_t size = status.size() * sizeof(s_mc_message_actors_status_one_t);
181 xbt_assert(channel_.send(status.data(), size) == 0, "Could not send ACTORS_STATUS_REPLY data");
184 // Serialize each transition to describe what each actor is doing
185 if (total_transitions > 0) {
186 std::vector<s_mc_message_simcall_probe_one_t> probes(total_transitions);
187 auto probes_iter = probes.begin();
189 for (const auto& actor_status : status) {
190 if (not actor_status.enabled)
193 const auto& actor = actor_list.at(actor_status.aid);
194 const int max_considered = actor_status.max_considered;
196 for (int times_considered = 0; times_considered < max_considered; times_considered++, probes_iter++) {
197 std::stringstream stream;
198 s_mc_message_simcall_probe_one_t& probe = *probes_iter;
200 if (actor->simcall_.observer_ != nullptr) {
201 actor->simcall_.observer_->prepare(times_considered);
202 actor->simcall_.observer_->serialize(stream);
204 stream << (short)mc::Transition::Type::UNKNOWN;
207 std::string str = stream.str();
208 xbt_assert(str.size() + 1 <= probe.buffer.size(),
209 "The serialized transition is too large for the buffer. Please fix the code.");
210 strncpy(probe.buffer.data(), str.c_str(), probe.buffer.size() - 1);
211 probe.buffer.back() = '\0';
213 // TODO: Do we need to reset `times_considered` for each actor's
214 // simcall observer here to the "original" value? We may need to
215 // add a method to handle this
219 size_t size = probes.size() * sizeof(s_mc_message_simcall_probe_one_t);
220 XBT_DEBUG("Deliver ACTOR_TRANSITION_PROBE payload");
221 xbt_assert(channel_.send(probes.data(), size) == 0, "Could not send ACTOR_TRANSITION_PROBE payload");
225 #define assert_msg_size(_name_, _type_) \
226 xbt_assert(received_size == sizeof(_type_), "Unexpected size for " _name_ " (%zd != %zu)", received_size, \
229 void AppSide::handle_messages() const
231 while (true) { // Until we get a CONTINUE message
232 XBT_DEBUG("Waiting messages from model-checker");
234 std::array<char, MC_MESSAGE_LENGTH> message_buffer;
235 ssize_t received_size = channel_.receive(message_buffer.data(), message_buffer.size());
237 xbt_assert(received_size >= 0, "Could not receive commands from the model-checker");
239 const s_mc_message_t* message = (s_mc_message_t*)message_buffer.data();
240 switch (message->type) {
241 case MessageType::DEADLOCK_CHECK:
242 assert_msg_size("DEADLOCK_CHECK", s_mc_message_t);
243 handle_deadlock_check(message);
246 case MessageType::CONTINUE:
247 assert_msg_size("MESSAGE_CONTINUE", s_mc_message_t);
250 case MessageType::SIMCALL_EXECUTE:
251 assert_msg_size("SIMCALL_EXECUTE", s_mc_message_simcall_execute_t);
252 handle_simcall_execute((s_mc_message_simcall_execute_t*)message_buffer.data());
255 case MessageType::FINALIZE:
256 assert_msg_size("FINALIZE", s_mc_message_int_t);
257 handle_finalize((s_mc_message_int_t*)message_buffer.data());
260 case MessageType::ACTORS_STATUS:
261 assert_msg_size("ACTORS_STATUS", s_mc_message_t);
262 handle_actors_status();
266 xbt_die("Received unexpected message %s (%i)", to_c_str(message->type), static_cast<int>(message->type));
272 void AppSide::main_loop() const
274 simgrid::mc::processes_time.resize(simgrid::kernel::actor::ActorImpl::get_maxpid());
275 MC_ignore_heap(simgrid::mc::processes_time.data(),
276 simgrid::mc::processes_time.size() * sizeof(simgrid::mc::processes_time[0]));
279 coverage_checkpoint();
282 simgrid::mc::execute_actors();
283 xbt_assert(channel_.send(MessageType::WAITING) == 0, "Could not send WAITING message to model-checker");
284 this->handle_messages();
288 void AppSide::report_assertion_failure() const
290 xbt_assert(channel_.send(MessageType::ASSERTION_FAILED) == 0, "Could not send assertion to model-checker");
291 this->handle_messages();
294 void AppSide::ignore_memory(void* addr, std::size_t size) const
296 if (not MC_is_active())
299 s_mc_message_ignore_memory_t message;
300 message.type = MessageType::IGNORE_MEMORY;
301 message.addr = (std::uintptr_t)addr;
303 xbt_assert(channel_.send(message) == 0, "Could not send IGNORE_MEMORY message to model-checker");
306 void AppSide::ignore_heap(void* address, std::size_t size) const
308 if (not MC_is_active())
311 const s_xbt_mheap_t* heap = mmalloc_get_current_heap();
313 s_mc_message_ignore_heap_t message;
314 message.type = MessageType::IGNORE_HEAP;
315 message.address = address;
317 message.block = ((char*)address - (char*)heap->heapbase) / BLOCKSIZE + 1;
318 if (heap->heapinfo[message.block].type == 0) {
319 message.fragment = -1;
320 heap->heapinfo[message.block].busy_block.ignore++;
322 message.fragment = (ADDR2UINT(address) % BLOCKSIZE) >> heap->heapinfo[message.block].type;
323 heap->heapinfo[message.block].busy_frag.ignore[message.fragment]++;
326 xbt_assert(channel_.send(message) == 0, "Could not send ignored region to MCer");
329 void AppSide::unignore_heap(void* address, std::size_t size) const
331 if (not MC_is_active())
334 s_mc_message_ignore_memory_t message;
335 message.type = MessageType::UNIGNORE_HEAP;
336 message.addr = (std::uintptr_t)address;
338 xbt_assert(channel_.send(message) == 0, "Could not send IGNORE_HEAP message to model-checker");
341 void AppSide::declare_symbol(const char* name, int* value) const
343 if (not MC_is_active())
346 s_mc_message_register_symbol_t message;
347 memset(&message, 0, sizeof(message));
348 message.type = MessageType::REGISTER_SYMBOL;
349 xbt_assert(strlen(name) + 1 <= message.name.size(), "Symbol is too long");
350 strncpy(message.name.data(), name, message.name.size() - 1);
351 message.callback = nullptr;
352 message.data = value;
353 xbt_assert(channel_.send(message) == 0, "Could send REGISTER_SYMBOL message to model-checker");
356 /** Register a stack in the model checker
358 * The stacks are allocated in the heap. The MC handle them specifically
359 * when we analyze/compare the content of the heap so it must be told where
360 * they are with this function.
362 void AppSide::declare_stack(void* stack, size_t size, ucontext_t* context) const
364 if (not MC_is_active())
367 const s_xbt_mheap_t* heap = mmalloc_get_current_heap();
369 s_stack_region_t region;
370 memset(®ion, 0, sizeof(region));
371 region.address = stack;
372 region.context = context;
374 region.block = ((char*)stack - (char*)heap->heapbase) / BLOCKSIZE + 1;
376 s_mc_message_stack_region_t message;
377 message.type = MessageType::STACK_REGION;
378 message.stack_region = region;
379 xbt_assert(channel_.send(message) == 0, "Could not send STACK_REGION to model-checker");
381 } // namespace simgrid::mc