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