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