Logo AND Algorithmique Numérique Distribuée

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