Search in sources :

Example 1 with DeclaredReferenceExpression

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

the class CXXIncludeTest method testDefinitionsAndDeclaration.

@Test
void testDefinitionsAndDeclaration() throws Exception {
    File file = new File("src/test/resources/include.cpp");
    TranslationUnitDeclaration tu = TestUtils.analyzeAndGetFirstTU(List.of(file), file.getParentFile().toPath(), true);
    for (Declaration d : tu.getDeclarations()) {
        System.out.println(d.getName() + " " + d.getLocation());
    }
    assertEquals(6, tu.getDeclarations().size());
    RecordDeclaration someClass = tu.getDeclarationsByName("SomeClass", RecordDeclaration.class).iterator().next();
    assertNotNull(someClass);
    Set<FunctionDeclaration> main = tu.getDeclarationsByName("main", FunctionDeclaration.class);
    assertFalse(main.isEmpty());
    ConstructorDeclaration someClassConstructor = tu.getDeclarationsByName("SomeClass", ConstructorDeclaration.class).iterator().next();
    assertNotNull(someClassConstructor);
    assertEquals(someClass, someClassConstructor.getRecordDeclaration());
    MethodDeclaration doSomething = tu.getDeclarationsByName("DoSomething", MethodDeclaration.class).iterator().next();
    assertNotNull(doSomething);
    assertEquals(someClass, doSomething.getRecordDeclaration());
    ReturnStatement returnStatement = doSomething.getBodyStatementAs(0, ReturnStatement.class);
    assertNotNull(returnStatement);
    DeclaredReferenceExpression ref = (DeclaredReferenceExpression) returnStatement.getReturnValue();
    assertNotNull(ref);
    FieldDeclaration someField = someClass.getField("someField");
    assertNotNull(someField);
    assertEquals(someField, ref.getRefersTo());
}
Also used : DeclaredReferenceExpression(de.fraunhofer.aisec.cpg.graph.statements.expressions.DeclaredReferenceExpression) ReturnStatement(de.fraunhofer.aisec.cpg.graph.statements.ReturnStatement) File(java.io.File) BaseTest(de.fraunhofer.aisec.cpg.BaseTest) Test(org.junit.jupiter.api.Test)

Example 2 with DeclaredReferenceExpression

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

the class EOGTest method testBranchProperty.

/**
 * Tests EOG branch edge property in if/else if/else construct
 *
 * @throws Exception
 */
