Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
89be71622e3c2588564802af2693de0bb228b1fb
[simgrid.git] / src / mc / sosp / mc_snapshot.cpp
1 /* Copyright (c) 2014-2019. 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 <cstddef> /* std::size_t */
7
8 #include "src/mc/mc_config.hpp"
9 #include "src/mc/mc_hash.hpp"
10 #include "src/mc/mc_smx.hpp"
11 #include "src/mc/sosp/mc_snapshot.hpp"
12
13 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(mc_snapshot, mc, "Taking and restoring snapshots");
14
15 /** @brief Read memory from a snapshot region broken across fragmented pages
16  *
17  *  @param addr    Process (non-snapshot) address of the data
18  *  @param region  Snapshot memory region where the data is located
19  *  @param target  Buffer to store the value
20  *  @param size    Size of the data to read in bytes
21  *  @return Pointer where the data is located (target buffer of original location)
22  */
23 const void* MC_region_read_fragmented(simgrid::mc::RegionSnapshot* region, void* target, const void* addr, size_t size)
24 {
25   // Last byte of the memory area:
26   void* end = (char*)addr + size - 1;
27
28   // TODO, we assume the chunks are aligned to natural chunk boundaries.
29   // We should remove this assumption.
30
31   // Page of the last byte of the memory area:
32   size_t page_end = simgrid::mc::mmu::split((std::uintptr_t)end).first;
33
34   void* dest = target;
35
36   if (dest == nullptr)
37     xbt_die("Missing destination buffer for fragmented memory access");
38
39   // Read each page:
40   while (simgrid::mc::mmu::split((std::uintptr_t)addr).first != page_end) {
41     void* snapshot_addr = mc_translate_address_region_chunked((uintptr_t)addr, region);
42     void* next_page     = (void*)simgrid::mc::mmu::join(simgrid::mc::mmu::split((std::uintptr_t)addr).first + 1, 0);
43     size_t readable     = (char*)next_page - (char*)addr;
44     memcpy(dest, snapshot_addr, readable);
45     addr = (char*)addr + readable;
46     dest = (char*)dest + readable;
47     size -= readable;
48   }
49
50   // Read the end:
51   void* snapshot_addr = mc_translate_address_region_chunked((uintptr_t)addr, region);
52   memcpy(dest, snapshot_addr, size);
53
54   return target;
55 }
56
57 /** Compare memory between snapshots (with known regions)
58  *
59  * @param addr1 Address in the first snapshot
60  * @param region1 Region of the address in the first snapshot
61  * @param addr2 Address in the second snapshot
62  * @param region2 Region of the address in the second snapshot
63  * @return same semantic as memcmp
64  */
65 int MC_snapshot_region_memcmp(const void* addr1, simgrid::mc::RegionSnapshot* region1, const void* addr2,
66                               simgrid::mc::RegionSnapshot* region2, size_t size)
67 {
68   // Using alloca() for large allocations may trigger stack overflow:
69   // use malloc if the buffer is too big.
70   bool stack_alloc = size < 64;
71   void* buffer1a   = nullptr;
72   void* buffer2a   = nullptr;
73   if (region1 != nullptr && region1->storage_type() != simgrid::mc::StorageType::Flat)
74     buffer1a = stack_alloc ? alloca(size) : ::operator new(size);
75   if (region2 != nullptr && region2->storage_type() != simgrid::mc::StorageType::Flat)
76     buffer2a = stack_alloc ? alloca(size) : ::operator new(size);
77   const void* buffer1 = MC_region_read(region1, buffer1a, addr1, size);
78   const void* buffer2 = MC_region_read(region2, buffer2a, addr2, size);
79   int res;
80   if (buffer1 == buffer2)
81     res = 0;
82   else
83     res = memcmp(buffer1, buffer2, size);
84   if (not stack_alloc) {
85     ::operator delete(buffer1a);
86     ::operator delete(buffer2a);
87   }
88   return res;
89 }
90
91 namespace simgrid {
92 namespace mc {
93 /************************************* Take Snapshot ************************************/
94 /****************************************************************************************/
95
96 void simgrid::mc::Snapshot::snapshot_regions(simgrid::mc::RemoteClient* process)
97 {
98   snapshot_regions_.clear();
99
100   for (auto const& object_info : process->object_infos)
101     add_region(simgrid::mc::RegionType::Data, object_info.get(), object_info->start_rw, object_info->start_rw,
102                object_info->end_rw - object_info->start_rw);
103
104   xbt_mheap_t heap = process->get_heap();
105   void* start_heap = heap->base;
106   void* end_heap   = heap->breakval;
107
108   add_region(simgrid::mc::RegionType::Heap, nullptr, start_heap, start_heap, (char*)end_heap - (char*)start_heap);
109   heap_bytes_used_     = mmalloc_get_bytes_used_remote(heap->heaplimit, process->get_malloc_info());
110   privatization_index_ = simgrid::mc::ProcessIndexMissing;
111 }
112
113 /** @brief Checks whether the variable is in scope for a given IP.
114  *
115  *  A variable may be defined only from a given value of IP.
116  *
117  *  @param var   Variable description
118  *  @param scope Scope description
119  *  @param ip    Instruction pointer
120  *  @return      true if the variable is valid
121  * */
122 static bool valid_variable(simgrid::mc::Variable* var, simgrid::mc::Frame* scope, const void* ip)
123 {
124   // The variable is not yet valid:
125   if (scope->range.begin() + var->start_scope > (std::uint64_t)ip)
126     return false;
127   else
128     return true;
129 }
130
131 static void fill_local_variables_values(mc_stack_frame_t stack_frame, simgrid::mc::Frame* scope, int process_index,
132                                         std::vector<s_local_variable_t>& result)
133 {
134   if (not scope || not scope->range.contain(stack_frame->ip))
135     return;
136
137   for (simgrid::mc::Variable& current_variable : scope->variables) {
138
139     if (not valid_variable(&current_variable, scope, (void*)stack_frame->ip))
140       continue;
141
142     s_local_variable_t new_var;
143     new_var.subprogram = stack_frame->frame;
144     new_var.ip         = stack_frame->ip;
145     new_var.name       = current_variable.name;
146     new_var.type       = current_variable.type;
147     new_var.address    = nullptr;
148
149     if (current_variable.address != nullptr)
150       new_var.address = current_variable.address;
151     else if (not current_variable.location_list.empty()) {
152       simgrid::dwarf::Location location = simgrid::dwarf::resolve(
153           current_variable.location_list, current_variable.object_info, &(stack_frame->unw_cursor),
154           (void*)stack_frame->frame_base, &mc_model_checker->process(), process_index);
155
156       if (not location.in_memory())
157         xbt_die("Cannot handle non-address variable");
158       new_var.address = location.address();
159
160     } else
161       xbt_die("No address");
162
163     result.push_back(std::move(new_var));
164   }
165
166   // Recursive processing of nested scopes:
167   for (simgrid::mc::Frame& nested_scope : scope->scopes)
168     fill_local_variables_values(stack_frame, &nested_scope, process_index, result);
169 }
170
171 static std::vector<s_local_variable_t> get_local_variables_values(std::vector<s_mc_stack_frame_t>& stack_frames,
172                                                                   int process_index)
173 {
174   std::vector<s_local_variable_t> variables;
175   for (s_mc_stack_frame_t& stack_frame : stack_frames)
176     fill_local_variables_values(&stack_frame, stack_frame.frame, process_index, variables);
177   return variables;
178 }
179
180 static std::vector<s_mc_stack_frame_t> unwind_stack_frames(simgrid::mc::UnwindContext* stack_context)
181 {
182   simgrid::mc::RemoteClient* process = &mc_model_checker->process();
183   std::vector<s_mc_stack_frame_t> result;
184
185   unw_cursor_t c = stack_context->cursor();
186
187   // TODO, check condition check (unw_init_local==0 means end of frame)
188
189   while (1) {
190
191     s_mc_stack_frame_t stack_frame;
192
193     stack_frame.unw_cursor = c;
194
195     unw_word_t ip;
196     unw_word_t sp;
197
198     unw_get_reg(&c, UNW_REG_IP, &ip);
199     unw_get_reg(&c, UNW_REG_SP, &sp);
200
201     stack_frame.ip = ip;
202     stack_frame.sp = sp;
203
204     // TODO, use real addresses in frame_t instead of fixing it here
205
206     simgrid::mc::Frame* frame = process->find_function(remote(ip));
207     stack_frame.frame         = frame;
208
209     if (frame) {
210       stack_frame.frame_name = frame->name;
211       stack_frame.frame_base = (unw_word_t)frame->frame_base(c);
212     } else {
213       stack_frame.frame_base = 0;
214       stack_frame.frame_name = std::string();
215     }
216
217     result.push_back(std::move(stack_frame));
218
219     /* Stop before context switch with maestro */
220     if (frame != nullptr && frame->name == "smx_ctx_wrapper")
221       break;
222
223     int ret = unw_step(&c);
224     if (ret == 0)
225       xbt_die("Unexpected end of stack.");
226     else if (ret < 0)
227       xbt_die("Error while unwinding stack");
228   }
229
230   xbt_assert(not result.empty(), "unw_init_local failed");
231
232   return result;
233 }
234
235 void simgrid::mc::Snapshot::snapshot_stacks(simgrid::mc::RemoteClient* process)
236 {
237   for (auto const& stack : process->stack_areas()) {
238     s_mc_snapshot_stack_t st;
239
240     // Read the context from remote process:
241     unw_context_t context;
242     mc_model_checker->process().read_bytes(&context, sizeof(context), remote(stack.context));
243
244     st.context.initialize(&mc_model_checker->process(), &context);
245
246     st.stack_frames    = unwind_stack_frames(&st.context);
247     st.local_variables = get_local_variables_values(st.stack_frames, stack.process_index);
248     st.process_index   = stack.process_index;
249
250     unw_word_t sp = st.stack_frames[0].sp;
251
252     stacks_.push_back(std::move(st));
253
254     size_t stack_size = (char*)stack.address + stack.size - (char*)sp;
255     stack_sizes_.push_back(stack_size);
256   }
257 }
258
259 static void snapshot_handle_ignore(simgrid::mc::Snapshot* snapshot)
260 {
261   xbt_assert(snapshot->process());
262
263   // Copy the memory:
264   for (auto const& region : mc_model_checker->process().ignored_regions()) {
265     s_mc_snapshot_ignored_data_t ignored_data;
266     ignored_data.start = (void*)region.addr;
267     ignored_data.data.resize(region.size);
268     // TODO, we should do this once per privatization segment:
269     snapshot->process()->read_bytes(ignored_data.data.data(), region.size, remote(region.addr),
270                                     simgrid::mc::ProcessIndexDisabled);
271     snapshot->ignored_data_.push_back(std::move(ignored_data));
272   }
273
274   // Zero the memory:
275   for (auto const& region : mc_model_checker->process().ignored_regions())
276     snapshot->process()->clear_bytes(remote(region.addr), region.size);
277 }
278 static void snapshot_ignore_restore(simgrid::mc::Snapshot* snapshot)
279 {
280   for (auto const& ignored_data : snapshot->ignored_data_)
281     snapshot->process()->write_bytes(ignored_data.data.data(), ignored_data.data.size(), remote(ignored_data.start));
282 }
283
284 Snapshot::Snapshot(int _num_state, RemoteClient* process)
285     : AddressSpace(process)
286     , num_state_(_num_state)
287     , heap_bytes_used_(0)
288     , enabled_processes_()
289     , privatization_index_(0)
290     , hash_(0)
291 {
292   for (auto const& p : process->actors())
293     enabled_processes_.insert(p.copy.getBuffer()->get_pid());
294
295   snapshot_handle_ignore(this);
296
297   /* Save the std heap and the writable mapped pages of libsimgrid and binary */
298   snapshot_regions(process);
299
300   to_ignore_ = process->ignored_heap();
301
302   if (_sg_mc_max_visited_states > 0 || not _sg_mc_property_file.get().empty()) {
303     snapshot_stacks(process);
304     if (_sg_mc_hash)
305       hash_ = simgrid::mc::hash(*this);
306   }
307
308   snapshot_ignore_restore(this);
309 }
310
311 void Snapshot::add_region(RegionType type, ObjectInformation* object_info, void* start_addr, void* permanent_addr,
312                           std::size_t size)
313 {
314   if (type == simgrid::mc::RegionType::Data)
315     xbt_assert(object_info, "Missing object info for object.");
316   else if (type == simgrid::mc::RegionType::Heap)
317     xbt_assert(not object_info, "Unexpected object info for heap region.");
318
319   simgrid::mc::RegionSnapshot* region = simgrid::mc::region(type, start_addr, permanent_addr, size);
320   region->object_info(object_info);
321   snapshot_regions_.push_back(std::unique_ptr<simgrid::mc::RegionSnapshot>(std::move(region)));
322 }
323
324 const void* Snapshot::read_bytes(void* buffer, std::size_t size, RemotePtr<void> address, int process_index,
325                                  ReadOptions options) const
326 {
327   RegionSnapshot* region = this->get_region((void*)address.address(), process_index);
328   if (region) {
329     const void* res = MC_region_read(region, buffer, (void*)address.address(), size);
330     if (buffer == res || options & ReadOptions::lazy())
331       return res;
332     else {
333       memcpy(buffer, res, size);
334       return buffer;
335     }
336   } else
337     return this->process()->read_bytes(buffer, size, address, process_index, options);
338 }
339 /** @brief Find the snapshoted region from a pointer
340  *
341  *  @param addr     Pointer
342  *  @param process_index rank requesting the region
343  * */
344 RegionSnapshot* Snapshot::get_region(const void* addr, int process_index) const
345 {
346   size_t n = snapshot_regions_.size();
347   for (size_t i = 0; i != n; ++i) {
348     RegionSnapshot* region = snapshot_regions_[i].get();
349     if (not(region && region->contain(simgrid::mc::remote(addr))))
350       continue;
351
352     return region;
353   }
354
355   return nullptr;
356 }
357
358 /** @brief Find the snapshoted region from a pointer, with a hinted_region */
359 RegionSnapshot* Snapshot::get_region(const void* addr, int process_index, RegionSnapshot* hinted_region) const
360 {
361   if (hinted_region->contain(simgrid::mc::remote(addr)))
362     return hinted_region;
363   else
364     return get_region(addr, process_index);
365 }
366
367 void Snapshot::restore(RemoteClient* process)
368 {
369   XBT_DEBUG("Restore snapshot %i", num_state_);
370
371   // Restore regions
372   for (std::unique_ptr<simgrid::mc::RegionSnapshot> const& region : snapshot_regions_) {
373     if (region) // privatized variables are not snapshoted
374       region.get()->restore();
375   }
376
377   snapshot_ignore_restore(this);
378   process->clear_cache();
379 }
380
381 } // namespace mc
382 } // namespace simgrid