Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
MC: rename remote/RemoteProcess to sosp/RemoteProcessMemory
[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/sosp/RemoteProcessMemory.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 <memory>
27 #include <numeric>
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 = {};
79   message.type                = MessageType::INITIAL_ADDRESSES;
80   message.mmalloc_default_mdp              = mmalloc_get_current_heap();
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 = {};
103   answer.type  = MessageType::DEADLOCK_CHECK_REPLY;
104   answer.value = deadlock;
105   xbt_assert(channel_.send(answer) == 0, "Could not send response");
106 }
107 void AppSide::handle_simcall_execute(const s_mc_message_simcall_execute_t* message) const
108 {
109   kernel::actor::ActorImpl* actor = kernel::EngineImpl::get_instance()->get_actor_by_pid(message->aid_);
110   xbt_assert(actor != nullptr, "Invalid pid %ld", message->aid_);
111
112   // The client may send some messages to the server while processing the transition
113   actor->simcall_handle(message->times_considered_);
114   // Say the server that the transition is over and that it should proceed
115   xbt_assert(channel_.send(MessageType::WAITING) == 0, "Could not send MESSAGE_WAITING to model-checker");
116
117   // Finish the RPC from the server: return a serialized observer, to build a Transition on Checker side
118   s_mc_message_simcall_execute_answer_t answer = {};
119   answer.type = MessageType::SIMCALL_EXECUTE_ANSWER;
120   std::stringstream stream;
121   if (actor->simcall_.observer_ != nullptr) {
122     actor->simcall_.observer_->serialize(stream);
123   } else {
124     stream << (short)mc::Transition::Type::UNKNOWN;
125   }
126   std::string str = stream.str();
127   xbt_assert(str.size() + 1 <= answer.buffer.size(),
128              "The serialized simcall is too large for the buffer. Please fix the code.");
129   strncpy(answer.buffer.data(), str.c_str(), answer.buffer.size() - 1);
130   answer.buffer.back() = '\0';
131
132   XBT_DEBUG("send SIMCALL_EXECUTE_ANSWER(%s) ~> '%s'", actor->get_cname(), str.c_str());
133   xbt_assert(channel_.send(answer) == 0, "Could not send response");
134 }
135
136 void AppSide::handle_finalize(const s_mc_message_int_t* msg) const
137 {
138   bool terminate_asap = msg->value;
139   XBT_DEBUG("Finalize (terminate = %d)", (int)terminate_asap);
140   if (not terminate_asap) {
141     if (XBT_LOG_ISENABLED(mc_client, xbt_log_priority_debug))
142       kernel::EngineImpl::get_instance()->display_all_actor_status();
143 #if HAVE_SMPI
144     XBT_DEBUG("Smpi_enabled: %d", SMPI_is_inited());
145     if (SMPI_is_inited())
146       SMPI_finalize();
147 #endif
148   }
149   coverage_checkpoint();
150   xbt_assert(channel_.send(MessageType::FINALIZE_REPLY) == 0, "Could not answer to FINALIZE");
151   std::fflush(stdout);
152   if (terminate_asap)
153     ::_Exit(0);
154 }
155 void AppSide::handle_actors_status() const
156 {
157   auto const& actor_list = kernel::EngineImpl::get_instance()->get_actor_list();
158   const int num_actors   = actor_list.size();
159   XBT_DEBUG("Serialize the actors to answer ACTORS_STATUS from the checker. %d actors to go.", num_actors);
160
161   std::vector<s_mc_message_actors_status_one_t> status(num_actors);
162   int i                 = 0;
163   int total_transitions = 0;
164
165   for (auto const& [aid, actor] : actor_list) {
166     status[i].aid            = aid;
167     status[i].enabled        = mc::actor_is_enabled(actor);
168     status[i].max_considered = actor->simcall_.observer_->get_max_consider();
169     status[i].n_transitions  = mc::actor_is_enabled(actor) ? status[i].max_considered : 0;
170     total_transitions += status[i].n_transitions;
171     i++;
172   }
173
174   struct s_mc_message_actors_status_answer_t answer = {};
175   answer.type             = MessageType::ACTORS_STATUS_REPLY;
176   answer.count            = num_actors;
177   answer.transition_count = total_transitions;
178
179   xbt_assert(channel_.send(answer) == 0, "Could not send ACTORS_STATUS_REPLY msg");
180   if (answer.count > 0) {
181     size_t size = status.size() * sizeof(s_mc_message_actors_status_one_t);
182     xbt_assert(channel_.send(status.data(), size) == 0, "Could not send ACTORS_STATUS_REPLY data");
183   }
184
185   // Serialize each transition to describe what each actor is doing
186   if (total_transitions > 0) {
187     std::vector<s_mc_message_simcall_probe_one_t> probes(total_transitions);
188     auto probes_iter = probes.begin();
189
190     for (const auto& actor_status : status) {
191       if (not actor_status.enabled)
192         continue;
193
194       const auto& actor        = actor_list.at(actor_status.aid);
195       const int max_considered = actor_status.max_considered;
196
197       for (int times_considered = 0; times_considered < max_considered; times_considered++, probes_iter++) {
198         std::stringstream stream;
199         s_mc_message_simcall_probe_one_t& probe = *probes_iter;
200
201         if (actor->simcall_.observer_ != nullptr) {
202           actor->simcall_.observer_->prepare(times_considered);
203           actor->simcall_.observer_->serialize(stream);
204         } else {
205           stream << (short)mc::Transition::Type::UNKNOWN;
206         }
207
208         std::string str = stream.str();
209         xbt_assert(str.size() + 1 <= probe.buffer.size(),
210                    "The serialized transition is too large for the buffer. Please fix the code.");
211         strncpy(probe.buffer.data(), str.c_str(), probe.buffer.size() - 1);
212         probe.buffer.back() = '\0';
213       }
214       // NOTE: We do NOT need to reset `times_considered` for each actor's
215       // simcall observer here to the "original" value (i.e. the value BEFORE
216       // multiple prepare() calls were made for serialization purposes) since
217       // each SIMCALL_EXECUTE provides a `times_considered` to be used to prepare
218       // the transition before execution.
219     }
220     XBT_DEBUG("Deliver ACTOR_TRANSITION_PROBE payload");
221
222     for (const auto& probe : probes)
223       xbt_assert(channel_.send(probe) == 0, "Could not send ACTOR_TRANSITION_PROBE payload");
224   }
225 }
226 void AppSide::handle_actors_maxpid() const
227 {
228   s_mc_message_int_t answer = {};
229   answer.type               = MessageType::ACTORS_MAXPID_REPLY;
230   answer.value              = kernel::actor::ActorImpl::get_maxpid();
231   xbt_assert(channel_.send(answer) == 0, "Could not send response");
232 }
233
234 #define assert_msg_size(_name_, _type_)                                                                                \
235   xbt_assert(received_size == sizeof(_type_), "Unexpected size for " _name_ " (%zd != %zu)", received_size,            \
236              sizeof(_type_))
237
238 void AppSide::handle_messages() const
239 {
240   while (true) { // Until we get a CONTINUE message
241     XBT_DEBUG("Waiting messages from model-checker");
242
243     std::array<char, MC_MESSAGE_LENGTH> message_buffer;
244     ssize_t received_size = channel_.receive(message_buffer.data(), message_buffer.size());
245
246     xbt_assert(received_size >= 0, "Could not receive commands from the model-checker");
247     xbt_assert(static_cast<size_t>(received_size) >= sizeof(s_mc_message_t), "Cannot handle short message (size=%zd)",
248                received_size);
249
250     const s_mc_message_t* message = (s_mc_message_t*)message_buffer.data();
251     switch (message->type) {
252       case MessageType::DEADLOCK_CHECK:
253         assert_msg_size("DEADLOCK_CHECK", s_mc_message_t);
254         handle_deadlock_check(message);
255         break;
256
257       case MessageType::CONTINUE:
258         assert_msg_size("MESSAGE_CONTINUE", s_mc_message_t);
259         return;
260
261       case MessageType::SIMCALL_EXECUTE:
262         assert_msg_size("SIMCALL_EXECUTE", s_mc_message_simcall_execute_t);
263         handle_simcall_execute((s_mc_message_simcall_execute_t*)message_buffer.data());
264         break;
265
266       case MessageType::FINALIZE:
267         assert_msg_size("FINALIZE", s_mc_message_int_t);
268         handle_finalize((s_mc_message_int_t*)message_buffer.data());
269         break;
270
271       case MessageType::ACTORS_STATUS:
272         assert_msg_size("ACTORS_STATUS", s_mc_message_t);
273         handle_actors_status();
274         break;
275
276       case MessageType::ACTORS_MAXPID:
277         assert_msg_size("ACTORS_MAXPID", s_mc_message_t);
278         handle_actors_maxpid();
279         break;
280
281       default:
282         xbt_die("Received unexpected message %s (%i)", to_c_str(message->type), static_cast<int>(message->type));
283         break;
284     }
285   }
286 }
287
288 void AppSide::main_loop() const
289 {
290   simgrid::mc::processes_time.resize(simgrid::kernel::actor::ActorImpl::get_maxpid());
291   MC_ignore_heap(simgrid::mc::processes_time.data(),
292                  simgrid::mc::processes_time.size() * sizeof(simgrid::mc::processes_time[0]));
293
294   sthread_disable();
295   coverage_checkpoint();
296   sthread_enable();
297   while (true) {
298     simgrid::mc::execute_actors();
299     xbt_assert(channel_.send(MessageType::WAITING) == 0, "Could not send WAITING message to model-checker");
300     this->handle_messages();
301   }
302 }
303
304 void AppSide::report_assertion_failure() const
305 {
306   xbt_assert(channel_.send(MessageType::ASSERTION_FAILED) == 0, "Could not send assertion to model-checker");
307   this->handle_messages();
308 }
309
310 void AppSide::ignore_memory(void* addr, std::size_t size) const
311 {
312   if (not MC_is_active())
313     return;
314
315   s_mc_message_ignore_memory_t message = {};
316   message.type = MessageType::IGNORE_MEMORY;
317   message.addr = (std::uintptr_t)addr;
318   message.size = size;
319   xbt_assert(channel_.send(message) == 0, "Could not send IGNORE_MEMORY message to model-checker");
320 }
321
322 void AppSide::ignore_heap(void* address, std::size_t size) const
323 {
324   if (not MC_is_active())
325     return;
326
327   const s_xbt_mheap_t* heap = mmalloc_get_current_heap();
328
329   s_mc_message_ignore_heap_t message = {};
330   message.type    = MessageType::IGNORE_HEAP;
331   message.address = address;
332   message.size    = size;
333   message.block   = ((char*)address - (char*)heap->heapbase) / BLOCKSIZE + 1;
334   if (heap->heapinfo[message.block].type == 0) {
335     message.fragment = -1;
336     heap->heapinfo[message.block].busy_block.ignore++;
337   } else {
338     message.fragment = (ADDR2UINT(address) % BLOCKSIZE) >> heap->heapinfo[message.block].type;
339     heap->heapinfo[message.block].busy_frag.ignore[message.fragment]++;
340   }
341
342   xbt_assert(channel_.send(message) == 0, "Could not send ignored region to MCer");
343 }
344
345 void AppSide::unignore_heap(void* address, std::size_t size) const
346 {
347   if (not MC_is_active())
348     return;
349
350   s_mc_message_ignore_memory_t message = {};
351   message.type = MessageType::UNIGNORE_HEAP;
352   message.addr = (std::uintptr_t)address;
353   message.size = size;
354   xbt_assert(channel_.send(message) == 0, "Could not send IGNORE_HEAP message to model-checker");
355 }
356
357 void AppSide::declare_symbol(const char* name, int* value) const
358 {
359   if (not MC_is_active())
360     return;
361
362   s_mc_message_register_symbol_t message = {};
363   message.type = MessageType::REGISTER_SYMBOL;
364   xbt_assert(strlen(name) + 1 <= message.name.size(), "Symbol is too long");
365   strncpy(message.name.data(), name, message.name.size() - 1);
366   message.callback = nullptr;
367   message.data     = value;
368   xbt_assert(channel_.send(message) == 0, "Could send REGISTER_SYMBOL message to model-checker");
369 }
370
371 /** Register a stack in the model checker
372  *
373  *  The stacks are allocated in the heap. The MC handle them specifically
374  *  when we analyze/compare the content of the heap so it must be told where
375  *  they are with this function.
376  */
377 void AppSide::declare_stack(void* stack, size_t size, ucontext_t* context) const
378 {
379   if (not MC_is_active())
380     return;
381
382   const s_xbt_mheap_t* heap = mmalloc_get_current_heap();
383
384   s_stack_region_t region = {};
385   region.address = stack;
386   region.context = context;
387   region.size    = size;
388   region.block   = ((char*)stack - (char*)heap->heapbase) / BLOCKSIZE + 1;
389
390   s_mc_message_stack_region_t message = {};
391   message.type         = MessageType::STACK_REGION;
392   message.stack_region = region;
393   xbt_assert(channel_.send(message) == 0, "Could not send STACK_REGION to model-checker");
394 }
395 } // namespace simgrid::mc