All Downloads are FREE. Search and download functionalities are using the official Maven repository.

src.main.java.com.mebigfatguy.fbcontrib.detect.FindClassCircularDependencies Maven / Gradle / Ivy

Go to download

An auxiliary findbugs.sourceforge.net plugin for java bug detectors that fall outside the narrow scope of detectors to be packaged with the product itself.

There is a newer version: 7.6.8
Show newest version
/*
 * fb-contrib - Auxiliary detectors for Java programs
 * Copyright (C) 2005-2018 Dave Brosius
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */
package com.mebigfatguy.fbcontrib.detect;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.annotation.Nullable;

import org.apache.bcel.classfile.Constant;
import org.apache.bcel.classfile.ConstantClass;
import org.apache.bcel.classfile.ElementValue;
import org.apache.bcel.classfile.JavaClass;

import com.mebigfatguy.fbcontrib.utils.BugType;
import com.mebigfatguy.fbcontrib.utils.SignatureUtils;
import com.mebigfatguy.fbcontrib.utils.ToString;
import com.mebigfatguy.fbcontrib.utils.Values;

import edu.umd.cs.findbugs.BugInstance;
import edu.umd.cs.findbugs.BugReporter;
import edu.umd.cs.findbugs.BytecodeScanningDetector;
import edu.umd.cs.findbugs.internalAnnotations.DottedClassName;

/**
 * looks for classes that have dependencies on each other in a circular way. Class initialization can be compromised in this scenario, and usually points to a
 * bad data model. Consider using interfaces to break this hard circular dependency.
 */
public class FindClassCircularDependencies extends BytecodeScanningDetector {

    private static final Pattern ARRAY_PATTERN = Pattern.compile("\\[+(L.*)");
    private Map> dependencyGraph = null;
    private BugReporter bugReporter;
    private String className;

    /**
     * constructs a FCCD detector given the reporter to report bugs on
     *
     * @param bugReporter
     *            the sync of bug reports
     */
    public FindClassCircularDependencies(BugReporter bugReporter) {
        this.bugReporter = bugReporter;
        this.dependencyGraph = new HashMap<>();
    }

    @Override
    public void visit(JavaClass obj) {
        className = obj.getClassName();
    }

    @Override
    public void visitAnnotation(@DottedClassName String annotationClass, Map map, boolean runtimeVisible) {
        if (!runtimeVisible) {
            return;
        }

        for (ElementValue v : map.values()) {
            if (v.getElementValueType() == ElementValue.CLASS) {
                String annotationClsAttr = SignatureUtils.stripSignature(v.stringifyValue());

                Set dependencies = getDependenciesForClass(className);
                dependencies.add(annotationClsAttr);
            }
        }
    }

    @Override
    public void sawOpcode(int seen) {
        if ((seen == INVOKESPECIAL) || (seen == INVOKESTATIC) || (seen == INVOKEVIRTUAL)) {
            processInvoke();

        } else if (seen == LDC) {
            processLoadConstant();
        }
    }

    private void processInvoke() {
        String refClsName = getClassConstantOperand();
        refClsName = normalizeArrayClass(refClsName.replace('/', '.'));

        if (refClsName == null) {
            return;
        }

        if (refClsName.startsWith(Values.JAVA)) {
            return;
        }

        if (className.equals(refClsName)) {
            return;
        }

        if (isEnclosingClassName(className, refClsName) || isEnclosingClassName(refClsName, className)) {
            return;
        }

        if (isStaticChild(className, refClsName) || isStaticChild(refClsName, className)) {
            return;
        }

        Set dependencies = getDependenciesForClass(className);
        dependencies.add(refClsName);
    }

    private void processLoadConstant() {
        Constant c = getConstantRefOperand();
        if (c instanceof ConstantClass) {
            String refClsName = normalizeArrayClass(getClassConstantOperand().replace('/', '.'));
            if (!refClsName.equals(className)) {
                Set dependencies = getDependenciesForClass(className);
                dependencies.add(refClsName);
            }
        }
    }

    @Nullable
    private String normalizeArrayClass(String clsName) {
        if (!clsName.startsWith(Values.SIG_ARRAY_PREFIX)) {
            return clsName;
        }

        Matcher m = ARRAY_PATTERN.matcher(clsName);
        if (!m.matches()) {
            return clsName;
        }

        return m.group(1);
    }

