-
Notifications
You must be signed in to change notification settings - Fork 139
/
Function.cpp
757 lines (671 loc) · 17.4 KB
/
Function.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
// -*- mode: C++ -*-
//
// Copyright (c) 2007, 2008, 2010, 2011 The University of Utah
// All rights reserved.
//
// This file is part of `csmith', a random generator of C programs.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
// This file was derived from a random program generator written by Bryan
// Turner. The attributions in that file was:
//
// Random Program Generator
// Bryan Turner (bryan.turner@pobox.com)
// July, 2005
//
#ifdef WIN32
#pragma warning(disable : 4786) /* Disable annoying warning messages */
#endif
#include "Function.h"
#include <cassert>
#include "Common.h"
#include "Block.h"
#include "CGContext.h"
#include "CGOptions.h"
#include "Constant.h"
#include "Effect.h"
#include "Statement.h"
#include "Type.h"
#include "VariableSelector.h"
#include "FactMgr.h"
#include "random.h"
#include "util.h"
#include "Fact.h"
#include "FactPointTo.h"
#include "FactMgr.h"
#include "VectorFilter.h"
#include "Error.h"
#include "DepthSpec.h"
#include "ExtensionMgr.h"
#include "OutputMgr.h"
using namespace std;
///////////////////////////////////////////////////////////////////////////////
static vector<Function*> FuncList; // List of all functions in the program
static vector<FactMgr*> FMList; // list of fact managers for each function
static long cur_func_idx; // Index into FuncList that we are currently working on
static bool param_first=true; // Flag to track output of commas
/*
* find FactMgr for a function
*/
FactMgr*
get_fact_mgr_for_func(const Function* func)
{
for (size_t i=0; i<FuncList.size(); i++) {
if (FuncList[i] == func) {
return FMList[i];
}
}
return 0;
}
/*
*
*/
FactMgr*
get_fact_mgr(const CGContext* cg)
{
return get_fact_mgr_for_func(cg->get_current_func());
}
const Function*
find_function_by_name(const string& name)
{
size_t i;
for (i=0; i<FuncList.size(); i++) {
if (FuncList[i]->name == name) {
return FuncList[i];
}
}
return NULL;
}
int
find_function_in_set(const vector<const Function*>& set, const Function* f)
{
size_t i;
for (i=0; i<set.size(); i++) {
if (set[i] == f) {
return i;
}
}
return -1;
}
const Block*
find_blk_for_var(const Variable* v)
{
if (v->is_global()) {
return NULL;
}
size_t i, j;
for (i=0; i<FuncList.size(); i++) {
const Function* func = FuncList[i];
// for a parameter of a function, pretend it's a variable belongs to the top block
if (v->is_argument() && find_variable_in_set(func->param, v) != -1) {
return func->body;
}
for (j=0; j<func->blocks.size(); j++) {
const Block* blk = func->blocks[j];
if (find_variable_in_set(blk->local_vars, v) != -1) {
return blk;
}
}
}
return NULL;
}
bool
Function::is_var_on_stack(const Variable* var, const Statement* stm) const
{
size_t i;
for (i=0; i<param.size(); i++) {
if (param[i]->match(var)) {
return true;
}
}
const Block* b = stm->parent;
while (b) {
if (find_variable_in_set(b->local_vars, var) != -1) {
return true;
}
b = b->parent;
}
return false;
}
/* find whether a variable is visible in the given statement
*/
bool
Function::is_var_visible(const Variable* var, const Statement* stm) const
{
return (var->is_global() || is_var_on_stack(var, stm)) ;
}
/*
* return true if a variable is out-of-scope at given statement
* note variable must be a local variable of this function to
* be a oos variable (sometimes DFA would analyze local variables
* from callers, they should remain "in-scope" for this function
*/
bool
Function::is_var_oos(const Variable* var, const Statement* stm) const
{
if (!is_var_visible(var, stm)) {
//return true;
size_t i;
for (i=0; i<blocks.size(); i++) {
if (find_variable_in_set(blocks[i]->local_vars, var) != -1) {
return true;
}
}
}
return false;
}
const vector<Function*>&
get_all_functions(void)
{
return FuncList;
}
/*
*
*/
// unsigned
long
FuncListSize(void)
{
return FuncList.size();
}
/*
*
*/
Function *
GetFirstFunction(void)
{
return FuncList[0];
}
/*
*
*/
static string
RandomFunctionName(void)
{
return gensym("func_");
}
/*-------------------------------------------------------------
* choose a random return type. only struct/unions and integer types
* (not incl. void) are qualified, (no arrays)
*************************************************************/
static const Type*
RandomReturnType(void)
{
const Type* t = 0;
t = Type::choose_random();
return t;
}
/*
* Choose a function from `funcs' to invoke.
* Return null if no suitable function can be found.
*/
Function *
Function::choose_func(vector<Function *> funcs,
const CGContext& cg_context,
const Type* type,
const CVQualifiers* qfer)
{
vector<Function *> ok_funcs;
vector<Function *>::iterator i;
for (i = funcs.begin(); i != funcs.end(); ++i) {
// skip any function which has incompatible return type
// if type = 0, we don't care
if (type && !type->is_convertable((*i)->return_type))
continue;
if (qfer && (*i)->rv && !qfer->match((*i)->rv->qfer))
continue;
// We cannot call a function that has an as-yet unknown effect.
// TODO: in practice, this means we never call an as-yet unbuilt func.
if ((*i)->is_effect_known() == false) {
continue;
}
// We cannot call a function with a side-effect that is in conflict with the current context
if (cg_context.in_conflict((*i)->get_feffect())) {
continue;
}
//// TODO: is this too strong for what we want?
//if (!((*i)->get_feffect().is_side_effect_free())
// && !effect_context.is_side_effect_free()) {
// continue;
//}
//// We cannot call a function that has a race with the current context.
//if ((*i)->get_feffect().has_race_with(effect_context)) {
// continue;
//}
// Otherwise, this is an acceptable choice.
ok_funcs.push_back(*i);
}
vector<Function *>::size_type ok_size = ok_funcs.size();
if (ok_size == 0) {
return 0;
}
if (ok_size == 1) {
return ok_funcs[0];
}
int index = rnd_upto(ok_size);
ERROR_GUARD(NULL);
return ok_funcs[index];
}
/*
*
*/
static unsigned int
ParamListProbability()
{
return rnd_upto(CGOptions::max_params());
}
/*
*
*/
static void
GenerateParameterList(Function &curFunc)
{
unsigned int max = ParamListProbability();
ERROR_RETURN();
for (unsigned int i =0; i <= max; i++) {
// With some probability, choose a new random variable, or one from
// parentParams, parentLocals, or the globals list.
//
// Also, build the parent's link structure for this invocation and push
// it onto the back.
//
VariableSelector::GenerateParameterVariable(curFunc);
ERROR_RETURN();
}
}
/*
*
*/
Function::Function(const string &name, const Type *return_type)
: name(name),
return_type(return_type),
body(0),
fact_changed(false),
union_field_read(false),
visited_cnt(0),
build_state(UNBUILT)
{
FuncList.push_back(this); // Add to global list of functions.
}
Function *
Function::make_random_signature(const CGContext& cg_context, const Type* type, const CVQualifiers* qfer)
{
if (type == 0)
type = RandomReturnType();
DEPTH_GUARD_BY_TYPE_RETURN(dtFunction, NULL);
ERROR_GUARD(NULL);
Function *f = new Function(RandomFunctionName(), type);
// dummy variable representing return variable, we don't care about the type, so use 0
string rvname = f->name + "_" + "rv";
CVQualifiers ret_qfer = qfer==0 ? CVQualifiers::random_qualifiers(type, Effect::READ, cg_context, true)
: qfer->random_qualifiers(true, Effect::READ, cg_context);
ERROR_GUARD(NULL);
f->rv = VariableSelector::make_dummy_variable(rvname, type, &ret_qfer);
GenerateParameterList(*f);
FMList.push_back(new FactMgr(f));
return f;
}
/*
*
*/
Function *
Function::make_random(const CGContext& cg_context, const Type* type, const CVQualifiers* qfer)
{
Function* f = make_random_signature(cg_context, type, qfer);
ERROR_GUARD(NULL);
f->GenerateBody(cg_context);
ERROR_GUARD(NULL);
return f;
}
/*
*
*/
Function *
Function::make_first(void)
{
const Type *ty = RandomReturnType();
ERROR_GUARD(NULL);
Function *f = new Function(RandomFunctionName(), ty);
// dummy variable representing return variable, we don't care about the type, so use 0
string rvname = f->name + "_" + "rv";
CVQualifiers ret_qfer = CVQualifiers::random_qualifiers(ty);
ERROR_GUARD(NULL);
f->rv = VariableSelector::make_dummy_variable(rvname, ty, &ret_qfer);
// create a fact manager for this function, with empty global facts
FactMgr* fm = new FactMgr(f);
FMList.push_back(fm);
ExtensionMgr::GenerateFirstParameterList(*f);
// No Parameter List
f->GenerateBody(CGContext::get_empty_context());
fm->setup_in_out_maps(true);
// collect info about global dangling pointers
fm->find_dangling_global_ptrs(f);
return f;
}
/*
*
*/
static int
OutputFormalParam(Variable *var, std::ostream *pOut)
{
std::ostream &out = *pOut;
if ( !param_first ) out << ", ";
param_first = false;
//var->type->Output( out );
if (!CGOptions::arg_structs() && var->type)
assert(var->type->eType != eStruct);
if (!CGOptions::arg_unions() && var->type)
assert(var->type->eType != eUnion);
var->output_qualified_type(out);
out << " " << var->name;
return 0;
}
/*
*
*/
void
Function::OutputFormalParamList(std::ostream &out)
{
if (param.size() == 0) {
assert(Type::void_type);
Type::void_type->Output(out);
} else {
param_first = true;
for_each(param.begin(),
param.end(),
std::bind2nd(std::ptr_fun(OutputFormalParam), &out));
}
}
/*
*
*/
void
Function::OutputHeader(std::ostream &out)
{
if (!CGOptions::return_structs() && return_type)
assert(return_type->eType != eStruct);
if (!CGOptions::return_unions() && return_type)
assert(return_type->eType != eUnion);
// force functions to be static if necessary
if (CGOptions::force_globals_static()) {
out << "static ";
}
rv->qfer.output_qualified_type(return_type, out);
out << " " << get_prefixed_name(name) << "(";
OutputFormalParamList( out );
out << ")";
}
/*
*
*/
void
Function::OutputForwardDecl(std::ostream &out)
{
OutputHeader(out);
out << ";";
outputln(out);
}
/*
*
*/
void
Function::Output(std::ostream &out)
{
OutputMgr::set_curr_func(name);
output_comment_line(out, "------------------------------------------");
if (!CGOptions::concise()) {
feffect.Output(out);
}
OutputHeader(out);
outputln(out);
if (CGOptions::depth_protect()) {
out << "if (DEPTH < MAX_DEPTH) ";
outputln(out);
}
FactMgr* fm = get_fact_mgr_for_func(this);
// if nothing interesting happens, we don't want to see facts for statements
if (!fact_changed && !union_field_read && !is_pointer_referenced()) {
fm = 0;
}
body->Output(out, fm);
if (CGOptions::depth_protect()) {
out << "else";
outputln(out);
// TODO: Needs to be fixed when return types are no longer simple
// types.
out << "return ";
ret_c->Output(out);
out << ";";
outputln(out);
}
outputln(out);
outputln(out);
}
/*
* Used for protecting depth
*/
void
Function::make_return_const()
{
if (CGOptions::depth_protect() && need_return_stmt()) {
assert(return_type);
if (return_type->eType == eSimple)
assert(return_type->simple_type != eVoid);
Constant *c = Constant::make_random(return_type);
ERROR_RETURN();
this->ret_c = c;
}
}
bool Function::need_return_stmt()
{
return (return_type->eType != eSimple || return_type->simple_type != eVoid);
}
/*
*
*/
void
Function::GenerateBody(const CGContext &prev_context)
{
if (build_state != UNBUILT) {
cerr << "warning: ignoring attempt to regenerate func" << endl;
return;
}
build_state = BUILDING;
Effect effect_accum;
CGContext cg_context(this, prev_context.get_effect_context(), &effect_accum);
cg_context.extend_call_chain(prev_context);
FactMgr* fm = get_fact_mgr_for_func(this);
for (size_t i=0; i<param.size(); i++) {
if (param[i]->type->ptr_type != 0) {
fm->global_facts.push_back(FactPointTo::make_fact(param[i], FactPointTo::tbd_ptr));
}
}
// Fill in the Function body.
body = Block::make_random(cg_context);
ERROR_RETURN();
body->set_depth_protect(true);
// compute the pointers that are statically referenced in the function
// including ones referenced by its callees
body->get_referenced_ptrs(referenced_ptrs);
// Compute the function's externally visible effect. Currently, this
// is just the effect on globals.
//effect.add_external_effect(*cg_context.get_effect_accum());
feffect.add_external_effect(fm->map_stm_effect[body]);
make_return_const();
ERROR_RETURN();
// Mark this function as built.
build_state = BUILT;
}
void
Function::generate_body_with_known_params(const CGContext &prev_context, Effect& effect_accum)
{
if (build_state != UNBUILT) {
cerr << "warning: ignoring attempt to regenerate func" << endl;
return;
}
build_state = BUILDING;
FactMgr* fm = get_fact_mgr_for_func(this);
CGContext cg_context(this, prev_context.get_effect_context(), &effect_accum);
cg_context.extend_call_chain(prev_context);
// inherit proper no-read/write directives from caller
VariableSet no_reads, no_writes, must_reads, must_writes, frame_vars;
prev_context.find_reachable_frame_vars(fm->global_facts, frame_vars);
prev_context.get_external_no_reads_writes(no_reads, no_writes, frame_vars);
RWDirective rwd(no_reads, no_writes, must_reads, must_writes);
cg_context.rw_directive = &rwd;
cg_context.flags = 0;
// Fill in the Function body.
body = Block::make_random(cg_context);
ERROR_RETURN();
body->set_depth_protect(true);
compute_summary();
make_return_const();
ERROR_RETURN();
// Mark this function as built.
build_state = BUILT;
}
void
Function::compute_summary(void)
{
FactMgr* fm = get_fact_mgr_for_func(this);
// compute the pointers that are statically referenced in the function
// including ones referenced by its callees
body->get_referenced_ptrs(referenced_ptrs);
// Compute the function's externally visible effect.
//effect.add_external_effect(*cg_context.get_effect_accum());
feffect.add_external_effect(fm->map_stm_effect[body]);
// determine whether an union field is read
union_field_read = body->read_union_field();
}
/*
*
*/
void
GenerateFunctions(void)
{
FactMgr::add_interested_facts(CGOptions::interested_facts());
// -----------------
// Create a basic first function, then generate a random graph from there.
/* Function *first = */ Function::make_first();
ERROR_RETURN();
// -----------------
// Create body of each function, continue until no new functions are created.
for (cur_func_idx = 0; cur_func_idx < FuncListSize(); cur_func_idx++) {
// Dynamically adds new functions to the end of the list..
if (FuncList[cur_func_idx]->is_built() == false) {
FuncList[cur_func_idx]->GenerateBody(CGContext::get_empty_context());
ERROR_RETURN();
}
}
FactPointTo::aggregate_all_pointto_sets();
ExtensionMgr::GenerateValues();
}
/*
*
*/
static int
OutputForwardDecl(Function *func, std::ostream *pOut)
{
func->OutputForwardDecl(*pOut);
return 0;
}
/*
*
*/
static int
OutputFunction(Function *func, std::ostream *pOut)
{
func->Output(*pOut);
return 0;
}
/*
*
*/
void
OutputForwardDeclarations(std::ostream &out)
{
outputln(out);
outputln(out);
output_comment_line(out, "--- FORWARD DECLARATIONS ---");
for_each(FuncList.begin(), FuncList.end(),
std::bind2nd(std::ptr_fun(OutputForwardDecl), &out));
}
/*
*
*/
void
OutputFunctions(std::ostream &out)
{
outputln(out);
outputln(out);
output_comment_line(out, "--- FUNCTIONS ---");
for_each(FuncList.begin(), FuncList.end(),
std::bind2nd(std::ptr_fun(OutputFunction), &out));
}
/*
* Delete a single function
*/
int
Function::deleteFunction(Function* func)
{
if (func) {
delete func;
func = 0;
}
return 0;
}
/*
* Release all dynamic memory
*/
void
Function::doFinalization(void)
{
for_each(FuncList.begin(), FuncList.end(), std::ptr_fun(deleteFunction));
FuncList.clear();
std::vector<FactMgr*>::iterator i;
for (i = FMList.begin(); i != FMList.end(); ++i) {
delete (*i);
}
FMList.clear();
FactMgr::doFinalization();
}
Function::~Function()
{
param.clear();
assert(stack.empty());
if (body) {
delete body;
body = NULL;
}
if (CGOptions::depth_protect() && ret_c) {
delete ret_c;
ret_c = NULL;
}
}
///////////////////////////////////////////////////////////////////////////////
// Local Variables:
// c-basic-offset: 4
// tab-width: 4
// End:
// End of file.