Logo AND Algorithmique Numérique Distribuée

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