@Test
void testBranchProperty() throws Exception {
    Path topLevel = Path.of("src", "test", "resources", "eog");
    List<TranslationUnitDeclaration> result = TestUtils.analyze(List.of(topLevel.resolve("EOG.java").toFile()), topLevel, true);
    // Test If-Block
    IfStatement firstIf = TestUtils.findByPredicate(TestUtils.subnodesOfType(result, IfStatement.class), l -> l.getLocation().getRegion().getStartLine() == 6).get(0);
    DeclaredReferenceExpression a = TestUtils.findByPredicate(TestUtils.subnodesOfType(result, DeclaredReferenceExpression.class), l -> l.getLocation().getRegion().getStartLine() == 8 && l.getName().equals("a")).get(0);
    DeclaredReferenceExpression b = TestUtils.findByPredicate(TestUtils.subnodesOfType(result, DeclaredReferenceExpression.class), l -> l.getLocation().getRegion().getStartLine() == 7 && l.getName().equals("b")).get(0);
    List<PropertyEdge<Node>> nextEOG = firstIf.getNextEOGEdges();
    assertEquals(2, nextEOG.size());
    for (PropertyEdge<Node> edge : nextEOG) {
        assertEquals(firstIf, edge.getStart());
        if (edge.getEnd().equals(b)) {
            assertEquals(true, edge.getProperty(Properties.BRANCH));
            assertEquals(0, edge.getProperty(Properties.INDEX));
        } else {
            assertEquals(a, edge.getEnd());
            assertEquals(false, edge.getProperty(Properties.BRANCH));
            assertEquals(1, edge.getProperty(Properties.INDEX));
        }
    }
    IfStatement elseIf = TestUtils.findByPredicate(TestUtils.subnodesOfType(result, IfStatement.class), l -> l.getLocation().getRegion().getStartLine() == 8).get(0);
    assertEquals(elseIf, firstIf.getElseStatement());
    DeclaredReferenceExpression b2 = TestUtils.findByPredicate(TestUtils.subnodesOfType(result, DeclaredReferenceExpression.class), l -> l.getLocation().getRegion().getStartLine() == 9 && l.getName().equals("b")).get(0);
    DeclaredReferenceExpression x = TestUtils.findByPredicate(TestUtils.subnodesOfType(result, DeclaredReferenceExpression.class), l -> l.getLocation().getRegion().getStartLine() == 11 && l.getName().equals("x")).get(0);
    nextEOG = elseIf.getNextEOGEdges();
    assertEquals(2, nextEOG.size());
    for (PropertyEdge<Node> edge : nextEOG) {
        assertEquals(elseIf, edge.getStart());
        if (edge.getEnd().equals(b2)) {
            assertEquals(true, edge.getProperty(Properties.BRANCH));
            assertEquals(0, edge.getProperty(Properties.INDEX));
        } else {
            assertEquals(x, edge.getEnd());
            assertEquals(false, edge.getProperty(Properties.BRANCH));
            assertEquals(1, edge.getProperty(Properties.INDEX));
        }
    }
}
Also used : Path(java.nio.file.Path) EvaluationOrderGraphPass(de.fraunhofer.aisec.cpg.passes.EvaluationOrderGraphPass) Properties(de.fraunhofer.aisec.cpg.graph.edge.Properties) SUBTREE(de.fraunhofer.aisec.cpg.helpers.Util.Connect.SUBTREE) de.fraunhofer.aisec.cpg.graph(de.fraunhofer.aisec.cpg.graph) BaseTest(de.fraunhofer.aisec.cpg.BaseTest) NodeComparator(de.fraunhofer.aisec.cpg.helpers.NodeComparator) ConstructorDeclaration(de.fraunhofer.aisec.cpg.graph.declarations.ConstructorDeclaration) Util(de.fraunhofer.aisec.cpg.helpers.Util) SubgraphWalker(de.fraunhofer.aisec.cpg.helpers.SubgraphWalker) FunctionDeclaration(de.fraunhofer.aisec.cpg.graph.declarations.FunctionDeclaration) PropertyEdge(de.fraunhofer.aisec.cpg.graph.edge.PropertyEdge) Path(java.nio.file.Path) EXITS(de.fraunhofer.aisec.cpg.helpers.Util.Edge.EXITS) PhysicalLocation.locationLink(de.fraunhofer.aisec.cpg.sarif.PhysicalLocation.locationLink) NODE(de.fraunhofer.aisec.cpg.helpers.Util.Connect.NODE) ALL(de.fraunhofer.aisec.cpg.helpers.Util.Quantifier.ALL) DeclaredReferenceExpression(de.fraunhofer.aisec.cpg.graph.statements.expressions.DeclaredReferenceExpression) Strategy(de.fraunhofer.aisec.cpg.processing.strategy.Strategy) TestUtils(de.fraunhofer.aisec.cpg.TestUtils) TransactionException(org.neo4j.ogm.exception.TransactionException) ANY(de.fraunhofer.aisec.cpg.helpers.Util.Quantifier.ANY) Collectors(java.util.stream.Collectors) File(java.io.File) BinaryOperator(de.fraunhofer.aisec.cpg.graph.statements.expressions.BinaryOperator) Objects(java.util.Objects) Test(org.junit.jupiter.api.Test) ENTRIES(de.fraunhofer.aisec.cpg.helpers.Util.Edge.ENTRIES) TranslationException(de.fraunhofer.aisec.cpg.frontends.TranslationException) List(java.util.List) IVisitor(de.fraunhofer.aisec.cpg.processing.IVisitor) Stream(java.util.stream.Stream) de.fraunhofer.aisec.cpg.graph.statements(de.fraunhofer.aisec.cpg.graph.statements) Assertions(org.junit.jupiter.api.Assertions) TranslationUnitDeclaration(de.fraunhofer.aisec.cpg.graph.declarations.TranslationUnitDeclaration) CallExpression(de.fraunhofer.aisec.cpg.graph.statements.expressions.CallExpression) DeclaredReferenceExpression(de.fraunhofer.aisec.cpg.graph.statements.expressions.DeclaredReferenceExpression) TranslationUnitDeclaration(de.fraunhofer.aisec.cpg.graph.declarations.TranslationUnitDeclaration) PropertyEdge(de.fraunhofer.aisec.cpg.graph.edge.PropertyEdge) BaseTest(de.fraunhofer.aisec.cpg.BaseTest) Test(org.junit.jupiter.api.Test)

