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