Fix bug about recursive function calls
[c11tester.git] / history.cc
1 #include <inttypes.h>
2 #include "history.h"
3 #include "action.h"
4 #include "funcnode.h"
5 #include "funcinst.h"
6 #include "common.h"
7 #include "concretepredicate.h"
8 #include "waitobj.h"
9
10 #include "model.h"
11 #include "execution.h"
12 #include "newfuzzer.h"
13
14 /** @brief Constructor */
15 ModelHistory::ModelHistory() :
16         func_counter(1),        /* function id starts with 1 */
17         func_map(),
18         func_map_rev(),
19         func_nodes(),
20         last_action(NULL)
21 {
22         /* The following are snapshot data structures */
23         write_history = new HashTable<void *, value_set_t *, uintptr_t, 0>();
24         loc_rd_func_nodes_map = new HashTable<void *, SnapVector<FuncNode *> *, uintptr_t, 0>();
25         loc_wr_func_nodes_map = new HashTable<void *, SnapVector<FuncNode *> *, uintptr_t, 0>();
26         loc_waiting_writes_map = new HashTable<void *, SnapVector<ConcretePredicate *> *, uintptr_t, 0>();
27         thrd_func_list = new SnapVector<func_id_list_t>();
28         thrd_last_entered_func = new SnapVector<uint32_t>();
29         thrd_waiting_write = new SnapVector<ConcretePredicate *>();
30         thrd_wait_obj = new SnapVector<WaitObj *>();
31         func_inst_act_maps = new HashTable<uint32_t, SnapVector<inst_act_map_t *> *, int, 0>(128);
32 }
33
34 ModelHistory::~ModelHistory()
35 {
36         // TODO: complete deconstructor; maybe not needed
37         for (uint i = 0;i < thrd_wait_obj->size();i++)
38                 delete (*thrd_wait_obj)[i];
39 }
40
41 void ModelHistory::enter_function(const uint32_t func_id, thread_id_t tid)
42 {
43         //model_print("thread %d entering func %d\n", tid, func_id);
44         uint id = id_to_int(tid);
45
46         if ( thrd_func_list->size() <= id ) {
47                 uint oldsize = thrd_func_list->size();
48                 thrd_func_list->resize( id + 1 );
49
50                 for (uint i = oldsize;i < id + 1;i++) {
51                         // push 0 as a dummy function id to a void seg fault
52                         new (&(*thrd_func_list)[i]) func_id_list_t();
53                         (*thrd_func_list)[i].push_back(0);
54                         thrd_last_entered_func->push_back(0);
55                 }
56         }
57
58         uint32_t last_entered_func_id = (*thrd_last_entered_func)[id];
59         (*thrd_last_entered_func)[id] = func_id;
60         (*thrd_func_list)[id].push_back(func_id);
61
62         if ( func_nodes.size() <= func_id )
63                 resize_func_nodes( func_id + 1 );
64
65         FuncNode * func_node = func_nodes[func_id];
66         func_node->function_entry_handler(tid);
67
68         /* Add edges between FuncNodes */
69         if (last_entered_func_id != 0) {
70                 FuncNode * last_func_node = func_nodes[last_entered_func_id];
71                 last_func_node->add_out_edge(func_node);
72         }
73
74         /* Monitor the statuses of threads waiting for tid */
75         // monitor_waiting_thread(func_id, tid);
76 }
77
78 /* @param func_id a non-zero value */
79 void ModelHistory::exit_function(const uint32_t func_id, thread_id_t tid)
80 {
81         uint32_t id = id_to_int(tid);
82         uint32_t last_func_id = (*thrd_func_list)[id].back();
83
84         if (last_func_id == func_id) {
85                 FuncNode * func_node = func_nodes[func_id];
86                 func_node->function_exit_handler(tid);
87
88                 (*thrd_func_list)[id].pop_back();
89         } else {
90                 ASSERT(false);
91         }
92         //model_print("thread %d exiting func %d\n", tid, func_id);
93 }
94
95 void ModelHistory::resize_func_nodes(uint32_t new_size)
96 {
97         uint32_t old_size = func_nodes.size();
98
99         if ( old_size < new_size )
100                 func_nodes.resize(new_size);
101
102         for (uint32_t id = old_size;id < new_size;id++) {
103                 const char * func_name = func_map_rev[id];
104                 FuncNode * func_node = new FuncNode(this);
105                 func_node->set_func_id(id);
106                 func_node->set_func_name(func_name);
107                 func_nodes[id] = func_node;
108         }
109 }
110
111 void ModelHistory::process_action(ModelAction *act, thread_id_t tid)
112 {
113         uint32_t thread_id = id_to_int(tid);
114         /* Return if thread tid has not entered any function that contains atomics */
115         if ( thrd_func_list->size() <= thread_id )
116                 return;
117
118         /* Monitor the statuses of threads waiting for tid */
119         // monitor_waiting_thread_counter(tid);
120
121         /* Every write action should be processed, including
122          * nonatomic writes (which have no position) */
123         if (act->is_write()) {
124                 void * location = act->get_location();
125                 uint64_t value = act->get_write_value();
126                 update_write_history(location, value);
127
128                 /* Notify FuncNodes that may read from this location */
129                 SnapVector<FuncNode *> * func_node_list = getRdFuncNodes(location);
130                 for (uint i = 0;i < func_node_list->size();i++) {
131                         FuncNode * func_node = (*func_node_list)[i];
132                         func_node->add_to_val_loc_map(value, location);
133                 }
134
135                 // check_waiting_write(act);
136         }
137
138         uint32_t func_id = (*thrd_func_list)[thread_id].back();
139
140         /* The following does not care about actions that are not inside
141          * any function that contains atomics or actions without a position */
142         if (func_id == 0 || act->get_position() == NULL)
143                 return;
144
145         if (skip_action(act))
146                 return;
147
148         FuncNode * func_node = func_nodes[func_id];
149         func_node->add_inst(act);
150
151         if (act->is_read()) {
152                 func_node->update_inst_act_map(tid, act);
153
154 //              Fuzzer * fuzzer = model->get_execution()->getFuzzer();
155 //              Predicate * selected_branch = ((NewFuzzer *)fuzzer)->get_selected_child_branch(tid);
156 //              func_node->set_predicate_tree_position(tid, selected_branch);
157         }
158 /*
159         if (act->is_write()) {
160                 Predicate * curr_pred = func_node->get_predicate_tree_position(tid);
161                 FuncInst * curr_inst = func_node->get_inst(act);
162
163                 if (curr_pred) {
164                         // Follow child
165                         curr_pred = curr_pred->follow_write_child(curr_inst);
166                 }
167                 func_node->set_predicate_tree_position(tid, curr_pred);
168         }
169 */
170
171         func_node->update_tree(act);
172         last_action = act;
173 }
174
175 /* Return the FuncNode given its func_id  */
176 FuncNode * ModelHistory::get_func_node(uint32_t func_id)
177 {
178         if (func_id == 0)
179                 return NULL;
180
181         // This node has not been added to func_nodes
182         if (func_nodes.size() <= func_id)
183                 return NULL;
184
185         return func_nodes[func_id];
186 }
187
188 /* Return the current FuncNode when given a thread id */
189 FuncNode * ModelHistory::get_curr_func_node(thread_id_t tid)
190 {
191         int thread_id = id_to_int(tid);
192         uint32_t func_id = (*thrd_func_list)[thread_id].back();
193
194         if (func_id != 0) {
195                 return func_nodes[func_id];
196         }
197
198         return NULL;
199 }
200
201 void ModelHistory::update_write_history(void * location, uint64_t write_val)
202 {
203         value_set_t * write_set = write_history->get(location);
204
205         if (write_set == NULL) {
206                 write_set = new value_set_t();
207                 write_history->put(location, write_set);
208         }
209
210         write_set->add(write_val);
211 }
212
213 void ModelHistory::update_loc_rd_func_nodes_map(void * location, FuncNode * node)
214 {
215         SnapVector<FuncNode *> * func_node_list = getRdFuncNodes(location);
216         func_node_list->push_back(node);
217 }
218
219 void ModelHistory::update_loc_wr_func_nodes_map(void * location, FuncNode * node)
220 {
221         SnapVector<FuncNode *> * func_node_list = getWrFuncNodes(location);
222         func_node_list->push_back(node);
223 }
224
225 SnapVector<FuncNode *> * ModelHistory::getRdFuncNodes(void * location)
226 {
227         SnapVector<FuncNode *> * func_node_list = loc_rd_func_nodes_map->get(location);
228         if (func_node_list == NULL) {
229                 func_node_list = new SnapVector<FuncNode *>();
230                 loc_rd_func_nodes_map->put(location, func_node_list);
231         }
232
233         return func_node_list;
234 }
235
236 SnapVector<FuncNode *> * ModelHistory::getWrFuncNodes(void * location)
237 {
238         SnapVector<FuncNode *> * func_node_list = loc_wr_func_nodes_map->get(location);
239         if (func_node_list == NULL) {
240                 func_node_list = new SnapVector<FuncNode *>();
241                 loc_wr_func_nodes_map->put(location, func_node_list);
242         }
243
244         return func_node_list;
245 }
246
247 /* When a thread is paused by Fuzzer, keep track of the condition it is waiting for */
248 void ModelHistory::add_waiting_write(ConcretePredicate * concrete)
249 {
250         void * location = concrete->get_location();
251         SnapVector<ConcretePredicate *> * waiting_conditions = loc_waiting_writes_map->get(location);
252         if (waiting_conditions == NULL) {
253                 waiting_conditions = new SnapVector<ConcretePredicate *>();
254                 loc_waiting_writes_map->put(location, waiting_conditions);
255         }
256
257         /* waiting_conditions should not have duplications */
258         waiting_conditions->push_back(concrete);
259
260         int thread_id = id_to_int(concrete->get_tid());
261         if (thrd_waiting_write->size() <= (uint) thread_id) {
262                 thrd_waiting_write->resize(thread_id + 1);
263         }
264
265         (*thrd_waiting_write)[thread_id] = concrete;
266 }
267
268 void ModelHistory::remove_waiting_write(thread_id_t tid)
269 {
270         ConcretePredicate * concrete = (*thrd_waiting_write)[ id_to_int(tid) ];
271         void * location = concrete->get_location();
272         SnapVector<ConcretePredicate *> * concrete_preds = loc_waiting_writes_map->get(location);
273
274         /* Linear search should be fine because presumably not many ConcretePredicates
275          * are at the same memory location */
276         for (uint i = 0;i < concrete_preds->size();i++) {
277                 ConcretePredicate * current = (*concrete_preds)[i];
278                 if (concrete == current) {
279                         (*concrete_preds)[i] = concrete_preds->back();
280                         concrete_preds->pop_back();
281                         break;
282                 }
283         }
284
285         int thread_id = id_to_int( concrete->get_tid() );
286         (*thrd_waiting_write)[thread_id] = NULL;
287         delete concrete;
288 }
289
290 /* Check if any other thread is waiting for this write action. If so, "notify" them */
291 void ModelHistory::check_waiting_write(ModelAction * write_act)
292 {
293         void * location = write_act->get_location();
294         uint64_t value = write_act->get_write_value();
295         SnapVector<ConcretePredicate *> * concrete_preds = loc_waiting_writes_map->get(location);
296         if (concrete_preds == NULL)
297                 return;
298
299         uint index = 0;
300         while (index < concrete_preds->size()) {
301                 ConcretePredicate * concrete_pred = (*concrete_preds)[index];
302                 SnapVector<struct concrete_pred_expr> * concrete_exprs = concrete_pred->getExpressions();
303                 bool satisfy_predicate = true;
304                 /* Check if the written value satisfies every predicate expression */
305                 for (uint i = 0;i < concrete_exprs->size();i++) {
306                         struct concrete_pred_expr concrete = (*concrete_exprs)[i];
307                         bool equality = false;
308                         switch (concrete.token) {
309                         case EQUALITY:
310                                 equality = (value == concrete.value);
311                                 break;
312                         case NULLITY:
313                                 equality = ((void*)value == NULL);
314                                 break;
315                         default:
316                                 model_print("unknown predicate token");
317                                 break;
318                         }
319
320                         if (equality != concrete.equality) {
321                                 satisfy_predicate = false;
322                                 break;
323                         }
324                 }
325
326                 if (satisfy_predicate) {
327                         /* Wake up threads */
328                         thread_id_t tid = concrete_pred->get_tid();
329                         Thread * thread = model->get_thread(tid);
330
331                         //model_print("** thread %d is woken up\n", thread->get_id());
332                         ((NewFuzzer *)model->get_execution()->getFuzzer())->notify_paused_thread(thread);
333                 }
334
335                 index++;
336         }
337 }
338
339 WaitObj * ModelHistory::getWaitObj(thread_id_t tid)
340 {
341         int thread_id = id_to_int(tid);
342         int old_size = thrd_wait_obj->size();
343         if (old_size <= thread_id) {
344                 thrd_wait_obj->resize(thread_id + 1);
345                 for (int i = old_size;i < thread_id + 1;i++) {
346                         (*thrd_wait_obj)[i] = new WaitObj( int_to_id(i) );
347                 }
348         }
349
350         return (*thrd_wait_obj)[thread_id];
351 }
352
353 void ModelHistory::add_waiting_thread(thread_id_t self_id,
354                                                                                                                                                         thread_id_t waiting_for_id, FuncNode * target_node, int dist)
355 {
356         WaitObj * self_wait_obj = getWaitObj(self_id);
357         self_wait_obj->add_waiting_for(waiting_for_id, target_node, dist);
358
359         /* Update waited-by relation */
360         WaitObj * other_wait_obj = getWaitObj(waiting_for_id);
361         other_wait_obj->add_waited_by(self_id);
362 }
363
364 /* Thread tid is woken up (or notified), so it is not waiting for others anymore */
365 void ModelHistory::remove_waiting_thread(thread_id_t tid)
366 {
367         WaitObj * self_wait_obj = getWaitObj(tid);
368         thrd_id_set_t * waiting_for = self_wait_obj->getWaitingFor();
369
370         /* Remove tid from waited_by's */
371         thrd_id_set_iter * iter = waiting_for->iterator();
372         while (iter->hasNext()) {
373                 thread_id_t other_id = iter->next();
374                 WaitObj * other_wait_obj = getWaitObj(other_id);
375                 other_wait_obj->remove_waited_by(tid);
376         }
377
378         self_wait_obj->clear_waiting_for();
379         delete iter;
380 }
381
382 void ModelHistory::stop_waiting_for_node(thread_id_t self_id,
383                                                                                                                                                                  thread_id_t waiting_for_id, FuncNode * target_node)
384 {
385         WaitObj * self_wait_obj = getWaitObj(self_id);
386         bool thread_removed = self_wait_obj->remove_waiting_for_node(waiting_for_id, target_node);
387
388         // model_print("\t%d gives up %d on node %d\n", self_id, waiting_for_id, target_node->get_func_id());
389
390         /* If thread self_id is not waiting for waiting_for_id anymore */
391         if (thread_removed) {
392                 WaitObj * other_wait_obj = getWaitObj(waiting_for_id);
393                 other_wait_obj->remove_waited_by(self_id);
394
395                 thrd_id_set_t * self_waiting_for = self_wait_obj->getWaitingFor();
396                 if ( self_waiting_for->isEmpty() ) {
397                         // model_print("\tthread %d waits for nobody, wake up\n", self_id);
398                         ModelExecution * execution = model->get_execution();
399                         Thread * thread = execution->get_thread(self_id);
400                         ((NewFuzzer *)execution->getFuzzer())->notify_paused_thread(thread);
401                 }
402         }
403 }
404
405 SnapVector<inst_act_map_t *> * ModelHistory::getThrdInstActMap(uint32_t func_id)
406 {
407         ASSERT(func_id != 0);
408
409         SnapVector<inst_act_map_t *> * maps = func_inst_act_maps->get(func_id);
410         if (maps == NULL) {
411                 maps = new SnapVector<inst_act_map_t *>();
412                 func_inst_act_maps->put(func_id, maps);
413         }
414
415         return maps;
416 }
417
418 bool ModelHistory::skip_action(ModelAction * act)
419 {
420         bool second_part_of_rmw = act->is_rmwc() || act->is_rmw();
421         modelclock_t curr_seq_number = act->get_seq_number();
422
423         /* Skip actions that are second part of a read modify write */
424         if (second_part_of_rmw)
425                 return true;
426
427         /* Skip actions with the same sequence number */
428         if (last_action != NULL) {
429                 if (last_action->get_seq_number() == curr_seq_number)
430                         return true;
431         }
432
433         /* Skip actions that are paused by fuzzer (sequence number is 0) */
434         if (curr_seq_number == 0)
435                 return true;
436
437         return false;
438 }
439
440 /* Monitor thread tid and decide whether other threads (that are waiting for tid)
441  * should keep waiting for this thread or not. Shall only be called when a thread
442  * enters a function.
443  *
444  * Heuristics: If the distance from the current FuncNode to some target node
445  * ever increases, stop waiting for this thread on this target node.
446  */
447 void ModelHistory::monitor_waiting_thread(uint32_t func_id, thread_id_t tid)
448 {
449         WaitObj * wait_obj = getWaitObj(tid);
450         thrd_id_set_t * waited_by = wait_obj->getWaitedBy();
451         FuncNode * curr_node = func_nodes[func_id];
452
453         /* For each thread waiting for tid */
454         thrd_id_set_iter * tid_iter = waited_by->iterator();
455         while (tid_iter->hasNext()) {
456                 thread_id_t waited_by_id = tid_iter->next();
457                 WaitObj * other_wait_obj = getWaitObj(waited_by_id);
458
459                 node_set_t * target_nodes = other_wait_obj->getTargetNodes(tid);
460                 node_set_iter * node_iter = target_nodes->iterator();
461                 while (node_iter->hasNext()) {
462                         FuncNode * target = node_iter->next();
463                         int old_dist = other_wait_obj->lookup_dist(tid, target);
464                         int new_dist = curr_node->compute_distance(target, old_dist);
465
466                         if (new_dist == -1) {
467                                 stop_waiting_for_node(waited_by_id, tid, target);
468                         }
469                 }
470
471                 delete node_iter;
472         }
473
474         delete tid_iter;
475 }
476
477 void ModelHistory::monitor_waiting_thread_counter(thread_id_t tid)
478 {
479         WaitObj * wait_obj = getWaitObj(tid);
480         thrd_id_set_t * waited_by = wait_obj->getWaitedBy();
481
482         // Thread tid has taken an action, update the counter for threads waiting for tid
483         thrd_id_set_iter * tid_iter = waited_by->iterator();
484         while (tid_iter->hasNext()) {
485                 thread_id_t waited_by_id = tid_iter->next();
486                 WaitObj * other_wait_obj = getWaitObj(waited_by_id);
487
488                 bool expire = other_wait_obj->incr_counter(tid);
489                 if (expire) {
490 //                      model_print("thread %d stops waiting for thread %d\n", waited_by_id, tid);
491                         wait_obj->remove_waited_by(waited_by_id);
492                         other_wait_obj->remove_waiting_for(tid);
493
494                         thrd_id_set_t * other_waiting_for = other_wait_obj->getWaitingFor();
495                         if ( other_waiting_for->isEmpty() ) {
496                                 // model_print("\tthread %d waits for nobody, wake up\n", self_id);
497                                 ModelExecution * execution = model->get_execution();
498                                 Thread * thread = execution->get_thread(waited_by_id);
499                                 ((NewFuzzer *)execution->getFuzzer())->notify_paused_thread(thread);
500                         }
501                 }
502         }
503
504         delete tid_iter;
505 }
506
507 /* Reallocate some snapshotted memories when new executions start */
508 void ModelHistory::set_new_exec_flag()
509 {
510         for (uint i = 1;i < func_nodes.size();i++) {
511                 FuncNode * func_node = func_nodes[i];
512                 func_node->set_new_exec_flag();
513         }
514 }
515
516 void ModelHistory::dump_func_node_graph()
517 {
518         model_print("digraph func_node_graph {\n");
519         for (uint i = 1;i < func_nodes.size();i++) {
520                 FuncNode * node = func_nodes[i];
521                 ModelList<FuncNode *> * out_edges = node->get_out_edges();
522
523                 model_print("\"%p\" [label=\"%s\"]\n", node, node->get_func_name());
524                 mllnode<FuncNode *> * it;
525                 for (it = out_edges->begin();it != NULL;it = it->getNext()) {
526                         FuncNode * other = it->getVal();
527                         model_print("\"%p\" -> \"%p\"\n", node, other);
528                 }
529         }
530         model_print("}\n");
531 }
532
533 void ModelHistory::print_func_node()
534 {
535         /* function id starts with 1 */
536         for (uint32_t i = 1;i < func_nodes.size();i++) {
537                 FuncNode * func_node = func_nodes[i];
538                 func_node->print_predicate_tree();
539
540 /*
541                 func_inst_list_mt * entry_insts = func_node->get_entry_insts();
542                 model_print("function %s has entry actions\n", func_node->get_func_name());
543
544                 mllnode<FuncInst*>* it;
545                 for (it = entry_insts->begin();it != NULL;it=it->getNext()) {
546                         FuncInst *inst = it->getVal();
547                         model_print("type: %d, at: %s\n", inst->get_type(), inst->get_position());
548                 }
549 */
550         }
551 }
552
553 void ModelHistory::print_waiting_threads()
554 {
555         ModelExecution * execution = model->get_execution();
556         for (unsigned int i = 0;i < execution->get_num_threads();i++) {
557                 thread_id_t tid = int_to_id(i);
558                 WaitObj * wait_obj = getWaitObj(tid);
559                 wait_obj->print_waiting_for();
560         }
561
562         for (unsigned int i = 0;i < execution->get_num_threads();i++) {
563                 thread_id_t tid = int_to_id(i);
564                 WaitObj * wait_obj = getWaitObj(tid);
565                 wait_obj->print_waited_by();
566         }
567 }