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