Search in sources :

Example 1 with CompoundStatement

use of de.fraunhofer.aisec.cpg.graph.statements.CompoundStatement in project cpg by Fraunhofer-AISEC.

the class VisitorTest method testAllEogNodeVisitor.

/**
 * Visits all nodes along EOG.
 */
@Test
void testAllEogNodeVisitor() {
    List<Node> nodeList = new ArrayList<>();
    RecordDeclaration recordDeclaration = namespace.getDeclarationAs(0, RecordDeclaration.class);
    MethodDeclaration method = recordDeclaration.getMethods().stream().filter(m -> m.getName().equals("method")).collect(Collectors.toList()).get(0);
    /* TODO A better way to get the "first" statement in a method body is needed.
    This is currently the only (fragile, ugly and unsafe) way to get to the first "real" statement in a method body.
    getNextEOG() and getNextCFG() return empty lists.
    */
    Statement firstStmt = ((CompoundStatement) method.getBody()).getStatements().get(0);
    firstStmt.accept(Strategy::EOG_FORWARD, new IVisitor<Node>() {

        public void visit(Node n) {
            System.out.println(n);
            nodeList.add(n);
        }
    });
    assertEquals(22, nodeList.size());
}
Also used : RecordDeclaration(de.fraunhofer.aisec.cpg.graph.declarations.RecordDeclaration) MethodDeclaration(de.fraunhofer.aisec.cpg.graph.declarations.MethodDeclaration) CompoundStatement(de.fraunhofer.aisec.cpg.graph.statements.CompoundStatement) Statement(de.fraunhofer.aisec.cpg.graph.statements.Statement) ReturnStatement(de.fraunhofer.aisec.cpg.graph.statements.ReturnStatement) Strategy(de.fraunhofer.aisec.cpg.processing.strategy.Strategy) BaseTest(de.fraunhofer.aisec.cpg.BaseTest) Test(org.junit.jupiter.api.Test)

Example 2 with CompoundStatement

use of de.fraunhofer.aisec.cpg.graph.statements.CompoundStatement in project cpg by Fraunhofer-AISEC.

the class VariableResolverCppTest method testAccessLocalVarNameInNestedBlock.

@Test
void testAccessLocalVarNameInNestedBlock() {
    CompoundStatement innerBlock = TestUtils.getSubnodeOfTypeWithName(forStatements.get(1), CompoundStatement.class, "");
    VariableDeclaration nestedDeclaration = TestUtils.getSubnodeOfTypeWithName(innerBlock, VariableDeclaration.class, "varName");
    VRUtil.assertUsageOf(callParamMap.get("func1_nested_block_shadowed_local_varName"), nestedDeclaration);
}
Also used : CompoundStatement(de.fraunhofer.aisec.cpg.graph.statements.CompoundStatement) ParamVariableDeclaration(de.fraunhofer.aisec.cpg.graph.declarations.ParamVariableDeclaration) VariableDeclaration(de.fraunhofer.aisec.cpg.graph.declarations.VariableDeclaration) BaseTest(de.fraunhofer.aisec.cpg.BaseTest) Test(org.junit.jupiter.api.Test)

Example 3 with CompoundStatement

use of de.fraunhofer.aisec.cpg.graph.statements.CompoundStatement in project cpg by Fraunhofer-AISEC.

the class CXXLanguageFrontendTest method testObjectCreation.

@Test
void testObjectCreation() throws Exception {
    File file = new File("src/test/resources/objcreation.cpp");
    TranslationUnitDeclaration declaration = TestUtils.analyzeAndGetFirstTU(List.of(file), file.getParentFile().toPath(), true);
    assertNotNull(declaration);
    // get the main method
    FunctionDeclaration main = declaration.getDeclarationAs(3, FunctionDeclaration.class);
    CompoundStatement statement = (CompoundStatement) main.getBody();
    // Integer i
    VariableDeclaration i = (VariableDeclaration) ((DeclarationStatement) statement.getStatements().get(0)).getSingleDeclaration();
    // type should be Integer
    assertEquals(TypeParser.createFrom("Integer", true), i.getType());
    // initializer should be a construct expression
    ConstructExpression constructExpression = (ConstructExpression) i.getInitializer();
    // type of the construct expression should also be Integer
    assertEquals(TypeParser.createFrom("Integer", true), constructExpression.getType());
    // auto (Integer) m
    VariableDeclaration m = (VariableDeclaration) ((DeclarationStatement) statement.getStatements().get(6)).getSingleDeclaration();
    // type should be Integer*
    assertEquals(TypeParser.createFrom("Integer*", true), m.getType());
    // initializer should be a new expression
    NewExpression newExpression = (NewExpression) m.getInitializer();
    // type of the new expression should also be Integer*
    assertEquals(TypeParser.createFrom("Integer*", true), newExpression.getType());
    // initializer should be a construct expression
    constructExpression = (ConstructExpression) newExpression.getInitializer();
    // type of the construct expression should be Integer
    assertEquals(TypeParser.createFrom("Integer", true), constructExpression.getType());
    // argument should be named k and of type m
    DeclaredReferenceExpression k = (DeclaredReferenceExpression) constructExpression.getArguments().get(0);
    assertEquals("k", k.getName());
    // type of the construct expression should also be Integer
    assertEquals(TypeParser.createFrom("int", true), k.getType());
}
Also used : FunctionDeclaration(de.fraunhofer.aisec.cpg.graph.declarations.FunctionDeclaration) CompoundStatement(de.fraunhofer.aisec.cpg.graph.statements.CompoundStatement) VariableDeclaration(de.fraunhofer.aisec.cpg.graph.declarations.VariableDeclaration) File(java.io.File) TranslationUnitDeclaration(de.fraunhofer.aisec.cpg.graph.declarations.TranslationUnitDeclaration) BaseTest(de.fraunhofer.aisec.cpg.BaseTest) Test(org.junit.jupiter.api.Test)

