Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Fix two sonar bugs
[simgrid.git] / src / mc / sosp / Snapshot.cpp
1 /* Copyright (c) 2014-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/sosp/Snapshot.hpp"
7 #include "src/mc/mc_config.hpp"
8
9 #include <cstddef> /* std::size_t */
10
11 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(mc_snapshot, mc, "Taking and restoring snapshots");
12 namespace simgrid::mc {
13 /************************************* Take Snapshot ************************************/
14 /****************************************************************************************/
15
16 void Snapshot::snapshot_regions(RemoteProcessMemory& memory)
17 {
18   snapshot_regions_.clear();
19
20   for (auto const& object_info : memory.object_infos)
21     add_region(RegionType::Data, memory, object_info.get(), object_info->start_rw,
22                object_info->end_rw - object_info->start_rw);
23
24   const s_xbt_mheap_t* heap = memory.get_heap();
25   void* start_heap = heap->base;
26   void* end_heap   = heap->breakval;
27
28   add_region(RegionType::Heap, memory, nullptr, start_heap, (char*)end_heap - (char*)start_heap);
29   heap_bytes_used_ = mmalloc_get_bytes_used_remote(heap->heaplimit, memory.get_malloc_info());
30 }
31
32 /** @brief Checks whether the variable is in scope for a given IP.
33  *
34  *  A variable may be defined only from a given value of IP.
35  *
36  *  @param var   Variable description
37  *  @param scope Scope description
38  *  @param ip    Instruction pointer
39  *  @return      true if the variable is valid
40  * */
41 static bool valid_variable(const simgrid::mc::Variable* var, simgrid::mc::Frame* scope, const void* ip)
42 {
43   // The variable is not yet valid:
44   if (scope->range.begin() + var->start_scope > (std::uint64_t)ip)
45     return false;
46   else
47     return true;
48 }
49
50 static void fill_local_variables_values(mc_stack_frame_t stack_frame, Frame* scope,
51                                         std::vector<s_local_variable_t>& result, AddressSpace* memory)
52 {
53   if (not scope || not scope->range.contain(stack_frame->ip))
54     return;
55
56   for (const Variable& current_variable : scope->variables) {
57     if (not valid_variable(&current_variable, scope, (void*)stack_frame->ip))
58       continue;
59
60     if (not current_variable.type) {
61       XBT_VERB("Ignore local variable without type: '%s' [%s]", current_variable.name.c_str(),
62                stack_frame->frame->name.c_str());
63       continue;
64     }
65
66     s_local_variable_t new_var;
67     new_var.subprogram = stack_frame->frame;
68     new_var.ip         = stack_frame->ip;
69     new_var.name       = current_variable.name;
70     new_var.type       = current_variable.type;
71     new_var.address    = nullptr;
72
73     if (current_variable.address != nullptr)
74       new_var.address = current_variable.address;
75     else if (not current_variable.location_list.empty()) {
76       dwarf::Location location =
77           simgrid::dwarf::resolve(current_variable.location_list, current_variable.object_info,
78                                   &(stack_frame->unw_cursor), (void*)stack_frame->frame_base, memory);
79
80       xbt_assert(location.in_memory(), "Cannot handle non-address variable");
81       new_var.address = location.address();
82     } else
83       xbt_die("No address");
84
85     result.push_back(std::move(new_var));
86   }
87
88   // Recursive processing of nested scopes:
89   for (Frame& nested_scope : scope->scopes)
90     fill_local_variables_values(stack_frame, &nested_scope, result, memory);
91 }
92
93 static std::vector<s_local_variable_t> get_local_variables_values(std::vector<s_mc_stack_frame_t>& stack_frames,
94                                                                   AddressSpace* memory)
95 {
96   std::vector<s_local_variable_t> variables;
97   for (s_mc_stack_frame_t& stack_frame : stack_frames)
98     fill_local_variables_values(&stack_frame, stack_frame.frame, variables, memory);
99   return variables;
100 }
101
102 static std::vector<s_mc_stack_frame_t> unwind_stack_frames(UnwindContext* stack_context,
103                                                            const RemoteProcessMemory* process_memory)
104 {
105   std::vector<s_mc_stack_frame_t> result;
106
107   unw_cursor_t c = stack_context->cursor();
108
109   // TODO, check condition check (unw_init_local==0 means end of frame)
110
111   while (true) {
112     s_mc_stack_frame_t stack_frame;
113
114     stack_frame.unw_cursor = c;
115
116     unw_word_t ip;
117     unw_word_t sp;
118
119     unw_get_reg(&c, UNW_REG_IP, &ip);
120     unw_get_reg(&c, UNW_REG_SP, &sp);
121
122     stack_frame.ip = ip;
123     stack_frame.sp = sp;
124
125     // TODO, use real addresses in frame_t instead of fixing it here
126
127     Frame* frame              = process_memory->find_function(remote(ip));
128     stack_frame.frame         = frame;
129
130     if (frame) {
131       stack_frame.frame_name = frame->name;
132       stack_frame.frame_base = (unw_word_t)frame->frame_base(c);
133     } else {
134       stack_frame.frame_base = 0;
135       stack_frame.frame_name = "";
136     }
137
138     result.push_back(std::move(stack_frame));
139
140     /* Stop before context switch with maestro */
141     if (frame != nullptr && frame->name == "smx_ctx_wrapper")
142       break;
143
144     int ret = unw_step(&c);
145     xbt_assert(ret >= 0, "Error while unwinding stack");
146     xbt_assert(ret != 0, "Unexpected end of stack.");
147   }
148
149   xbt_assert(not result.empty(), "unw_init_local failed");
150
151   return result;
152 }
153
154 void Snapshot::snapshot_stacks(RemoteProcessMemory& process_memory)
155 {
156   for (auto const& stack : process_memory.stack_areas()) {
157     s_mc_snapshot_stack_t st;
158
159     // Read the context from remote process memory:
160     unw_context_t context;
161     process_memory.read_bytes(&context, sizeof(context), remote(stack.context));
162
163     st.context.initialize(process_memory, &context);
164
165     st.stack_frames    = unwind_stack_frames(&st.context, &process_memory);
166     st.local_variables = get_local_variables_values(st.stack_frames, &process_memory);
167
168     unw_word_t sp = st.stack_frames[0].sp;
169
170     stacks_.push_back(std::move(st));
171
172     size_t stack_size = (char*)stack.address + stack.size - (char*)sp;
173     stack_sizes_.push_back(stack_size);
174   }
175 }
176
177 void Snapshot::handle_ignore()
178 {
179   xbt_assert(get_remote_process_memory());
180
181   // Copy the memory:
182   for (auto const& region : get_remote_process_memory()->ignored_regions()) {
183     s_mc_snapshot_ignored_data_t ignored_data;
184     ignored_data.start = (void*)region.addr;
185     ignored_data.data.resize(region.size);
186     get_remote_process_memory()->read_bytes(ignored_data.data.data(), region.size, remote(region.addr));
187     ignored_data_.push_back(std::move(ignored_data));
188   }
189
190   // Zero the memory:
191   for (auto const& region : get_remote_process_memory()->ignored_regions())
192     get_remote_process_memory()->clear_bytes(remote(region.addr), region.size);
193 }
194
195 void Snapshot::ignore_restore() const
196 {
197   for (auto const& ignored_data : ignored_data_)
198     get_remote_process_memory()->write_bytes(ignored_data.data.data(), ignored_data.data.size(),
199                                              remote(ignored_data.start));
200 }
201
202 Snapshot::Snapshot(long num_state, PageStore& store, RemoteProcessMemory& memory)
203     : AddressSpace(&memory), page_store_(store), num_state_(num_state)
204 {
205   XBT_DEBUG("Taking snapshot %ld", num_state);
206
207   handle_ignore();
208
209   /* Save the std heap and the writable mapped pages of libsimgrid and binary */
210   snapshot_regions(memory);
211
212   to_ignore_ = memory.ignored_heap();
213
214   if (_sg_mc_max_visited_states > 0 || not _sg_mc_property_file.get().empty()) {
215     snapshot_stacks(memory);
216     hash_ = this->do_hash();
217   }
218
219   ignore_restore();
220 }
221
222 void Snapshot::add_region(RegionType type, RemoteProcessMemory& memory, ObjectInformation* object_info,
223                           void* start_addr, std::size_t size)
224 {
225   if (type == RegionType::Data)
226     xbt_assert(object_info, "Missing object info for object.");
227   else if (type == RegionType::Heap)
228     xbt_assert(not object_info, "Unexpected object info for heap region.");
229
230   auto* region = new Region(page_store_, memory, type, start_addr, size);
231   region->object_info(object_info);
232   snapshot_regions_.push_back(std::unique_ptr<Region>(region));
233 }
234
235 void* Snapshot::read_bytes(void* buffer, std::size_t size, RemotePtr<void> address, ReadOptions options) const
236 {
237   const Region* region = this->get_region((void*)address.address());
238   if (region) {
239     void* res = region->read(buffer, (void*)address.address(), size);
240     if (buffer == res || options & ReadOptions::lazy())
241       return res;
242     else {
243       memcpy(buffer, res, size);
244       return buffer;
245     }
246   } else
247     return this->get_remote_process_memory()->read_bytes(buffer, size, address, options);
248 }
249 /** @brief Find the snapshotted region from a pointer
250  *
251  *  @param addr     Pointer
252  * */
253 Region* Snapshot::get_region(const void* addr) const
254 {
255   size_t n = snapshot_regions_.size();
256   for (size_t i = 0; i != n; ++i) {
257     Region* region = snapshot_regions_[i].get();
258     if (not(region && region->contain(simgrid::mc::remote(addr))))
259       continue;
260
261     return region;
262   }
263
264   return nullptr;
265 }
266
267 /** @brief Find the snapshotted region from a pointer, with a hinted_region */
268 Region* Snapshot::get_region(const void* addr, Region* hinted_region) const
269 {
270   if (hinted_region->contain(simgrid::mc::remote(addr)))
271     return hinted_region;
272   else
273     return get_region(addr);
274 }
275
276 void Snapshot::restore(RemoteProcessMemory& memory) const
277 {
278   XBT_DEBUG("Restore snapshot %ld", num_state_);
279
280   // Restore regions
281   for (std::unique_ptr<Region> const& region : snapshot_regions_) {
282     region->restore(memory);
283   }
284
285   ignore_restore();
286   memory.clear_cache();
287 }
288
289 /* ----------- Hashing logic -------------- */
290 class djb_hash {
291   hash_type state_ = 5381LL;
292
293 public:
294   template <class T> void update(T& x) { state_ = (state_ << 5) + state_ + x; }
295   hash_type value() const { return state_; }
296 };
297 hash_type Snapshot::do_hash() const
298 {
299   XBT_DEBUG("START hash %ld", num_state_);
300   djb_hash hash;
301   // TODO:
302   // * nb_processes
303   // * heap_bytes_used
304   // * root variables
305   // * basic stack frame information
306   // * stack frame local variables
307   XBT_DEBUG("END hash %ld", num_state_);
308   return hash.value();
309 }
310
311 } // namespace simgrid::mc