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