Logo AND Algorithmique Numérique Distribuée

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