Fix warning
[c11tester.git] / newfuzzer.cc
1 #include "newfuzzer.h"
2 #include "threads-model.h"
3 #include "action.h"
4 #include "history.h"
5 #include "funcnode.h"
6 #include "funcinst.h"
7 #include "concretepredicate.h"
8 #include "waitobj.h"
9
10 #include "model.h"
11 #include "schedule.h"
12 #include "execution.h"
13
14 NewFuzzer::NewFuzzer() :
15         thrd_last_read_act(),
16         thrd_last_func_inst(),
17         available_branches_tmp_storage(),
18         thrd_selected_child_branch(),
19         thrd_pruned_writes(),
20         paused_thread_list(),
21         paused_thread_table(128),
22         failed_predicates(32),
23         dist_info_vec()
24 {}
25
26 /**
27  * @brief Register the ModelHistory and ModelExecution engine
28  */
29 void NewFuzzer::register_engine(ModelHistory * history, ModelExecution *execution)
30 {
31         this->history = history;
32         this->execution = execution;
33 }
34
35 int NewFuzzer::selectWrite(ModelAction *read, SnapVector<ModelAction *> * rf_set)
36 {
37 //      return random() % rf_set->size();
38
39         thread_id_t tid = read->get_tid();
40         int thread_id = id_to_int(tid);
41
42         if (thrd_last_read_act.size() <= (uint) thread_id) {
43                 thrd_last_read_act.resize(thread_id + 1);
44                 thrd_last_func_inst.resize(thread_id + 1);
45         }
46
47         // A new read action is encountered, select a random child branch of current predicate
48         if (read != thrd_last_read_act[thread_id]) {
49                 FuncNode * func_node = history->get_curr_func_node(tid);
50                 Predicate * curr_pred = func_node->get_predicate_tree_position(tid);
51                 FuncInst * read_inst = func_node->get_inst(read);
52                 inst_act_map_t * inst_act_map = func_node->get_inst_act_map(tid);
53
54                 if (curr_pred != NULL)  {
55                         Predicate * selected_branch = NULL;
56
57                         if (check_store_visibility(curr_pred, read_inst, inst_act_map, rf_set))
58                                 selected_branch = selectBranch(tid, curr_pred, read_inst);
59                         else {
60                                 // no child of curr_pred matches read_inst, check back edges
61                                 PredSet * back_edges = curr_pred->get_backedges();
62                                 PredSetIter * it = back_edges->iterator();
63
64                                 while (it->hasNext()) {
65                                         curr_pred = it->next();
66                                         if (check_store_visibility(curr_pred, read_inst, inst_act_map, rf_set)) {
67                                                 selected_branch = selectBranch(tid, curr_pred, read_inst);
68                                                 break;
69                                         }
70                                 }
71                         }
72
73                         prune_writes(tid, selected_branch, rf_set, inst_act_map);
74                 }
75
76                 if (!failed_predicates.isEmpty())
77                         failed_predicates.reset();
78
79                 thrd_last_read_act[thread_id] = read;
80                 thrd_last_func_inst[thread_id] = read_inst;
81         }
82
83         ASSERT(rf_set->size() != 0);
84         int random_index = random() % rf_set->size();
85
86         return random_index;
87 }
88
89 /* For children of curr_pred that matches read_inst.
90  * If any store in rf_set satisfies the a child's predicate,
91  * increment the store visibility count for it.
92  *
93  * @return False if no child matches read_inst
94  */
95 bool NewFuzzer::check_store_visibility(Predicate * curr_pred, FuncInst * read_inst,
96                                                                                                                                                          inst_act_map_t * inst_act_map, SnapVector<ModelAction *> * rf_set)
97 {
98         available_branches_tmp_storage.clear();
99
100         ASSERT(!rf_set->empty());
101         if (curr_pred == NULL || read_inst == NULL)
102                 return false;
103
104         ModelVector<Predicate *> * children = curr_pred->get_children();
105         bool any_child_match = false;
106
107         /* Iterate over all predicate children */
108         for (uint i = 0;i < children->size();i++) {
109                 Predicate * branch = (*children)[i];
110
111                 /* The children predicates may have different FuncInsts */
112                 if (branch->get_func_inst() == read_inst) {
113                         PredExprSet * pred_expressions = branch->get_pred_expressions();
114                         any_child_match = true;
115
116                         /* Do not check unset predicates */
117                         if (pred_expressions->isEmpty()) {
118                                 available_branches_tmp_storage.push_back(branch);
119                                 continue;
120                         }
121
122                         branch->incr_total_checking_count();
123
124                         /* Iterate over all write actions */
125                         for (uint j = 0;j < rf_set->size();j++) {
126                                 ModelAction * write_act = (*rf_set)[j];
127                                 uint64_t write_val = write_act->get_write_value();
128                                 bool dummy = true;
129                                 bool satisfy_predicate = check_predicate_expressions(pred_expressions, inst_act_map, write_val, &dummy);
130
131                                 /* If one write value satisfies the predicate, go to check the next predicate */
132                                 if (satisfy_predicate) {
133                                         branch->incr_store_visible_count();
134                                         available_branches_tmp_storage.push_back(branch);
135                                         break;
136                                 }
137                         }
138                 }
139         }
140
141         return any_child_match;
142 }
143
144 /* Select a random branch from the children of curr_pred
145  * @return The selected branch
146  */
147 Predicate * NewFuzzer::selectBranch(thread_id_t tid, Predicate * curr_pred, FuncInst * read_inst)
148 {
149         int thread_id = id_to_int(tid);
150         if ( thrd_selected_child_branch.size() <= (uint) thread_id)
151                 thrd_selected_child_branch.resize(thread_id + 1);
152
153         if (curr_pred == NULL || read_inst == NULL) {
154                 thrd_selected_child_branch[thread_id] = NULL;
155                 return NULL;
156         }
157
158         // predicate children have not been generated
159         if (available_branches_tmp_storage.size() == 0) {
160                 thrd_selected_child_branch[thread_id] = NULL;
161                 return NULL;
162         }
163
164         int index = choose_index(&available_branches_tmp_storage);
165         Predicate * random_branch = available_branches_tmp_storage[ index ];
166         thrd_selected_child_branch[thread_id] = random_branch;
167
168         return random_branch;
169 }
170
171 /**
172  * @brief Select a branch from the given predicate branch
173  */
174 int NewFuzzer::choose_index(SnapVector<Predicate *> * branches)
175 {
176         return random() % branches->size();
177 }
178
179 Predicate * NewFuzzer::get_selected_child_branch(thread_id_t tid)
180 {
181         int thread_id = id_to_int(tid);
182         if (thrd_selected_child_branch.size() <= (uint) thread_id)
183                 return NULL;
184
185         return thrd_selected_child_branch[thread_id];
186 }
187
188 /* Remove writes from the rf_set that do not satisfie the selected predicate,
189  * and store them in thrd_pruned_writes
190  *
191  * @return true if rf_set is pruned
192  */
193 bool NewFuzzer::prune_writes(thread_id_t tid, Predicate * pred,
194                                                                                                                  SnapVector<ModelAction *> * rf_set, inst_act_map_t * inst_act_map)
195 {
196         if (pred == NULL)
197                 return false;
198
199         PredExprSet * pred_expressions = pred->get_pred_expressions();
200         if (pred_expressions->getSize() == 0)   // unset predicates
201                 return false;
202
203         int thread_id = id_to_int(tid);
204         uint old_size = thrd_pruned_writes.size();
205         if (thrd_pruned_writes.size() <= (uint) thread_id) {
206                 uint new_size = thread_id + 1;
207                 thrd_pruned_writes.resize(new_size);
208                 for (uint i = old_size;i < new_size;i++)
209                         thrd_pruned_writes[i] = new SnapVector<ModelAction *>();
210         }
211         SnapVector<ModelAction *> * pruned_writes = thrd_pruned_writes[thread_id];
212         pruned_writes->clear(); // clear the old pruned_writes set
213
214         bool pruned = false;
215         uint index = 0;
216
217         while ( index < rf_set->size() ) {
218                 ModelAction * write_act = (*rf_set)[index];
219                 uint64_t write_val = write_act->get_write_value();
220                 bool no_predicate = false;
221                 bool satisfy_predicate = check_predicate_expressions(pred_expressions, inst_act_map, write_val, &no_predicate);
222
223                 if (no_predicate)
224                         return false;
225
226                 if (!satisfy_predicate) {
227                         ASSERT(rf_set != NULL);
228                         (*rf_set)[index] = rf_set->back();
229                         rf_set->pop_back();
230                         pruned_writes->push_back(write_act);
231                         pruned = true;
232                 } else
233                         index++;
234         }
235
236         return pruned;
237 }
238
239 /* @brief Put a thread to sleep because no writes in rf_set satisfies the selected predicate.
240  *
241  * @param thread A thread whose last action is a read
242  */
243 void NewFuzzer::conditional_sleep(Thread * thread)
244 {
245         int index = paused_thread_list.size();
246
247         model->getScheduler()->add_sleep(thread);
248         paused_thread_list.push_back(thread);
249         paused_thread_table.put(thread, index); // Update table
250
251         /* Add the waiting condition to ModelHistory */
252         ModelAction * read = thread->get_pending();
253         thread_id_t tid = thread->get_id();
254         FuncNode * func_node = history->get_curr_func_node(tid);
255         inst_act_map_t * inst_act_map = func_node->get_inst_act_map(tid);
256
257         Predicate * selected_branch = get_selected_child_branch(tid);
258         ConcretePredicate * concrete = selected_branch->evaluate(inst_act_map, tid);
259         concrete->set_location(read->get_location());
260
261         history->add_waiting_write(concrete);
262         /* history->add_waiting_thread is already called in find_threads */
263 }
264
265 bool NewFuzzer::has_paused_threads()
266 {
267         return paused_thread_list.size() != 0;
268 }
269
270 Thread * NewFuzzer::selectThread(int * threadlist, int numthreads)
271 {
272         if (numthreads == 0 && has_paused_threads()) {
273                 wake_up_paused_threads(threadlist, &numthreads);
274                 //model_print("list size: %d, active t id: %d\n", numthreads, threadlist[0]);
275         }
276
277         int random_index = random() % numthreads;
278         int thread = threadlist[random_index];
279         thread_id_t curr_tid = int_to_id(thread);
280         return execution->get_thread(curr_tid);
281 }
282
283 /* Force waking up one of threads paused by Fuzzer, because otherwise
284  * the Fuzzer is not making progress
285  */
286 void NewFuzzer::wake_up_paused_threads(int * threadlist, int * numthreads)
287 {
288         int random_index = random() % paused_thread_list.size();
289         Thread * thread = paused_thread_list[random_index];
290         model->getScheduler()->remove_sleep(thread);
291
292         Thread * last_thread = paused_thread_list.back();
293         paused_thread_list[random_index] = last_thread;
294         paused_thread_list.pop_back();
295         paused_thread_table.put(last_thread, random_index);     // Update table
296         paused_thread_table.remove(thread);
297
298         thread_id_t tid = thread->get_id();
299         history->remove_waiting_write(tid);
300         history->remove_waiting_thread(tid);
301
302         threadlist[*numthreads] = tid;
303         (*numthreads)++;
304
305 /*--
306         Predicate * selected_branch = get_selected_child_branch(tid);
307         update_predicate_score(selected_branch, SLEEP_FAIL_TYPE3);
308  */
309
310         model_print("thread %d is woken up\n", tid);
311 }
312
313 /* Wake up conditional sleeping threads if the desired write is available */
314 void NewFuzzer::notify_paused_thread(Thread * thread)
315 {
316         ASSERT(paused_thread_table.contains(thread));
317
318         int index = paused_thread_table.get(thread);
319         model->getScheduler()->remove_sleep(thread);
320
321         Thread * last_thread = paused_thread_list.back();
322         paused_thread_list[index] = last_thread;
323         paused_thread_list.pop_back();
324         paused_thread_table.put(last_thread, index);    // Update table
325         paused_thread_table.remove(thread);
326
327         thread_id_t tid = thread->get_id();
328         history->remove_waiting_write(tid);
329         history->remove_waiting_thread(tid);
330
331 /*--
332         Predicate * selected_branch = get_selected_child_branch(tid);
333         update_predicate_score(selected_branch, SLEEP_SUCCESS);
334  */
335
336         model_print("** thread %d is woken up\n", tid);
337 }
338
339 /* Find threads that may write values that the pending read action is waiting for.
340  * Side effect: waiting thread related info are stored in dist_info_vec
341  *
342  * @return True if any thread is found
343  */
344 bool NewFuzzer::find_threads(ModelAction * pending_read)
345 {
346         ASSERT(pending_read->is_read());
347
348         void * location = pending_read->get_location();
349         thread_id_t self_id = pending_read->get_tid();
350         bool finds_waiting_for = false;
351
352         SnapVector<FuncNode *> * func_node_list = history->getWrFuncNodes(location);
353         for (uint i = 0;i < func_node_list->size();i++) {
354                 FuncNode * target_node = (*func_node_list)[i];
355                 for (uint i = 1;i < execution->get_num_threads();i++) {
356                         thread_id_t tid = int_to_id(i);
357                         if (tid == self_id)
358                                 continue;
359
360                         FuncNode * node = history->get_curr_func_node(tid);
361                         /* It is possible that thread tid is not in any FuncNode */
362                         if (node == NULL)
363                                 continue;
364
365                         int distance = node->compute_distance(target_node);
366                         if (distance != -1) {
367                                 finds_waiting_for = true;
368                                 //model_print("thread: %d; distance from node %d to node %d: %d\n", tid, node->get_func_id(), target_node->get_func_id(), distance);
369
370                                 dist_info_vec.push_back(node_dist_info(tid, target_node, distance));
371                         }
372                 }
373         }
374
375         return finds_waiting_for;
376 }
377
378 bool NewFuzzer::check_predicate_expressions(PredExprSet * pred_expressions,
379                                                                                                                                                                                 inst_act_map_t * inst_act_map, uint64_t write_val, bool * no_predicate)
380 {
381         bool satisfy_predicate = true;
382
383         PredExprSetIter * pred_expr_it = pred_expressions->iterator();
384         while (pred_expr_it->hasNext()) {
385                 struct pred_expr * expression = pred_expr_it->next();
386                 bool equality;
387
388                 switch (expression->token) {
389                 case NOPREDICATE:
390                         *no_predicate = true;
391                         break;
392                 case EQUALITY:
393                         FuncInst * to_be_compared;
394                         ModelAction * last_act;
395                         uint64_t last_read;
396
397                         to_be_compared = expression->func_inst;
398                         last_act = inst_act_map->get(to_be_compared);
399                         last_read = last_act->get_reads_from_value();
400
401                         equality = (write_val == last_read);
402                         if (equality != expression->value)
403                                 satisfy_predicate = false;
404                         break;
405                 case NULLITY:
406                         // TODO: implement likely to be null
407                         equality = ((void*) (write_val & 0xffffffff) == NULL);
408                         if (equality != expression->value)
409                                 satisfy_predicate = false;
410                         break;
411                 default:
412                         model_print("unknown predicate token\n");
413                         break;
414                 }
415
416                 if (!satisfy_predicate)
417                         break;
418         }
419
420         return satisfy_predicate;
421 }
422
423 bool NewFuzzer::shouldWait(const ModelAction * act)
424 {
425         return random() & 1;
426 }