Search in sources :

Example 11 with Node

use of de.fraunhofer.aisec.cpg.graph.Node 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)

Example 12 with Node

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

the class VariableResolverCppTest method initTests.

@BeforeAll
void initTests() throws ExecutionException, InterruptedException {
    final String topLevelPath = "src/test/resources/variables_extended/cpp/";
    List<String> fileNames = Arrays.asList("scope_variables.cpp", "external_class.cpp");
    List<File> fileLocations = fileNames.stream().map(fileName -> new File(topLevelPath + fileName)).collect(Collectors.toList());
    TranslationConfiguration config = TranslationConfiguration.builder().sourceLocations(fileLocations.toArray(new File[fileNames.size()])).topLevel(new File(topLevelPath)).defaultPasses().debugParser(true).defaultLanguages().failOnError(true).loadIncludes(true).build();
    TranslationManager analyzer = TranslationManager.builder().config(config).build();
    List<TranslationUnitDeclaration> tu = analyzer.analyze().get().getTranslationUnits();
    List<Node> nodes = tu.stream().flatMap(tUnit -> SubgraphWalker.flattenAST(tUnit).stream()).collect(Collectors.toList());
    List<CallExpression> calls = TestUtils.findByName(Util.filterCast(nodes, CallExpression.class), "printLog");
    calls.sort(new NodeComparator());
    List<RecordDeclaration> records = Util.filterCast(nodes, RecordDeclaration.class);
    // Extract all Variable declarations and field declarations for matching
    externalClass = TestUtils.getOfTypeWithName(nodes, RecordDeclaration.class, "ExternalClass");
    externVarName = TestUtils.getSubnodeOfTypeWithName(externalClass, FieldDeclaration.class, "varName");
    externStaticVarName = TestUtils.getSubnodeOfTypeWithName(externalClass, FieldDeclaration.class, "staticVarName");
    outerClass = TestUtils.getOfTypeWithName(nodes, RecordDeclaration.class, "ScopeVariables");
    outerVarName = outerClass.getFields().stream().filter(n -> n.getName().equals("varName")).findFirst().get();
    outerStaticVarName = outerClass.getFields().stream().filter(n -> n.getName().equals("staticVarName")).findFirst().get();
    outerImpThis = outerClass.getFields().stream().filter(n -> n.getName().equals("this")).findFirst().get();
    List<RecordDeclaration> classes = Util.filterCast(nodes, RecordDeclaration.class);
    // Inner class and its fields
    innerClass = TestUtils.getOfTypeWithName(nodes, RecordDeclaration.class, "ScopeVariables::InnerClass");
    innerVarName = innerClass.getFields().stream().filter(n -> n.getName().equals("varName")).findFirst().get();
    innerStaticVarName = innerClass.getFields().stream().filter(n -> n.getName().equals("staticVarName")).findFirst().get();
    innerImpThis = innerClass.getFields().stream().filter(n -> n.getName().equals("this")).findFirst().get();
    main = TestUtils.getOfTypeWithName(nodes, FunctionDeclaration.class, "main");
    // Functions in the outer and inner object
    outerFunction1 = outerClass.getMethods().stream().filter(method -> method.getName().equals("function1")).collect(Collectors.toList()).get(0);
    forStatements = Util.filterCast(SubgraphWalker.flattenAST(outerFunction1), ForStatement.class);
    outerFunction2 = outerClass.getMethods().stream().filter(method -> method.getName().equals("function2")).collect(Collectors.toList()).get(0);
    outerFunction3 = outerClass.getMethods().stream().filter(method -> method.getName().equals("function3")).collect(Collectors.toList()).get(0);
    outerFunction4 = outerClass.getMethods().stream().filter(method -> method.getName().equals("function4")).collect(Collectors.toList()).get(0);
    outerFunction5 = outerClass.getMethods().stream().filter(method -> method.getName().equals("function5")).collect(Collectors.toList()).get(0);
    innerFunction1 = innerClass.getMethods().stream().filter(method -> method.getName().equals("function1")).collect(Collectors.toList()).get(0);
    innerFunction2 = innerClass.getMethods().stream().filter(method -> method.getName().equals("function2")).collect(Collectors.toList()).get(0);
    for (CallExpression call : calls) {
        Expression first = call.getArguments().get(0);
        String logId = ((Literal) first).getValue().toString();
        Expression second = call.getArguments().get(1);
        callParamMap.put(logId, second);
    }
}
Also used : Assertions.assertNotNull(org.junit.jupiter.api.Assertions.assertNotNull) Arrays(java.util.Arrays) FieldDeclaration(de.fraunhofer.aisec.cpg.graph.declarations.FieldDeclaration) HashMap(java.util.HashMap) BaseTest(de.fraunhofer.aisec.cpg.BaseTest) NodeComparator(de.fraunhofer.aisec.cpg.helpers.NodeComparator) Literal(de.fraunhofer.aisec.cpg.graph.statements.expressions.Literal) ForStatement(de.fraunhofer.aisec.cpg.graph.statements.ForStatement) TestInstance(org.junit.jupiter.api.TestInstance) BeforeAll(org.junit.jupiter.api.BeforeAll) Util(de.fraunhofer.aisec.cpg.helpers.Util) Map(java.util.Map) SubgraphWalker(de.fraunhofer.aisec.cpg.helpers.SubgraphWalker) FunctionDeclaration(de.fraunhofer.aisec.cpg.graph.declarations.FunctionDeclaration) Node(de.fraunhofer.aisec.cpg.graph.Node) ParamVariableDeclaration(de.fraunhofer.aisec.cpg.graph.declarations.ParamVariableDeclaration) MethodDeclaration(de.fraunhofer.aisec.cpg.graph.declarations.MethodDeclaration) VariableDeclaration(de.fraunhofer.aisec.cpg.graph.declarations.VariableDeclaration) DeclaredReferenceExpression(de.fraunhofer.aisec.cpg.graph.statements.expressions.DeclaredReferenceExpression) TestUtils(de.fraunhofer.aisec.cpg.TestUtils) RecordDeclaration(de.fraunhofer.aisec.cpg.graph.declarations.RecordDeclaration) IfStatement(de.fraunhofer.aisec.cpg.graph.statements.IfStatement) Collectors(java.util.stream.Collectors) File(java.io.File) ExecutionException(java.util.concurrent.ExecutionException) Test(org.junit.jupiter.api.Test) Expression(de.fraunhofer.aisec.cpg.graph.statements.expressions.Expression) List(java.util.List) CompoundStatement(de.fraunhofer.aisec.cpg.graph.statements.CompoundStatement) CatchClause(de.fraunhofer.aisec.cpg.graph.statements.CatchClause) MemberExpression(de.fraunhofer.aisec.cpg.graph.statements.expressions.MemberExpression) TranslationConfiguration(de.fraunhofer.aisec.cpg.TranslationConfiguration) TranslationManager(de.fraunhofer.aisec.cpg.TranslationManager) TranslationUnitDeclaration(de.fraunhofer.aisec.cpg.graph.declarations.TranslationUnitDeclaration) CallExpression(de.fraunhofer.aisec.cpg.graph.statements.expressions.CallExpression) NodeComparator(de.fraunhofer.aisec.cpg.helpers.NodeComparator) Node(de.fraunhofer.aisec.cpg.graph.Node) TranslationManager(de.fraunhofer.aisec.cpg.TranslationManager) TranslationConfiguration(de.fraunhofer.aisec.cpg.TranslationConfiguration) TranslationUnitDeclaration(de.fraunhofer.aisec.cpg.graph.declarations.TranslationUnitDeclaration) FieldDeclaration(de.fraunhofer.aisec.cpg.graph.declarations.FieldDeclaration) RecordDeclaration(de.fraunhofer.aisec.cpg.graph.declarations.RecordDeclaration) FunctionDeclaration(de.fraunhofer.aisec.cpg.graph.declarations.FunctionDeclaration) DeclaredReferenceExpression(de.fraunhofer.aisec.cpg.graph.statements.expressions.DeclaredReferenceExpression) Expression(de.fraunhofer.aisec.cpg.graph.statements.expressions.Expression) MemberExpression(de.fraunhofer.aisec.cpg.graph.statements.expressions.MemberExpression) CallExpression(de.fraunhofer.aisec.cpg.graph.statements.expressions.CallExpression) ForStatement(de.fraunhofer.aisec.cpg.graph.statements.ForStatement) File(java.io.File) CallExpression(de.fraunhofer.aisec.cpg.graph.statements.expressions.CallExpression) BeforeAll(org.junit.jupiter.api.BeforeAll)

