com.ibm.wala.classLoader.IClass Java Examples

The following examples show how to use com.ibm.wala.classLoader.IClass. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ClassHierarchyAnalyzer.java    From fasten with Apache License 2.0 6 votes vote down vote up
/**
 * Process class.
 *
 * @param klass Class
 */
private void processClass(IClass klass) {
    Map<Selector, List<IMethod>> interfaceMethods = klass.getDirectInterfaces()
            .stream()
            .flatMap(o -> o.getDeclaredMethods().stream())
            .collect(
                    Collectors.groupingBy(IMethod::getSelector)
            );

    for (IMethod declaredMethod : klass.getDeclaredMethods()) {

        List<IMethod> methodInterfaces = interfaceMethods.get(declaredMethod.getSelector());

        processMethod(klass, declaredMethod, methodInterfaces);
    }
}
 
Example #2
Source File: ClassHierarchyAnalyzer.java    From fasten with Apache License 2.0 6 votes vote down vote up
/**
 * Find super classes, interfaces and source file name of a given class.
 *
 * @param klass Class
 */
private void addClassToCHA(final IClass klass) {
    final var className = Method.getClassName(klass.getReference());

    final var sourceFileName = className.split("[$%]")[0] + ".java";
    final List<FastenURI> interfaces = new ArrayList<>();

    for (final var implementedInterface : klass.getAllImplementedInterfaces()) {
        interfaces.add(getClassURI(implementedInterface));
    }

    final LinkedList<FastenURI> superClasses = superClassHierarchy(klass.getSuperclass(),
            new LinkedList<>());

    partialCallGraph.getClassHierarchy().put(getClassURI(klass),
            new RevisionCallGraph.Type(sourceFileName,
                    new HashMap<>(), superClasses, interfaces));
}
 
Example #3
Source File: LayoutFileParser.java    From LibScout with Apache License 2.0 6 votes vote down vote up
private IClass getLayoutClass(IClassHierarchy cha, String clazzName) {
	// This is due to the fault-tolerant xml parser
	if (clazzName.equals("view")) clazzName = "View";

	IClass iclazz = null;
	if (iclazz == null)
		iclazz = cha.lookupClass(TypeReference.findOrCreate(ClassLoaderReference.Application, Utils.convertToBrokenDexBytecodeNotation(clazzName)));
	if (iclazz == null && !packageName.isEmpty())
		iclazz = cha.lookupClass(TypeReference.findOrCreate(ClassLoaderReference.Application, Utils.convertToBrokenDexBytecodeNotation(packageName + "." + clazzName)));
	if (iclazz == null)
		iclazz = cha.lookupClass(TypeReference.findOrCreate(ClassLoaderReference.Application, Utils.convertToBrokenDexBytecodeNotation("android.widget." + clazzName)));
	if (iclazz == null)	
		iclazz = cha.lookupClass(TypeReference.findOrCreate(ClassLoaderReference.Application, Utils.convertToBrokenDexBytecodeNotation("android.webkit." + clazzName)));
	if (iclazz == null)
		iclazz = cha.lookupClass(TypeReference.findOrCreate(ClassLoaderReference.Application, Utils.convertToBrokenDexBytecodeNotation("android.view." + clazzName)));
	
	// PreferenceScreen, PreferenceCategory, (i)shape, item, selector, scale, corners, solid .. tags are no classes and thus there will be no corresponding layout class
	if (iclazz == null)	
		logger.trace(Utils.INDENT + "Could not find layout class " + clazzName);

	return iclazz;
}
 
Example #4
Source File: PublicInterfaceExtractor.java    From LibScout with Apache License 2.0 6 votes vote down vote up
public static Set<IMethod> getPublicInterface(IClassHierarchy cha) {
    int classCount = 0;   // how many distinct classes have public methods
    HashSet<IMethod> pubMethods = new HashSet<IMethod>();

    for (IClass clazz: cha) {
        if (!WalaUtils.isAppClass(clazz)) continue;

        Collection<? extends IMethod> methods = clazz.getDeclaredMethods();

        // filter anything but public and non-compiler generated methods
        methods = methods.stream()
                .filter(m -> {
                    int code = AccessFlags.getMethodAccessCode(m);
                    return code > 0 && (code & AccessFlags.getPublicOnlyFilter()) == 0x0;
                })  // if predicate is true, keep in list
                .filter(m -> !(m.isBridge() || m.isSynthetic()))   // filter compiler-generated methods
                .collect(Collectors.toCollection(ArrayList::new));

        if (!methods.isEmpty()) classCount++;
        pubMethods.addAll(methods);
    }

    logger.debug("[getPublicInterface] Retrieved " + pubMethods.size() + " public methods from " + classCount + " distinct classes");
    return pubMethods;
}
 
