Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
MC: display the status of all actors in case of deadlock
[simgrid.git] / src / mc / remote / AppSide.cpp
1 /* Copyright (c) 2015-2022. 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/remote/RemoteProcess.hpp"
15 #if HAVE_SMPI
16 #include "src/smpi/include/private.hpp"
17 #endif
18 #include "xbt/coverage.h"
19 #include "xbt/str.h"
20 #include "xbt/xbt_modinter.h" /* mmalloc_preinit to get the default mmalloc arena address */
21 #include <simgrid/modelchecker.h>
22
23 #include <cerrno>
24 #include <cstdio> // setvbuf
25 #include <cstdlib>
26 #include <cstring>
27 #include <memory>
28 #include <sys/ptrace.h>
29 #include <sys/socket.h>
30 #include <sys/types.h>
31
32 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(mc_client, mc, "MC client logic");
33 XBT_LOG_EXTERNAL_CATEGORY(mc_global);
34
35 namespace simgrid::mc {
36
37 std::unique_ptr<AppSide> AppSide::instance_;
38
39 AppSide* AppSide::initialize()
40 {
41   if (not std::getenv(MC_ENV_SOCKET_FD)) // We are not in MC mode: don't initialize the MC world
42     return nullptr;
43
44   // Do not break if we are called multiple times:
45   if (instance_)
46     return instance_.get();
47
48   simgrid::mc::cfg_do_model_check = true;
49
50   setvbuf(stdout, nullptr, _IOLBF, 0);
51
52   // Fetch socket from MC_ENV_SOCKET_FD:
53   const char* fd_env = std::getenv(MC_ENV_SOCKET_FD);
54   int fd             = xbt_str_parse_int(fd_env, "Not a number in variable '" MC_ENV_SOCKET_FD "'");
55   XBT_DEBUG("Model-checked application found socket FD %i", fd);
56
57   // Check the socket type/validity:
58   int type;
59   socklen_t socklen = sizeof(type);
60   xbt_assert(getsockopt(fd, SOL_SOCKET, SO_TYPE, &type, &socklen) == 0, "Could not check socket type");
61   xbt_assert(type == SOCK_SEQPACKET, "Unexpected socket type %i", type);
62   XBT_DEBUG("Model-checked application found expected socket type");
63
64   instance_ = std::make_unique<simgrid::mc::AppSide>(fd);
65
66   // Wait for the model-checker:
67   errno = 0;
68 #if defined __linux__
69   ptrace(PTRACE_TRACEME, 0, nullptr, nullptr);
70 #elif defined BSD
71   ptrace(PT_TRACE_ME, 0, nullptr, 0);
72 #else
73 #error "no ptrace equivalent coded for this platform"
74 #endif
75   xbt_assert(errno == 0 && raise(SIGSTOP) == 0, "Could not wait for the model-checker (errno = %d: %s)", errno,
76              strerror(errno));
77
78   s_mc_message_initial_addresses_t message{MessageType::INITIAL_ADDRESSES, mmalloc_get_current_heap(),
79                                            kernel::actor::ActorImpl::get_maxpid_addr()};
80   xbt_assert(instance_->channel_.send(message) == 0, "Could not send the initial message with addresses.");
81
82   instance_->handle_messages();
83   return instance_.get();
84 }
85
86 void AppSide::handle_deadlock_check(const s_mc_message_t*) const
87 {
88   auto* engine           = kernel::EngineImpl::get_instance();
89   const auto& actor_list = engine->get_actor_list();
90   bool deadlock = not actor_list.empty() && std::none_of(begin(actor_list), end(actor_list), [](const auto& kv) {
91     return mc::actor_is_enabled(kv.second);
92   });
93
94   if (deadlock) {
95     XBT_CINFO(mc_global, "**************************");
96     XBT_CINFO(mc_global, "*** DEADLOCK DETECTED ***");
97     XBT_CINFO(mc_global, "**************************");
98     engine->display_all_actor_status();
99   }
100   // Send result:
101   s_mc_message_int_t answer{MessageType::DEADLOCK_CHECK_REPLY, deadlock};
102   xbt_assert(channel_.send(answer) == 0, "Could not send response");
103 }
104 void AppSide::handle_simcall_execute(const s_mc_message_simcall_execute_t* message) const
105 {
106   kernel::actor::ActorImpl* actor = kernel::EngineImpl::get_instance()->get_actor_by_pid(message->aid_);
107   xbt_assert(actor != nullptr, "Invalid pid %ld", message->aid_);
108
109   // The client may send some messages to the server while processing the transition
110   actor->simcall_handle(message->times_considered_);
111   // Say the server that the transition is over and that it should proceed
112   xbt_assert(channel_.send(MessageType::WAITING) == 0, "Could not send MESSAGE_WAITING to model-checker");
113
114   // Finish the RPC from the server: return a serialized observer, to build a Transition on Checker side
115   s_mc_message_simcall_execute_answer_t answer;
116   memset(&answer, 0, sizeof(answer));
117   answer.type = MessageType::SIMCALL_EXECUTE_ANSWER;
118   std::stringstream stream;
119   if (actor->simcall_.observer_ != nullptr) {
120     actor->simcall_.observer_->serialize(stream);
121   } else {
122     stream << (short)mc::Transition::Type::UNKNOWN;
123   }
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';
129
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");
132 }
133
134 void AppSide::handle_finalize(const s_mc_message_int_t* msg) const
135 {
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();
141 #if HAVE_SMPI
142     XBT_DEBUG("Smpi_enabled: %d", SMPI_is_inited());
143     if (SMPI_is_inited())
144       SMPI_finalize();
145 #endif
146   }
147   coverage_checkpoint();
148   xbt_assert(channel_.send(MessageType::FINALIZE_REPLY) == 0, "Could not answer to FINALIZE");
149   std::fflush(stdout);
150   if (terminate_asap)
151     ::_Exit(0);
152 }
153 void AppSide::handle_actors_status() const
154 {
155   auto const& actor_list = kernel::EngineImpl::get_instance()->get_actor_list();
156   int count              = actor_list.size();
157   XBT_DEBUG("Serialize the actors to answer ACTORS_STATUS from the checker. %d actors to go.", count);
158
159   struct s_mc_message_actors_status_answer_t answer {
160     MessageType::ACTORS_STATUS_REPLY, count
161   };
162   std::vector<s_mc_message_actors_status_one_t> status(count);
163   int i = 0;
164   for (auto const& [aid, actor] : actor_list) {
165     status[i].aid            = aid;
166     status[i].enabled        = mc::actor_is_enabled(actor);
167     status[i].max_considered = actor->simcall_.observer_->get_max_consider();
168     i++;
169   }
170   xbt_assert(channel_.send(answer) == 0, "Could not send ACTORS_STATUS_REPLY msg");
171   if (answer.count > 0) {
172     size_t size = status.size() * sizeof(s_mc_message_actors_status_one_t);
173     xbt_assert(channel_.send(status.data(), size) == 0, "Could not send ACTORS_STATUS_REPLY data");
174   }
175 }
176
177 #define assert_msg_size(_name_, _type_)                                                                                \
178   xbt_assert(received_size == sizeof(_type_), "Unexpected size for " _name_ " (%zd != %zu)", received_size,            \
179              sizeof(_type_))
180
181 void AppSide::handle_messages() const
182 {
183   while (true) { // Until we get a CONTINUE message
184     XBT_DEBUG("Waiting messages from model-checker");
185
186     std::array<char, MC_MESSAGE_LENGTH> message_buffer;
187     ssize_t received_size = channel_.receive(message_buffer.data(), message_buffer.size());
188
189     xbt_assert(received_size >= 0, "Could not receive commands from the model-checker");
190
191     const s_mc_message_t* message = (s_mc_message_t*)message_buffer.data();
192     switch (message->type) {
193       case MessageType::DEADLOCK_CHECK:
194         assert_msg_size("DEADLOCK_CHECK", s_mc_message_t);
195         handle_deadlock_check(message);
196         break;
197
198       case MessageType::CONTINUE:
199         assert_msg_size("MESSAGE_CONTINUE", s_mc_message_t);
200         return;
201
202       case MessageType::SIMCALL_EXECUTE:
203         assert_msg_size("SIMCALL_EXECUTE", s_mc_message_simcall_execute_t);
204         handle_simcall_execute((s_mc_message_simcall_execute_t*)message_buffer.data());
205         break;
206
207       case MessageType::FINALIZE:
208         assert_msg_size("FINALIZE", s_mc_message_int_t);
209         handle_finalize((s_mc_message_int_t*)message_buffer.data());
210         break;
211
212       case MessageType::ACTORS_STATUS:
213         assert_msg_size("ACTORS_STATUS", s_mc_message_t);
214         handle_actors_status();
215         break;
216
217       default:
218         xbt_die("Received unexpected message %s (%i)", to_c_str(message->type), static_cast<int>(message->type));
219         break;
220     }
221   }
222 }
223
224 void AppSide::main_loop() const
225 {
226   simgrid::mc::processes_time.resize(simgrid::kernel::actor::ActorImpl::get_maxpid());
227   MC_ignore_heap(simgrid::mc::processes_time.data(),
228                  simgrid::mc::processes_time.size() * sizeof(simgrid::mc::processes_time[0]));
229
230   coverage_checkpoint();
231   while (true) {
232     simgrid::mc::execute_actors();
233     xbt_assert(channel_.send(MessageType::WAITING) == 0, "Could not send WAITING message to model-checker");
234     this->handle_messages();
235   }
236 }
237
238 void AppSide::report_assertion_failure() const
239 {
240   xbt_assert(channel_.send(MessageType::ASSERTION_FAILED) == 0, "Could not send assertion to model-checker");
241   this->handle_messages();
242 }
243
244 void AppSide::ignore_memory(void* addr, std::size_t size) const
245 {
246   if (not MC_is_active())
247     return;
248
249   s_mc_message_ignore_memory_t message;
250   message.type = MessageType::IGNORE_MEMORY;
251   message.addr = (std::uintptr_t)addr;
252   message.size = size;
253   xbt_assert(channel_.send(message) == 0, "Could not send IGNORE_MEMORY message to model-checker");
254 }
255
256 void AppSide::ignore_heap(void* address, std::size_t size) const
257 {
258   if (not MC_is_active())
259     return;
260
261   const s_xbt_mheap_t* heap = mmalloc_get_current_heap();
262
263   s_mc_message_ignore_heap_t message;
264   message.type    = MessageType::IGNORE_HEAP;
265   message.address = address;
266   message.size    = size;
267   message.block   = ((char*)address - (char*)heap->heapbase) / BLOCKSIZE + 1;
268   if (heap->heapinfo[message.block].type == 0) {
269     message.fragment = -1;
270     heap->heapinfo[message.block].busy_block.ignore++;
271   } else {
272     message.fragment = (ADDR2UINT(address) % BLOCKSIZE) >> heap->heapinfo[message.block].type;
273     heap->heapinfo[message.block].busy_frag.ignore[message.fragment]++;
274   }
275
276   xbt_assert(channel_.send(message) == 0, "Could not send ignored region to MCer");
277 }
278
279 void AppSide::unignore_heap(void* address, std::size_t size) const
280 {
281   if (not MC_is_active())
282     return;
283
284   s_mc_message_ignore_memory_t message;
285   message.type = MessageType::UNIGNORE_HEAP;
286   message.addr = (std::uintptr_t)address;
287   message.size = size;
288   xbt_assert(channel_.send(message) == 0, "Could not send IGNORE_HEAP message to model-checker");
289 }
290
291 void AppSide::declare_symbol(const char* name, int* value) const
292 {
293   if (not MC_is_active())
294     return;
295
296   s_mc_message_register_symbol_t message;
297   memset(&message, 0, sizeof(message));
298   message.type = MessageType::REGISTER_SYMBOL;
299   xbt_assert(strlen(name) + 1 <= message.name.size(), "Symbol is too long");
300   strncpy(message.name.data(), name, message.name.size() - 1);
301   message.callback = nullptr;
302   message.data     = value;
303   xbt_assert(channel_.send(message) == 0, "Could send REGISTER_SYMBOL message to model-checker");
304 }
305
306 /** Register a stack in the model checker
307  *
308  *  The stacks are allocated in the heap. The MC handle them specifically
309  *  when we analyze/compare the content of the heap so it must be told where
310  *  they are with this function.
311  */
312 void AppSide::declare_stack(void* stack, size_t size, ucontext_t* context) const
313 {
314   if (not MC_is_active())
315     return;
316
317   const s_xbt_mheap_t* heap = mmalloc_get_current_heap();
318
319   s_stack_region_t region;
320   memset(&region, 0, sizeof(region));
321   region.address = stack;
322   region.context = context;
323   region.size    = size;
324   region.block   = ((char*)stack - (char*)heap->heapbase) / BLOCKSIZE + 1;
325
326   s_mc_message_stack_region_t message;
327   message.type         = MessageType::STACK_REGION;
328   message.stack_region = region;
329   xbt_assert(channel_.send(message) == 0, "Could not send STACK_REGION to model-checker");
330 }
331 } // namespace simgrid::mc