Example 13 with Node

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

the class CallResolverTest method testScopedFunctionResolutionFunctionGlobal.

void testScopedFunctionResolutionFunctionGlobal(List<TranslationUnitDeclaration> result, List<CallExpression> calls) {
    CallExpression fh = TestUtils.findByUniquePredicate(calls, c -> c.getLocation().getRegion().getStartLine() == 4);
    Literal<?> literal7 = TestUtils.findByUniquePredicate(TestUtils.subnodesOfType(result, Literal.class), l -> l.getValue().equals(7));
    assertEquals(1, fh.getInvokes().size());
    assertFalse(fh.getInvokes().get(0).isImplicit());
    assertEquals(2, fh.getInvokes().get(0).getLocation().getRegion().getStartLine());
    assertEquals(1, fh.getArguments().size());
    assertEquals(3, ((Literal) fh.getArguments().get(0)).getValue());
    assertTrue(fh.getInvokes().get(0).getNextEOG().contains(literal7));
    for (Node node : fh.getInvokes().get(0).getNextEOG()) {
        assertTrue(node.equals(literal7) || literal7.getNextEOG().contains(node));
    }
}
Also used : Literal(de.fraunhofer.aisec.cpg.graph.statements.expressions.Literal) Node(de.fraunhofer.aisec.cpg.graph.Node) CallExpression(de.fraunhofer.aisec.cpg.graph.statements.expressions.CallExpression)

