Fix
[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 "predicate.h"
8 #include "concretepredicate.h"
9 #include "waitobj.h"
10
11 #include "model.h"
12 #include "schedule.h"
13 #include "execution.h"
14
15 NewFuzzer::NewFuzzer() :
16         thrd_last_read_act(),
17         thrd_last_func_inst(),
18         thrd_selected_child_branch(),
19         thrd_pruned_writes(),
20         paused_thread_list(),
21         paused_thread_table(128),
22         failed_predicates(32)
23 {}
24
25 /**
26  * @brief Register the ModelHistory and ModelExecution engine
27  */
28 void NewFuzzer::register_engine(ModelHistory * history, ModelExecution *execution)
29 {
30         this->history = 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
51                 FuncInst * read_inst = func_node->get_inst(read);
52                 Predicate * selected_branch = selectBranch(tid, curr_pred, read_inst);
53
54                 inst_act_map_t * inst_act_map = func_node->get_inst_act_map(tid);
55                 prune_writes(tid, selected_branch, rf_set, inst_act_map);
56
57                 if (!failed_predicates.isEmpty())
58                         failed_predicates.reset();
59
60                 thrd_last_read_act[thread_id] = read;
61                 thrd_last_func_inst[thread_id] = read_inst;
62         }
63
64         // No write satisfies the selected predicate, so pause this thread.
65         while ( rf_set->size() == 0 ) {
66                 Thread * read_thread = execution->get_thread(tid);
67                 Predicate * selected_branch = get_selected_child_branch(tid);
68                 bool should_reselect_predicate = false;
69                 //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());
70
71                 if (!find_threads(read)) {
72                         update_predicate_score(selected_branch, SLEEP_FAIL_TYPE1);
73                         should_reselect_predicate = true;
74                 } else if (!should_conditional_sleep(selected_branch)) {
75                         update_predicate_score(selected_branch, SLEEP_FAIL_TYPE2);
76                         should_reselect_predicate = true;
77                 } else {
78                         // reset thread pending action and revert sequence numbers
79                         read_thread->set_pending(read);
80                         read->reset_seq_number();
81                         execution->restore_last_seq_num();
82
83                         conditional_sleep(read_thread);
84                         // Returning -1 stops the while loop of ModelExecution::process_read
85                         return -1;
86                 }
87
88                 if (should_reselect_predicate) {
89                         SnapVector<ModelAction *> * pruned_writes = thrd_pruned_writes[thread_id];
90                         for (uint i = 0; i < pruned_writes->size(); i++) {
91                                 rf_set->push_back( (*pruned_writes)[i] );
92                         }
93
94                         // Reselect a predicate and prune writes
95                         Predicate * curr_pred = selected_branch->get_parent();
96                         FuncInst * read_inst = thrd_last_func_inst[thread_id];
97                         selected_branch = selectBranch(tid, curr_pred, read_inst);
98
99                         FuncNode * func_node = history->get_curr_func_node(tid);
100                         inst_act_map_t * inst_act_map = func_node->get_inst_act_map(tid);
101                         prune_writes(tid, selected_branch, rf_set, inst_act_map);
102
103                         ASSERT(selected_branch);
104                 }
105         }
106
107         ASSERT(rf_set->size() != 0);
108         int random_index = random() % rf_set->size();
109
110         return random_index;
111 }
112
113 /* Select a random branch from the children of curr_pred 
114  * @return The selected branch
115  */
116 Predicate * NewFuzzer::selectBranch(thread_id_t tid, Predicate * curr_pred, FuncInst * read_inst)
117 {
118         int thread_id = id_to_int(tid);
119         if ( thrd_selected_child_branch.size() <= (uint) thread_id)
120                 thrd_selected_child_branch.resize(thread_id + 1);
121
122         if (curr_pred == NULL || read_inst == NULL) {
123                 thrd_selected_child_branch[thread_id] = NULL;
124                 return NULL;
125         }
126
127         ModelVector<Predicate *> * children = curr_pred->get_children();
128         SnapVector<Predicate *> branches;
129         uint32_t numerator = 1;
130
131         for (uint i = 0; i < children->size(); i++) {
132                 Predicate * child = (*children)[i];
133                 if (child->get_func_inst() == read_inst && !failed_predicates.contains(child)) {
134                         branches.push_back(child);
135
136                         // max of (exploration counts + 1)
137                         if (child->get_expl_count() + 1 > numerator)
138                                 numerator = child->get_expl_count() + 1;
139                 }
140         }
141
142         // predicate children have not been generated
143         if (branches.size() == 0) {
144                 thrd_selected_child_branch[thread_id] = NULL;
145                 return NULL;
146         }
147
148         // randomly select a branch
149         // int random_index = random() % branches.size();
150         // Predicate * random_branch = branches[ random_index ];
151
152         int index = choose_index(&branches, numerator);
153         Predicate * random_branch = branches[ index ];
154         thrd_selected_child_branch[thread_id] = random_branch;
155
156         // Update predicate tree position
157         FuncNode * func_node = history->get_curr_func_node(tid);
158         func_node->set_predicate_tree_position(tid, random_branch);
159
160         return random_branch;
161 }
162
163 /**
164  * @brief Select a branch from the given predicate branches based
165  * on their exploration counts.
166  *
167  * Let b_1, ..., b_n be branches with exploration counts c_1, ..., c_n
168  * M := max(c_1, ..., c_n) + 1
169  * Factor f_i := M / (c_i + 1)
170  * The probability p_i that branch b_i is selected:
171  *      p_i := f_i / (f_1 + ... + f_n)
172  *           = \fraction{ 1/(c_i + 1) }{ 1/(c_1 + 1) + ... + 1/(c_n + 1) }
173  *
174  * Note: (1) c_i + 1 is used because counts may be 0.
175  *       (2) The numerator of f_i is chosen to reduce the effect of underflow
176  *      
177  * @param numerator is M defined above
178  */
179 int NewFuzzer::choose_index(SnapVector<Predicate *> * branches, uint32_t numerator)
180 {
181         if (branches->size() == 1)
182                 return 0;
183
184         double total_factor = 0;
185         SnapVector<double> factors = SnapVector<double>( branches->size() + 1 );
186         for (uint i = 0; i < branches->size(); i++) {
187                 Predicate * branch = (*branches)[i];
188                 double factor = (double) numerator / (branch->get_expl_count() + 5 * branch->get_fail_count() + 1);
189                 total_factor += factor;
190                 factors.push_back(factor);
191         }
192
193         double prob = (double) random() / RAND_MAX;
194         double prob_sum = 0;
195         int index = 0;
196
197         for (uint i = 0; i < factors.size(); i++) {
198                 index = i;
199                 prob_sum += (double) (factors[i] / total_factor);
200                 if (prob_sum > prob) {
201                         break;
202                 }
203         }
204
205         return index;
206 }
207
208 Predicate * NewFuzzer::get_selected_child_branch(thread_id_t tid)
209 {
210         int thread_id = id_to_int(tid);
211         if (thrd_selected_child_branch.size() <= (uint) thread_id)
212                 return NULL;
213
214         return thrd_selected_child_branch[thread_id];
215 }
216
217 /* Remove writes from the rf_set that do not satisfie the selected predicate, 
218  * and store them in thrd_pruned_writes
219  *
220  * @return true if rf_set is pruned
221  */
222 bool NewFuzzer::prune_writes(thread_id_t tid, Predicate * pred,
223         SnapVector<ModelAction *> * rf_set, inst_act_map_t * inst_act_map)
224 {
225         if (pred == NULL)
226                 return false;
227
228         PredExprSet * pred_expressions = pred->get_pred_expressions();
229         if (pred_expressions->getSize() == 0)   // unset predicates
230                 return false;
231
232         int thread_id = id_to_int(tid);
233         uint old_size = thrd_pruned_writes.size();
234         if (thrd_pruned_writes.size() <= (uint) thread_id) {
235                 uint new_size = thread_id + 1;
236                 thrd_pruned_writes.resize(new_size);
237                 for (uint i = old_size; i < new_size; i++)
238                         thrd_pruned_writes[i] = new SnapVector<ModelAction *>();
239         }
240         SnapVector<ModelAction *> * pruned_writes = thrd_pruned_writes[thread_id];
241         pruned_writes->clear(); // clear the old pruned_writes set
242
243         bool pruned = false;
244         uint index = 0;
245
246         while ( index < rf_set->size() ) {
247                 ModelAction * write_act = (*rf_set)[index];
248                 uint64_t write_val = write_act->get_write_value();
249                 bool satisfy_predicate = true;
250
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                                         return false;
259                                 case EQUALITY:
260                                         FuncInst * to_be_compared;
261                                         ModelAction * last_act;
262                                         uint64_t last_read;
263
264                                         to_be_compared = expression->func_inst;
265                                         last_act = inst_act_map->get(to_be_compared);
266                                         last_read = last_act->get_reads_from_value();
267
268                                         equality = (write_val == last_read);
269                                         if (equality != expression->value)
270                                                 satisfy_predicate = false;
271                                         break;
272                                 case NULLITY:
273                                         equality = ((void*)write_val == NULL);
274                                         if (equality != expression->value)
275                                                 satisfy_predicate = false;
276                                         break;
277                                 default:
278                                         model_print("unknown predicate token\n");
279                                         break;
280                         }
281
282                         if (!satisfy_predicate)
283                                 break;
284                 }
285
286                 if (!satisfy_predicate) {
287                         ASSERT(rf_set != NULL);
288                         (*rf_set)[index] = rf_set->back();
289                         rf_set->pop_back();
290                         pruned_writes->push_back(write_act);
291                         pruned = true;
292                 } else
293                         index++;
294         }
295
296         return pruned;
297 }
298
299 /* @brief Put a thread to sleep because no writes in rf_set satisfies the selected predicate. 
300  *
301  * @param thread A thread whose last action is a read
302  */
303 void NewFuzzer::conditional_sleep(Thread * thread)
304 {
305         int index = paused_thread_list.size();
306
307         model->getScheduler()->add_sleep(thread);
308         paused_thread_list.push_back(thread);
309         paused_thread_table.put(thread, index); // Update table
310
311         /* Add the waiting condition to ModelHistory */
312         ModelAction * read = thread->get_pending();
313         thread_id_t tid = thread->get_id();
314         FuncNode * func_node = history->get_curr_func_node(tid);
315         inst_act_map_t * inst_act_map = func_node->get_inst_act_map(tid);
316
317         Predicate * selected_branch = get_selected_child_branch(tid);
318         ConcretePredicate * concrete = selected_branch->evaluate(inst_act_map, tid);
319         concrete->set_location(read->get_location());
320
321         history->add_waiting_write(concrete);
322         /* history->add_waiting_thread is already called in find_threads */
323 }
324
325 bool NewFuzzer::should_conditional_sleep(Predicate *)
326 {
327         return true;
328 }
329
330 bool NewFuzzer::has_paused_threads()
331 {
332         return paused_thread_list.size() != 0;
333 }
334
335 Thread * NewFuzzer::selectThread(int * threadlist, int numthreads)
336 {
337         if (numthreads == 0 && has_paused_threads()) {
338                 wake_up_paused_threads(threadlist, &numthreads);
339                 //model_print("list size: %d, active t id: %d\n", numthreads, threadlist[0]);
340         }
341
342         int random_index = random() % numthreads;
343         int thread = threadlist[random_index];
344         thread_id_t curr_tid = int_to_id(thread);
345         return execution->get_thread(curr_tid);
346 }
347
348 /* Force waking up one of threads paused by Fuzzer, because otherwise
349  * the Fuzzer is not making progress
350  */
351 void NewFuzzer::wake_up_paused_threads(int * threadlist, int * numthreads)
352 {
353         int random_index = random() % paused_thread_list.size();
354         Thread * thread = paused_thread_list[random_index];
355         model->getScheduler()->remove_sleep(thread);
356
357         Thread * last_thread = paused_thread_list.back();
358         paused_thread_list[random_index] = last_thread;
359         paused_thread_list.pop_back();
360         paused_thread_table.put(last_thread, random_index);     // Update table
361         paused_thread_table.remove(thread);
362
363         thread_id_t tid = thread->get_id();
364         history->remove_waiting_write(tid);
365         history->remove_waiting_thread(tid);
366
367         threadlist[*numthreads] = tid;
368         (*numthreads)++;
369
370         Predicate * selected_branch = get_selected_child_branch(tid);
371         update_predicate_score(selected_branch, SLEEP_FAIL_TYPE3);
372
373         model_print("thread %d is woken up\n", tid);
374 }
375
376 /* Wake up conditional sleeping threads if the desired write is available */
377 void NewFuzzer::notify_paused_thread(Thread * thread)
378 {
379         ASSERT(paused_thread_table.contains(thread));
380
381         int index = paused_thread_table.get(thread);
382         model->getScheduler()->remove_sleep(thread);
383
384         Thread * last_thread = paused_thread_list.back();
385         paused_thread_list[index] = last_thread;
386         paused_thread_list.pop_back();
387         paused_thread_table.put(last_thread, index);    // Update table
388         paused_thread_table.remove(thread);
389
390         thread_id_t tid = thread->get_id();
391         history->remove_waiting_write(tid);
392         history->remove_waiting_thread(tid);
393
394         Predicate * selected_branch = get_selected_child_branch(tid);
395         update_predicate_score(selected_branch, SLEEP_SUCCESS);
396
397         model_print("** thread %d is woken up\n", tid);
398 }
399
400 /* Find threads that may write values that the pending read action is waiting for
401  * @return True if any thread is found
402  */
403 bool NewFuzzer::find_threads(ModelAction * pending_read)
404 {
405         ASSERT(pending_read->is_read());
406
407         void * location = pending_read->get_location();
408         thread_id_t self_id = pending_read->get_tid();
409         bool finds_waiting_for = false;
410
411         SnapVector<FuncNode *> * func_node_list = history->getWrFuncNodes(location);
412         for (uint i = 0; i < func_node_list->size(); i++) {
413                 FuncNode * target_node = (*func_node_list)[i];
414                 for (uint i = 1; i < execution->get_num_threads(); i++) {
415                         thread_id_t tid = int_to_id(i);
416                         if (tid == self_id)
417                                 continue;
418
419                         FuncNode * node = history->get_curr_func_node(tid);
420                         /* It is possible that thread tid is not in any FuncNode */
421                         if (node == NULL)
422                                 continue;
423
424                         int distance = node->compute_distance(target_node);
425                         if (distance != -1) {
426                                 history->add_waiting_thread(self_id, tid, target_node, distance);
427                                 finds_waiting_for = true;
428                                 //model_print("thread: %d; distance from node %d to node %d: %d\n", tid, node->get_func_id(), target_node->get_func_id(), distance);
429                         }
430                 }
431         }
432
433         return finds_waiting_for;
434 }
435
436 /* Update predicate counts and scores (asynchronous) when the read value is not available
437  *
438  * @param type
439  *        type 1: find_threads return false
440  *        type 2: find_threads return true, but the fuzzer decides that that thread shall not sleep based on sleep score
441  *        type 3: threads are put to sleep but woken up before the waited value appears
442  *        type 4: threads are put to sleep and the waited vaule appears (success)
443  */
444 void NewFuzzer::update_predicate_score(Predicate * predicate, sleep_result_t type)
445 {
446         switch (type) {
447                 case SLEEP_FAIL_TYPE1:
448                         predicate->incr_fail_count();
449
450                         /* Do not choose this predicate when reselecting a new branch */
451                         failed_predicates.put(predicate, true);
452                         break;
453                 case SLEEP_FAIL_TYPE2:
454                         predicate->incr_fail_count();
455                         predicate->decr_sleep_score(1);
456                         failed_predicates.put(predicate, true);
457                         break;
458                 case SLEEP_FAIL_TYPE3:
459                         predicate->incr_fail_count();
460                         predicate->incr_sleep_score(10);
461                         break;
462                 case SLEEP_SUCCESS:
463                         predicate->decr_sleep_score(10);
464                         break;
465                 default:
466                         model_print("unknown predicate result type.\n");
467                         break;
468         }
469 }
470
471 bool NewFuzzer::shouldWait(const ModelAction * act)
472 {
473         return random() & 1;
474 }