Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
sanitize things around FINALIZE_REPLY despite my laziness as it seems to break on...
[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   xbt_assert(channel_.send(status, sizeof(status)) == 0, "Could not send ACTORS_STATUS_REPLY data");
162 }
163
164 #define assert_msg_size(_name_, _type_)                                                                                \
165   xbt_assert(received_size == sizeof(_type_), "Unexpected size for " _name_ " (%zd != %zu)", received_size,            \
166              sizeof(_type_))
167
168 void AppSide::handle_messages() const
169 {
170   while (true) { // Until we get a CONTINUE message
171     XBT_DEBUG("Waiting messages from model-checker");
172
173     std::array<char, MC_MESSAGE_LENGTH> message_buffer;
174     ssize_t received_size = channel_.receive(message_buffer.data(), message_buffer.size());
175
176     xbt_assert(received_size >= 0, "Could not receive commands from the model-checker");
177
178     const s_mc_message_t* message = (s_mc_message_t*)message_buffer.data();
179     switch (message->type) {
180       case MessageType::DEADLOCK_CHECK:
181         assert_msg_size("DEADLOCK_CHECK", s_mc_message_t);
182         handle_deadlock_check(message);
183         break;
184
185       case MessageType::CONTINUE:
186         assert_msg_size("MESSAGE_CONTINUE", s_mc_message_t);
187         return;
188
189       case MessageType::SIMCALL_EXECUTE:
190         assert_msg_size("SIMCALL_EXECUTE", s_mc_message_simcall_execute_t);
191         handle_simcall_execute((s_mc_message_simcall_execute_t*)message_buffer.data());
192         break;
193
194       case MessageType::FINALIZE:
195         assert_msg_size("FINALIZE", s_mc_message_int_t);
196         handle_finalize((s_mc_message_int_t*)message_buffer.data());
197         break;
198
199       case MessageType::ACTORS_STATUS:
200         assert_msg_size("ACTORS_STATUS", s_mc_message_t);
201         handle_actors_status();
202         break;
203
204       default:
205         xbt_die("Received unexpected message %s (%i)", to_c_str(message->type), static_cast<int>(message->type));
206         break;
207     }
208   }
209 }
210
211 void AppSide::main_loop() const
212 {
213   simgrid::mc::processes_time.resize(simgrid::kernel::actor::ActorImpl::get_maxpid());
214   MC_ignore_heap(simgrid::mc::processes_time.data(),
215                  simgrid::mc::processes_time.size() * sizeof(simgrid::mc::processes_time[0]));
216
217   coverage_checkpoint();
218   while (true) {
219     simgrid::mc::execute_actors();
220     xbt_assert(channel_.send(MessageType::WAITING) == 0, "Could not send WAITING message to model-checker");
221     this->handle_messages();
222   }
223 }
224
225 void AppSide::report_assertion_failure() const
226 {
227   xbt_assert(channel_.send(MessageType::ASSERTION_FAILED) == 0, "Could not send assertion to model-checker");
228   this->handle_messages();
229 }
230
231 void AppSide::ignore_memory(void* addr, std::size_t size) const
232 {
233   if (not MC_is_active())
234     return;
235
236   s_mc_message_ignore_memory_t message;
237   message.type = MessageType::IGNORE_MEMORY;
238   message.addr = (std::uintptr_t)addr;
239   message.size = size;
240   xbt_assert(channel_.send(message) == 0, "Could not send IGNORE_MEMORY message to model-checker");
241 }
242
243 void AppSide::ignore_heap(void* address, std::size_t size) const
244 {
245   if (not MC_is_active())
246     return;
247
248   const s_xbt_mheap_t* heap = mmalloc_get_current_heap();
249
250   s_mc_message_ignore_heap_t message;
251   message.type    = MessageType::IGNORE_HEAP;
252   message.address = address;
253   message.size    = size;
254   message.block   = ((char*)address - (char*)heap->heapbase) / BLOCKSIZE + 1;
255   if (heap->heapinfo[message.block].type == 0) {
256     message.fragment = -1;
257     heap->heapinfo[message.block].busy_block.ignore++;
258   } else {
259     message.fragment = (ADDR2UINT(address) % BLOCKSIZE) >> heap->heapinfo[message.block].type;
260     heap->heapinfo[message.block].busy_frag.ignore[message.fragment]++;
261   }
262
263   xbt_assert(channel_.send(message) == 0, "Could not send ignored region to MCer");
264 }
265
266 void AppSide::unignore_heap(void* address, std::size_t size) const
267 {
268   if (not MC_is_active())
269     return;
270
271   s_mc_message_ignore_memory_t message;
272   message.type = MessageType::UNIGNORE_HEAP;
273   message.addr = (std::uintptr_t)address;
274   message.size = size;
275   xbt_assert(channel_.send(message) == 0, "Could not send IGNORE_HEAP message to model-checker");
276 }
277
278 void AppSide::declare_symbol(const char* name, int* value) const
279 {
280   s_mc_message_register_symbol_t message;
281   memset(&message, 0, sizeof(message));
282   message.type = MessageType::REGISTER_SYMBOL;
283   xbt_assert(strlen(name) + 1 <= message.name.size(), "Symbol is too long");
284   strncpy(message.name.data(), name, message.name.size());
285   message.callback = nullptr;
286   message.data     = value;
287   xbt_assert(channel_.send(message) == 0, "Could send REGISTER_SYMBOL message to model-checker");
288 }
289
290 /** Register a stack in the model checker
291  *
292  *  The stacks are allocated in the heap. The MC handle them specifically
293  *  when we analyze/compare the content of the heap so it must be told where
294  *  they are with this function.
295  */
296 void AppSide::declare_stack(void* stack, size_t size, ucontext_t* context) const
297 {
298   if (not MC_is_active())
299     return;
300
301   const s_xbt_mheap_t* heap = mmalloc_get_current_heap();
302
303   s_stack_region_t region;
304   memset(&region, 0, sizeof(region));
305   region.address = stack;
306   region.context = context;
307   region.size    = size;
308   region.block   = ((char*)stack - (char*)heap->heapbase) / BLOCKSIZE + 1;
309
310   s_mc_message_stack_region_t message;
311   message.type         = MessageType::STACK_REGION;
312   message.stack_region = region;
313   xbt_assert(channel_.send(message) == 0, "Could not send STACK_REGION to model-checker");
314 }
315 } // namespace simgrid::mc