Logo AND Algorithmique Numérique Distribuée

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