com.ibm.wala.types.ClassLoaderReference Java Examples

The following examples show how to use com.ibm.wala.types.ClassLoaderReference. 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: ArtifactResolverTest.java    From fasten with Apache License 2.0 6 votes vote down vote up
@Test
void findJarFileUsingMethod() throws IOException {
    ArtifactResolver artifactResolver = new ArtifactResolver(graph.getClassHierarchy());
    JarFile jarFile = new JarFile(jar);

    CGNode correctClassLoaderNode = null;

    for (CGNode node : graph) {

        if (!node.getMethod()
                .getDeclaringClass()
                .getClassLoader()
                .getReference()
                .equals(ClassLoaderReference.Application)) {
            continue;
        }

        correctClassLoaderNode = node;
        break;
    }

    assertNotNull(correctClassLoaderNode);
    assertEquals(jarFile.getName(), artifactResolver
            .findJarFileUsingMethod(correctClassLoaderNode.getMethod().getReference()).getName());
}
 
Example #2
Source File: LibraryApiAnalysis.java    From LibScout with Apache License 2.0 6 votes vote down vote up
private IClassHierarchy createClassHierarchy(File libCodeFile)  throws ClassHierarchyException, IOException, ClassNotFoundException {
    // create analysis scope and generate class hierarchy
    final AnalysisScope scope = AnalysisScope.createJavaAnalysisScope();

    JarFile jf = libCodeFile.getName().endsWith(".aar")? new AarFile(libCodeFile).getJarFile() : new JarFile((libCodeFile));
    scope.addToScope(ClassLoaderReference.Application, jf);
    scope.addToScope(ClassLoaderReference.Primordial, new JarFile(LibScoutConfig.pathToAndroidJar));
    IClassHierarchy cha = ClassHierarchyFactory.makeWithRoot(scope);

    // cleanup tmp files if library input was an .aar file
    if (libCodeFile.getName().endsWith(".aar")) {
        File tmpJar = new File(jf.getName());
        tmpJar.delete();
        logger.trace(Utils.indent() + "tmp jar-file deleted at " + tmpJar.getName());
    }

    return cha;
}
 
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: 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 #5
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 #6
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 #7
Source File: DefinitelyDerefedParamsDriver.java    From NullAway with MIT License 4 votes vote down vote up
private void analyzeFile(String pkgName, String inPath, boolean includeNonPublicClasses)
    throws IOException, ClassHierarchyException {
  InputStream jarIS = null;
  if (inPath.endsWith(".jar") || inPath.endsWith(".aar")) {
    jarIS = getInputStream(inPath);
    if (jarIS == null) {
      return;
    }
  } else if (!new File(inPath).exists()) {
    return;
  }
  AnalysisScope scope = AnalysisScopeReader.makePrimordialScope(null);
  scope.setExclusions(
      new FileOfClasses(
          new ByteArrayInputStream(DEFAULT_EXCLUSIONS.getBytes(StandardCharsets.UTF_8))));
  if (jarIS != null) scope.addInputStreamForJarToScope(ClassLoaderReference.Application, jarIS);
  else AnalysisScopeReader.addClassPathToScope(inPath, scope, ClassLoaderReference.Application);
  AnalysisOptions options = new AnalysisOptions(scope, null);
  AnalysisCache cache = new AnalysisCacheImpl();
  IClassHierarchy cha = ClassHierarchyFactory.makeWithRoot(scope);
  Warnings.clear();

  // Iterate over all classes:methods in the 'Application' and 'Extension' class loaders
  for (IClassLoader cldr : cha.getLoaders()) {
    if (!cldr.getName().toString().equals("Primordial")) {
      for (IClass cls : Iterator2Iterable.make(cldr.iterateAllClasses())) {
        if (cls instanceof PhantomClass) continue;
        // Only process classes in specified classpath and not its dependencies.
        // TODO: figure the right way to do this
        if (!pkgName.isEmpty() && !cls.getName().toString().startsWith(pkgName)) continue;
        // Skip non-public / ABI classes
        if (!cls.isPublic() && !includeNonPublicClasses) continue;
        LOG(DEBUG, "DEBUG", "analyzing class: " + cls.getName().toString());
        for (IMethod mtd : Iterator2Iterable.make(cls.getDeclaredMethods().iterator())) {
          // Skip methods without parameters, abstract methods, native methods
          // some Application classes are Primordial (why?)
          if (shouldCheckMethod(mtd)) {
            Preconditions.checkNotNull(mtd, "method not found");
            DefinitelyDerefedParams analysisDriver = null;
            String sign = "";
            // Parameter analysis
            if (mtd.getNumberOfParameters() > (mtd.isStatic() ? 0 : 1)) {
              // Skip methods by looking at bytecode
              try {
                if (!CodeScanner.getFieldsRead(mtd).isEmpty()
                    || !CodeScanner.getFieldsWritten(mtd).isEmpty()
                    || !CodeScanner.getCallSites(mtd).isEmpty()) {
                  analysisDriver = getAnalysisDriver(mtd, options, cache);
                  Set<Integer> result = analysisDriver.analyze();
                  sign = getSignature(mtd);
                  LOG(DEBUG, "DEBUG", "analyzed method: " + sign);
                  if (!result.isEmpty() || DEBUG) {
                    nonnullParams.put(sign, result);
                    LOG(
                        DEBUG,
                        "DEBUG",
                        "Inferred Nonnull param for method: " + sign + " = " + result.toString());
                  }
                }
              } catch (Exception e) {
                LOG(
                    DEBUG,
                    "DEBUG",
                    "Exception while scanning bytecodes for " + mtd + " " + e.getMessage());
              }
            }
            analyzeReturnValue(options, cache, mtd, analysisDriver, sign);
          }
        }
      }
    }
  }
  long endTime = System.currentTimeMillis();
  LOG(
      VERBOSE,
      "Stats",
      inPath
          + " >> time(ms): "
          + (endTime - analysisStartTime)
          + ", bytecode size: "
          + analyzedBytes
          + ", rate (ms/KB): "
          + (analyzedBytes > 0 ? (((endTime - analysisStartTime) * 1000) / analyzedBytes) : 0));
}
 