Example #5
Source File: WalaUtils.java    From LibScout with Apache License 2.0 6 votes vote down vote up
public static IMethod getIMethod(IClassHierarchy cha, String signature) {  // TODO: throw exceptions
	String clazzName = Utils.getFullClassName(signature);
	String selector = signature.substring(clazzName.length()+1); 

	try {
		IClass clazz = WalaUtils.lookupClass(cha, clazzName);
		for (IMethod m: clazz.getAllMethods()) { // DeclaredMethods()) -> only impl./overriden methods
			if (m.getSelector().toString().equals(selector)) {
				return m;
			}
		}
	} catch (ClassNotFoundException e) {
		logger.debug("Classname " + clazzName + " could not be looked up!");
	}
	return null;  // TODO: throw exception
}
 
Example #6
Source File: WalaUtils.java    From LibScout with Apache License 2.0 5 votes vote down vote up
/**
 * Hierarchical lookup of an {@link IMethod} via {@link IClass} and {@link CallSiteReference}.
 * @param clazz   the {@link IClass} to start with
 * @param csr  the {@link CallSiteReference}
 * @return  a {@link IMethod} object of the resolved method or null
	 */
public static IMethod resolveMethod(IClass clazz, CallSiteReference csr) {
	IMethod targetMethod = null;

	while (targetMethod == null && !WalaUtils.isObjectClass(clazz)) {
		targetMethod = clazz.getMethod(csr.getDeclaredTarget().getSelector());
		if (targetMethod != null)
			break;

		clazz = clazz.getSuperclass();
	}
	return targetMethod;
}
 
Example #7
Source File: ArtifactResolver.java    From fasten with Apache License 2.0 5 votes vote down vote up
/**
 * Get a jar file containing given class.
 *
 * @param klass Class
 * @return Jar File
 */
private JarFile classToJarFile(IClass klass) {
    Objects.requireNonNull(klass);

    if (klass instanceof ArrayClass) {
        ArrayClass arrayClass = (ArrayClass) klass;
        IClass innerClass = arrayClass.getElementClass();

        if (innerClass == null) {
            // getElementClass returns null for primitive types
            if (klass.getReference().getArrayElementType().isPrimitiveType()) {
                try {
                    return new JarFile("rt.jar");
                } catch (IOException e) {
                    return null;
                }
            }

            return null;
        }
    }

    if (klass instanceof ShrikeClass) {
        var shrikeKlass = (ShrikeClass) klass;
        var moduleEntry = shrikeKlass.getModuleEntry();

        return ((JarFileEntry) moduleEntry).getJarFile();

    }

    return null;
}
 
Example #8
Source File: WalaUtils.java    From LibScout with Apache License 2.0 5 votes vote down vote up
/**
 * Collects all implemented interfaces for a given class
 * @param clazz  the IClass object to analyze
 * @return a set of IClass objects representing the interfaces
 */
public static Set<IClass> collectAllInterfaces(IClass clazz) {
	// do not check array classes
	if (clazz.isArrayClass()) return new HashSet<IClass>();
	
	Set<IClass> interfaces = new HashSet<IClass>(clazz.getDirectInterfaces());
	for (IClass c : clazz.getDirectInterfaces())
		interfaces.addAll(collectAllInterfaces(c));

	return interfaces;
}
 
Example #9
Source File: WalaUtils.java    From LibScout with Apache License 2.0 5 votes vote down vote up
/**
 * Looks up an IClass for a given class name
 * @param cha  a {@link IClassHierarchy}
 * @param clazzName  in java notation, e.g. "de.infsec.MyActivity"
 * @return a {@link IClass} object
 * @throws ClassNotFoundException
 */