Example 14 with Node

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

the class CallResolverTest method testDefaultArgumentsInDeclaration.

@Test
void testDefaultArgumentsInDeclaration() throws Exception {
    List<TranslationUnitDeclaration> result = TestUtils.analyze(List.of(Path.of(topLevel.toString(), "defaultargs", "defaultInDeclaration.cpp").toFile()), topLevel, true);
    List<CallExpression> calls = TestUtils.subnodesOfType(result, CallExpression.class);
    List<FunctionDeclaration> functionDeclarations = TestUtils.subnodesOfType(result, FunctionDeclaration.class);
    FunctionDeclaration displayDeclaration = TestUtils.findByUniquePredicate(functionDeclarations, f -> f.getName().equals("display") && !f.isDefinition() && !f.isImplicit());
    FunctionDeclaration displayDefinition = TestUtils.findByUniquePredicate(functionDeclarations, f -> f.getName().equals("display") && f.isDefinition() && !f.isImplicit());
    // Check defines edge
    assertEquals(displayDefinition, displayDeclaration.getDefinition());
    // Check defaults edge of ParamVariableDeclaration
    assertEquals(displayDeclaration.getDefaultParameters(), displayDefinition.getDefaultParameters());
    // Check call display(1);
    CallExpression display1 = TestUtils.findByUniquePredicate(calls, c -> {
        assert c.getCode() != null;
        return c.getCode().equals("display(1);");
    });
    // it will contain two nodes: the definition and the declaration. this is a general
    // problem, that we need to tackle in the future, how to combine those two. See
    // https://github.com/Fraunhofer-AISEC/cpg/issues/194
    assertEquals(2, display1.getInvokes().size());
    assertTrue(display1.getInvokes().contains(displayDeclaration));
    assertEquals("1", display1.getArguments().get(0).getCode());
    assertTrue(displayDeclaration.getNextEOG().contains(displayDeclaration.getDefaultParameters().get(1)));
    assertTrue(displayDeclaration.getNextEOG().contains(displayDeclaration.getDefaultParameters().get(0)));
    assertTrue(displayDeclaration.getDefaultParameters().get(0).getNextEOG().contains(displayDeclaration.getDefaultParameters().get(1)));
    for (Node node : displayDeclaration.getNextEOG()) {
        assertTrue(node.equals(displayDeclaration.getDefaultParameters().get(0)) || node.equals(displayDeclaration.getDefaultParameters().get(1)) || displayDeclaration.getDefaultParameters().get(1).getNextEOG().contains(node));
    }
    CallExpression display = TestUtils.findByUniquePredicate(calls, c -> {
        assert c.getCode() != null;
        return c.getCode().equals("display();");
    });
    assertEquals(2, display.getInvokes().size());
    assertTrue(display.getInvokes().contains(displayDeclaration));
    assertEquals(0, display.getArguments().size());
    CallExpression displayCount$ = TestUtils.findByUniquePredicate(calls, c -> {
        assert c.getCode() != null;
        return c.getCode().equals("display(count, '$');");
    });
    assertEquals(2, display.getInvokes().size());
    assertTrue(display.getInvokes().contains(displayDeclaration));
    assertEquals("count", displayCount$.getArguments().get(0).getName());
    assertEquals("'$'", displayCount$.getArguments().get(1).getCode());
    CallExpression display10 = TestUtils.findByUniquePredicate(calls, c -> {
        assert c.getCode() != null;
        return c.getCode().equals("display(10.0);");
    });
    assertEquals(2, display10.getInvokes().size());
    assertTrue(display.getInvokes().contains(displayDeclaration));
    assertEquals(1, display10.getArguments().size());
    assertTrue(display10.getArguments().get(0) instanceof CastExpression);
    assertEquals("10.0", ((CastExpression) display10.getArguments().get(0)).getExpression().getCode());
    assertEquals("int", ((CastExpression) display10.getArguments().get(0)).getCastType().getName());
}
Also used : Node(de.fraunhofer.aisec.cpg.graph.Node) CastExpression(de.fraunhofer.aisec.cpg.graph.statements.expressions.CastExpression) CallExpression(de.fraunhofer.aisec.cpg.graph.statements.expressions.CallExpression) BaseTest(de.fraunhofer.aisec.cpg.BaseTest) Test(org.junit.jupiter.api.Test)

