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