public static IClass lookupClass(IClassHierarchy cha, String clazzName) throws ClassNotFoundException {
	if (clazzName == null)
		throw new ClassNotFoundException(Utils.INDENT + "class name is NULL");
	
	String convertedClass = Utils.convertToBrokenDexBytecodeNotation(clazzName);
	IClass iclazz = cha.lookupClass(TypeReference.findOrCreate(ClassLoaderReference.Application, convertedClass));
	
	if (iclazz == null)
		throw new ClassNotFoundException(Utils.INDENT + "[lookupClass] Could'nt lookup IClass for " + clazzName);
	
	return iclazz;
}
 
Example #10
Source File: WalaUtils.java    From LibScout with Apache License 2.0 5 votes vote down vote up
public static boolean isAppClass(IClass clazz) {
	// Normalization:
	// filter empty dummy classes
	// possibly related too: http://bugs.java.com/bugdatabase/view_bug.do?bug_id=4295934
	boolean isEmptyInnerClass = WalaUtils.isInnerClass(clazz)
								&& isAnonymousInnerClass(clazz)
								&& (clazz.getDeclaredMethods().isEmpty() || 
								   (clazz.getDeclaredMethods().size() == 1 && clazz.getDeclaredMethods().iterator().next().isClinit())
								&& clazz.getDeclaredInstanceFields().isEmpty()
								&& clazz.getDeclaredStaticFields().isEmpty()
								&& clazz.getDirectInterfaces().isEmpty());

	return clazz.getClassHierarchy().getScope().isApplicationLoader(clazz.getClassLoader()) && !isAndroidResourceClass(clazz) && !isEmptyInnerClass && !clazz.isSynthetic();
}
 
Example #11
Source File: WalaUtils.java    From LibScout with Apache License 2.0 5 votes vote down vote up
/**
 * Retrieves all superclasses for a given class including itself
 * @param clazz  the input IClass object
 * @return  a list of IClass superclass objects including the input class
 */
public static List<IClass> getSuperClassesIncluding(IClass clazz) {
	LinkedList<IClass> superclasses = new LinkedList<IClass>(getSuperClasses(clazz));
	superclasses.addFirst(clazz);
	
	return superclasses;
}
 
Example #12
Source File: WalaUtils.java    From LibScout with Apache License 2.0 5 votes vote down vote up
/**
 * Retrieves all superclasses for a given class
 * @param clazz  the input IClass object
 * @return  a list of IClass superclass objects or an empty list if there is no superclass
 */
public static List<IClass> getSuperClasses(IClass clazz) {
	ArrayList<IClass> superclasses = new ArrayList<IClass>();

	while (clazz.getSuperclass() != null) {  
		clazz = clazz.getSuperclass();
		superclasses.add(clazz);
	}
	
	return superclasses;
}
 
Example #13
Source File: WalaUtils.java    From LibScout with Apache License 2.0 5 votes vote down vote up
public static boolean isInnerClassOf(IClass clazz, IClass testClazz) {
	// TODO: innerclass check would be easier if the dex bytecode annotations would have been parsed!
	//       here we have to fallback to the potentially non-reliable name check
	String clazzName = getClassName(clazz);
	String testClazzName = getClassName(testClazz);
	
	return testClazzName.contains("$") && testClazzName.startsWith(clazzName);
}
 
Example #14
Source File: LayoutFileParser.java    From LibScout with Apache License 2.0 5 votes vote down vote up
@Override
    	public NodeVisitor child(String ns, String name) {
if (name == null || name.isEmpty()) {
 			logger.trace(Utils.INDENT + "Encountered a null node name or empty node name "
 					+ "in file " + layoutFile + ", skipping node...");
 			return null;
 		}
			
 		String tname = name.trim();
 		if (tname.equals("include"))       /// TODO NOT SURE IF THIS IS CORRECT, include can occur in the middle of the file, anything afterwards seems not to be parsed anymore
 		   return new IncludeParser(layoutFile);

 		// For layout defined fragments we need the class name that is either specified via the name- or class-tag
 		if (tname.equals("fragment")) 
 			return new FragmentParser(cha, layoutFile, clazz);

 		// The "merge" tag merges the next hierarchy level into the current
 		// one for flattening hierarchies.
 		if (tname.equals("merge"))
 		    return new LayoutParser(cha, layoutFile, clazz);
 		
final IClass childClass = getLayoutClass(cha, tname);
if (childClass != null && 
   (WalaUtils.classifyClazz(childClass) == AndroidClassType.LayoutContainer || WalaUtils.classifyClazz(childClass) == AndroidClassType.View))
    			return new LayoutParser(cha, layoutFile, childClass);
else
	return super.child(ns, name);
    	}
 