Example 3 with DeclaredReferenceExpression

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

the class CXXSymbolConfigurationTest method testWithoutSymbols.

@Test
void testWithoutSymbols() throws TranslationException {
    // parse without symbols
    TranslationUnitDeclaration tu = new CXXLanguageFrontend(TranslationConfiguration.builder().defaultPasses().build(), new ScopeManager()).parse(new File("src/test/resources/symbols.cpp"));
    Set<FunctionDeclaration> main = tu.getDeclarationsByName("main", FunctionDeclaration.class);
    assertFalse(main.isEmpty());
    FunctionDeclaration funcDecl = main.iterator().next();
    BinaryOperator binaryOperator = funcDecl.getBodyStatementAs(0, BinaryOperator.class);
    assertNotNull(binaryOperator);
    // without additional symbols, the first line will look like a reference (to something we do not
    // know)
    DeclaredReferenceExpression dre = binaryOperator.getRhsAs(DeclaredReferenceExpression.class);
    assertNotNull(dre);
    assertEquals("HELLO_WORLD", dre.getName());
    binaryOperator = funcDecl.getBodyStatementAs(1, BinaryOperator.class);
    assertNotNull(binaryOperator);
    // without additional symbols, the second line will look like a function call (to something we
    // do not know)
    CallExpression call = binaryOperator.getRhsAs(CallExpression.class);
    assertNotNull(call);
    assertEquals("INCREASE", call.getName());
}
Also used : FunctionDeclaration(de.fraunhofer.aisec.cpg.graph.declarations.FunctionDeclaration) ScopeManager(de.fraunhofer.aisec.cpg.passes.scopes.ScopeManager) DeclaredReferenceExpression(de.fraunhofer.aisec.cpg.graph.statements.expressions.DeclaredReferenceExpression) BinaryOperator(de.fraunhofer.aisec.cpg.graph.statements.expressions.BinaryOperator) TranslationUnitDeclaration(de.fraunhofer.aisec.cpg.graph.declarations.TranslationUnitDeclaration) File(java.io.File) CallExpression(de.fraunhofer.aisec.cpg.graph.statements.expressions.CallExpression) BaseTest(de.fraunhofer.aisec.cpg.BaseTest) Test(org.junit.jupiter.api.Test)

Example 4 with DeclaredReferenceExpression

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

the class VariableUsageResolver method resolveFieldUsages.