Example 15 with Node

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

the class ConstructorsTest method testCPPPartialDefault.

@Test
void testCPPPartialDefault() throws Exception {
    List<TranslationUnitDeclaration> result = TestUtils.analyze(List.of(Path.of(topLevel.toString(), "defaultarg", "constructorDefault.cpp").toFile()), topLevel, true);
    List<ConstructorDeclaration> constructors = TestUtils.subnodesOfType(result, ConstructorDeclaration.class);
    List<VariableDeclaration> variables = TestUtils.subnodesOfType(result, VariableDeclaration.class);
    ConstructorDeclaration singleDefaultArg = TestUtils.findByUniquePredicate(constructors, c -> c.getParameters().size() == 2 && c.getName().equals("E"));
    Literal<?> literal10 = TestUtils.findByUniquePredicate(TestUtils.subnodesOfType(result, Literal.class), l -> l.getValue().equals(10));
    VariableDeclaration e1 = TestUtils.findByUniqueName(variables, "e1");
    assertTrue(e1.getInitializer() instanceof ConstructExpression);
    ConstructExpression e1Initializer = (ConstructExpression) e1.getInitializer();
    assertTrue(e1Initializer.getConstructor().isInferred());
    assertEquals(0, e1Initializer.getArguments().size());
    VariableDeclaration e2 = TestUtils.findByUniqueName(variables, "e2");
    assertTrue(e2.getInitializer() instanceof ConstructExpression);
    ConstructExpression e2Initializer = (ConstructExpression) e2.getInitializer();
    assertEquals(singleDefaultArg, e2Initializer.getConstructor());
    assertEquals(1, e2Initializer.getArguments().size());
    assertEquals(5, ((Literal) e2Initializer.getArguments().get(0)).getValue());
    assertTrue(singleDefaultArg.getNextEOG().contains(literal10));
    for (Node node : singleDefaultArg.getNextEOG()) {
        if (!node.equals(literal10)) {
            assertTrue(literal10.getNextEOG().contains(node));
        }
    }
    VariableDeclaration e3 = TestUtils.findByUniqueName(variables, "e3");
    assertTrue(e3.getInitializer() instanceof ConstructExpression);
    ConstructExpression e3Initializer = (ConstructExpression) e3.getInitializer();
    assertEquals(singleDefaultArg, e3Initializer.getConstructor());
    assertEquals(2, e3Initializer.getArguments().size());
    assertEquals(6, ((Literal) e3Initializer.getArguments().get(0)).getValue());
    assertEquals(7, ((Literal) e3Initializer.getArguments().get(1)).getValue());
}
Also used : ConstructorDeclaration(de.fraunhofer.aisec.cpg.graph.declarations.ConstructorDeclaration) Node(de.fraunhofer.aisec.cpg.graph.Node) VariableDeclaration(de.fraunhofer.aisec.cpg.graph.declarations.VariableDeclaration) TranslationUnitDeclaration(de.fraunhofer.aisec.cpg.graph.declarations.TranslationUnitDeclaration) Test(org.junit.jupiter.api.Test) BaseTest(de.fraunhofer.aisec.cpg.BaseTest)