Example #15
Source File: PackageTree.java    From LibScout with Apache License 2.0 5 votes vote down vote up
public static PackageTree make(IClassHierarchy cha, boolean appClassesOnly, Set<String> filteredPackages) {
	PackageTree tree = new PackageTree();
	for (IClass clazz: cha) {
		if (!appClassesOnly || (appClassesOnly && WalaUtils.isAppClass(clazz))) {
			if (filteredPackages == null || !filteredPackages.contains(PackageUtils.getPackageName(clazz)))
				tree.update(clazz);
		}
	}
	return tree;
	
}
 
Example #16
Source File: PackageTree.java    From LibScout with Apache License 2.0 5 votes vote down vote up
/**
 * Generate PackageTree with class name references provided as
 * collection of {@link IClass}, {@link String}, or {@link PackageNode} objects.
 * @param col  Collection of {@link IClass}, {@link String}, or {@link PackageNode} objects
 * @return {@link PackageTree} instance
 */
public static PackageTree make(Collection<?> col) {
	PackageTree tree = new PackageTree();
	for (Object o: col) {
		if (o instanceof IClass)
			tree.update((IClass) o);
		else if (o instanceof String)
			tree.update((String) o, true);
		else if (o instanceof PackageNode)
			tree.update(((PackageNode) o).packageName, false);
	}

	return tree;
}
 
Example #17
Source File: PackageTree.java    From LibScout with Apache License 2.0 5 votes vote down vote up
public void updateTreeClazzCount(IClassHierarchy cha) {
	Set<String> packages = this.getAllPackages();
	
	for (IClass clazz: cha) {
		if (WalaUtils.isAppClass(clazz)) {
			if (packages.contains(PackageUtils.getPackageName(clazz))) {
				updateClazzCount(clazz);
			}
		}
	}
	
}
 
Example #18
Source File: PackageTree.java    From LibScout with Apache License 2.0 5 votes vote down vote up
private boolean updateClazzCount(IClass clazz) {
	List<String> struct = PackageUtils.parsePackage(clazz);
	
	// update
	Node curNode = rootNode;
	for (int i = 0; i < struct.size(); i++) {
		curNode = matchChilds(curNode, struct.get(i));
		
		if (curNode == null)
			return false;
	}

	curNode.clazzCount++; 
	return true;
}
 
Example #19
Source File: DefaultClassNodeComp.java    From LibScout with Apache License 2.0 5 votes vote down vote up
@Override
public ClassNode comp(Collection<? extends Node> methodNodes, IClass clazz, TreeConfig config) {
    String className = config.keepClassNames ? WalaUtils.simpleName(clazz) : "";

    // default behaviour, just create hash from child nodes
    ClassNode cn = new ClassNode(HashTree.compNode(methodNodes, true, config.getHasher()).hash, className);
    if (!config.pruneMethods) cn.childs = new ArrayList<>(methodNodes);

    return cn;
}
 
Example #20
Source File: WalaUtils.java    From LibScout with Apache License 2.0 5 votes vote down vote up
/**
 * Looks up a method by name in a class object. If the method is overloaded,
 * the first one found is returned.
 * @param clazz  IClass object
 * @param methodName name of the method to be looked up
 * @return IMethod if method is declared in clazz, null otherwise
 */
public static IMethod getMethodByName(IClass clazz, String methodName) {
	for (IMethod m: clazz.getAllMethods()) { // DeclaredMethods()) -> only impl./overriden methods
		if (m.getSelector().toString().startsWith(methodName)) {
			return m;
		}
	}
	return null;
}
 
Example #21
Source File: CallGraphAnalyzer.java    From fasten with Apache License 2.0 5 votes vote down vote up
/**
 * Get class loader with correct class loader.
 *
 * @param reference Method reference
 * @return Method reference with correct class loader
 */
private MethodReference correctClassLoader(final MethodReference reference) {
    IClass klass = rawCallGraph.getClassHierarchy().lookupClass(reference.getDeclaringClass());

    if (klass == null) {
        return MethodReference.findOrCreate(ClassLoaderReference.Extension,
                reference.getDeclaringClass().getName().toString(),
                reference.getName().toString(),
                reference.getDescriptor().toString());
    }

    return MethodReference.findOrCreate(klass.getReference(), reference.getSelector());

}
 