Example #8
Source File: LibraryProfiler.java    From LibScout with Apache License 2.0 4 votes vote down vote up
private void extractFingerPrints() throws IOException, ClassHierarchyException, ClassNotFoundException {
	long starttime = System.currentTimeMillis();
	
	logger.info("Process library: " + libraryFile.getName());
	logger.info("Library description:");
	for (String desc: libDesc.getDescription())
		logger.info(desc);
	
	// create analysis scope and generate class hierarchy
	final AnalysisScope scope = AnalysisScope.createJavaAnalysisScope();
	
	JarFile jf = libraryFile.getName().endsWith(".aar")? new AarFile(libraryFile).getJarFile() : new JarFile(libraryFile); 
	scope.addToScope(ClassLoaderReference.Application, jf);
	scope.addToScope(ClassLoaderReference.Primordial, new JarFile(LibScoutConfig.pathToAndroidJar));

	IClassHierarchy cha = ClassHierarchyFactory.makeWithRoot(scope);
	WalaUtils.getChaStats(cha);
	
	// cleanup tmp files if library input was an .aar file
	if (libraryFile.getName().endsWith(".aar")) {
		File tmpJar = new File(jf.getName());
		tmpJar.delete();
		logger.debug(Utils.indent() + "tmp jar-file deleted at " + tmpJar.getName());
	}
	
	PackageTree pTree = Profile.generatePackageTree(cha);
	if (pTree.getRootPackage() == null) {
		logger.warn(Utils.INDENT + "Library contains multiple root packages");
	}

	List<HashTree> hTrees = Profile.generateHashTrees(cha);

	// if hash tree is empty do not dump a profile
	if (hTrees.isEmpty() || hTrees.get(0).getNumberOfClasses() == 0) {
		logger.error("Empty Hash Tree generated - SKIP");
		return;
	}

	// write profile to disk
	serialize(pTree, hTrees);

	logger.info("");
	logger.info("Processing time: " + Utils.millisecondsToFormattedTime(System.currentTimeMillis() - starttime));
}
 
Example #9
Source File: EntryPointsGenerator.java    From fasten with Apache License 2.0 2 votes vote down vote up
/**
 * Check if given class "belongs" to the application loader.
 *
 * @param klass Class to check
 * @return true if class "belongs", false otherwise
 */
private static Boolean isApplication(final IClass klass) {
    return klass.getClassLoader().getReference().equals(ClassLoaderReference.Application);
}
 
Example #10
Source File: AnalysisContext.java    From fasten with Apache License 2.0 2 votes vote down vote up
/**
 * Check if given method "belongs" to application call.
 *
 * @param reference Method reference
 * @return true if method "belongs" to application scope, false otherwise
 */
private boolean inApplicationScope(final MethodReference reference) {
    return reference.getDeclaringClass().getClassLoader()
            .equals(ClassLoaderReference.Application);
}