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