示例#1
0
  private void scanForModel(Context context) throws IOException {
    String packageName = context.getPackageName();
    String sourcePath = context.getApplicationInfo().sourceDir;
    List<String> paths = new ArrayList<String>();

    if (sourcePath != null && !(new File(sourcePath).isDirectory())) {
      DexFile dexfile = new DexFile(sourcePath);
      Enumeration<String> entries = dexfile.entries();

      while (entries.hasMoreElements()) {
        paths.add(entries.nextElement());
      }
    }
    // Robolectric fallback
    else {
      ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
      Enumeration<URL> resources = classLoader.getResources("");

      while (resources.hasMoreElements()) {
        String path = resources.nextElement().getFile();
        if (path.contains("bin") || path.contains("classes")) {
          paths.add(path);
        }
      }
    }

    for (String path : paths) {
      File file = new File(path);
      scanForModelClasses(file, packageName, context.getClassLoader());
    }
  }
示例#2
0
  public void scan() throws IOException, ClassNotFoundException, NoSuchMethodException {
    long timeBegin = System.currentTimeMillis();

    PathClassLoader classLoader = (PathClassLoader) getContext().getClassLoader();
    // PathClassLoader classLoader = (PathClassLoader)
    // Thread.currentThread().getContextClassLoader();//This also works good
    DexFile dexFile = new DexFile(getContext().getPackageCodePath());
    Enumeration<String> classNames = dexFile.entries();
    while (classNames.hasMoreElements()) {
      String className = classNames.nextElement();
      if (isTargetClassName(className)) {
        // Class<?> aClass = Class.forName(className);//java.lang.ExceptionInInitializerError
        // Class<?> aClass = Class.forName(className, false, classLoader);//tested on
        // 魅蓝Note(M463C)_Android4.4.4 and Mi2s_Android5.1.1
        Class<?> aClass =
            classLoader.loadClass(
                className); // tested on 魅蓝Note(M463C)_Android4.4.4 and Mi2s_Android5.1.1
        if (isTargetClass(aClass)) {
          onScanResult(aClass);
        }
      }
    }

    long timeEnd = System.currentTimeMillis();
    long timeElapsed = timeEnd - timeBegin;
    Log.d(TAG, "scan() cost " + timeElapsed + "ms");
  }
示例#3
0
    private static void install(ClassLoader loader, List<File> additionalClassPathEntries)
        throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException, IOException {
      /* The patched class loader is expected to be a descendant of
       * dalvik.system.DexClassLoader. We modify its
       * fields mPaths, mFiles, mZips and mDexs to append additional DEX
       * file entries.
       */
      int extraSize = additionalClassPathEntries.size();

      Field pathField = findField(loader, "path");

      StringBuilder path = new StringBuilder((String) pathField.get(loader));
      String[] extraPaths = new String[extraSize];
      File[] extraFiles = new File[extraSize];
      ZipFile[] extraZips = new ZipFile[extraSize];
      DexFile[] extraDexs = new DexFile[extraSize];
      for (ListIterator<File> iterator = additionalClassPathEntries.listIterator();
          iterator.hasNext(); ) {
        File additionalEntry = iterator.next();
        String entryPath = additionalEntry.getAbsolutePath();
        path.append(':').append(entryPath);
        int index = iterator.previousIndex();
        extraPaths[index] = entryPath;
        extraFiles[index] = additionalEntry;
        extraZips[index] = new ZipFile(additionalEntry);
        extraDexs[index] = DexFile.loadDex(entryPath, entryPath + ".dex", 0);
      }

      pathField.set(loader, path.toString());
      expandFieldArray(loader, "mPaths", extraPaths);
      expandFieldArray(loader, "mFiles", extraFiles);
      expandFieldArray(loader, "mZips", extraZips);
      expandFieldArray(loader, "mDexs", extraDexs);
    }
 /**
  * Gets the names of all entries contained in given apk file, that match given filter.
  *
  * @throws IOException
  */
 private void addEntriesFromApk(Set<String> entryNames, String apkPath, ClassNameFilter filter)
     throws IOException {
   DexFile dexFile = null;
   try {
     dexFile = new DexFile(apkPath);
     Enumeration<String> apkClassNames = getDexEntries(dexFile);
     while (apkClassNames.hasMoreElements()) {
       String apkClassName = apkClassNames.nextElement();
       if (filter.accept(apkClassName)) {
         entryNames.add(apkClassName);
       }
     }
   } finally {
     if (dexFile != null) {
       dexFile.close();
     }
   }
 }
