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