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