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