protected void resolveFieldUsages(Node current, RecordDeclaration curClass) {
    if (current instanceof MemberExpression) {
        MemberExpression memberExpression = (MemberExpression) current;
        Declaration baseTarget = null;
        if (memberExpression.getBase() instanceof DeclaredReferenceExpression) {
            DeclaredReferenceExpression base = (DeclaredReferenceExpression) memberExpression.getBase();
            if (lang instanceof JavaLanguageFrontend && base.getName().equals("super")) {
                if (curClass != null && !curClass.getSuperClasses().isEmpty()) {
                    var superType = curClass.getSuperClasses().get(0);
                    var superRecord = recordMap.get(superType);
                    if (superRecord == null) {
                        log.error("Could not find referring super type {} for {} in the record map. Will set the super type to java.lang.Object", superType.getTypeName(), curClass.getName());
                        base.setType(TypeParser.createFrom(Object.class.getName(), true));
                    } else {
                        baseTarget = superRecord.getThis();
                        base.setRefersTo(baseTarget);
                    }
                } else {
                    // no explicit super type -> java.lang.Object
                    Type objectType = TypeParser.createFrom(Object.class.getName(), true);
                    base.setType(objectType);
                }
            } else {
                baseTarget = resolveBase((DeclaredReferenceExpression) memberExpression.getBase());
                base.setRefersTo(baseTarget);
            }
            if (baseTarget instanceof EnumDeclaration) {
                String name = memberExpression.getName();
                Optional<EnumConstantDeclaration> memberTarget = ((EnumDeclaration) baseTarget).getEntries().stream().filter(e -> e.getName().equals(name)).findFirst();
                if (memberTarget.isPresent()) {
                    memberExpression.setRefersTo(memberTarget.get());
                    return;
                }
            } else if (baseTarget instanceof RecordDeclaration) {
                Type baseType = TypeParser.createFrom(baseTarget.getName(), true);
                if (!recordMap.containsKey(baseType)) {
                    final Type containingT = baseType;
                    Optional<Type> fqnResolvedType = recordMap.keySet().stream().filter(t -> t.getName().endsWith("." + containingT.getName())).findFirst();
                    if (fqnResolvedType.isPresent()) {
                        baseType = fqnResolvedType.get();
                    }
                }
                memberExpression.setRefersTo(resolveMember(baseType, memberExpression));
                return;
            }
        }
        Type baseType = memberExpression.getBase().getType();
        if (!recordMap.containsKey(baseType)) {
            final Type containingT = baseType;
            Optional<Type> fqnResolvedType = recordMap.keySet().stream().filter(t -> t.getName().endsWith("." + containingT.getName())).findFirst();
            if (fqnResolvedType.isPresent()) {
                baseType = fqnResolvedType.get();
            }
        }
        memberExpression.setRefersTo(resolveMember(baseType, memberExpression));
    }
}
Also used : Util.warnWithFileLocation(de.fraunhofer.aisec.cpg.helpers.Util.warnWithFileLocation) java.util(java.util) DeclaredReferenceExpression(de.fraunhofer.aisec.cpg.graph.statements.expressions.DeclaredReferenceExpression) Logger(org.slf4j.Logger) LoggerFactory(org.slf4j.LoggerFactory) de.fraunhofer.aisec.cpg.graph(de.fraunhofer.aisec.cpg.graph) ScopedWalker(de.fraunhofer.aisec.cpg.helpers.SubgraphWalker.ScopedWalker) NodeBuilder.newRecordDeclaration(de.fraunhofer.aisec.cpg.graph.NodeBuilder.newRecordDeclaration) Collectors(java.util.stream.Collectors) TranslationResult(de.fraunhofer.aisec.cpg.TranslationResult) MemberCallExpression(de.fraunhofer.aisec.cpg.graph.statements.expressions.MemberCallExpression) Matcher(java.util.regex.Matcher) de.fraunhofer.aisec.cpg.graph.declarations(de.fraunhofer.aisec.cpg.graph.declarations) MemberExpression(de.fraunhofer.aisec.cpg.graph.statements.expressions.MemberExpression) Util(de.fraunhofer.aisec.cpg.helpers.Util) de.fraunhofer.aisec.cpg.graph.types(de.fraunhofer.aisec.cpg.graph.types) Pattern(java.util.regex.Pattern) JavaLanguageFrontend(de.fraunhofer.aisec.cpg.frontends.java.JavaLanguageFrontend) Nullable(org.checkerframework.checker.nullness.qual.Nullable) MemberExpression(de.fraunhofer.aisec.cpg.graph.statements.expressions.MemberExpression) NodeBuilder.newRecordDeclaration(de.fraunhofer.aisec.cpg.graph.NodeBuilder.newRecordDeclaration) DeclaredReferenceExpression(de.fraunhofer.aisec.cpg.graph.statements.expressions.DeclaredReferenceExpression) NodeBuilder.newRecordDeclaration(de.fraunhofer.aisec.cpg.graph.NodeBuilder.newRecordDeclaration) JavaLanguageFrontend(de.fraunhofer.aisec.cpg.frontends.java.JavaLanguageFrontend)

Example 5 with DeclaredReferenceExpression

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

the class VariableUsageResolver method resolveLocalVarUsage.