示例#5
0
  /**
   * 获取某一个包名下的所有类名
   *
   * @param context
   * @param packageName
   * @return
   * @throws IOException
   */
  public static List<String> getPackageAllClassName(Context context, String packageName)
      throws IOException {
    String sourcePath = context.getApplicationInfo().sourceDir;
    List<String> paths = new ArrayList<String>();

    if (sourcePath != null) {
      DexFile dexfile = new DexFile(sourcePath);
      Enumeration<String> entries = dexfile.entries();

      while (entries.hasMoreElements()) {
        String element = entries.nextElement();
        if (element.contains(packageName)) {
          paths.add(element);
        }
      }
    }

    return paths;
  }
  /* Scans all classes accessible from the context class loader which belong to the given package and subpackages.
   *
   * @param packageName The base package
   * @return The classes
   * @throws ClassNotFoundException
   * @throws IOException
   */
  @SuppressWarnings("unchecked")
  private static List<String> getClasses(String packageName, Context c) throws IOException {
    ArrayList<String> classNames = new ArrayList<String>();

    String zpath = c.getApplicationInfo().sourceDir;

    if (zpath == null) {
      zpath = "/data/app/org.odk.collect.apk";
    }

    DexFile df = new DexFile(new File(zpath));
    for (Enumeration<String> en = df.entries(); en.hasMoreElements(); ) {
      String cn = en.nextElement();
      if (cn.startsWith(packageName) && !cn.contains(".test.")) {
        try {
          Class prototype = Class.forName(cn);
          if (prototype.isInterface()) {
            continue;
          }
          boolean emptyc = false;
          for (Constructor<?> cons : prototype.getConstructors()) {
            if (cons.getParameterTypes().length == 0) {
              emptyc = true;
            }
          }
          if (!emptyc) {
            continue;
          }
          if (Externalizable.class.isAssignableFrom(prototype)) {
            classNames.add(cn);
          }
        } catch (Throwable e) {
          // nothing should every make this crash
        }
      }
    }

    return classNames;
  }
  @Override
  public <T> Collection<Class<? extends T>> getDescendants(
      Class<T> parentType, String packageName) {
    List<Class<? extends T>> result = new ArrayList<Class<? extends T>>();

    Enumeration<String> entries = dexFile.entries();
    while (entries.hasMoreElements()) {
      String className = entries.nextElement();
      if (isInPackage(className, packageName) && !isGenerated(className)) {
        Class<? extends T> clazz = loadClass(className);
        if (clazz != null && !parentType.equals(clazz) && parentType.isAssignableFrom(clazz)) {
          result.add(clazz.asSubclass(parentType));
        }
      }
    }
    return result;
  }
  /**
   * Performs dex-opt on the elements of {@code classPath}, if needed. We choose the instruction set
   * of the current runtime.
   */
  private static void performSystemServerDexOpt(String classPath) {
    final String[] classPathElements = classPath.split(":");
    final InstallerConnection installer = new InstallerConnection();
    installer.waitForConnection();
    final String instructionSet = VMRuntime.getRuntime().vmInstructionSet();

    try {
      for (String classPathElement : classPathElements) {
        final int dexoptNeeded =
            DexFile.getDexOptNeeded(classPathElement, "*", instructionSet, false /* defer */);
        if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
          installer.dexopt(
              classPathElement, Process.SYSTEM_UID, instructionSet, dexoptNeeded, 0 /*dexFlags*/);
        }
      }
    } catch (IOException ioe) {
      throw new RuntimeException("Error starting system_server", ioe);
    } finally {
      installer.disconnect();
    }
  }
  private static ArrayList<Object> reloadInterface(
      Context c, Activity a, String interfaceName, String version) {

    ArrayList<Object> loadedInterfaceDetails = null;

    try {
      Context applicationContext = c;
      String fName = interfaceName + "_v" + version + ".apk";

      String fullJARPath = applicationContext.getFilesDir().getPath().toString() + "/";
      fullJARPath += fName;

      File file = new File(fullJARPath);
      file.setReadable(true, false);

      URL fileUrl;
      fileUrl = file.toURL();
      if (!file.exists()) {
        throw new Exception("File " + fName + " not found");
      }

      ClassLoader cl = c.getClassLoader();

      DexFile df =
          DexFile.loadDex(
              file.getAbsolutePath(),
              c.getFilesDir().getAbsolutePath() + "/outputdexcontainer_" + interfaceName + ".dex",
              0);

      Class clazz = df.loadClass("com/sdp/deviceinterfaces/" + interfaceName, cl);

      p("Loading inner classes for: " + interfaceName);
      try {
        String prefix = "com.sdp.deviceinterfaces." + interfaceName + "$";
        Enumeration<String> entries = df.entries();
        while (entries.hasMoreElements()) {
          String nn = entries.nextElement();
          if (nn.contains(prefix)) {
            String innerClassPath = nn.replace(".", "/");
            p("Loading Also: " + innerClassPath);
            try {
              df.loadClass(innerClassPath, clazz.getClassLoader());
            } catch (Exception e) {
              p("Error while loading: " + innerClassPath + ", " + e.toString());
            }
          }
        }
        p("Inner classes loaded too");
      } catch (Exception e) {
        p("Error while loading innerclasses: " + e.toString());
      }

      Object whatInstance = clazz.newInstance();

      try {
        Method myMethod1 = clazz.getMethod("setApplicationContext", new Class[] {Context.class});
        myMethod1.invoke(whatInstance, new Object[] {c});

      } catch (Exception e) {
        p("Error adding Application Context: " + e.toString() + ", ");
        return null;
      }

      // Special cases
      try {
        Method setActionMethod = clazz.getMethod("setActivity", new Class[] {Activity.class});
        setActionMethod.invoke(whatInstance, new Object[] {a});

      } catch (Exception e) {
        p("Error adding Activity: " + e.toString() + ", ");
      }

      loadedInterfaceDetails = new ArrayList<Object>();
      loadedInterfaceDetails.add(interfaceName);
      loadedInterfaceDetails.add(clazz);
      loadedInterfaceDetails.add(whatInstance);
      return loadedInterfaceDetails;
    } catch (Exception e) {
      p("Error while loading class: " + interfaceName + ", " + e.toString());
      return null;
    }
  }
 /**
  * Retrieves the entry names from given {@link DexFile}.
  *
  * <p>Exposed for unit testing.
  *
  * @param dexFile
  * @return {@link Enumeration} of {@link String}s
  */
 Enumeration<String> getDexEntries(DexFile dexFile) {
   return dexFile.entries();
 }
  private int performDexOptLI(
      PackageParser.Package pkg,
      String[] targetInstructionSets,
      boolean forceDex,
      boolean defer,
      ArraySet<String> done) {
    final String[] instructionSets =
        targetInstructionSets != null
            ? targetInstructionSets
            : getAppDexInstructionSets(pkg.applicationInfo);

    if (done != null) {
      done.add(pkg.packageName);
      if (pkg.usesLibraries != null) {
        performDexOptLibsLI(pkg.usesLibraries, instructionSets, forceDex, defer, done);
      }
      if (pkg.usesOptionalLibraries != null) {
        performDexOptLibsLI(pkg.usesOptionalLibraries, instructionSets, forceDex, defer, done);
      }
    }

    if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) == 0) {
      return DEX_OPT_SKIPPED;
    }

    final boolean vmSafeMode = (pkg.applicationInfo.flags & ApplicationInfo.FLAG_VM_SAFE_MODE) != 0;
    final boolean debuggable = (pkg.applicationInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;

    final List<String> paths = pkg.getAllCodePathsExcludingResourceOnly();
    boolean performedDexOpt = false;
    // There are three basic cases here:
    // 1.) we need to dexopt, either because we are forced or it is needed
    // 2.) we are deferring a needed dexopt
    // 3.) we are skipping an unneeded dexopt
    final String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
    for (String dexCodeInstructionSet : dexCodeInstructionSets) {
      if (!forceDex && pkg.mDexOptPerformed.contains(dexCodeInstructionSet)) {
        continue;
      }

      for (String path : paths) {
        final int dexoptNeeded;
        if (forceDex) {
          dexoptNeeded = DexFile.DEX2OAT_NEEDED;
        } else {
          try {
            dexoptNeeded =
                DexFile.getDexOptNeeded(path, pkg.packageName, dexCodeInstructionSet, defer);
          } catch (IOException ioe) {
            Slog.w(TAG, "IOException reading apk: " + path, ioe);
            return DEX_OPT_FAILED;
          }
        }

        if (!forceDex && defer && dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
          // We're deciding to defer a needed dexopt. Don't bother dexopting for other
          // paths and instruction sets. We'll deal with them all together when we process
          // our list of deferred dexopts.
          addPackageForDeferredDexopt(pkg);
          return DEX_OPT_DEFERRED;
        }

        if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
          final String dexoptType;
          String oatDir = null;
          if (dexoptNeeded == DexFile.DEX2OAT_NEEDED) {
            dexoptType = "dex2oat";
            try {
              oatDir = createOatDirIfSupported(pkg, dexCodeInstructionSet);
            } catch (IOException ioe) {
              Slog.w(TAG, "Unable to create oatDir for package: " + pkg.packageName);
              return DEX_OPT_FAILED;
            }
          } else if (dexoptNeeded == DexFile.PATCHOAT_NEEDED) {
            dexoptType = "patchoat";
          } else if (dexoptNeeded == DexFile.SELF_PATCHOAT_NEEDED) {
            dexoptType = "self patchoat";
          } else {
            throw new IllegalStateException("Invalid dexopt needed: " + dexoptNeeded);
          }

          Log.i(
              TAG,
              "Running dexopt ("
                  + dexoptType
                  + ") on: "
                  + path
                  + " pkg="
                  + pkg.applicationInfo.packageName
                  + " isa="
                  + dexCodeInstructionSet
                  + " vmSafeMode="
                  + vmSafeMode
                  + " debuggable="
                  + debuggable
                  + " oatDir = "
                  + oatDir);
          final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
          final int ret =
              mPackageManagerService.mInstaller.dexopt(
                  path,
                  sharedGid,
                  !pkg.isForwardLocked(),
                  pkg.packageName,
                  dexCodeInstructionSet,
                  dexoptNeeded,
                  vmSafeMode,
                  debuggable,
                  oatDir);

          // Dex2oat might fail due to compiler / verifier errors. We soldier on
          // regardless, and attempt to interpret the app as a safety net.
          if (ret == 0) {
            performedDexOpt = true;
          }
        }
      }

      // At this point we haven't failed dexopt and we haven't deferred dexopt. We must
      // either have either succeeded dexopt, or have had getDexOptNeeded tell us
      // it isn't required. We therefore mark that this package doesn't need dexopt unless
      // it's forced. performedDexOpt will tell us whether we performed dex-opt or skipped
      // it.
      pkg.mDexOptPerformed.add(dexCodeInstructionSet);
    }

    // If we've gotten here, we're sure that no error occurred and that we haven't
    // deferred dex-opt. We've either dex-opted one more paths or instruction sets or
    // we've skipped all of them because they are up to date. In both cases this
    // package doesn't need dexopt any longer.
    return performedDexOpt ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED;
  }