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