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