Final fix; needs to be careful about the side effect of NewFuzzer::find_threads
[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_sleep = should_conditional_sleep(selected_branch);
69                 bool should_reselect_predicate = false;
70
71                 //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());
72
73                 if ( find_threads(read, should_sleep) ) {
74                         if (should_sleep) {
75                                 // reset thread pending action and revert sequence numbers
76                                 read_thread->set_pending(read);
77                                 read->reset_seq_number();
78                                 execution->restore_last_seq_num();
79
80                                 conditional_sleep(read_thread);
81                                 // Returning -1 stops the while loop of ModelExecution::process_read
82                                 return -1;
83                         } else {
84                                 update_predicate_score(selected_branch, SLEEP_FAIL_TYPE2);
85                                 should_reselect_predicate = true;
86                         }
87                 } else {
88                         update_predicate_score(selected_branch, SLEEP_FAIL_TYPE1);
89                         should_reselect_predicate = true;
90                 }
91
92                 if (should_reselect_predicate) {
93                         SnapVector<ModelAction *> * pruned_writes = thrd_pruned_writes[thread_id];
94                         for (uint i = 0; i < pruned_writes->size(); i++) {
95                                 rf_set->push_back( (*pruned_writes)[i] );
96                         }
97
98                         // Reselect a predicate and prune writes
99                         Predicate * curr_pred = selected_branch->get_parent();
100                         FuncInst * read_inst = thrd_last_func_inst[thread_id];
101                         selected_branch = selectBranch(tid, curr_pred, read_inst);
102
103                         FuncNode * func_node = history->get_curr_func_node(tid);
104                         inst_act_map_t * inst_act_map = func_node->get_inst_act_map(tid);
105                         prune_writes(tid, selected_branch, rf_set, inst_act_map);
106
107                         ASSERT(selected_branch);
108                 }
109         }
110
111         ASSERT(rf_set->size() != 0);
112         int random_index = random() % rf_set->size();
113
114         return random_index;
115 }
116
117 /* Select a random branch from the children of curr_pred 
118  * @return The selected branch
119  */
120 Predicate * NewFuzzer::selectBranch(thread_id_t tid, Predicate * curr_pred, FuncInst * read_inst)
121 {
122         int thread_id = id_to_int(tid);
123         if ( thrd_selected_child_branch.size() <= (uint) thread_id)
124                 thrd_selected_child_branch.resize(thread_id + 1);
125
126         if (curr_pred == NULL || read_inst == NULL) {
127                 thrd_selected_child_branch[thread_id] = NULL;
128                 return NULL;
129         }
130
131         ModelVector<Predicate *> * children = curr_pred->get_children();
132         SnapVector<Predicate *> branches;
133         uint32_t numerator = 1;
134
135         for (uint i = 0; i < children->size(); i++) {
136                 Predicate * child = (*children)[i];
137                 if (child->get_func_inst() == read_inst && !failed_predicates.contains(child)) {
138                         branches.push_back(child);
139
140                         // max of (exploration counts + 1)
141                         if (child->get_expl_count() + 1 > numerator)
142                                 numerator = child->get_expl_count() + 1;
143                 }
144         }
145
146         // predicate children have not been generated
147         if (branches.size() == 0) {
148                 thrd_selected_child_branch[thread_id] = NULL;
149                 return NULL;
150         }
151
152         // randomly select a branch
153         // int random_index = random() % branches.size();
154         // Predicate * random_branch = branches[ random_index ];
155
156         int index = choose_index(&branches, numerator);
157         Predicate * random_branch = branches[ index ];
158         thrd_selected_child_branch[thread_id] = random_branch;
159
160         // Update predicate tree position
161         FuncNode * func_node = history->get_curr_func_node(tid);
162         func_node->set_predicate_tree_position(tid, random_branch);
163
164         return random_branch;
165 }
166
167 /**
168  * @brief Select a branch from the given predicate branches based
169  * on their exploration counts.
170  *
171  * Let b_1, ..., b_n be branches with exploration counts c_1, ..., c_n
172  * M := max(c_1, ..., c_n) + 1
173  * Factor f_i := M / (c_i + 1)
174  * The probability p_i that branch b_i is selected:
175  *      p_i := f_i / (f_1 + ... + f_n)
176  *           = \fraction{ 1/(c_i + 1) }{ 1/(c_1 + 1) + ... + 1/(c_n + 1) }
177  *
178  * Note: (1) c_i + 1 is used because counts may be 0.
179  *       (2) The numerator of f_i is chosen to reduce the effect of underflow
180  *      
181  * @param numerator is M defined above
182  */
183 int NewFuzzer::choose_index(SnapVector<Predicate *> * branches, uint32_t numerator)
184 {
185         if (branches->size() == 1)
186                 return 0;
187
188         double total_factor = 0;
189         SnapVector<double> factors = SnapVector<double>( branches->size() + 1 );
190         for (uint i = 0; i < branches->size(); i++) {
191                 Predicate * branch = (*branches)[i];
192                 double factor = (double) numerator / (branch->get_expl_count() + 5 * branch->get_fail_count() + 1);
193                 total_factor += factor;
194                 factors.push_back(factor);
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 < factors.size(); i++) {
202                 index = i;
203                 prob_sum += (double) (factors[i] / total_factor);
204                 if (prob_sum > prob) {
205                         break;
206                 }
207         }
208
209         return index;
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, Predicate * pred,
227         SnapVector<ModelAction *> * rf_set, inst_act_map_t * inst_act_map)
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 index = 0;
249
250         while ( index < rf_set->size() ) {
251                 ModelAction * write_act = (*rf_set)[index];
252                 uint64_t write_val = write_act->get_write_value();
253                 bool satisfy_predicate = true;
254
255                 PredExprSetIter * pred_expr_it = pred_expressions->iterator();
256                 while (pred_expr_it->hasNext()) {
257                         struct pred_expr * expression = pred_expr_it->next();
258                         bool equality;
259
260                         switch (expression->token) {
261                                 case NOPREDICATE:
262                                         return false;
263                                 case EQUALITY:
264                                         FuncInst * to_be_compared;
265                                         ModelAction * last_act;
266                                         uint64_t last_read;
267
268                                         to_be_compared = expression->func_inst;
269                                         last_act = inst_act_map->get(to_be_compared);
270                                         last_read = last_act->get_reads_from_value();
271
272                                         equality = (write_val == last_read);
273                                         if (equality != expression->value)
274                                                 satisfy_predicate = false;
275                                         break;
276                                 case NULLITY:
277                                         equality = ((void*)write_val == NULL);
278                                         if (equality != expression->value)
279                                                 satisfy_predicate = false;
280                                         break;
281                                 default:
282                                         model_print("unknown predicate token\n");
283                                         break;
284                         }
285
286                         if (!satisfy_predicate)
287                                 break;
288                 }
289
290                 if (!satisfy_predicate) {
291                         ASSERT(rf_set != NULL);
292                         (*rf_set)[index] = rf_set->back();
293                         rf_set->pop_back();
294                         pruned_writes->push_back(write_act);
295                         pruned = true;
296                 } else
297                         index++;
298         }
299
300         return pruned;
301 }
302
303 /* @brief Put a thread to sleep because no writes in rf_set satisfies the selected predicate. 
304  *
305  * @param thread A thread whose last action is a read
306  */
307 void NewFuzzer::conditional_sleep(Thread * thread)
308 {
309         int index = paused_thread_list.size();
310
311         model->getScheduler()->add_sleep(thread);
312         paused_thread_list.push_back(thread);
313         paused_thread_table.put(thread, index); // Update table
314
315         /* Add the waiting condition to ModelHistory */
316         ModelAction * read = thread->get_pending();
317         thread_id_t tid = thread->get_id();
318         FuncNode * func_node = history->get_curr_func_node(tid);
319         inst_act_map_t * inst_act_map = func_node->get_inst_act_map(tid);
320
321         Predicate * selected_branch = get_selected_child_branch(tid);
322         ConcretePredicate * concrete = selected_branch->evaluate(inst_act_map, tid);
323         concrete->set_location(read->get_location());
324
325         history->add_waiting_write(concrete);
326         /* history->add_waiting_thread is already called in find_threads */
327 }
328
329 /**
330  * Decides whether a thread should condition sleep based on
331  * the sleep score of the chosen predicate.
332  *
333  * sleep_score = 100: never sleeps
334  * sleep_score = 0: always sleeps
335  **/
336 bool NewFuzzer::should_conditional_sleep(Predicate * predicate)
337 {
338         int sleep_score = predicate->get_sleep_score();
339         int random_num = random() % 100;
340
341         /* should sleep if random_num falls within [sleep_score, 100] */
342         if (random_num >= sleep_score)
343                 return true;
344
345         return false;
346 }
347
348 bool NewFuzzer::has_paused_threads()
349 {
350         return paused_thread_list.size() != 0;
351 }
352
353 Thread * NewFuzzer::selectThread(int * threadlist, int numthreads)
354 {
355         if (numthreads == 0 && has_paused_threads()) {
356                 wake_up_paused_threads(threadlist, &numthreads);
357                 //model_print("list size: %d, active t id: %d\n", numthreads, threadlist[0]);
358         }
359
360         int random_index = random() % numthreads;
361         int thread = threadlist[random_index];
362         thread_id_t curr_tid = int_to_id(thread);
363         return execution->get_thread(curr_tid);
364 }
365
366 /* Force waking up one of threads paused by Fuzzer, because otherwise
367  * the Fuzzer is not making progress
368  */
369 void NewFuzzer::wake_up_paused_threads(int * threadlist, int * numthreads)
370 {
371         int random_index = random() % paused_thread_list.size();
372         Thread * thread = paused_thread_list[random_index];
373         model->getScheduler()->remove_sleep(thread);
374
375         Thread * last_thread = paused_thread_list.back();
376         paused_thread_list[random_index] = last_thread;
377         paused_thread_list.pop_back();
378         paused_thread_table.put(last_thread, random_index);     // Update table
379         paused_thread_table.remove(thread);
380
381         thread_id_t tid = thread->get_id();
382         history->remove_waiting_write(tid);
383         history->remove_waiting_thread(tid);
384
385         threadlist[*numthreads] = tid;
386         (*numthreads)++;
387
388         Predicate * selected_branch = get_selected_child_branch(tid);
389         update_predicate_score(selected_branch, SLEEP_FAIL_TYPE3);
390
391         model_print("thread %d is woken up\n", tid);
392 }
393
394 /* Wake up conditional sleeping threads if the desired write is available */
395 void NewFuzzer::notify_paused_thread(Thread * thread)
396 {
397         ASSERT(paused_thread_table.contains(thread));
398
399         int index = paused_thread_table.get(thread);
400         model->getScheduler()->remove_sleep(thread);
401
402         Thread * last_thread = paused_thread_list.back();
403         paused_thread_list[index] = last_thread;
404         paused_thread_list.pop_back();
405         paused_thread_table.put(last_thread, index);    // Update table
406         paused_thread_table.remove(thread);
407
408         thread_id_t tid = thread->get_id();
409         history->remove_waiting_write(tid);
410         history->remove_waiting_thread(tid);
411
412         Predicate * selected_branch = get_selected_child_branch(tid);
413         update_predicate_score(selected_branch, SLEEP_SUCCESS);
414
415         model_print("** thread %d is woken up\n", tid);
416 }
417
418 /* Find threads that may write values that the pending read action is waiting for.
419  * Side effect: waiting threads are added if should_sleep is true
420  *
421  * @param should_sleep Indicate whether waiting threads should be added or not
422  * @return True if any thread is found
423  */
424 bool NewFuzzer::find_threads(ModelAction * pending_read, bool should_sleep)
425 {
426         ASSERT(pending_read->is_read());
427
428         void * location = pending_read->get_location();
429         thread_id_t self_id = pending_read->get_tid();
430         bool finds_waiting_for = false;
431
432         SnapVector<FuncNode *> * func_node_list = history->getWrFuncNodes(location);
433         for (uint i = 0; i < func_node_list->size(); i++) {
434                 FuncNode * target_node = (*func_node_list)[i];
435                 for (uint i = 1; i < execution->get_num_threads(); i++) {
436                         thread_id_t tid = int_to_id(i);
437                         if (tid == self_id)
438                                 continue;
439
440                         FuncNode * node = history->get_curr_func_node(tid);
441                         /* It is possible that thread tid is not in any FuncNode */
442                         if (node == NULL)
443                                 continue;
444
445                         int distance = node->compute_distance(target_node);
446                         if (distance != -1) {
447                                 finds_waiting_for = true;
448                                 //model_print("thread: %d; distance from node %d to node %d: %d\n", tid, node->get_func_id(), target_node->get_func_id(), distance);
449
450                                 if (should_sleep) {
451                                         history->add_waiting_thread(self_id, tid, target_node, distance);
452                                 }
453                         }
454                 }
455         }
456
457         return finds_waiting_for;
458 }
459
460 /* Update predicate counts and scores (asynchronous) when the read value is not available
461  *
462  * @param type
463  *        type 1: find_threads return false
464  *        type 2: find_threads return true, but the fuzzer decides that that thread shall not sleep based on sleep score
465  *        type 3: threads are put to sleep but woken up before the waited value appears
466  *        type 4: threads are put to sleep and the waited vaule appears (success)
467  */
468 void NewFuzzer::update_predicate_score(Predicate * predicate, sleep_result_t type)
469 {
470         switch (type) {
471                 case SLEEP_FAIL_TYPE1:
472                         predicate->incr_fail_count();
473
474                         /* Do not choose this predicate when reselecting a new branch */
475                         failed_predicates.put(predicate, true);
476                         break;
477                 case SLEEP_FAIL_TYPE2:
478                         predicate->incr_fail_count();
479                         predicate->decr_sleep_score(1);
480                         failed_predicates.put(predicate, true);
481                         break;
482                 case SLEEP_FAIL_TYPE3:
483                         predicate->incr_fail_count();
484                         predicate->incr_sleep_score(10);
485                         break;
486                 case SLEEP_SUCCESS:
487                         predicate->decr_sleep_score(10);
488                         break;
489                 default:
490                         model_print("unknown predicate result type.\n");
491                         break;
492         }
493 }
494
495 bool NewFuzzer::shouldWait(const ModelAction * act)
496 {
497         return random() & 1;
498 }