Example #22
Source File: ClassHierarchyAnalyzer.java    From fasten with Apache License 2.0 5 votes vote down vote up
/**
 * Add all classes in application scope to class hierarchy.
 */
public void resolveCHA() throws NullPointerException {
    IClassLoader classLoader = rawCallGraph.getClassHierarchy()
            .getLoader(ClassLoaderReference.Application);

    for (Iterator<IClass> it = classLoader.iterateAllClasses(); it.hasNext(); ) {
        IClass klass = it.next();
        processClass(klass);
    }
}
 
Example #23
Source File: ClassHierarchyAnalyzer.java    From fasten with Apache License 2.0 5 votes vote down vote up
/**
 * Process method, it's super methods and interfaces.
 *
 * @param klass          Class
 * @param declaredMethod Method
 * @param interfaces     Interfaces implemented by method
 */
private void processMethod(IClass klass, IMethod declaredMethod, List<IMethod> interfaces) {
    if (declaredMethod.isPrivate()) {
        return;
    }
    IClass superKlass = klass.getSuperclass();
    addMethod(declaredMethod);

    IMethod superMethod = superKlass.getMethod(declaredMethod.getSelector());
    if (superMethod != null) {
        addMethod(superMethod);
    }

    if (interfaces != null) {
        for (IMethod interfaceMethod : interfaces) {
            addMethod(interfaceMethod);
        }
    }

    if (superKlass.isAbstract() && superMethod == null && interfaces == null) {

        Map<Selector, List<IMethod>> derivedInterfaces = superKlass.getDirectInterfaces()
                .stream()
                .flatMap(o -> o.getDeclaredMethods().stream())
                .collect(Collectors.groupingBy(IMethod::getSelector));

        List<IMethod> derivedInterfacesMethods =
                derivedInterfaces.get(declaredMethod.getSelector());

        if (derivedInterfacesMethods != null
                && derivedInterfacesMethods.size() > 0) {
            for (IMethod method : derivedInterfacesMethods) {
                addMethod(method);
            }
        }
    }
}
 
Example #24
Source File: ClassHierarchyAnalyzer.java    From fasten with Apache License 2.0 5 votes vote down vote up
/**
 * Recursively creates a list of super classes of a given class in the order of inheritance.
 *
 * @param klass Class
 * @param aux   Auxiliary list
 * @return List of super classes
 */
private LinkedList<FastenURI> superClassHierarchy(final IClass klass,
                                                  final LinkedList<FastenURI> aux)
        throws NullPointerException {
    aux.add(getClassURI(klass));
    if (klass.getSuperclass() == null) {
        return aux;
    }

    return superClassHierarchy(klass.getSuperclass(), aux);
}
 
Example #25
Source File: AndroidView.java    From LibScout with Apache License 2.0 4 votes vote down vote up
public IClass getViewClass() {
	return this.viewClazz;
}
 
Example #26
Source File: WalaUtils.java    From LibScout with Apache License 2.0 4 votes vote down vote up
public static boolean isObjectClass(IClass clazz) {
	return "java.lang.Object".equals(simpleName(clazz));
}
 
Example #27
Source File: FragmentLayoutControl.java    From LibScout with Apache License 2.0 4 votes vote down vote up
public IClass getFragmentClass() {
	return this.fragmentClazz;
}
 
Example #28
Source File: LayoutFileParser.java    From LibScout with Apache License 2.0 4 votes vote down vote up
public FragmentParser(IClassHierarchy cha, String layoutFile, IClass viewClazz) {
	super(cha, layoutFile, viewClazz);
}
 
Example #29
Source File: LayoutFileParser.java    From LibScout with Apache License 2.0 4 votes vote down vote up
public LayoutParser(IClassHierarchy cha, String layoutFile, IClass clazz) {
	this.cha = cha;
	this.layoutFile = layoutFile;
	this.clazz = clazz;
}
 
Example #30
Source File: AndroidView.java    From LibScout with Apache License 2.0 4 votes vote down vote up
public AndroidView(int id, String layoutFile, IClass viewClass) {
	this.id = id;
	this.layoutFile = layoutFile;
	this.viewClazz = viewClass;
}