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