Aggregations

Node (de.fraunhofer.aisec.cpg.graph.Node)17 BaseTest (de.fraunhofer.aisec.cpg.BaseTest)11 Test (org.junit.jupiter.api.Test)11 CallExpression (de.fraunhofer.aisec.cpg.graph.statements.expressions.CallExpression)8 TranslationUnitDeclaration (de.fraunhofer.aisec.cpg.graph.declarations.TranslationUnitDeclaration)7 Literal (de.fraunhofer.aisec.cpg.graph.statements.expressions.Literal)6 VariableDeclaration (de.fraunhofer.aisec.cpg.graph.declarations.VariableDeclaration)5 File (java.io.File)5 TranslationConfiguration (de.fraunhofer.aisec.cpg.TranslationConfiguration)3 TranslationManager (de.fraunhofer.aisec.cpg.TranslationManager)3 ConstructorDeclaration (de.fraunhofer.aisec.cpg.graph.declarations.ConstructorDeclaration)3 CompoundStatement (de.fraunhofer.aisec.cpg.graph.statements.CompoundStatement)3 MemberExpression (de.fraunhofer.aisec.cpg.graph.statements.expressions.MemberExpression)3 NodeComparator (de.fraunhofer.aisec.cpg.helpers.NodeComparator)3 Collectors (java.util.stream.Collectors)3 TestUtils (de.fraunhofer.aisec.cpg.TestUtils)2 SubGraph (de.fraunhofer.aisec.cpg.graph.SubGraph)2 FieldDeclaration (de.fraunhofer.aisec.cpg.graph.declarations.FieldDeclaration)2 FunctionDeclaration (de.fraunhofer.aisec.cpg.graph.declarations.FunctionDeclaration)2 MethodDeclaration (de.fraunhofer.aisec.cpg.graph.declarations.MethodDeclaration)2