int main(int argc, char** argv) { SgProject* proj = frontend(argc,argv); SgFunctionDeclaration* mainDecl = SageInterface::findMain(proj); SgFunctionDefinition* mainDef = mainDecl->get_definition(); std::vector<SgNode*> ifExps; ifExps = NodeQuery::querySubTree(mainDef, V_SgIfStmt); for (int i = 0; i < ifExps.size(); i++) { getIfConds(isSgIfStmt(ifExps[i]), isSgScopeStatement(mainDef)); } std::vector<SgNode*> assignNodes = NodeQuery::querySubTree(mainDef, V_SgVariableDeclaration); std::cout << assignNodes.size() << " nodes found" << std::endl; std::vector<SgBinaryOp*> bin_ops; std::vector<SgUnaryOp*> un_ops; std::vector<SgNode*> other; std::vector<SgExpression*> results; for (std::vector<SgNode*>::iterator i = assignNodes.begin(); i != assignNodes.end(); i++) { SgVariableDeclaration* vdecl = isSgVariableDeclaration(*i); SgInitializedNamePtrList vlst = vdecl->get_variables(); SgInitializedName* initName = isSgInitializedName((*(vlst.begin()))); SgExpression* exp = isSgAssignInitializer(initName->get_initializer())->get_operand(); std::cout << exp->class_name() << std::endl; if (!isSgFunctionCallExp(exp)) { getExps(exp, isSgInitializedName(*i), results, 0); std::cout << "prefixes" << std::endl; for (int j = 0; j < prefixes.size(); j++) { SgExprStatement* expSt = SageBuilder::buildExprStatement_nfi(prefixes[j]); SageInterface::insertStatement(isSgVariableDeclaration(*i),expSt,true); std::cout << prefixes[j]->class_name() << std::endl; } std::cout << "results" << std::endl; for (int j = 0; j < results.size(); j++) { std::cout << results[j]->class_name() << std::endl; } std::cout << "postfixes" << std::endl; for (int j = 0; j < postfixes.size(); j++) { SgExprStatement* expSt = SageBuilder::buildExprStatement_nfi(postfixes[j]); SageInterface::insertStatement(isSgVariableDeclaration(*i),expSt,false); std::cout << postfixes[j]->class_name() << std::endl; } replaceExps(exp,vdecl); simplifyExps(exp); } } backend(proj); return 0; }
void virtual visit (SgNode* n) { if (isSgProject(n)|| isSgSourceFile(n)||isSgInitializedName(n)||isSgLocatedNode(n)) { setId (n); } }
void FortranAnalysis::visit(SgProcedureHeaderStatement * func_decl) { SgFunctionDefinition * func_def = isSgFunctionDefinition(func_decl->get_definition()); if (func_def == NULL) return; SgInitializedNamePtrList func_args = func_decl->get_parameterList()->get_args(); SgInitializedNamePtrList::const_iterator it_args; for (it_args = func_args.begin(); it_args != func_args.end(); it_args++) { SgInitializedName * const func_arg = isSgInitializedName(*it_args); SgSymbol * const sym = func_def->lookup_symbol(func_arg->get_name()); if (sym == NULL) { debug("FortranAnalysis::visit: no symbol for name %s\n", func_arg->get_name().getString().c_str()); } else if (isSgArrayType(sym->get_type()) != NULL) { sym->setAttribute("dummy_attr", new AstTextAttribute("DUMMY_ARRAY_ARG")); debug("SgFunctionDeclaration: adding dummy array attribute to %s\n", sym->get_name().getString().c_str()); } else { sym->setAttribute("dummy_attr", new AstTextAttribute("DUMMY_ARG")); debug("SgFunctionDeclaration: adding dummy attribute to %s\n", sym->get_name().getString().c_str()); } } }
void visitorTraversal::visit(SgNode* n) { // There are three types ir IR nodes that can be queried for scope: // - SgStatement, and // - SgInitializedName SgStatement* statement = isSgStatement(n); if (statement != NULL) { SgScopeStatement* scope = statement->get_scope(); ROSE_ASSERT(scope != NULL); printf ("SgStatement = %12p = %30s has scope = %12p = %s (total number = %d) \n", statement,statement->class_name().c_str(), scope,scope->class_name().c_str(),(int)scope->numberOfNodes()); } SgInitializedName* initializedName = isSgInitializedName(n); if (initializedName != NULL) { SgScopeStatement* scope = initializedName->get_scope(); ROSE_ASSERT(scope != NULL); printf ("SgInitializedName = %12p = %30s has scope = %12p = %s (total number = %d)\n", initializedName,initializedName->get_name().str(), scope,scope->class_name().c_str(),(int)scope->numberOfNodes()); } }
ffi_type *getFFIClassType(SgClassType *ct) { const StructLayoutInfo &sli = typeLayout(ct); ffi_type **fieldTypes = new ffi_type*[sli.fields.size()]; allocatedTypeArrays.push_back(fieldTypes); for (size_t i = 0; i < sli.fields.size(); i++) { SgNode *decl = sli.fields[i].decl; if (SgInitializedName *in = isSgInitializedName(decl)) { fieldTypes[i] = getFFIType(in->get_type()); } else if (SgBaseClass *bc = isSgBaseClass(decl)) { fieldTypes[i] = getFFIType(bc->get_base_class()->get_type()); } else { throw InterpError("Encountered unsupported field decl: " + decl->class_name()); } } ffi_type *ctType = new ffi_type; allocatedTypes.push_back(ctType); ctType->elements = fieldTypes; return ctType; }
/* * Fix OP function calls and inject debug names */ void OPSource::fixOpStructs(SgNode *n) { SgInitializedName* initname = isSgInitializedName(n); if(initname) { string var_name = initname->get_name().getString(); SgConstructorInitializer *initer = isSgConstructorInitializer(initname->get_initializer()); if(initer) { string class_name = initer->get_class_decl()->get_name().getString(); if(class_name.find("op_dat") != string::npos || class_name.find("op_dat_gbl") != string::npos || class_name.compare("_op_ptr") == 0 || class_name.compare("_op_set") == 0 || class_name.compare("_op_dat_const") == 0) { cout << "---Injecting Debug Name: " << var_name << "---" << endl; SgExprListExp* list = initer->get_args(); SgExpressionPtrList &exprs = list->get_expressions(); if( isSgStringVal(exprs.back()) == NULL ) { list->append_expression(buildStringVal(var_name)); } } } } }
void StaticConstructorTraversal::visit(SgNode *n) { // Get declared variables SgInitializedName *vName = isSgInitializedName(n); if (vName && !isAcreIgnore(vName->get_declaration())) { Sg_File_Info *fInfo = vName->get_file_info(); SgScopeStatement *scope = vName->get_scope(); // Find global variables (variables in namespaces count, e.g. std) if (!fInfo->isCompilerGenerated() && (isSgGlobal(scope) || isSgNamespaceDefinitionStatement(scope))) { // Walk typedefs until reach pointer to base type SgTypedefType *tdType = isSgTypedefType(vName->get_type()); while (tdType && isSgTypedefType(tdType->get_base_type())) tdType = isSgTypedefType(tdType->get_base_type()); // Determine if type is a class (i.e. type with a constructor) SgClassType *cType = isSgClassType(vName->get_type()); if (tdType) cType = isSgClassType(tdType->get_base_type()); // Output location of globals with a static constructor if (cType) { *out << "Static Constructor Violation: " << fInfo->get_filename() << " @ " << fInfo->get_line() << "\n"; } } } }
/*QY: This is used to support traversal of AST by the POET interpreter*/ bool POETAstInterface::MatchAstTypeName(const Ast& n, const std::string& tname) { if (tname == "EXP") { return AstInterface::IsExpression((SgNode*)n) != AST_NULL; } else if (tname == "ExpStmt") { SgExprStatement* s = isSgExprStatement((SgNode*)n); return (s != 0); } else if (tname == "FunctionDecl") { return AstInterface :: IsFunctionDefinition((SgNode*)n); } else if (tname == "For") { return isSgForStatement((SgNode*)n) != 0; } else if (tname == "Assign") { return AstInterface::IsAssignment((SgNode*)n); } else if (tname == "Pragma") { return isSgPragmaDeclaration((SgNode*)n) != 0; } else if (tname == "VarDecl") { return isSgVariableDeclaration((SgNode*)n) != 0; } else if (tname == "Variable") { return isSgInitializedName((SgNode*)n); } else if (tname == "Loop") {} else std::cerr << "does not recognize type name:" << tname << "\n"; return false; }
inline void printNode(ostream& o, const NodeT& n) { string id = n.id(); string nodeColor = "black"; if (isSgStatement(n.getNode())) nodeColor = "blue"; else if (isSgExpression(n.getNode())) nodeColor = "green"; else if (isSgInitializedName(n.getNode())) nodeColor = "red"; o << id << " [label=\"" << escapeString(Debug ? n.toStringForDebugging() : n.toString()) << "\", color=\"" << nodeColor << "\", style=\"" << (n.isInteresting() ? "solid" : "dotted") << "\"];\n"; }
bool TaintAnalysis::magic_tainted(SgNode *node, FiniteVarsExprsProductLattice *prodLat) { if (isSgInitializedName(node)) { SgInitializedName *iname = isSgInitializedName(node); std::string vname = iname->get_name().getString(); TaintLattice *tlat = dynamic_cast<TaintLattice*>(prodLat->getVarLattice(varID(iname))); if (tlat && 0==vname.compare(0, 7, "TAINTED")) { bool modified = tlat->set_vertex(TaintLattice::VERTEX_TAINTED); if (debug) { *debug <<"TaintAnalysis::magic_tainted: lattice is magically " <<tlat->to_string() <<(modified?" (modified)":" (not modified)") <<"\n"; } return modified; } } else if (isSgVarRefExp(node)) { SgVarRefExp *vref = isSgVarRefExp(node); std::string vname = vref->get_symbol()->get_name().getString(); TaintLattice *tlat = dynamic_cast<TaintLattice*>(prodLat->getVarLattice(varID(vref))); if (tlat && 0==vname.compare(0, 7, "TAINTED")) { bool modified = tlat->set_vertex(TaintLattice::VERTEX_TAINTED); if (debug) { *debug <<"TaintAnalysis::magic_tainted: lattice is magically " <<tlat->to_string() <<(modified?" (modified)":" (not modified)") <<"\n"; } return modified; } } else if (isSgVariableDeclaration(node)) { SgVariableDeclaration *vdecl = isSgVariableDeclaration(node); const SgInitializedNamePtrList &inames = vdecl->get_variables(); for (size_t i=0; i<inames.size(); ++i) { std::string vname = inames[i]->get_name().getString(); TaintLattice *tlat = dynamic_cast<TaintLattice*>(prodLat->getVarLattice(varID(inames[i]))); if (tlat && 0==vname.compare(0, 7, "TAINTED")) { bool modified = tlat->set_vertex(TaintLattice::VERTEX_TAINTED); if (debug) { *debug <<"TaintAnalysis::magic_tainted: lattice is magically " <<tlat->to_string() <<(modified?" (modified)":" (not modified)") <<"\n"; } return modified; } } } return false; }
InheritedAttribute BugSeeding::evaluateInheritedAttribute ( SgNode* astNode, InheritedAttribute inheritedAttribute ) { // Use this if we only want to seed bugs in loops bool isLoop = inheritedAttribute.isLoop || (isSgForStatement(astNode) != NULL) || (isSgWhileStmt(astNode) != NULL) || (isSgDoWhileStmt(astNode) != NULL); // Add Fortran support isLoop = isLoop || (isSgFortranDo(astNode) != NULL); // Mark future noes in this subtree as being part of a loop inheritedAttribute.isLoop = isLoop; // To test this on simple codes, optionally allow it to be applied everywhere bool applyEveryWhere = true; if (isLoop == true || applyEveryWhere == true) { // The inherited attribute is true iff we are inside a loop and this is a SgPntrArrRefExp. SgPntrArrRefExp *arrayReference = isSgPntrArrRefExp(astNode); if (arrayReference != NULL) { // Mark as a vulnerability inheritedAttribute.isVulnerability = true; // Now change the array index (to seed the buffer overflow bug) SgVarRefExp* arrayVarRef = isSgVarRefExp(arrayReference->get_lhs_operand()); ROSE_ASSERT(arrayVarRef != NULL); ROSE_ASSERT(arrayVarRef->get_symbol() != NULL); SgInitializedName* arrayName = isSgInitializedName(arrayVarRef->get_symbol()->get_declaration()); ROSE_ASSERT(arrayName != NULL); SgArrayType* arrayType = isSgArrayType(arrayName->get_type()); ROSE_ASSERT(arrayType != NULL); SgExpression* arraySize = arrayType->get_index(); SgTreeCopy copyHelp; // Make a copy of the expression used to hold the array size in the array declaration. SgExpression* arraySizeCopy = isSgExpression(arraySize->copy(copyHelp)); ROSE_ASSERT(arraySizeCopy != NULL); // This is the existing index expression SgExpression* indexExpression = arrayReference->get_rhs_operand(); ROSE_ASSERT(indexExpression != NULL); // Build a new expression: "array[n]" --> "array[n+arraySizeCopy]", where the arraySizeCopy is a size of "array" SgExpression* newIndexExpression = buildAddOp(indexExpression,arraySizeCopy); // Substitute the new expression for the old expression arrayReference->set_rhs_operand(newIndexExpression); } } return inheritedAttribute; }
int main(int argc, char* argv[]) { SgProject* proj = frontend(argc,argv); SgFunctionDeclaration* mainDecl = SageInterface::findMain(proj); SgFunctionDefinition* mainDef = mainDecl->get_definition(); // std::vector<SgNode*> dotExps = NodeQuery::querySubTree(mainDef, V_SgDotExp); std::vector<SgNode*> varRefs = NodeQuery::querySubTree(mainDef,V_SgVarRefExp); int classExps = 0; for (unsigned int i = 0; i < varRefs.size(); i++) { if (isSgClassType(isSgVarRefExp(varRefs[i])->get_type())) { SgClassType* ct = isSgClassType(isSgVarRefExp(varRefs[i])->get_type()); std::cout << "name of ref: " << isSgVarRefExp(varRefs[i])->get_symbol()->get_name().getString() << std::endl; if (SageInterface::isStructType(ct)) { SgDeclarationStatement* decl = isSgType(ct)->getAssociatedDeclaration(); SgDeclarationStatement* defining_decl = decl->get_definingDeclaration(); if (!(defining_decl->isNameOnly())) { if (isSgClassDeclaration(defining_decl)) { if (isSgClassDeclaration(defining_decl)->get_definition()) { SgDeclarationStatementPtrList member_stats = isSgClassDeclaration(defining_decl)->get_definition()->get_members(); SgDeclarationStatementPtrList::iterator j = member_stats.begin(); for (; j != member_stats.end(); j++) { SgDeclarationStatement* d = isSgDeclarationStatement(*j); std::cout << "decl stat name: " << d->class_name() << std::endl; SgInitializedNamePtrList init_lst = isSgVariableDeclaration(d)->get_variables(); SgInitializedNamePtrList::iterator k = init_lst.begin(); std::cout << "variables in initialized name ptr list..." << std::endl; for (; k != init_lst.end(); k++) { std::cout << isSgInitializedName(*k)->get_name().getString() << std::endl; std::cout << isSgInitializedName(*k)->get_type()->class_name() << std::endl; } } classExps+=1; } } } } } } std::cout << "num class_exp: " << classExps << std::endl; return 0; }
virtual void visit(SgNode* n) { #if 0 // Debugging code if (!isSgInitializedName(n)) n->unparseToString(); #endif SgFunctionCallExp* n2 = isSgFunctionCallExp(n); if (n2) { calls_to_inline.push_back(n2); } }
// the default interesting filter bool defaultFilter (CFGNode cfgn) { SgNode * node = cfgn.getNode(); assert (node != NULL) ; //Keep the last index for initialized names. This way the definition of the variable doesn't //propagate to its assign initializer. if (isSgInitializedName(node)) { return (cfgn == node->cfgForEnd()); } else return (cfgn.isInteresting()); }
bool FortranAnalysis::isFunctionArg(SgInitializedName * arg) { SgInitializedNamePtrList func_args = src_func_decl->get_parameterList()->get_args(); SgInitializedNamePtrList::iterator it_args; for (it_args = func_args.begin(); it_args != func_args.end(); it_args++) { SgInitializedName * func_arg = isSgInitializedName(*it_args); if (arg->get_name() == func_arg->get_name()) { return true; } } return false; }
bool isDataflowInteresting(CFGNode cn) { ROSE_ASSERT (cn.getNode()); return (cn.getNode()->cfgIsIndexInteresting(cn.getIndex()) && //!isSgFunctionRefExp(cn.getNode()) && !isSgExprListExp(cn.getNode()) && !isSgForInitStatement(cn.getNode()) && //!isSgVarRefExp(cn.getNode()) && //!isSgValueExp(cn.getNode()) && //!isSgExprStatement(cn.getNode()) && !(isSgInitializedName(cn.getNode()) && cn.getIndex()==0)) || (isSgIfStmt(cn.getNode()) && cn.getIndex()==1 || cn.getIndex()==2); }
// adds to declaredVars the set of all variables declared within the given AST sub-tree // onlyGlobal - if onlyGlobal==true, only global variables are added // getCompilerGen - if =true, the returned set includes compiler-generated variables and doesn't if =false void getDeclaredVars(SgNode* root, bool onlyGlobal, varIDSet& declaredVars, bool getCompilerGen=false) { /*!!! NOTE: THIS CODE DOES NOT CAPTURE FIELDS WITHIN STRUCTS, UNIONS AND CLASSES !!! */ Rose_STL_Container<SgNode*> initNames = NodeQuery::querySubTree(root, V_SgInitializedName); for(Rose_STL_Container<SgNode*>::iterator it = initNames.begin(); it != initNames.end(); it++) { ROSE_ASSERT(isSgInitializedName(*it)); // skip over compiler-generated names if necessary if(!getCompilerGen && (*it)->get_file_info()->isCompilerGenerated()) continue; varID var(isSgInitializedName(*it)); //printf(" getDeclaredVars() var=%s\n", var.str().c_str()); // if this is a declaration of a variable with a globally visible scope //if(isGlobalVarDecl(isSgInitializedName(*it))) if(!onlyGlobal || var.isGlobal()) { //printf(" inserting\n"); declaredVars.insert(var); } } }
/** * Use visually distinct identifiers * * \note also checks DCL31-C */ bool DCL02_C( const SgNode *node ) { static std::map<const SgScopeStatement *, std::set<std::string> > scopeMap; static std::map<std::string, const SgInitializedName *> strVarMap; const SgScopeStatement *scope = isSgScopeStatement(node); if (!scope) return false; bool violation = false; if (isSgGlobal(scope)) { std::set<std::string> externNames; /** populate scopeMap */ FOREACH_SUBNODE(scope, nodes, i, V_SgInitializedName) { SgInitializedName *var = isSgInitializedName(*i); assert(var); if (isCompilerGeneratedNode(var) || !isSgDeclarationStatement(var->get_parent()) || findParentOfType(var, SgCtorInitializerList) || findParentOfType(var, SgClassDeclaration) // Might be too strong || var->get_name().getString().empty() || (var->get_name().getString().substr(0,2) == "__")) continue; /** Ignore function prototypes */ const SgFunctionDeclaration * fnDecl = findParentOfType(var, SgFunctionDeclaration); if (fnDecl && !fnDecl->get_definition()) continue; if (isExternVar(var)) { if (externNames.find(var->get_name().getString()) != externNames.end()) continue; externNames.insert(var->get_name().getString()); } const SgScopeStatement *varScope = var->get_scope(); std::string str (normalize_string(var->get_name().str(), isExternVar(var))); if (scopeMap[varScope].find(str) != scopeMap[varScope].end()) { DCL02_report_error(var); violation = true; } else { scopeMap[varScope].insert(str); strVarMap[str] = var; } } return false; }
std::vector<SgType*> getTypesFromNode(SgNode* node) { switch(node->variantT()) { case V_SgInitializedName: return typeVectorFromType(isSgInitializedName(node)->get_type()); case V_SgCastExp: return typeVectorFromType(isSgCastExp(node)->get_type() ); case V_SgSizeOfOp: return typeVectorFromType(isSgSizeOfOp(node)->get_operand_type() ); default: return std::vector<SgType*>(); }; }
VariableIdSet AnalysisAbstractionLayer::astSubTreeVariables(SgNode* node, VariableIdMapping& vidm) { VariableIdSet vset; RoseAst ast(node); for(RoseAst::iterator i=ast.begin();i!=ast.end();++i) { VariableId vid; // default creates intentionally an invalid id. if(SgVariableDeclaration* varDecl=isSgVariableDeclaration(*i)) { vid=vidm.variableId(varDecl); } else if(SgVarRefExp* varRefExp=isSgVarRefExp(*i)) { vid=vidm.variableId(varRefExp); } else if(SgInitializedName* initName=isSgInitializedName(*i)) { vid=vidm.variableId(initName); } if(vid.isValid()) vset.insert(vid); } return vset; }
/** * Do not reuse variable names in subscopes */ bool DCL01_C( const SgNode *node ) { const SgInitializedName *varInitName = isSgInitializedName(node); if (!varInitName) return false; const SgName varName = varInitName->get_name(); const SgScopeStatement *varScope = varInitName->get_scope(); assert(varScope); while(!isSgGlobal(varScope)) { varScope = varScope->get_scope(); if(varScope->symbol_exists(varName)) { print_error(node, "DCL01-C", ("Do not reuse variable names in subscopes: " + varName.getString()).c_str(), true); return true; } } return false; }
void ClangToSageTranslator::setCompilerGeneratedFileInfo(SgNode * node, bool to_be_unparse) { Sg_File_Info * start_fi = Sg_File_Info::generateDefaultFileInfoForCompilerGeneratedNode(); Sg_File_Info * end_fi = Sg_File_Info::generateDefaultFileInfoForCompilerGeneratedNode(); start_fi->setCompilerGenerated(); end_fi->setCompilerGenerated(); if (to_be_unparse) { start_fi->setOutputInCodeGeneration(); end_fi->setOutputInCodeGeneration(); } ROSE_ASSERT(start_fi != NULL && end_fi != NULL); #if DEBUG_SOURCE_LOCATION std::cerr << "Set File_Info for " << node << " of type " << node->class_name() << std::endl; #endif SgLocatedNode * located_node = isSgLocatedNode(node); SgInitializedName * init_name = isSgInitializedName(node); if (located_node == NULL && init_name == NULL) { std::cerr << "Consistency error: try to set a Sage node which is not a SgLocatedNode or a SgInitializedName as compiler generated" << std::endl; exit(-1); } else if (located_node != NULL) { Sg_File_Info * fi = located_node->get_startOfConstruct(); if (fi != NULL) delete fi; fi = located_node->get_endOfConstruct(); if (fi != NULL) delete fi; located_node->set_startOfConstruct(start_fi); located_node->set_endOfConstruct(end_fi); } else if (init_name != NULL) { Sg_File_Info * fi = init_name->get_startOfConstruct(); if (fi != NULL) delete fi; fi = init_name->get_endOfConstruct(); if (fi != NULL) delete fi; init_name->set_startOfConstruct(start_fi); init_name->set_endOfConstruct(end_fi); } }
void FortranAnalysis::visit(SgFunctionDefinition * func_def) { SgFunctionDeclaration * func_decl = isSgFunctionDeclaration(func_def->get_declaration()); if (func_decl == NULL) return; SgInitializedNamePtrList func_args = func_decl->get_parameterList()->get_args(); SgInitializedNamePtrList::iterator arg = func_args.begin(); // for (it_args = func_args.begin(); it_args != func_args.end(); it_args++) { while (arg != func_args.end()) { SgInitializedName * func_arg = isSgInitializedName(*arg++); SgSymbol * sym = func_def->lookup_symbol(func_arg->get_name()); SgType * type = sym->get_type(); if (sym == NULL) { printf("FortranAnalysis::visit: no symbol for name %s\n", func_arg->get_name().getString().c_str()); } else if (isSgArrayType(type) != NULL) { printf("WARNING: arg %s must be a scalar\n", func_arg->get_name().str()); sym->setAttribute("dummy_attr", new AstTextAttribute("DUMMY_ARRAY_TYPE_ARG")); } else if (isSgNamedType(type)) { sym->setAttribute("dummy_attr", new AstTextAttribute("DUMMY_NAMED_TYPE_ARG")); } else { sym->setAttribute("dummy_attr", new AstTextAttribute("DUMMY_ARG")); } if (sym != NULL && isElementalArrayType(func_arg)) { sym->setAttribute("elemental_attr", new AstTextAttribute("ELEMENTAL_ARRAY")); sym->setAttribute("index_attr", new AstTextAttribute("idx")); } if (sym != NULL && hasArrayDescriptor(func_arg)) { sym->setAttribute("descriptor_attr", new AstTextAttribute("desc_"+func_arg->get_name())); sym->setAttribute("index_attr", new AstTextAttribute("idx_"+func_arg->get_name())); } } }
void Driver<Sage>::addPointerToTopParentDeclaration(SgSymbol * symbol, unsigned file_id) { SgSymbol * parent = symbol; std::map<SgSymbol *, SgSymbol *>::const_iterator it_parent = p_parent_map.find(symbol); assert(it_parent != p_parent_map.end()); while (it_parent->second != NULL) { parent = it_parent->second; it_parent = p_parent_map.find(parent); assert(it_parent != p_parent_map.end()); } assert(parent != NULL); SgDeclarationStatement * decl_to_add = NULL; SgVariableSymbol * var_sym = isSgVariableSymbol(parent); if (var_sym != NULL) { assert(var_sym == symbol); SgInitializedName * init_name = isSgInitializedName(var_sym->get_symbol_basis()); assert(init_name != NULL); // TODO } else decl_to_add = isSgDeclarationStatement(parent->get_symbol_basis()); assert(decl_to_add != NULL); std::map<unsigned, SgSourceFile *>::iterator it_file = id_to_file_map.find(file_id); assert(it_file != id_to_file_map.end()); SgSourceFile * file = it_file->second; assert(file != NULL); SgGlobal * global_scope = file->get_globalScope(); assert(global_scope != NULL); const std::vector<SgDeclarationStatement *> & declaration_list = global_scope->getDeclarationList(); if (find(declaration_list.begin(), declaration_list.end(), decl_to_add) == declaration_list.end()) SageInterface::prependStatement(decl_to_add, global_scope); }
void testOMPForSensitiveInsertion() { annotateAllOmpFors(project); Rose_STL_Container<SgNode*> iteratorUses = NodeQuery::querySubTree(project, V_SgInitializedName); OMPcfgRWTransaction trans; //VirtualCFG::cfgRWTransaction trans; trans.beginTransaction(); for(Rose_STL_Container<SgNode*>::iterator it = iteratorUses.begin(); it!=iteratorUses.end(); it++) { SgInitializedName *initName = isSgInitializedName(*it); ROSE_ASSERT(initName); //printf("initialized Name <%s | %s>\n", initName->get_parent()->unparseToString().c_str(), initName->get_parent()->class_name().c_str()); if(initName->get_name().getString() == "iterator") { //printf(" inserting1 at spot <%s | %s>\n", initName->get_parent()->unparseToString().c_str(), initName->get_parent()->class_name().c_str()); trans.insertBefore(initName, fooCallCreate()); trans.insertAfter(initName, fooCallCreate()); } } iteratorUses = NodeQuery::querySubTree(project, V_SgVarRefExp); for(Rose_STL_Container<SgNode*>::iterator it = iteratorUses.begin(); it!=iteratorUses.end(); it++) { SgVarRefExp *varRef = isSgVarRefExp(*it); ROSE_ASSERT(varRef); if(varRef->get_symbol()->get_name().getString() == "iterator") { //printf(" inserting2 at spot <%s | %s>\n", varRef->get_parent()->unparseToString().c_str(), varRef->get_parent()->class_name().c_str()); trans.insertBefore(varRef->get_parent(), fooCallCreate()); trans.insertAfter(varRef->get_parent(), fooCallCreate()); } } trans.commitTransaction(); }
bool ClangToSageTranslator::VisitEnumDecl(clang::EnumDecl * enum_decl, SgNode ** node) { #if DEBUG_VISIT_DECL std::cerr << "ClangToSageTranslator::VisitEnumDecl" << std::endl; #endif bool res = true; SgName name(enum_decl->getNameAsString()); clang::EnumDecl * prev_enum_decl = enum_decl->getPreviousDeclaration(); SgEnumSymbol * sg_prev_enum_sym = isSgEnumSymbol(GetSymbolFromSymbolTable(prev_enum_decl)); SgEnumDeclaration * sg_prev_enum_decl = sg_prev_enum_sym == NULL ? NULL : isSgEnumDeclaration(sg_prev_enum_sym->get_declaration()); sg_prev_enum_decl = sg_prev_enum_decl == NULL ? NULL : isSgEnumDeclaration(sg_prev_enum_decl->get_definingDeclaration()); SgEnumDeclaration * sg_enum_decl = SageBuilder::buildEnumDeclaration(name, SageBuilder::topScopeStack()); *node = sg_enum_decl; if (sg_prev_enum_decl == NULL || sg_prev_enum_decl->get_enumerators().size() == 0) { clang::EnumDecl::enumerator_iterator it; for (it = enum_decl->enumerator_begin(); it != enum_decl->enumerator_end(); it++) { SgNode * tmp_enumerator = Traverse(*it); SgInitializedName * enumerator = isSgInitializedName(tmp_enumerator); ROSE_ASSERT(enumerator); enumerator->set_scope(SageBuilder::topScopeStack()); sg_enum_decl->append_enumerator(enumerator); } } else { sg_enum_decl->set_definingDeclaration(sg_prev_enum_decl); sg_enum_decl->set_firstNondefiningDeclaration(sg_prev_enum_decl->get_firstNondefiningDeclaration()); } return VisitDecl(enum_decl, node) && res; }
void DataFlow<Annotation, Language, Runtime>::createContextFromLoopTree( const LoopTrees<Annotation> & loop_trees, context_t & context ) const { assert(context.datas.empty()); assert(context.datas_in.empty()); assert(context.datas_out.empty()); assert(context.accesses_map.empty()); typename std::set<Data<Annotation> *>::iterator it_data; const std::vector<Data<Annotation> *> & data_vect = loop_trees.getDatas(); context.datas.insert(data_vect.begin(), data_vect.end()); for (it_data = context.datas.begin(); it_data != context.datas.end(); it_data++) { assert(*it_data != NULL); if ((*it_data)->isFlowIn()) context.datas_in.insert(*it_data); if ((*it_data)->isFlowOut()) context.datas_out.insert(*it_data); } const std::vector<typename LoopTrees<Annotation>::node_t *> & nodes = loop_trees.getNodes(); typename std::vector<typename LoopTrees<Annotation>::node_t *>::const_iterator it_node; for (it_node = nodes.begin(); it_node != nodes.end(); it_node++) { typename LoopTrees<Annotation>::cond_t * cond = dynamic_cast<typename LoopTrees<Annotation>::cond_t *>(*it_node); typename LoopTrees<Annotation>::stmt_t * stmt = dynamic_cast<typename LoopTrees<Annotation>::stmt_t *>(*it_node); if (cond == NULL && stmt == NULL) continue; typename std::map<typename LoopTrees<Annotation>::node_t *, accesses_list_t>::iterator it_access = context.accesses_map.insert(std::pair<typename LoopTrees<Annotation>::node_t *, accesses_list_t>(*it_node, accesses_list_t())).first; std::vector<data_access_t> & read = it_access->second.reads; std::vector<data_access_t> & write = it_access->second.writes; if (cond != NULL) { assert(false); /// \todo } else if (stmt != NULL) { SgExprStatement * expr_stmt = isSgExprStatement(stmt->statement); SgVariableDeclaration * var_decl = isSgVariableDeclaration(stmt->statement); if (expr_stmt != NULL) { SgExpression * exp = expr_stmt->get_expression(); assert(exp != NULL); SgBinaryOp * bin_op = isSgBinaryOp(exp); if (bin_op != NULL) { SgExpression * lhs_exp = bin_op->get_lhs_operand_i(); SgExpression * rhs_exp = bin_op->get_rhs_operand_i(); assert(lhs_exp != NULL && rhs_exp != NULL); SgAssignOp * assign_op = isSgAssignOp(exp); SgCompoundAssignOp * compound_assign_op = isSgCompoundAssignOp(exp); assert((assign_op != NULL) xor (compound_assign_op != NULL)); // FIXME expression statement are not always made of assignement if (assign_op != NULL || compound_assign_op != NULL) { append_access(lhs_exp, write, context); // add access in lhs to write set append_access(rhs_exp, read, context); // add access in rhs to read set } if (compound_assign_op != NULL) { append_access(lhs_exp, read, context); // add access in lhs to read set } } else assert(false); // FIXME expression statement are not always made of binary op } else if (var_decl != NULL) { assert(var_decl->get_variables().size() == 1); SgInitializedName * init_name = isSgInitializedName(var_decl->get_variables()[0]); assert(init_name != NULL); SgInitializer * init = isSgInitializer(init_name->get_initptr()); if (init != NULL) { SgAssignInitializer * assign_init = isSgAssignInitializer(init); if (assign_init != NULL) { SgExpression * exp = assign_init->get_operand_i(); assert(exp != NULL); append_access(exp, read, context); } else assert(false); } } else assert(false); } } }
void CompassAnalyses::VariableNameEqualsDatabaseName::Traversal:: visit(SgNode* node) { if( isSgAssignInitializer(node) != NULL ) assignExp = node; if( isSgAssignOp(node) != NULL ) assignExp = node; SgFunctionCallExp* funcCall = isSgFunctionCallExp(node); // See if we have a dot expression or arrow expression which // accesses the desired member function in the class we are looking for. if ( funcCall != NULL ) { SgExpression* funcExp = funcCall->get_function(); if ( ( isSgDotExp(funcExp) != NULL ) | ( isSgArrowExp(funcExp) != NULL ) ) { SgBinaryOp* binOp = isSgBinaryOp(funcExp); SgExpression* rhsOp = binOp->get_rhs_operand(); // SgExpression* lhsOp = binOp->get_lhs_operand(); if ( SgMemberFunctionRefExp* funcRef = isSgMemberFunctionRefExp(rhsOp) ) { // std::cout << "c1\n" ; SgMemberFunctionSymbol* funcSymbol = funcRef->get_symbol(); ROSE_ASSERT(funcSymbol->get_declaration() != NULL); // DQ (1/16/2008): Note that the defining declaration need not exist (see test2001_11.C) // ROSE_ASSERT(funcSymbol->get_declaration()->get_definingDeclaration() != NULL); if (funcSymbol->get_declaration()->get_definingDeclaration() != NULL) { SgMemberFunctionDeclaration* funcDecl = isSgMemberFunctionDeclaration(funcSymbol->get_declaration()->get_definingDeclaration()); ROSE_ASSERT( funcDecl != NULL ); SgClassDefinition* clDef = isSgClassDefinition(funcDecl->get_scope()); SgClassDeclaration* clDecl = isSgClassDeclaration(clDef->get_declaration()); // SgClassDeclaration* clDecl = funcDecl->get_associatedClassDeclaration(); ROSE_ASSERT( clDecl != NULL ); std::string className = clDecl->get_name().getString(); ROSE_ASSERT(funcDecl != NULL); std::string functionName = funcDecl->get_name().getString(); // If the class is the class we are looking for see if the member function // access is to the member function we are interested in. // std::cout << "className = " << className << std::endl; // std::cout << "functionName = " << functionName << std::endl; if ( (className == classToLookFor) && ( functionName == memberFunctionToLookFor ) ) { SgExprListExp* actualArgs = funcCall->get_args(); SgExpressionPtrList& actualExpArgs = actualArgs->get_expressions (); ROSE_ASSERT(actualExpArgs.size() == 1); Rose_STL_Container<SgNode*> nodeLst = NodeQuery::querySubTree(*actualExpArgs.begin(), V_SgStringVal); ROSE_ASSERT( nodeLst.size() > 0); SgStringVal* actualArg = isSgStringVal(*nodeLst.begin()); ROSE_ASSERT(actualArg != NULL); std::string stringArg = actualArg->get_value(); std::cout << "arg:" << stringArg << std::endl; std::string varName; // SgInitializedName* initName = NULL; if ( SgAssignInitializer* assignInit = isSgAssignInitializer(assignExp) ) { SgInitializedName* initName = isSgInitializedName(assignInit->get_parent()); ROSE_ASSERT(initName != NULL); varName = initName->get_name().getString(); } else { if ( SgAssignOp* assignOp = isSgAssignOp(assignExp) ) { SgExpression* lhsOp = assignOp->get_lhs_operand(); SgVarRefExp* varRef = isSgVarRefExp(lhsOp); ROSE_ASSERT(varRef!=NULL); SgVariableSymbol* varSymbol = varRef->get_symbol(); ROSE_ASSERT(varSymbol != NULL); SgInitializedName* initName = varSymbol->get_declaration(); varName = initName->get_name().getString(); } } if (varName != "") { // we are only interested in the part of the argument after the last ":" // Database scopes in ALE3D are separated by ":" size_t posCol = stringArg.find_last_of(':'); if (posCol != std::string::npos) stringArg = stringArg.substr(posCol+1); //Find violations to the rule if ( stringArg != varName) { output->addOutput(new CheckerOutput(assignExp)); std::cout << "violation" << varName << std::endl; } else { std::cout << "non=violation" << varName << std::endl; } } } } } } } } // End of the visit function.
bool ClangToSageTranslator::VisitFunctionDecl(clang::FunctionDecl * function_decl, SgNode ** node) { #if DEBUG_VISIT_DECL std::cerr << "ClangToSageTranslator::VisitFunctionDecl" << std::endl; #endif bool res = true; // FIXME: There is something weird here when try to Traverse a function reference in a recursive function (when first Traverse is not complete) // It seems that it tries to instantiate the decl inside the function... // It may be faster to recode from scratch... // If I am not wrong this have been fixed.... SgName name(function_decl->getNameAsString()); SgType * ret_type = buildTypeFromQualifiedType(function_decl->getResultType()); SgFunctionParameterList * param_list = SageBuilder::buildFunctionParameterList_nfi(); applySourceRange(param_list, function_decl->getSourceRange()); // FIXME find the good SourceRange (should be stored by Clang...) for (unsigned i = 0; i < function_decl->getNumParams(); i++) { SgNode * tmp_init_name = Traverse(function_decl->getParamDecl(i)); SgInitializedName * init_name = isSgInitializedName(tmp_init_name); if (tmp_init_name != NULL && init_name == NULL) { std::cerr << "Runtime error: tmp_init_name != NULL && init_name == NULL" << std::endl; res = false; continue; } param_list->append_arg(init_name); } if (function_decl->isVariadic()) { SgName empty = ""; SgType * ellipses_type = SgTypeEllipse::createType(); param_list->append_arg(SageBuilder::buildInitializedName_nfi(empty, ellipses_type, NULL)); } SgFunctionDeclaration * sg_function_decl; if (function_decl->isThisDeclarationADefinition()) { sg_function_decl = SageBuilder::buildDefiningFunctionDeclaration(name, ret_type, param_list, NULL); sg_function_decl->set_definingDeclaration(sg_function_decl); if (function_decl->isVariadic()) { sg_function_decl->hasEllipses(); } if (!function_decl->hasBody()) { std::cerr << "Defining function declaration without body..." << std::endl; res = false; } /* if (sg_function_decl->get_definition() != NULL) SageInterface::deleteAST(sg_function_decl->get_definition()); SgFunctionDefinition * function_definition = new SgFunctionDefinition(sg_function_decl, NULL); SgInitializedNamePtrList & init_names = param_list->get_args(); SgInitializedNamePtrList::iterator it; for (it = init_names.begin(); it != init_names.end(); it++) { (*it)->set_scope(function_definition); SgSymbolTable * st = function_definition->get_symbol_table(); ROSE_ASSERT(st != NULL); SgVariableSymbol * tmp_sym = new SgVariableSymbol(*it); st->insert((*it)->get_name(), tmp_sym); } */ SgFunctionDefinition * function_definition = sg_function_decl->get_definition(); if (sg_function_decl->get_definition()->get_body() != NULL) SageInterface::deleteAST(sg_function_decl->get_definition()->get_body()); SageBuilder::pushScopeStack(function_definition); SgNode * tmp_body = Traverse(function_decl->getBody()); SgBasicBlock * body = isSgBasicBlock(tmp_body); SageBuilder::popScopeStack(); if (tmp_body != NULL && body == NULL) { std::cerr << "Runtime error: tmp_body != NULL && body == NULL" << std::endl; res = false; } else { function_definition->set_body(body); body->set_parent(function_definition); applySourceRange(function_definition, function_decl->getSourceRange()); } sg_function_decl->set_definition(function_definition); function_definition->set_parent(sg_function_decl); SgFunctionDeclaration * first_decl; if (function_decl->getFirstDeclaration() == function_decl) { SgFunctionParameterList * param_list_ = SageBuilder::buildFunctionParameterList_nfi(); setCompilerGeneratedFileInfo(param_list_); SgInitializedNamePtrList & init_names = param_list->get_args(); SgInitializedNamePtrList::iterator it; for (it = init_names.begin(); it != init_names.end(); it++) { SgInitializedName * init_param = new SgInitializedName(**it); setCompilerGeneratedFileInfo(init_param); param_list_->append_arg(init_param); } first_decl = SageBuilder::buildNondefiningFunctionDeclaration(name, ret_type, param_list_, NULL); setCompilerGeneratedFileInfo(first_decl); first_decl->set_parent(SageBuilder::topScopeStack()); first_decl->set_firstNondefiningDeclaration(first_decl); if (function_decl->isVariadic()) first_decl->hasEllipses(); } else { SgSymbol * tmp_symbol = GetSymbolFromSymbolTable(function_decl->getFirstDeclaration()); SgFunctionSymbol * symbol = isSgFunctionSymbol(tmp_symbol); if (tmp_symbol != NULL && symbol == NULL) { std::cerr << "Runtime error: tmp_symbol != NULL && symbol == NULL" << std::endl; res = false; } if (symbol != NULL) first_decl = isSgFunctionDeclaration(symbol->get_declaration()); } sg_function_decl->set_firstNondefiningDeclaration(first_decl); first_decl->set_definingDeclaration(sg_function_decl); } else { sg_function_decl = SageBuilder::buildNondefiningFunctionDeclaration(name, ret_type, param_list, NULL); if (function_decl->isVariadic()) sg_function_decl->hasEllipses(); SgInitializedNamePtrList & init_names = param_list->get_args(); SgInitializedNamePtrList::iterator it; for (it = init_names.begin(); it != init_names.end(); it++) { (*it)->set_scope(SageBuilder::topScopeStack()); } if (function_decl->getFirstDeclaration() != function_decl) { SgSymbol * tmp_symbol = GetSymbolFromSymbolTable(function_decl->getFirstDeclaration()); SgFunctionSymbol * symbol = isSgFunctionSymbol(tmp_symbol); if (tmp_symbol != NULL && symbol == NULL) { std::cerr << "Runtime error: tmp_symbol != NULL && symbol == NULL" << std::endl; res = false; } SgFunctionDeclaration * first_decl = NULL; if (symbol != NULL) { first_decl = isSgFunctionDeclaration(symbol->get_declaration()); } else { // FIXME Is it correct? SgNode * tmp_first_decl = Traverse(function_decl->getFirstDeclaration()); first_decl = isSgFunctionDeclaration(tmp_first_decl); ROSE_ASSERT(first_decl != NULL); // ROSE_ASSERT(!"We should have see the first declaration already"); } if (first_decl != NULL) { if (first_decl->get_firstNondefiningDeclaration() != NULL) sg_function_decl->set_firstNondefiningDeclaration(first_decl->get_firstNondefiningDeclaration()); else { ROSE_ASSERT(first_decl->get_firstNondefiningDeclaration() != NULL); } } else { ROSE_ASSERT(!"First declaration not found!"); } } else { sg_function_decl->set_firstNondefiningDeclaration(sg_function_decl); } } ROSE_ASSERT(sg_function_decl->get_firstNondefiningDeclaration() != NULL); /* // TODO Fix problem with function symbols... SgSymbol * symbol = GetSymbolFromSymbolTable(function_decl); if (symbol == NULL) { SgFunctionSymbol * func_sym = new SgFunctionSymbol(isSgFunctionDeclaration(sg_function_decl->get_firstNondefiningDeclaration())); SageBuilder::topScopeStack()->insert_symbol(name, func_sym); } */ // ROSE_ASSERT(GetSymbolFromSymbolTable(function_decl) != NULL); *node = sg_function_decl; return VisitDeclaratorDecl(function_decl, node) && res; }
void FixupSelfReferentialMacrosInAST::visit ( SgNode* node ) { // DQ (3/11/2006): Set NULL pointers where we would like to have none. // printf ("In FixupSelfReferentialMacrosInAST::visit(): node = %s \n",node->class_name().c_str()); ROSE_ASSERT(node != NULL); switch (node->variantT()) { case V_SgInitializedName: { SgInitializedName* initializedName = isSgInitializedName(node); ROSE_ASSERT(initializedName != NULL); SgType* type = initializedName->get_type()->stripType(); SgClassType* classType = isSgClassType(type); if (classType != NULL) { SgClassDeclaration* targetClassDeclaration = isSgClassDeclaration(classType->get_declaration()); SgName className = targetClassDeclaration->get_name(); // printf ("In FixupSelfReferentialMacrosInAST::visit(): Found a class declaration name = %s \n",className.str()); // For sudo_exec_pty.c also look for siginfo if (className == "sigaction" || className == "siginfo") { // printf ("In FixupSelfReferentialMacrosInAST::visit(): Found a sigaction type \n"); // Note we could also check that the declaration came from a known header file. SgStatement* associatedStatement = isSgStatement(initializedName->get_parent()); if (associatedStatement != NULL) { // Add a macro to undefine the "#define sa_handler __sigaction_handler.sa_handler" macro. // printf ("In FixupSelfReferentialMacrosInAST::visit(): Add a macro to undefine the macro #define sa_handler __sigaction_handler.sa_handler \n"); // PreprocessingInfo* macro = new PreprocessingInfo(DirectiveType, const std::string & inputString,const std::string & filenameString, int line_no , int col_no,int nol, RelativePositionType relPos ); PreprocessingInfo::DirectiveType directiveType = PreprocessingInfo::CpreprocessorUndefDeclaration; // We are puting out all macros anytime we see either type. This might be too much... // From the sigaction.h file (included by signal.h): addMacro(associatedStatement,"#undef sa_handler\n",directiveType); addMacro(associatedStatement,"#undef sa_sigaction\n",directiveType); // From the siginfo.h file (included by signal.h): addMacro(associatedStatement,"#undef si_pid\n", directiveType); addMacro(associatedStatement,"#undef si_uid\n", directiveType); addMacro(associatedStatement,"#undef si_timerid\n",directiveType); addMacro(associatedStatement,"#undef si_overrun\n",directiveType); addMacro(associatedStatement,"#undef si_status\n", directiveType); addMacro(associatedStatement,"#undef si_utime\n", directiveType); addMacro(associatedStatement,"#undef si_stime\n", directiveType); addMacro(associatedStatement,"#undef si_value\n", directiveType); addMacro(associatedStatement,"#undef si_int\n", directiveType); addMacro(associatedStatement,"#undef si_ptr\n", directiveType); addMacro(associatedStatement,"#undef si_addr\n", directiveType); addMacro(associatedStatement,"#undef si_band\n", directiveType); addMacro(associatedStatement,"#undef si_fd\n", directiveType); } } } } default: { // printf ("Not handled in FixupSelfReferentialMacrosInAST::visit(%s) \n",node->class_name().c_str()); } } }