protected void resolveLocalVarUsage(RecordDeclaration currentClass, Node parent, Node current) {
    if (lang == null) {
        Util.errorWithFileLocation(current, log, "Could not resolve local variable usage: language frontend is null");
        return;
    }
    if (current instanceof DeclaredReferenceExpression && !(current instanceof MemberExpression)) {
        DeclaredReferenceExpression ref = (DeclaredReferenceExpression) current;
        if (parent instanceof MemberCallExpression && current == ((MemberCallExpression) parent).getMember() && !(ref.getType() instanceof FunctionPointerType)) {
            // function pointer call
            return;
        }
        // only consider resolving, if the language frontend did not specify a resolution
        Optional<? extends Declaration> refersTo = ref.getRefersTo() == null ? Optional.ofNullable(lang.getScopeManager().resolveReference(ref)) : Optional.of(ref.getRefersTo());
        Type recordDeclType = null;
        if (currentClass != null) {
            recordDeclType = TypeParser.createFrom(currentClass.getName(), true);
        }
        if (ref.getType() instanceof FunctionPointerType && refersTo.isEmpty()) {
            refersTo = resolveFunctionPtr(recordDeclType, ref);
        }
        // only add new nodes for non-static unknown
        if (refersTo.isEmpty() && !(((DeclaredReferenceExpression) current).isStaticAccess()) && recordDeclType != null && recordMap.containsKey(recordDeclType)) {
            // Maybe we are referring to a field instead of a local var
            if (current.getName().contains(lang.getNamespaceDelimiter())) {
                List<String> path = Arrays.asList(current.getName().split(Pattern.quote(lang.getNamespaceDelimiter())));
                recordDeclType = TypeParser.createFrom(String.join(lang.getNamespaceDelimiter(), path.subList(0, path.size() - 1)), true);
            }
            ValueDeclaration field = resolveMember(recordDeclType, (DeclaredReferenceExpression) current);
            if (field != null) {
                refersTo = Optional.of(field);
            }
        }
        // just enables CXX static fields
        if (refersTo.isEmpty() && current.getName().contains(lang.getNamespaceDelimiter())) {
            var path = Arrays.asList(current.getName().split(Pattern.quote(lang.getNamespaceDelimiter())));
            recordDeclType = TypeParser.createFrom(String.join(lang.getNamespaceDelimiter(), path.subList(0, path.size() - 1)), true);
            var field = resolveMember(recordDeclType, (DeclaredReferenceExpression) current);
            if (field != null) {
                refersTo = Optional.of(field);
            }
        }
        if (refersTo.isPresent()) {
            ref.setRefersTo(refersTo.get());
        } else {
            warnWithFileLocation(current, log, "Did not find a declaration for {}", ref.getName());
        }
    }
}
Also used : MemberExpression(de.fraunhofer.aisec.cpg.graph.statements.expressions.MemberExpression) DeclaredReferenceExpression(de.fraunhofer.aisec.cpg.graph.statements.expressions.DeclaredReferenceExpression) MemberCallExpression(de.fraunhofer.aisec.cpg.graph.statements.expressions.MemberCallExpression)

Aggregations

DeclaredReferenceExpression (de.fraunhofer.aisec.cpg.graph.statements.expressions.DeclaredReferenceExpression)10 BaseTest (de.fraunhofer.aisec.cpg.BaseTest)7 Test (org.junit.jupiter.api.Test)7 TranslationUnitDeclaration (de.fraunhofer.aisec.cpg.graph.declarations.TranslationUnitDeclaration)3 CallExpression (de.fraunhofer.aisec.cpg.graph.statements.expressions.CallExpression)3 MemberExpression (de.fraunhofer.aisec.cpg.graph.statements.expressions.MemberExpression)3 File (java.io.File)3 de.fraunhofer.aisec.cpg.graph (de.fraunhofer.aisec.cpg.graph)2 FunctionDeclaration (de.fraunhofer.aisec.cpg.graph.declarations.FunctionDeclaration)2 ReturnStatement (de.fraunhofer.aisec.cpg.graph.statements.ReturnStatement)2 BinaryOperator (de.fraunhofer.aisec.cpg.graph.statements.expressions.BinaryOperator)2 MemberCallExpression (de.fraunhofer.aisec.cpg.graph.statements.expressions.MemberCallExpression)2 Util (de.fraunhofer.aisec.cpg.helpers.Util)2 Collectors (java.util.stream.Collectors)2 TestUtils (de.fraunhofer.aisec.cpg.TestUtils)1 TranslationResult (de.fraunhofer.aisec.cpg.TranslationResult)1 TranslationException (de.fraunhofer.aisec.cpg.frontends.TranslationException)1 JavaLanguageFrontend (de.fraunhofer.aisec.cpg.frontends.java.JavaLanguageFrontend)1 NodeBuilder.newRecordDeclaration (de.fraunhofer.aisec.cpg.graph.NodeBuilder.newRecordDeclaration)1 de.fraunhofer.aisec.cpg.graph.declarations (de.fraunhofer.aisec.cpg.graph.declarations)1