com.ibm.wala.ipa.cha.ClassHierarchyFactory Java Examples

The following examples show how to use com.ibm.wala.ipa.cha.ClassHierarchyFactory. 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: CallGraphConstructor.java    From fasten with Apache License 2.0 6 votes vote down vote up
/**
 * Create a call graph instance given a class path.
 *
 * @param classpath Path to class or jar file
 * @return Call Graph
 */
public static CallGraph generateCallGraph(final String classpath)
        throws IOException, ClassHierarchyException, CallGraphBuilderCancelException {
    final var classLoader = Thread.currentThread().getContextClassLoader();
    final var exclusionFile = new File(Objects.requireNonNull(classLoader
            .getResource("Java60RegressionExclusions.txt")).getFile());

    final var scope = AnalysisScopeReader
            .makeJavaBinaryAnalysisScope(classpath, exclusionFile);

    final var cha = ClassHierarchyFactory.makeWithRoot(scope);

    final var entryPointsGenerator = new EntryPointsGenerator(cha);
    final var entryPoints = entryPointsGenerator.getEntryPoints();
    final var options = new AnalysisOptions(scope, entryPoints);
    final var cache = new AnalysisCacheImpl();

    final var builder = Util.makeZeroCFABuilder(Language.JAVA, options, cache, cha, scope);

    return builder.makeCallGraph(options, null);
}
 
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: LibraryIdentifier.java    From LibScout with Apache License 2.0 6 votes vote down vote up
private void createClassHierarchy() throws IOException, ClassHierarchyException {
	long s = System.currentTimeMillis();

	// check if we have a multi-dex file
	stats.isMultiDex = ApkUtils.isMultiDexApk(stats.appFile);
	if (stats.isMultiDex)
		logger.info("Multi-dex apk detected - Code is merged to single class hierarchy!");

	// create analysis scope and generate class hierarchy
	// we do not need additional libraries like support libraries,
	// as they are statically linked in the app code.
	final AnalysisScope scope = AndroidAnalysisScope.setUpAndroidAnalysisScope(new File(stats.appFile.getAbsolutePath()).toURI(), null /* no exclusions */, null /* we always pass an android lib */, LibScoutConfig.pathToAndroidJar.toURI());

	cha = ClassHierarchyFactory.makeWithRoot(scope);
	logger.info("Generated class hierarchy (in " + Utils.millisecondsToFormattedTime(System.currentTimeMillis() - s) + ")");
	WalaUtils.getChaStats(cha);
}
 
Example #4
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 #5
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));
}