Logo AND Algorithmique Numérique Distribuée

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