Fix NewFuzzer::selectWrite - check back edges
[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         thrd_selected_child_branch(),
18         thrd_pruned_writes(),
19         paused_thread_list(),
20         paused_thread_table(128),
21         failed_predicates(32),
22         dist_info_vec()
23 {}
24
25 /**
26  * @brief Register the ModelHistory and ModelExecution engine
27  */
28 void NewFuzzer::register_engine(ModelHistory * history, ModelExecution *execution)
29 {
30         this->history = history;
31         this->execution = execution;
32 }
33
34 int NewFuzzer::selectWrite(ModelAction *read, SnapVector<ModelAction *> * rf_set)
35 {
36 //      return random() % rf_set->size();
37
38         thread_id_t tid = read->get_tid();
39         int thread_id = id_to_int(tid);
40
41         if (thrd_last_read_act.size() <= (uint) thread_id) {
42                 thrd_last_read_act.resize(thread_id + 1);
43                 thrd_last_func_inst.resize(thread_id + 1);
44         }
45
46         // A new read action is encountered, select a random child branch of current predicate
47         if (read != thrd_last_read_act[thread_id]) {
48                 FuncNode * func_node = history->get_curr_func_node(tid);
49                 Predicate * curr_pred = func_node->get_predicate_tree_position(tid);
50                 FuncInst * read_inst = func_node->get_inst(read);
51                 inst_act_map_t * inst_act_map = func_node->get_inst_act_map(tid);
52
53                 if (curr_pred != NULL)  {
54                         Predicate * selected_branch = NULL;
55
56                         if (check_store_visibility(curr_pred, read_inst, inst_act_map, rf_set))
57                                 selected_branch = selectBranch(tid, curr_pred, read_inst);
58                         else {
59                                 // no child of curr_pred matches read_inst, check back edges
60                                 PredSet * back_edges = curr_pred->get_backedges();
61                                 PredSetIter * it = back_edges->iterator();
62
63                                 while (it->hasNext()) {
64                                         curr_pred = it->next();
65                                         if (check_store_visibility(curr_pred, read_inst, inst_act_map, rf_set)) {
66                                                 selected_branch = selectBranch(tid, curr_pred, read_inst);
67                                                 break;
68                                         }
69                                 }
70                         }
71
72                         prune_writes(tid, selected_branch, rf_set, inst_act_map);
73                 }
74
75                 if (!failed_predicates.isEmpty())
76                         failed_predicates.reset();
77
78                 thrd_last_read_act[thread_id] = read;
79                 thrd_last_func_inst[thread_id] = read_inst;
80         }
81
82         // No write satisfies the selected predicate, so pause this thread.
83         while ( rf_set->size() == 0 ) {
84                 Predicate * selected_branch = get_selected_child_branch(tid);
85
86                 //model_print("the %d read action of thread %d at %p is unsuccessful\n", read->get_seq_number(), read_thread->get_id(), read->get_location());
87
88                 SnapVector<ModelAction *> * pruned_writes = thrd_pruned_writes[thread_id];
89                 for (uint i = 0;i < pruned_writes->size();i++) {
90                         rf_set->push_back( (*pruned_writes)[i] );
91                 }
92
93                 // Reselect a predicate and prune writes
94                 Predicate * curr_pred = selected_branch->get_parent();
95                 FuncInst * read_inst = thrd_last_func_inst[thread_id];
96                 selected_branch = selectBranch(tid, curr_pred, read_inst);
97
98                 FuncNode * func_node = history->get_curr_func_node(tid);
99                 inst_act_map_t * inst_act_map = func_node->get_inst_act_map(tid);
100                 prune_writes(tid, selected_branch, rf_set, inst_act_map);
101
102                 ASSERT(selected_branch);
103         }
104
105         ASSERT(rf_set->size() != 0);
106         int random_index = random() % rf_set->size();
107
108         return random_index;
109 }
110
111 /* For children of curr_pred that matches read_inst.
112  * If any store in rf_set satisfies the a child's predicate,
113  * increment the store visibility count for it.
114  *
115  * @return False if no child matches read_inst
116  */
117 bool NewFuzzer::check_store_visibility(Predicate * curr_pred, FuncInst * read_inst,
118 inst_act_map_t * inst_act_map, SnapVector<ModelAction *> * rf_set)
119 {
120         ASSERT(!rf_set->empty());
121         if (curr_pred == NULL || read_inst == NULL)
122                 return false;
123
124         ModelVector<Predicate *> * children = curr_pred->get_children();
125         bool any_child_match = false;
126
127         /* Iterate over all predicate children */
128         for (uint i = 0;i < children->size();i++) {
129                 Predicate * branch = (*children)[i];
130
131                 /* The children predicates may have different FuncInsts */
132                 if (branch->get_func_inst() == read_inst) {
133                         PredExprSet * pred_expressions = branch->get_pred_expressions();
134                         any_child_match = true;
135
136                         /* Do not check unset predicates */
137                         if (pred_expressions->isEmpty())
138                                 continue;
139
140                         branch->incr_total_checking_count();
141
142                         /* Iterate over all write actions */
143                         for (uint j = 0;j < rf_set->size();j++) {
144                                 ModelAction * write_act = (*rf_set)[j];
145                                 uint64_t write_val = write_act->get_write_value();
146                                 bool dummy = true;
147                                 bool satisfy_predicate = check_predicate_expressions(pred_expressions, inst_act_map, write_val, &dummy);
148
149                                 /* If one write value satisfies the predicate, go to check the next predicate */
150                                 if (satisfy_predicate) {
151                                         branch->incr_store_visible_count();
152                                         break;
153                                 }
154                         }
155                 }
156         }
157
158         return any_child_match;
159 }
160
161
162 /* Select a random branch from the children of curr_pred
163  * @return The selected branch
164  */
165 Predicate * NewFuzzer::selectBranch(thread_id_t tid, Predicate * curr_pred, FuncInst * read_inst)
166 {
167         int thread_id = id_to_int(tid);
168         if ( thrd_selected_child_branch.size() <= (uint) thread_id)
169                 thrd_selected_child_branch.resize(thread_id + 1);
170
171         if (curr_pred == NULL || read_inst == NULL) {
172                 thrd_selected_child_branch[thread_id] = NULL;
173                 return NULL;
174         }
175
176         ModelVector<Predicate *> * children = curr_pred->get_children();
177         SnapVector<Predicate *> branches;
178
179         for (uint i = 0; i < children->size(); i++) {
180                 Predicate * child = (*children)[i];
181                 if (child->get_func_inst() == read_inst && !failed_predicates.contains(child)) {
182                         branches.push_back(child);
183                 }
184         }
185
186         // predicate children have not been generated
187         if (branches.size() == 0) {
188                 thrd_selected_child_branch[thread_id] = NULL;
189                 return NULL;
190         }
191
192         int index = choose_index(&branches, 0);
193         Predicate * random_branch = branches[ index ];
194         thrd_selected_child_branch[thread_id] = random_branch;
195
196         return random_branch;
197 }
198
199 /**
200  * @brief Select a branch from the given predicate branches based
201  * on their exploration counts.
202  *
203  * Let b_1, ..., b_n be branches with exploration counts c_1, ..., c_n
204  * M := max(c_1, ..., c_n) + 1
205  * Factor f_i := M / (c_i + 1)
206  * The probability p_i that branch b_i is selected:
207  *      p_i := f_i / (f_1 + ... + f_n)
208  *           = \fraction{ 1/(c_i + 1) }{ 1/(c_1 + 1) + ... + 1/(c_n + 1) }
209  *
210  * Note: (1) c_i + 1 is used because counts may be 0.
211  *       (2) The numerator of f_i is chosen to reduce the effect of underflow
212  *
213  * @param numerator is M defined above
214  */
215 int NewFuzzer::choose_index(SnapVector<Predicate *> * branches, uint32_t numerator)
216 {
217         return random() % branches->size();
218 /*--
219         if (branches->size() == 1)
220                 return 0;
221
222         double total_factor = 0;
223         SnapVector<double> factors = SnapVector<double>( branches->size() + 1 );
224         for (uint i = 0; i < branches->size(); i++) {
225                 Predicate * branch = (*branches)[i];
226                 double factor = (double) numerator / (branch->get_expl_count() + 5 * branch->get_fail_count() + 1);
227                 total_factor += factor;
228                 factors.push_back(factor);
229         }
230
231         double prob = (double) random() / RAND_MAX;
232         double prob_sum = 0;
233         int index = 0;
234
235         for (uint i = 0; i < factors.size(); i++) {
236                 index = i;
237                 prob_sum += (double) (factors[i] / total_factor);
238                 if (prob_sum > prob) {
239                         break;
240                 }
241         }
242
243         return index;
244  */
245 }
246
247 Predicate * NewFuzzer::get_selected_child_branch(thread_id_t tid)
248 {
249         int thread_id = id_to_int(tid);
250         if (thrd_selected_child_branch.size() <= (uint) thread_id)
251                 return NULL;
252
253         return thrd_selected_child_branch[thread_id];
254 }
255
256 /* Remove writes from the rf_set that do not satisfie the selected predicate,
257  * and store them in thrd_pruned_writes
258  *
259  * @return true if rf_set is pruned
260  */
261 bool NewFuzzer::prune_writes(thread_id_t tid, Predicate * pred,
262 SnapVector<ModelAction *> * rf_set, inst_act_map_t * inst_act_map)
263 {
264         if (pred == NULL)
265                 return false;
266
267         PredExprSet * pred_expressions = pred->get_pred_expressions();
268         if (pred_expressions->getSize() == 0)   // unset predicates
269                 return false;
270
271         int thread_id = id_to_int(tid);
272         uint old_size = thrd_pruned_writes.size();
273         if (thrd_pruned_writes.size() <= (uint) thread_id) {
274                 uint new_size = thread_id + 1;
275                 thrd_pruned_writes.resize(new_size);
276                 for (uint i = old_size;i < new_size;i++)
277                         thrd_pruned_writes[i] = new SnapVector<ModelAction *>();
278         }
279         SnapVector<ModelAction *> * pruned_writes = thrd_pruned_writes[thread_id];
280         pruned_writes->clear(); // clear the old pruned_writes set
281
282         bool pruned = false;
283         uint index = 0;
284
285         while ( index < rf_set->size() ) {
286                 ModelAction * write_act = (*rf_set)[index];
287                 uint64_t write_val = write_act->get_write_value();
288                 bool no_predicate = false;
289                 bool satisfy_predicate = check_predicate_expressions(pred_expressions, inst_act_map, write_val, &no_predicate);
290
291                 if (no_predicate)
292                         return false;
293
294                 if (!satisfy_predicate) {
295                         ASSERT(rf_set != NULL);
296                         (*rf_set)[index] = rf_set->back();
297                         rf_set->pop_back();
298                         pruned_writes->push_back(write_act);
299                         pruned = true;
300                 } else
301                         index++;
302         }
303
304         return pruned;
305 }
306
307 /* @brief Put a thread to sleep because no writes in rf_set satisfies the selected predicate.
308  *
309  * @param thread A thread whose last action is a read
310  */
311 void NewFuzzer::conditional_sleep(Thread * thread)
312 {
313         int index = paused_thread_list.size();
314
315         model->getScheduler()->add_sleep(thread);
316         paused_thread_list.push_back(thread);
317         paused_thread_table.put(thread, index); // Update table
318
319         /* Add the waiting condition to ModelHistory */
320         ModelAction * read = thread->get_pending();
321         thread_id_t tid = thread->get_id();
322         FuncNode * func_node = history->get_curr_func_node(tid);
323         inst_act_map_t * inst_act_map = func_node->get_inst_act_map(tid);
324
325         Predicate * selected_branch = get_selected_child_branch(tid);
326         ConcretePredicate * concrete = selected_branch->evaluate(inst_act_map, tid);
327         concrete->set_location(read->get_location());
328
329         history->add_waiting_write(concrete);
330         /* history->add_waiting_thread is already called in find_threads */
331 }
332
333 /**
334  * Decides whether a thread should condition sleep based on
335  * the sleep score of the chosen predicate.
336  *
337  * sleep_score = 0: never sleeps
338  * sleep_score = 100: always sleeps
339  **/
340 bool NewFuzzer::should_conditional_sleep(Predicate * predicate)
341 {
342         return false;
343         /*
344            int sleep_score = predicate->get_sleep_score();
345            int random_num = random() % 100;
346
347            // should sleep if random_num falls within [0, sleep_score)
348            if (random_num < sleep_score)
349                 return true;
350
351            return false;
352          */
353 }
354
355 bool NewFuzzer::has_paused_threads()
356 {
357         return paused_thread_list.size() != 0;
358 }
359
360 Thread * NewFuzzer::selectThread(int * threadlist, int numthreads)
361 {
362         if (numthreads == 0 && has_paused_threads()) {
363                 wake_up_paused_threads(threadlist, &numthreads);
364                 //model_print("list size: %d, active t id: %d\n", numthreads, threadlist[0]);
365         }
366
367         int random_index = random() % numthreads;
368         int thread = threadlist[random_index];
369         thread_id_t curr_tid = int_to_id(thread);
370         return execution->get_thread(curr_tid);
371 }
372
373 /* Force waking up one of threads paused by Fuzzer, because otherwise
374  * the Fuzzer is not making progress
375  */
376 void NewFuzzer::wake_up_paused_threads(int * threadlist, int * numthreads)
377 {
378         int random_index = random() % paused_thread_list.size();
379         Thread * thread = paused_thread_list[random_index];
380         model->getScheduler()->remove_sleep(thread);
381
382         Thread * last_thread = paused_thread_list.back();
383         paused_thread_list[random_index] = last_thread;
384         paused_thread_list.pop_back();
385         paused_thread_table.put(last_thread, random_index);     // Update table
386         paused_thread_table.remove(thread);
387
388         thread_id_t tid = thread->get_id();
389         history->remove_waiting_write(tid);
390         history->remove_waiting_thread(tid);
391
392         threadlist[*numthreads] = tid;
393         (*numthreads)++;
394
395 /*--
396         Predicate * selected_branch = get_selected_child_branch(tid);
397         update_predicate_score(selected_branch, SLEEP_FAIL_TYPE3);
398  */
399
400         model_print("thread %d is woken up\n", tid);
401 }
402
403 /* Wake up conditional sleeping threads if the desired write is available */
404 void NewFuzzer::notify_paused_thread(Thread * thread)
405 {
406         ASSERT(paused_thread_table.contains(thread));
407
408         int index = paused_thread_table.get(thread);
409         model->getScheduler()->remove_sleep(thread);
410
411         Thread * last_thread = paused_thread_list.back();
412         paused_thread_list[index] = last_thread;
413         paused_thread_list.pop_back();
414         paused_thread_table.put(last_thread, index);    // Update table
415         paused_thread_table.remove(thread);
416
417         thread_id_t tid = thread->get_id();
418         history->remove_waiting_write(tid);
419         history->remove_waiting_thread(tid);
420
421 /*--
422         Predicate * selected_branch = get_selected_child_branch(tid);
423         update_predicate_score(selected_branch, SLEEP_SUCCESS);
424  */
425
426         model_print("** thread %d is woken up\n", tid);
427 }
428
429 /* Find threads that may write values that the pending read action is waiting for.
430  * Side effect: waiting thread related info are stored in dist_info_vec
431  *
432  * @return True if any thread is found
433  */
434 bool NewFuzzer::find_threads(ModelAction * pending_read)
435 {
436         ASSERT(pending_read->is_read());
437
438         void * location = pending_read->get_location();
439         thread_id_t self_id = pending_read->get_tid();
440         bool finds_waiting_for = false;
441
442         SnapVector<FuncNode *> * func_node_list = history->getWrFuncNodes(location);
443         for (uint i = 0;i < func_node_list->size();i++) {
444                 FuncNode * target_node = (*func_node_list)[i];
445                 for (uint i = 1;i < execution->get_num_threads();i++) {
446                         thread_id_t tid = int_to_id(i);
447                         if (tid == self_id)
448                                 continue;
449
450                         FuncNode * node = history->get_curr_func_node(tid);
451                         /* It is possible that thread tid is not in any FuncNode */
452                         if (node == NULL)
453                                 continue;
454
455                         int distance = node->compute_distance(target_node);
456                         if (distance != -1) {
457                                 finds_waiting_for = true;
458                                 //model_print("thread: %d; distance from node %d to node %d: %d\n", tid, node->get_func_id(), target_node->get_func_id(), distance);
459
460                                 dist_info_vec.push_back(node_dist_info(tid, target_node, distance));
461                         }
462                 }
463         }
464
465         return finds_waiting_for;
466 }
467
468 /* Update predicate counts and scores (asynchronous) when the read value is not available
469  *
470  * @param type
471  *        type 1: find_threads return false
472  *        type 2: find_threads return true, but the fuzzer decides that that thread shall not sleep based on sleep score
473  *        type 3: threads are put to sleep but woken up before the waited value appears
474  *        type 4: threads are put to sleep and the waited vaule appears (success)
475  */
476
477 /*--
478    void NewFuzzer::update_predicate_score(Predicate * predicate, sleep_result_t type)
479    {
480         switch (type) {
481                 case SLEEP_FAIL_TYPE1:
482                         predicate->incr_fail_count();
483
484                         // Do not choose this predicate when reselecting a new branch
485                         failed_predicates.put(predicate, true);
486                         break;
487                 case SLEEP_FAIL_TYPE2:
488                         predicate->incr_fail_count();
489                         predicate->incr_sleep_score(1);
490                         failed_predicates.put(predicate, true);
491                         break;
492                 case SLEEP_FAIL_TYPE3:
493                         predicate->incr_fail_count();
494                         predicate->decr_sleep_score(10);
495                         break;
496                 case SLEEP_SUCCESS:
497                         predicate->incr_sleep_score(10);
498                         break;
499                 default:
500                         model_print("unknown predicate result type.\n");
501                         break;
502         }
503    }
504  */
505
506 bool NewFuzzer::check_predicate_expressions(PredExprSet * pred_expressions,
507 inst_act_map_t * inst_act_map, uint64_t write_val, bool * no_predicate)
508 {
509         bool satisfy_predicate = true;
510
511         PredExprSetIter * pred_expr_it = pred_expressions->iterator();
512         while (pred_expr_it->hasNext()) {
513                 struct pred_expr * expression = pred_expr_it->next();
514                 bool equality;
515
516                 switch (expression->token) {
517                         case NOPREDICATE:
518                                 *no_predicate = true;
519                                 break;
520                         case EQUALITY:
521                                 FuncInst * to_be_compared;
522                                 ModelAction * last_act;
523                                 uint64_t last_read;
524
525                                 to_be_compared = expression->func_inst;
526                                 last_act = inst_act_map->get(to_be_compared);
527                                 last_read = last_act->get_reads_from_value();
528
529                                 equality = (write_val == last_read);
530                                 if (equality != expression->value)
531                                         satisfy_predicate = false;
532                                 break;
533                         case NULLITY:
534                                 // TODO: implement likely to be null
535                                 equality = ((void*) (write_val & 0xffffffff) == NULL);
536                                 if (equality != expression->value)
537                                         satisfy_predicate = false;
538                                 break;
539                         default:
540                                 model_print("unknown predicate token\n");
541                                 break;
542                 }
543
544                 if (!satisfy_predicate)
545                         break;
546         }
547
548         return satisfy_predicate;
549 }
550
551 bool NewFuzzer::shouldWait(const ModelAction * act)
552 {
553         return random() & 1;
554 }