Example 4 with CompoundStatement

use of de.fraunhofer.aisec.cpg.graph.statements.CompoundStatement in project cpg by Fraunhofer-AISEC.

the class DeclarationHandler method handleClassOrInterfaceDeclaration.

public RecordDeclaration handleClassOrInterfaceDeclaration(ClassOrInterfaceDeclaration classInterDecl) {
    // TODO: support other kinds, such as interfaces
    String fqn = classInterDecl.getNameAsString();
    // Todo adapt name using a new type of scope "Namespace/Package scope"
    // if (packageDeclaration != null) {
    // name = packageDeclaration.getNameAsString() + "." + name;
    // }
    fqn = getAbsoluteName(fqn);
    // add a type declaration
    RecordDeclaration recordDeclaration = newRecordDeclaration(fqn, "class", null, true, lang, classInterDecl);
    recordDeclaration.setSuperClasses(classInterDecl.getExtendedTypes().stream().map(this.lang::getTypeAsGoodAsPossible).collect(Collectors.toList()));
    recordDeclaration.setImplementedInterfaces(classInterDecl.getImplementedTypes().stream().map(this.lang::getTypeAsGoodAsPossible).collect(Collectors.toList()));
    TypeManager.getInstance().addTypeParameter(recordDeclaration, classInterDecl.getTypeParameters().stream().map(t -> new ParameterizedType(t.getNameAsString())).collect(Collectors.toList()));
    Map<Boolean, List<String>> partitioned = this.lang.getContext().getImports().stream().collect(Collectors.partitioningBy(ImportDeclaration::isStatic, Collectors.mapping(i -> {
        String iName = i.getNameAsString();
        // we need to ensure that x.* imports really preserve the asterisk!
        if (i.isAsterisk() && !iName.endsWith(".*")) {
            iName += ".*";
        }
        return iName;
    }, Collectors.toList())));
    recordDeclaration.setStaticImportStatements(partitioned.get(true));
    recordDeclaration.setImportStatements(partitioned.get(false));
    lang.getScopeManager().enterScope(recordDeclaration);
    lang.getScopeManager().addDeclaration(recordDeclaration.getThis());
    // TODO: 'this' identifier for multiple instances?
    for (BodyDeclaration<?> decl : classInterDecl.getMembers()) {
        if (decl instanceof com.github.javaparser.ast.body.FieldDeclaration) {
            // will be added via the scopemanager
            handle(decl);
        } else if (decl instanceof com.github.javaparser.ast.body.MethodDeclaration) {
            de.fraunhofer.aisec.cpg.graph.declarations.MethodDeclaration md = (de.fraunhofer.aisec.cpg.graph.declarations.MethodDeclaration) handle(decl);
            recordDeclaration.addMethod(md);
        } else if (decl instanceof com.github.javaparser.ast.body.ConstructorDeclaration) {
            de.fraunhofer.aisec.cpg.graph.declarations.ConstructorDeclaration c = (de.fraunhofer.aisec.cpg.graph.declarations.ConstructorDeclaration) handle(decl);
            recordDeclaration.addConstructor(c);
        } else if (decl instanceof com.github.javaparser.ast.body.ClassOrInterfaceDeclaration) {
            recordDeclaration.addDeclaration(handle(decl));
        } else if (decl instanceof com.github.javaparser.ast.body.InitializerDeclaration) {
            InitializerDeclaration id = (InitializerDeclaration) decl;
            CompoundStatement initializerBlock = lang.getStatementHandler().handleBlockStatement(id.getBody());
            initializerBlock.setStaticBlock(id.isStatic());
            recordDeclaration.addStatement(initializerBlock);
        } else {
            log.debug("Member {} of type {} is something that we do not parse yet: {}", decl, recordDeclaration.getName(), decl.getClass().getSimpleName());
        }
    }
    if (recordDeclaration.getConstructors().isEmpty()) {
        de.fraunhofer.aisec.cpg.graph.declarations.ConstructorDeclaration constructorDeclaration = newConstructorDeclaration(recordDeclaration.getName(), recordDeclaration.getName(), recordDeclaration);
        recordDeclaration.addConstructor(constructorDeclaration);
        lang.getScopeManager().addDeclaration(constructorDeclaration);
    }
    lang.processAnnotations(recordDeclaration, classInterDecl);
    lang.getScopeManager().leaveScope(recordDeclaration);
    return recordDeclaration;
}
Also used : ProblemNode(de.fraunhofer.aisec.cpg.graph.ProblemNode) ParameterizedType(de.fraunhofer.aisec.cpg.graph.types.ParameterizedType) ResolvedConstructorDeclaration(com.github.javaparser.resolution.declarations.ResolvedConstructorDeclaration) NodeList(com.github.javaparser.ast.NodeList) List(java.util.List) CompoundStatement(de.fraunhofer.aisec.cpg.graph.statements.CompoundStatement) ResolvedMethodDeclaration(com.github.javaparser.resolution.declarations.ResolvedMethodDeclaration) RecordDeclaration(de.fraunhofer.aisec.cpg.graph.declarations.RecordDeclaration) InitializerDeclaration(com.github.javaparser.ast.body.InitializerDeclaration) ClassOrInterfaceDeclaration(com.github.javaparser.ast.body.ClassOrInterfaceDeclaration)