    /**
     * returns a set of dependent class names for a class, and if it doesn't exist create the set install it, and then return;
     *
     * @param clsName
     *            the class for which you are trying to get dependencies
     * @return the active set of classes that are dependent on the specified class
     */
    private Set getDependenciesForClass(String clsName) {
        Set dependencies = dependencyGraph.get(clsName);
        if (dependencies == null) {
            dependencies = new HashSet<>();
            dependencyGraph.put(clsName, dependencies);
        }

        return dependencies;
    }

    private boolean isEnclosingClassName(String outerClass, String innerClass) {
        return innerClass.startsWith(outerClass) && (innerClass.indexOf(Values.INNER_CLASS_SEPARATOR) >= 0);
    }

    @Override
    public void report() {
        removeDependencyLeaves();

        LoopFinder lf = new LoopFinder();

        while (!dependencyGraph.isEmpty()) {
            String clsName = dependencyGraph.keySet().iterator().next();
            Set loop = lf.findLoop(dependencyGraph, clsName);
            boolean pruneLeaves;
            if (loop != null) {
                BugInstance bug = new BugInstance(this, BugType.FCCD_FIND_CLASS_CIRCULAR_DEPENDENCY.name(), NORMAL_PRIORITY);
                for (String loopCls : loop) {
                    bug.addClass(loopCls);
                }
                bugReporter.reportBug(bug);
                pruneLeaves = removeLoopLinks(loop);
            } else {
                dependencyGraph.remove(clsName);
                pruneLeaves = true;
            }
            if (pruneLeaves) {
                removeDependencyLeaves();
            }
        }

        dependencyGraph.clear();
    }

    private boolean isStaticChild(String child, String parent) {
        if (!child.startsWith(parent)) {
            return false;
        }

        int parentLength = parent.length();
        return ((child.charAt(parentLength) == '.') && (child.indexOf('.', parentLength + 1) < 0));
    }

    private void removeDependencyLeaves() {
        boolean changed = true;
        while (changed) {
            changed = false;
            Iterator> it = dependencyGraph.values().iterator();
            while (it.hasNext()) {
                Set dependencies = it.next();

                boolean foundClass = false;
                Iterator dit = dependencies.iterator();
                while (dit.hasNext()) {
                    foundClass = dependencyGraph.containsKey(dit.next());
                    if (!foundClass) {
                        dit.remove();
                        changed = true;
                    }
                }
                if (dependencies.isEmpty()) {
                    it.remove();
                    changed = true;
                }
            }
        }
    }

    private boolean removeLoopLinks(Set loop) {
        Set dependencies = null;
        for (String clsName : loop) {
            if (dependencies != null) {
                dependencies.remove(clsName);
            }
            dependencies = dependencyGraph.get(clsName);
        }
        if (dependencies != null) {
            dependencies.remove(loop.iterator().next());
        }

        boolean removedClass = false;
        Iterator cIt = loop.iterator();
        while (cIt.hasNext()) {
            String clsName = cIt.next();
            dependencies = dependencyGraph.get(clsName);
            if (dependencies.isEmpty()) {
                cIt.remove();
                removedClass = true;
            }
        }
        return removedClass;
    }

    /**
     * finds class dependency loops in a directed graph
     */
    static class LoopFinder {

        private Map> dGraph = null;
        private String startClass = null;
        private Set visited = null;
        private Set loop = null;

        @Nullable
        public Set findLoop(Map> dependencyGraph, String startCls) {
            dGraph = dependencyGraph;
            startClass = startCls;
            visited = new HashSet<>();
            loop = new LinkedHashSet<>();
            if (findLoop(startClass)) {
                return loop;
            }
            return null;
        }

        private boolean findLoop(String curClass) {
            if (curClass.indexOf(Values.INNER_CLASS_SEPARATOR) >= 0) {
                return false;
            }

            Set dependencies = dGraph.get(curClass);
            if (dependencies == null) {
                return false;
            }

            visited.add(curClass);
            loop.add(curClass);
            for (String depClass : dependencies) {
                if (depClass.equals(startClass)) {
                    return true;
                }

                if (visited.contains(depClass)) {
                    continue;
                }

                if (findLoop(depClass)) {
                    return true;
                }
            }
            loop.remove(curClass);
            return false;
        }

        @Override
        public String toString() {
            return ToString.build(this);
        }
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy