Logo AND Algorithmique Numérique Distribuée

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