Example 5 with CompoundStatement

use of de.fraunhofer.aisec.cpg.graph.statements.CompoundStatement in project cpg by Fraunhofer-AISEC.

the class CXXLanguageFrontendTest method testRegionsCfg.

@Test
void testRegionsCfg() throws Exception {
    File file = new File("src/test/resources/cfg.cpp");
    TranslationUnitDeclaration declaration = TestUtils.analyzeAndGetFirstTU(List.of(file), file.getParentFile().toPath(), true);
    FunctionDeclaration fdecl = declaration.getDeclarationAs(0, FunctionDeclaration.class);
    CompoundStatement body = (CompoundStatement) fdecl.getBody();
    Map<String, Region> expected = new HashMap<>();
    expected.put("cout << \"bla\";", new Region(4, 3, 4, 17));
    expected.put("cout << \"blubb\";", new Region(5, 3, 5, 19));
    expected.put("return 0;", new Region(15, 3, 15, 12));
    for (Node d : body.getStatements()) {
        if (expected.containsKey(d.getCode())) {
            assertEquals(expected.get(d.getCode()), d.getLocation().getRegion(), d.getCode());
            expected.remove(d.getCode());
        }
    }
    assertTrue(expected.isEmpty(), String.join(", ", expected.keySet()));
}
Also used : FunctionDeclaration(de.fraunhofer.aisec.cpg.graph.declarations.FunctionDeclaration) CompoundStatement(de.fraunhofer.aisec.cpg.graph.statements.CompoundStatement) Node(de.fraunhofer.aisec.cpg.graph.Node) Region(de.fraunhofer.aisec.cpg.sarif.Region) File(java.io.File) TranslationUnitDeclaration(de.fraunhofer.aisec.cpg.graph.declarations.TranslationUnitDeclaration) BaseTest(de.fraunhofer.aisec.cpg.BaseTest) Test(org.junit.jupiter.api.Test)

Aggregations

CompoundStatement (de.fraunhofer.aisec.cpg.graph.statements.CompoundStatement)10 BaseTest (de.fraunhofer.aisec.cpg.BaseTest)9 Test (org.junit.jupiter.api.Test)9 FunctionDeclaration (de.fraunhofer.aisec.cpg.graph.declarations.FunctionDeclaration)7 TranslationUnitDeclaration (de.fraunhofer.aisec.cpg.graph.declarations.TranslationUnitDeclaration)7 File (java.io.File)7 ReturnStatement (de.fraunhofer.aisec.cpg.graph.statements.ReturnStatement)5 Statement (de.fraunhofer.aisec.cpg.graph.statements.Statement)5 VariableDeclaration (de.fraunhofer.aisec.cpg.graph.declarations.VariableDeclaration)4 CaseStatement (de.fraunhofer.aisec.cpg.graph.statements.CaseStatement)4 DeclarationStatement (de.fraunhofer.aisec.cpg.graph.statements.DeclarationStatement)4 DefaultStatement (de.fraunhofer.aisec.cpg.graph.statements.DefaultStatement)4 ForEachStatement (de.fraunhofer.aisec.cpg.graph.statements.ForEachStatement)4 IfStatement (de.fraunhofer.aisec.cpg.graph.statements.IfStatement)4 SwitchStatement (de.fraunhofer.aisec.cpg.graph.statements.SwitchStatement)4 TryStatement (de.fraunhofer.aisec.cpg.graph.statements.TryStatement)4 RecordDeclaration (de.fraunhofer.aisec.cpg.graph.declarations.RecordDeclaration)2 NodeList (com.github.javaparser.ast.NodeList)1 ClassOrInterfaceDeclaration (com.github.javaparser.ast.body.ClassOrInterfaceDeclaration)1 InitializerDeclaration (com.github.javaparser.ast.body.InitializerDeclaration)1