Java Examples for dalvik.system.DexClassLoader
The following java examples will help you to understand the usage of dalvik.system.DexClassLoader. These source code samples are taken from different open source projects.
Example 1
| Project: audit-master File: MainActivity.java View source code |
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
DexClassLoader localDexClassLoader = new DexClassLoader(Environment.getExternalStorageDirectory().getPath() + "/test.apk", getBaseContext().getCacheDir().getPath(), null, ClassLoader.getSystemClassLoader());
} catch (Exception e) {
Log.e("testcaseLog", "文件ä¸?å˜åœ¨");
}
}Example 2
| Project: sl4a-librarys-master File: ExternalClassLoader.java View source code |
public Object load(Collection<String> dexPaths, Collection<String> nativePaths, String className) throws Exception {
String dexOutputDir = "/sdcard/dexoutput";
String joinedDexPaths = StringUtils.join(dexPaths, ":");
String joinedNativeLibPaths = nativePaths != null ? StringUtils.join(nativePaths, ":") : null;
DexClassLoader loader = new DexClassLoader(joinedDexPaths, dexOutputDir, joinedNativeLibPaths, this.getClass().getClassLoader());
Class<?> classToLoad = Class.forName(className, true, loader);
return classToLoad.newInstance();
}Example 3
| Project: YAHFA-master File: MainApp.java View source code |
@Override
protected void attachBaseContext(Context base) {
super.attachBaseContext(base);
/*
Build and put the demoPlugin apk in sdcard before running the demoApp
*/
HookMain hookMain = new HookMain();
ClassLoader classLoader = getClassLoader();
DexClassLoader dexClassLoader = new DexClassLoader("/sdcard/demoPlugin-debug.apk", getCodeCacheDir().getAbsolutePath(), null, classLoader);
hookMain.doHookDefault(dexClassLoader, classLoader);
}Example 4
| Project: AppJone-master File: AndroidClassLoader.java View source code |
public static Class<?> loadClassLoader(Context c, String dexPath, String className) {
// 路径为/data/data/packageName/app_myxxx
File dexOutputDir = c.getDir("dex", Context.MODE_MULTI_PROCESS);
// 设定到sdcard会导致代ç ?注入攻击
DexClassLoader classLoader = new DexClassLoader(dexPath, dexOutputDir.getAbsolutePath(), null, ClassLoader.getSystemClassLoader().getParent());
Class<?> mLoadClass = null;
try {
mLoadClass = classLoader.loadClass(className);
} catch (Exception e) {
System.out.println(e.getMessage());
}
return mLoadClass;
}Example 5
| Project: hk-master File: DynamicCodeLoaderHooker.java View source code |
/** * Attach on DexClassLoader class */ private void attachOnDexClassLoaderClass() { Map<String, Integer> methodsToHook = new HashMap<String, Integer>(); methodsToHook.put("DexClassLoader", 2); methodsToHook.put("findLibrary", 1); methodsToHook.put("findResource", 1); try { hookMethods(null, "dalvik.system.DexClassLoader", methodsToHook); SubstrateMain.log("hooking dalvik.system.DexClassLoader methods sucessful"); } catch (HookerInitializationException e) { SubstrateMain.log("hooking dalvik.system.DexClassLoader methods has failed", e); } }
Example 6
| Project: curso-avanzado-android-master File: MultiDexClassLoader.java View source code |
@Override
public Class<?> findClass(String className) throws ClassNotFoundException {
Class<?> clazz = null;
for (DexClassLoader classLoader : this.classLoaders) {
try {
clazz = classLoader.loadClass(className);
} catch (ClassNotFoundException e) {
continue;
}
if (clazz != null) {
return clazz;
}
}
throw new ClassNotFoundException(className + " in loader " + this);
}Example 7
| Project: freeline-master File: DexUtils.java View source code |
public static boolean inject(PathClassLoader classLoader, File dex, File opt) {
Log.i(TAG, dex.getAbsolutePath() + " dex length: " + dex.length());
Log.i(TAG, opt.getAbsolutePath() + " opt length: " + opt.length());
DexFile[] dexFiles = null;
Field pathListField = null;
Field fDexElements = null;
Object dstObject = null;
try {
Object newDexElements;
int dexLength;
if (VERSION.SDK_INT >= 14) {
pathListField = ReflectUtil.fieldGetOrg(classLoader, Class.forName("dalvik.system.BaseDexClassLoader"), "pathList");
fDexElements = ReflectUtil.fieldGetOrg(pathListField.get(classLoader), "dexElements");
Object e = fDexElements.get(pathListField.get(classLoader));
dstObject = e;
dexFiles = new DexFile[Array.getLength(e)];
for (int i = 0; i < Array.getLength(e); ++i) {
newDexElements = Array.get(e, i);
dexFiles[i] = (DexFile) ReflectUtil.fieldGet(newDexElements, "dexFile");
}
} else {
pathListField = ReflectUtil.fieldGetOrg(classLoader, "mDexs");
dstObject = pathListField.get(classLoader);
dexFiles = new DexFile[Array.getLength(dstObject)];
for (dexLength = 0; dexLength < Array.getLength(dstObject); ++dexLength) {
dexFiles[dexLength] = (DexFile) Array.get(dstObject, dexLength);
}
}
dexLength = Array.getLength(dstObject) + 1;
newDexElements = Array.newInstance(fDexElements.getType().getComponentType(), dexLength);
DexClassLoader dynamicDex = new DexClassLoader(dex.getAbsolutePath(), opt.getAbsolutePath(), null, classLoader.getParent());
Log.i(TAG, "after opt, dex len:" + dex.length() + "; opt len:" + opt.length());
Object pathList = pathListField.get(dynamicDex);
Object dexElements = fDexElements.get(pathList);
Object firstDexElement = Array.get(dexElements, 0);
Array.set(newDexElements, 0, firstDexElement);
for (int i = 0; i < dexLength - 1; ++i) {
Object element = Array.get(dstObject, i);
Array.set(newDexElements, i + 1, element);
}
if (VERSION.SDK_INT >= 14) {
fDexElements.set(pathListField.get(classLoader), newDexElements);
} else {
pathListField.set(classLoader, newDexElements);
}
return true;
} catch (Exception e) {
Log.e(TAG, "fail to override classloader " + classLoader + " with " + dex.getAbsolutePath(), e);
return false;
}
}Example 8
| Project: life-master File: Server.java View source code |
/**
* çƒéƒ¨ç½² åŠ è½½è¡¥ä¸?
*
* 1. 将补ä¸?文件 ä¿?å˜ä¸º /data/data/.../files/instant-run/dex-temp/reload0x????.dex
* 2. ç„¶å?Ž é€šè¿‡ æ¤ dex 去创建一个 DexClassLoader
* 3. 通过创建的 DexClassLoader 去寻找内部的 AppPatchesLoaderImpl类
* 4. 进而获� getPatchedClasses 方法,得到 String[] classes
* 5. 然�打 String[] classes 的 Log
* 6. AppPatchesLoaderImpl �上转为 PatchesLoader 类型
* 7. 调用 ( AppPatchesLoaderImpl )PatchesLoader.load() 方法打上 $override å’Œ $change æ ‡è®°ä½?
*
* @param updateMode 更新模�
* @param patch 补�
* @return 更新模�
*/
private int handleHotSwapPatch(int updateMode, @NonNull ApplicationPatch patch) {
if (Log.isLoggable(LOG_TAG, Log.VERBOSE)) {
Log.v(LOG_TAG, "Received incremental code patch");
}
try {
String dexFile = FileManager.writeTempDexFile(patch.getBytes());
if (dexFile == null) {
Log.e(LOG_TAG, "No file to write the code to");
return updateMode;
} else if (Log.isLoggable(LOG_TAG, Log.VERBOSE)) {
Log.v(LOG_TAG, "Reading live code from " + dexFile);
}
String nativeLibraryPath = FileManager.getNativeLibraryFolder().getPath();
DexClassLoader dexClassLoader = new DexClassLoader(dexFile, mApplication.getCacheDir().getPath(), nativeLibraryPath, getClass().getClassLoader());
// we should transform this process with an interface/impl
Class<?> aClass = Class.forName("com.android.tools.fd.runtime.AppPatchesLoaderImpl", true, dexClassLoader);
try {
if (Log.isLoggable(LOG_TAG, Log.VERBOSE)) {
Log.v(LOG_TAG, "Got the patcher class " + aClass);
}
PatchesLoader loader = (PatchesLoader) aClass.newInstance();
if (Log.isLoggable(LOG_TAG, Log.VERBOSE)) {
Log.v(LOG_TAG, "Got the patcher instance " + loader);
}
String[] getPatchedClasses = (String[]) aClass.getDeclaredMethod("getPatchedClasses").invoke(loader);
if (Log.isLoggable(LOG_TAG, Log.VERBOSE)) {
Log.v(LOG_TAG, "Got the list of classes ");
for (String getPatchedClass : getPatchedClasses) {
Log.v(LOG_TAG, "class " + getPatchedClass);
}
}
if (!loader.load()) {
updateMode = UPDATE_MODE_COLD_SWAP;
}
} catch (Exception e) {
Log.e(LOG_TAG, "Couldn't apply code changes", e);
e.printStackTrace();
updateMode = UPDATE_MODE_COLD_SWAP;
}
} catch (Throwable e) {
Log.e(LOG_TAG, "Couldn't apply code changes", e);
updateMode = UPDATE_MODE_COLD_SWAP;
}
return updateMode;
}Example 9
| Project: Nuwa-master File: DexUtils.java View source code |
public static void injectDexAtFirst(String dexPath, String defaultDexOptPath) throws NoSuchFieldException, IllegalAccessException, ClassNotFoundException {
DexClassLoader dexClassLoader = new DexClassLoader(dexPath, defaultDexOptPath, dexPath, getPathClassLoader());
Object baseDexElements = getDexElements(getPathList(getPathClassLoader()));
Object newDexElements = getDexElements(getPathList(dexClassLoader));
Object allDexElements = combineArray(newDexElements, baseDexElements);
Object pathList = getPathList(getPathClassLoader());
ReflectionUtils.setField(pathList, pathList.getClass(), "dexElements", allDexElements);
}Example 10
| Project: RipplePower-master File: APKShellActivity.java View source code |
private void putAPKLoader(APKObject apkobj) throws IOException {
DexClassLoader loader = APKDexLoader.getClassLoader(apkobj.getAPKPath(), this, getClassLoader());
apkobj.setAPKLoader(loader);
String top = apkobj.getTopActivityName();
if (top == null) {
top = apkobj.getActivityInfos()[0].name;
apkobj.setTopActivityName(top);
}
try {
Activity myAPK = (Activity) apkobj.getAPKLoader().loadClass(apkobj.getTopActivityName()).newInstance();
apkobj.setCurrentAPKActivity(myAPK);
} catch (Exception e) {
throw new RuntimeException(e.getMessage());
}
}Example 11
| Project: sandro-master File: WatcherLoader.java View source code |
/**
* �动qute监控器
*/
public static void startQuteWatcher(Context context) {
Intent intent = new Intent();
intent.setClassName("com.tinyscreen.quteWatcher", "com.tinyscreen.quteWatcher.QuteWatcherActivity");
PackageManager pm = context.getPackageManager();
final List<ResolveInfo> plugins = pm.queryIntentActivities(intent, 0);
if (plugins == null || plugins.size() == 0) {
Log.e("WatcherLoader", "plugins==null || plugins.size()==0");
return;
}
ResolveInfo rinfo = plugins.get(0);
ActivityInfo ainfo = rinfo.activityInfo;
// String div = System.getProperty("path.separator");
String packageName = ainfo.packageName;
String dexPath = ainfo.applicationInfo.sourceDir;
String dexOutputDir = context.getApplicationInfo().dataDir;
String libPath = null;
DexClassLoader cl = new DexClassLoader(dexPath, dexOutputDir, libPath, context.getClass().getClassLoader());
try {
Class<?> clazz = cl.loadClass(packageName + ".log.Log");
LogUtil.WATCHER = (WatcherService) clazz.newInstance();
LogUtil.WATCHER.setContext(context);
} catch (ClassNotFoundException e1) {
Log.e("WatcherLoader", "ClassNotFoundException : " + e1.toString());
} catch (IllegalAccessException e) {
Log.e("WatcherLoader", "IllegalAccessException : " + e.toString());
} catch (InstantiationException e) {
Log.e("WatcherLoader", "InstantiationException : " + e.toString());
}
Log.i("WatcherLoader", "load success!!");
}Example 12
| Project: robovm-master File: Main.java View source code |
/*
* Create an instance of DexClassLoader. The test harness doesn't
* have visibility into dalvik.system.*, so we do this through
* reflection.
*/
private static ClassLoader getDexClassLoader() {
String odexDir;
/*
String androidData = System.getenv("ANDROID_DATA");
if (androidData == null)
androidData = "";
odexDir = androidData + "/" + ODEX_DIR;
*/
File test = new File(ODEX_DIR);
if (test.isDirectory())
odexDir = ODEX_DIR;
else
odexDir = ODEX_ALT;
//System.out.println("Output dir is " + odexDir);
ClassLoader myLoader = Main.class.getClassLoader();
Class dclClass;
try {
dclClass = myLoader.loadClass("dalvik.system.DexClassLoader");
} catch (ClassNotFoundException cnfe) {
throw new RuntimeException("dalvik.system.DexClassLoader not found");
}
Constructor ctor;
try {
ctor = dclClass.getConstructor(String.class, String.class, String.class, ClassLoader.class);
} catch (NoSuchMethodException nsme) {
throw new RuntimeException("DCL ctor", nsme);
}
// create an instance, using the path we found
Object dclObj;
try {
dclObj = ctor.newInstance(CLASS_PATH, odexDir, LIB_DIR, myLoader);
} catch (Exception ex) {
throw new RuntimeException("DCL newInstance", ex);
}
return (ClassLoader) dclObj;
}Example 13
| Project: android-classyshark-master File: ClassesListActivity.java View source code |
@Override
public void run() {
try {
Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
final DexClassLoader loader = DexLoaderBuilder.fromBytes(ClassesListActivity.this, bytes);
ClassesListActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Class<?> loadClass;
try {
loadClass = loader.loadClass(classesList.getClassName(position));
Reflector reflector = new Reflector(loadClass);
reflector.generateClassData();
String result = reflector.toString();
Intent i = new Intent(ClassesListActivity.this, SourceViewerActivity.class);
i.putExtra(ClassesListActivity.SELECTED_CLASS_NAME, classesList.getClassName(position));
i.putExtra(ClassesListActivity.SELECTED_CLASS_DUMP, result);
startActivity(i);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
});
} catch (Exception e) {
e.printStackTrace();
}
}Example 14
| Project: AndroidDynamicLoader-master File: FragmentLoader.java View source code |
@Override
protected void onCreate(Bundle savedInstanceState) {
if ("com.dianping.intent.action.LOAD_FRAGMENT".equals(getIntent().getAction())) {
// we need to setup environment before super.onCreate
try {
String path = getIntent().getStringExtra("path");
InputStream ins = MyApplication.instance().getAssets().open(path);
byte[] bytes = new byte[ins.available()];
ins.read(bytes);
ins.close();
File f = new File(MyApplication.instance().getFilesDir(), "dex");
f.mkdir();
f = new File(f, "FL_" + Integer.toHexString(path.hashCode()) + ".apk");
FileOutputStream fos = new FileOutputStream(f);
fos.write(bytes);
fos.close();
File fo = new File(MyApplication.instance().getFilesDir(), "dexout");
fo.mkdir();
DexClassLoader dcl = new DexClassLoader(f.getAbsolutePath(), fo.getAbsolutePath(), null, super.getClassLoader());
cl = dcl;
try {
AssetManager am = (AssetManager) AssetManager.class.newInstance();
am.getClass().getMethod("addAssetPath", String.class).invoke(am, f.getAbsolutePath());
asm = am;
} catch (Exception e) {
throw new RuntimeException(e);
}
Resources superRes = super.getResources();
res = new Resources(asm, superRes.getDisplayMetrics(), superRes.getConfiguration());
thm = res.newTheme();
thm.setTo(super.getTheme());
} catch (Exception e) {
e.printStackTrace();
}
}
super.onCreate(savedInstanceState);
FrameLayout rootView = new FrameLayout(this);
rootView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
rootView.setId(android.R.id.primary);
setContentView(rootView);
if (savedInstanceState != null)
return;
if ("com.dianping.intent.action.LOAD_FRAGMENT".equals(getIntent().getAction())) {
try {
String fragmentClass = getIntent().getStringExtra("class");
Fragment f = (Fragment) getClassLoader().loadClass(fragmentClass).newInstance();
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.add(android.R.id.primary, f);
ft.commit();
} catch (Exception e) {
Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
}
} else {
Fragment f = new ListApkFragment();
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.add(android.R.id.primary, f);
ft.commit();
}
}Example 15
| Project: AnoleFix-master File: Anole.java View source code |
public static void applyPatch(Context context, String dexFile) {
try {
ClassLoader classLoader = context.getClass().getClassLoader();
String nativeLibraryPath;
try {
nativeLibraryPath = (String) classLoader.getClass().getMethod("getLdLibraryPath").invoke(classLoader);
} catch (Throwable t) {
nativeLibraryPath = getNativeLibraryFolder(context).getPath();
}
DexClassLoader dexClassLoader = new DexClassLoader(dexFile, context.getCacheDir().getPath(), nativeLibraryPath, context.getClass().getClassLoader());
// we should transform this process with an interface/impl
Class<?> aClass = Class.forName("dodola.anole.runtime.AppPatchesLoaderImpl", true, dexClassLoader);
try {
PatchesLoader loader = (PatchesLoader) aClass.newInstance();
String[] getPatchedClasses = (String[]) aClass.getDeclaredMethod("getPatchedClasses").invoke(loader);
Log.v(LOG_TAG, "Got the list of classes ");
for (String getPatchedClass : getPatchedClasses) {
Log.v(LOG_TAG, "class " + getPatchedClass);
}
if (!loader.load()) {
}
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception ex) {
ex.printStackTrace();
}
}Example 16
| Project: JavaDN-master File: AndroidClassLoader.java View source code |
// api 3+
@TargetApi(Build.VERSION_CODES.CUPCAKE)
public Class<?> loadClass(String className) {
String dexDir = ctx.getDir("dex", Context.MODE_PRIVATE).getAbsolutePath();
DexClassLoader loader = new DexClassLoader(getLibFile().getAbsolutePath(), dexDir, null, ctx.getClassLoader());
Class<?> klass = null;
try {
klass = loader.loadClass(className);
} catch (ClassNotFoundException e) {
Log.d(TAG, e.getMessage());
}
return klass;
}Example 17
| Project: javassist-android-master File: MainActivity.java View source code |
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView view = (TextView) findViewById(R.id.textview_title);
final File dexFile = new File(getFilesDir(), DEX_FILE_NAME_MYCLASSES);
if (!dexFile.exists() || FORCE_GENRATE_DEX) {
// generate DEX and ODEX file.
try {
// generate "xxx.class" file via Javassist.
final ClassPool cp = ClassPool.getDefault(getApplicationContext());
final CtClass cls = cp.makeClass("hoge");
final CtConstructor ctor = new CtConstructor(null, cls);
ctor.setBody("{}");
cls.addConstructor(ctor);
final CtMethod m1 = CtMethod.make("public java.lang.String toString() { return \"hoge.toString() is called.\"; }", cls);
cls.addMethod(m1);
final CtMethod m2 = CtMethod.make("public void setText(android.widget.TextView view) { view.setText((java.lang.CharSequence)\"hoge.setText() is called.\"); }", cls);
cls.addMethod(m2);
cls.writeFile(getFilesDir().getAbsolutePath());
// convert from "xxx.class" to "xxx.dex"
final DexFile df = new DexFile();
final String dexFilePath = dexFile.getAbsolutePath();
df.addClass(new File(getFilesDir(), "hoge.class"));
df.writeFile(dexFilePath);
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
}
}
if (dexFile.exists()) {
try {
final DexClassLoader dcl = new DexClassLoader(dexFile.getAbsolutePath(), getCacheDir().getAbsolutePath(), getApplicationInfo().nativeLibraryDir, getClassLoader());
String title = null;
final Class<?> class_hoge = dcl.loadClass("hoge");
final Constructor<?> ctor = class_hoge.getConstructor(new Class<?>[0]);
final Object obj = ctor.newInstance(new Object[0]);
title = obj.toString();
view.setText(title);
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
try {
final Method m = obj.getClass().getDeclaredMethod("setText", TextView.class);
m.invoke(obj, view);
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}, 2000);
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}Example 18
| Project: RPG-Character-Sheets-master File: ClassByReflection.java View source code |
@SuppressWarnings("unchecked")
public static <T, K> List<K> getAll(Context context, Class<T> superc) {
if (cache.containsKey(superc.getCanonicalName())) {
Log.d("CACHE", "GET");
return (List<K>) cache.get(superc.getCanonicalName());
}
String packageName = context.getPackageName();
Log.d("PACKAGE", packageName);
String apkName;
List<K> list = new ArrayList<K>();
try {
apkName = context.getPackageManager().getApplicationInfo(packageName, 0).sourceDir;
} catch (NameNotFoundException e1) {
Log.d("DEBUG", e1.getMessage());
return list;
}
DexFile dexFile;
try {
dexFile = new DexFile(apkName);
} catch (IOException e1) {
Log.d("DEBUG", e1.getMessage());
return list;
}
ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
String absolutePath = new ContextWrapper(context).getCacheDir().getAbsolutePath();
PathClassLoader pathClassLoader = new PathClassLoader(apkName, contextClassLoader);
DexClassLoader dexClassLoader = new DexClassLoader(apkName, absolutePath, null, pathClassLoader);
Enumeration<String> entries = dexFile.entries();
while (entries.hasMoreElements()) {
String entry = entries.nextElement();
// only check items that exists in source package (not in libraries)
if (entry.startsWith(packageName)) {
Class<?> entryClass;
try {
// dexFile.loadClass(entry,
entryClass = dexClassLoader.loadClass(entry);
} catch (ClassNotFoundException e) {
Log.d("DEBUG", e.getMessage());
continue;
}
if (entryClass != null && !entryClass.isInterface() && !Modifier.isAbstract(entryClass.getModifiers())) {
boolean isPublic = false;
Constructor<?>[] constructors = entryClass.getConstructors();
for (Constructor<?> c : constructors) {
isPublic = Modifier.isPublic(c.getModifiers());
}
if (!isPublic) {
continue;
}
Class<?> superclass = entryClass.getSuperclass();
while (superclass != null && superclass != superc) {
superclass = superclass.getSuperclass();
}
if (superclass != null && superclass == superc) {
try {
K obj = (K) entryClass.newInstance();
list.add(obj);
} catch (InstantiationException e) {
Log.d("DEBUG", e.getMessage());
e.printStackTrace();
} catch (IllegalAccessException e) {
Log.d("DEBUG", e.getMessage());
e.printStackTrace();
}
}
}
}
}
Log.d("CACHE", "PUT");
cache.put(superc.getCanonicalName(), new ArrayList<K>(list));
return list;
}Example 19
| Project: understand-plugin-framework-master File: BaseDexClassLoaderHookHelper.java View source code |
public static void patchClassLoader(ClassLoader cl, File apkFile, File optDexFile) throws IllegalAccessException, NoSuchMethodException, IOException, InvocationTargetException, InstantiationException, NoSuchFieldException {
// 获� BaseDexClassLoader : pathList
Field pathListField = DexClassLoader.class.getSuperclass().getDeclaredField("pathList");
pathListField.setAccessible(true);
Object pathListObj = pathListField.get(cl);
// 获� PathList: Element[] dexElements
Field dexElementArray = pathListObj.getClass().getDeclaredField("dexElements");
dexElementArray.setAccessible(true);
Object[] dexElements = (Object[]) dexElementArray.get(pathListObj);
// Element 类型
Class<?> elementClass = dexElements.getClass().getComponentType();
// 创建一个数组, 用�替�原始的数组
Object[] newElements = (Object[]) Array.newInstance(elementClass, dexElements.length + 1);
// æž„é€ æ?’ä»¶Element(File file, boolean isDirectory, File zip, DexFile dexFile) è¿™ä¸ªæž„é€ å‡½æ•°
Constructor<?> constructor = elementClass.getConstructor(File.class, boolean.class, File.class, DexFile.class);
Object o = constructor.newInstance(apkFile, false, apkFile, DexFile.loadDex(apkFile.getCanonicalPath(), optDexFile.getAbsolutePath(), 0));
Object[] toAddElementArray = new Object[] { o };
// 把原始的elements�制进去
System.arraycopy(dexElements, 0, newElements, 0, dexElements.length);
// �件的那个element�制进去
System.arraycopy(toAddElementArray, 0, newElements, dexElements.length, toAddElementArray.length);
// 替�
dexElementArray.set(pathListObj, newElements);
}Example 20
| Project: AndroidPlugin-master File: PluginClientManager.java View source code |
/**
* add a apk client. Before start a plugin Activity, we should do this
* first.<br/>
* NOTE : will only be called by host apk.
*
* @param dexPath
*/
public PluginClientInfo addPluginClient(String dexPath) {
// when loadApk is called by host apk, we assume that plugin is invoked
// by host.
PackageManager packageManager = mContext.getPackageManager();
int flags = PackageManager.GET_ACTIVITIES | PackageManager.GET_CONFIGURATIONS | PackageManager.GET_INSTRUMENTATION | PackageManager.GET_PERMISSIONS | PackageManager.GET_PROVIDERS | PackageManager.GET_RECEIVERS | PackageManager.GET_SERVICES | PackageManager.GET_SIGNATURES;
PackageInfo packageInfo = packageManager.getPackageArchiveInfo(dexPath, flags);
if (packageInfo == null) {
return null;
}
final String packageName = packageInfo.packageName;
PluginClientInfo pluginPackage = mPluginClientPackages.get(packageName);
if (pluginPackage == null) {
DexClassLoader dexClassLoader = null;
if (mPluginClientDexClassLoaders.containsKey(packageName)) {
dexClassLoader = mPluginClientDexClassLoaders.get(packageName);
} else {
dexClassLoader = createDexClassLoader(dexPath, packageInfo.packageName, packageInfo.versionName);
mPluginClientDexClassLoaders.put(packageName, dexClassLoader);
}
AssetManager assetManager = createAssetManager(dexPath);
Resources resources = createResources(assetManager);
pluginPackage = new PluginClientInfo(packageName, dexPath, dexClassLoader, assetManager, resources, packageInfo);
mPluginClientPackages.put(packageName, pluginPackage);
}
if (!mPluginClientDexPaths.containsKey(packageName)) {
mPluginClientDexPaths.put(packageName, dexPath);
}
return pluginPackage;
}Example 21
| Project: EvolveWrapper-master File: Utils.java View source code |
/**
* Load the classes.dex file from an APK or JAR file.
*
* @param a An activity in the currently running application
* @param context The application context for the currently running application
* @param file The name of the APK or JAR file to load (ex: myapp.apk)
*
* @return The path to the APK file
*/
public static String loadDexFile(Activity a, Context context, String file) {
try {
File f = new File(context.getFilesDir(), file);
//If the file doesn't exist, create it from the bundled one in assets
if (!f.exists()) {
copyAsset(context, file);
}
System.out.println(f.getAbsolutePath());
DexClassLoader dcl = new DexClassLoader(f.getAbsolutePath(), context.getCacheDir().getAbsolutePath(), null, context.getClassLoader());
DynamicApp.classLoader = dcl;
return f.getAbsolutePath();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}Example 22
| Project: mcp-master File: ScriptTranslationCache.java View source code |
public static Script get(android.content.Context context, File file) throws IOException {
//does the cached file exist?
File dexFile = getDexFile(context, file);
if (!dexFile.exists() || dexFile.lastModified() < file.lastModified()) {
dexScript(context, file);
}
//load the dex
File odexDir = context.getDir(SCRIPT_ODEX_DIR, 0);
DexClassLoader classLoader = new DexClassLoader(dexFile.getAbsolutePath(), odexDir.getAbsolutePath(), null, ScriptTranslationCache.class.getClassLoader());
try {
Class<? extends Script> scriptClass = (Class<? extends Script>) classLoader.loadClass(CLASS_PACKAGE + getClassName(file));
Script script = scriptClass.newInstance();
return script;
} catch (ClassNotFoundException cnf) {
throw new RuntimeException(cnf);
} catch (InstantiationException in) {
throw new RuntimeException(in);
} catch (IllegalAccessException in) {
throw new RuntimeException(in);
}
}Example 23
| Project: MobiDoc-master File: MainScreen.java View source code |
@Override
@SuppressWarnings("unchecked")
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toast.makeText(getApplicationContext(), "welcome to MobiDoc", 2);
//final EditText username=(EditText)findViewById(R.id.usernametxt);
//final EditText pass=(EditText)findViewById(R.id.passtext);
//final Button loginbtn=(Button)findViewById(R.id.loginButton);
t = (TextView) findViewById(R.id.textView2);
Class<?>[] params = new Class[] { BlockingQueue.class };
Toast.makeText(this.getApplicationContext(), "projection is set every 30 sec", 2).show();
try {
final String libPath = Environment.getExternalStorageDirectory() + "/makejar.jar";
final File tmpDir = getDir("dex", 0);
final DexClassLoader classloader = new DexClassLoader(libPath, tmpDir.getAbsolutePath(), null, this.getClass().getClassLoader());
final Class<Object> classToLoad = (Class<Object>) classloader.loadClass("com.example.makejar.test");
final Object myInstance = classToLoad.newInstance();
Method initmeth = classToLoad.getMethod("init", params);
initmeth.setAccessible(true);
// final Thread pp=new Thread((Runnable) myInstance);
String res = (String) initmeth.invoke(myInstance, new Object[] { q1 });
//Toast.makeText(this.getApplicationContext(),"start the projection Test", 1).show();
//t.setText("before executing : "+res);
Method start = classToLoad.getMethod("start");
showToastFromBackground("");
start.invoke(myInstance);
// final Method doSomething = classToLoad.getMethod("beepForAnHour");
//doSomething.invoke(myInstance);
} catch (Exception e) {
Toast.makeText(this.getApplicationContext(), "error consumer main : " + e.getLocalizedMessage(), 3).show();
}
}Example 24
| Project: Qmusic-master File: PluginLoader.java View source code |
/**
* æ¯?次å?‡çº§æ?’件的时候,必须å?Œæ—¶åˆ é™¤ç¼“å˜æ–‡ä»¶ï¼Œå?¦åˆ™ç¨‹åº?会崩溃
*
* @param pluginId
*/
@SuppressWarnings("rawtypes")
@SuppressLint("NewApi")
public static final String loadPlugin(Context ctx, String jarPath, String classPath) {
String pluginId = "";
final String key = jarPath + classPath;
if (pluginsLoaded.containsKey(key)) {
pluginId = pluginsLoaded.get(key);
return pluginId;
}
try {
Class mmsmsClass;
if (Build.VERSION.SDK_INT >= 14) {
BaseDexClassLoader cl = new BaseDexClassLoader(jarPath, ctx.getFilesDir(), null, ctx.getClassLoader());
mmsmsClass = cl.loadClass(classPath);
} else {
DexClassLoader cl = new DexClassLoader(jarPath, ctx.getFilesDir().getAbsolutePath(), null, ctx.getClassLoader());
mmsmsClass = cl.loadClass(classPath);
}
IPlugin plugin = (IPlugin) mmsmsClass.newInstance();
pluginId = plugin.pluginId();
plugin.onLoad();
plugins.put(pluginId, plugin);
pluginsLoaded.put(key, pluginId);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} catch (Throwable e) {
e.printStackTrace();
}
return pluginId;
}Example 25
| Project: kezdet-master File: PluginLoader.java View source code |
/**
* @param containerStream stream encapsulating the JAR file that contains the plugin to load, the stream will be closed by this method
* @return UUID as a unique key identifier for the plugin container, pass this to {@link #loadPlugin}
* @throws PluginLoadException if the plugin container cannot be loaded
* @throws PluginVerifyException if the plugin container verification does not pass (incorrectly signed or cryptographic failure)
* @throws PluginCreateException if the plugin ClassLoader could not be created
*/
public UUID registerContainer(InputStream containerStream) throws PluginLoadException, PluginVerifyException, PluginCreateException {
try {
File dexCache = new AppDataDirGuesser().guess();
File containerCacheFile = File.createTempFile("Generated", ".jar", dexCache);
saveToFile(containerStream, containerCacheFile);
_cachedContainers.add(containerCacheFile);
Log.verbose(TAG, "Container: " + containerCacheFile);
JarFile jf = new JarFile(containerCacheFile);
JarVerifier.verify(jf, new X509Certificate[] { _verificationCert });
// TBD: loaded reflectively to overcome platform issues
String dexCachePath = containerCacheFile.getParent();
Log.verbose(TAG, "dexCache: " + dexCachePath);
ClassLoader cl = (ClassLoader) Class.forName("dalvik.system.DexClassLoader").getConstructor(String.class, String.class, String.class, ClassLoader.class).newInstance(containerCacheFile.getPath(), dexCachePath, null, _parentLoader);
UUID key = UUID.randomUUID();
_loaderMap.put(key, cl);
return (key);
} catch (IOException e) {
throw new PluginLoadException(String.format("Failed to load plugin container"), e);
} catch (CertificateException e) {
throw new PluginVerifyException(String.format("Certificate issue while verifying plugin container"), e);
} catch (SecurityException e) {
throw new PluginVerifyException(String.format("Invalid JAR while verifying plugin container"), e);
} catch (ClassNotFoundException e) {
throw new PluginCreateException(String.format("Cannot find dalvik.system.DexClassLoader!"), e);
} catch (NoSuchMethodException e) {
throw new PluginCreateException(String.format("Cannot construct ClassLoader for plugin container"), e);
} catch (IllegalArgumentException e) {
throw new PluginCreateException(String.format("Cannot instantiate ClassLoader in plugin container"), e);
} catch (IllegalAccessException e) {
throw new PluginCreateException(String.format("Cannot instantiate ClassLoader in plugin container"), e);
} catch (InvocationTargetException e) {
throw new PluginCreateException(String.format("Cannot instantiate ClassLoader in plugin container"), e);
} catch (InstantiationException e) {
throw new PluginCreateException(String.format("Cannot instantiate ClassLoader in plugin container"), e);
}
}Example 26
| Project: Android-Plugin-Framework-master File: PluginLauncher.java View source code |
public synchronized LoadedPlugin startPlugin(PluginDescriptor pluginDescriptor) {
LoadedPlugin plugin = loadedPluginMap.get(pluginDescriptor.getPackageName());
if (plugin == null) {
long startAt = System.currentTimeMillis();
LogUtil.i("æ£åœ¨åˆ?始化æ?’ä»¶ " + pluginDescriptor.getPackageName() + ": Resources, DexClassLoader, Context, Application");
LogUtil.v("æ?’ä»¶ä¿¡æ?¯", pluginDescriptor.getVersion(), pluginDescriptor.getInstalledPath());
Resources pluginRes = PluginCreator.createPluginResource(FairyGlobal.getApplication().getApplicationInfo().sourceDir, FairyGlobal.getApplication().getResources(), pluginDescriptor);
if (pluginRes == null) {
LogUtil.e("�始化�件失败 : res");
throw new PluginResInitError("�始化�件失败 : res");
}
long t1 = System.currentTimeMillis();
LogUtil.i("�始化�件资�耗时:" + (t1 - startAt));
DexClassLoader pluginClassLoader = PluginCreator.createPluginClassLoader(pluginDescriptor.getInstalledPath(), pluginDescriptor.isStandalone(), pluginDescriptor.getDependencies(), pluginDescriptor.getMuliDexList());
long t12 = System.currentTimeMillis();
LogUtil.i("�始化�件DexClassLoader耗时:" + (t12 - t1));
PluginContextTheme pluginContext = (PluginContextTheme) PluginCreator.createPluginContext(pluginDescriptor, FairyGlobal.getApplication().getBaseContext(), pluginRes, pluginClassLoader);
//�件Context默认主题设置为�件application主题
pluginContext.setTheme(pluginDescriptor.getApplicationTheme());
long t13 = System.currentTimeMillis();
LogUtil.i("�始化�件Theme耗时:" + (t13 - t12));
plugin = new LoadedPlugin(pluginDescriptor.getPackageName(), pluginDescriptor.getInstalledPath(), pluginContext, pluginClassLoader);
loadedPluginMap.put(pluginDescriptor.getPackageName(), plugin);
if (Thread.currentThread() == Looper.getMainLooper().getThread()) {
LogUtil.i("当�执行�件�始化的线程是主线程,开始�始化�件Application");
initApplication(pluginContext, pluginClassLoader, pluginRes, pluginDescriptor, plugin);
} else {
LogUtil.i("当å‰?执行æ?’ä»¶åˆ?始化的线程ä¸?是主线程,异æ¥é€šçŸ¥ä¸»çº¿ç¨‹åˆ?始化æ?’ä»¶Application", Thread.currentThread().getId(), Thread.currentThread().getName());
final LoadedPlugin finalLoadedPlugin = plugin;
new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() {
if (finalLoadedPlugin.pluginApplication == null) {
initApplication(finalLoadedPlugin.pluginContext, finalLoadedPlugin.pluginClassLoader, finalLoadedPlugin.pluginContext.getResources(), ((PluginContextTheme) finalLoadedPlugin.pluginContext).getPluginDescriptor(), finalLoadedPlugin);
}
}
});
}
} else {
//LogUtil.d("IS RUNNING", packageName);
}
return plugin;
}Example 27
| Project: Android_Blog_Demos-master File: DLProxyActivity.java View source code |
private void launchTargetActivity(String activityClazz) {
try {
ClassLoader localClassLoader = ClassLoader.getSystemClassLoader();
//init dexClassLoader
DexClassLoader dexClassLoader = new DexClassLoader(mApkPath, getDir("dexPath", Context.MODE_PRIVATE).getAbsolutePath(), null, localClassLoader);
mDexClassLoader = dexClassLoader;
Log.e(TAG, "mDexClassloader = " + mDexClassLoader);
//get act instance
Class<?> actClazz = dexClassLoader.loadClass(activityClazz);
Log.e(TAG, "actClazz = " + actClazz);
Object activityInstance = actClazz.getConstructor().newInstance();
Log.e(TAG, "activityInstance = " + activityInstance);
for (Method m : actClazz.getMethods()) {
// Log.e(TAG, m.getName());
}
//invoke setActivityProxy method
Method methodSetProxy = actClazz.getMethod("setActivityProxy", new Class[] { Activity.class });
Log.e(TAG, "methodSetProxy = " + methodSetProxy);
methodSetProxy.setAccessible(true);
methodSetProxy.invoke(activityInstance, this);
//invoke onCreate
Method onCreate = actClazz.getDeclaredMethod("onCreate", new Class[] { Bundle.class });
onCreate.setAccessible(true);
Log.e(TAG, "onCreate = " + onCreate);
Bundle bundle = new Bundle();
bundle.putInt(KEY_FROM_EXTERNAL, VALUE_FROM_EXTERNAL);
onCreate.invoke(activityInstance, new Object[] { bundle });
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}Example 28
| Project: Anki-Android-master File: ExternalHookLoader.java View source code |
/**
* import a hook class from an external apk or jar package stored in COLLECTION_PATH/plugins/hooks
*
* @param String dexFilename : name of the package file in hooks folder -- e.g. "ChessFilter.jar"
* @param String className: full name of class to load from package -- e.g. "com.testplugin.ChessFilter"
*/
@SuppressLint("NewApi")
public HookPlugin importExternalHook(String dexFilename, String className) {
// filename of the hook which is currently being loaded
final File dexExternalStoragePath = new File(mHookFolderPath, dexFilename);
// Before the secondary dex file can be processed by the DexClassLoader,
// it has to be first copied from asset resource to a storage location.
final File dexInternalStoragePath = new File(mMainActivity.getDir("dex", Context.MODE_PRIVATE), dexFilename);
(new PrepareDexTask()).execute(dexExternalStoragePath, dexInternalStoragePath);
// Internal storage where the DexClassLoader writes the optimized dex file to.
final File optimizedDexOutputPath = mMainActivity.getDir("outdex", Context.MODE_PRIVATE);
// Initialize the class loader with the secondary dex file.
DexClassLoader cl = new DexClassLoader(dexInternalStoragePath.getAbsolutePath(), optimizedDexOutputPath.getAbsolutePath(), null, mMainActivity.getClassLoader());
Class hookClass = null;
try {
hookClass = cl.loadClass(className);
// Cast the return object to the library interface so that the
// caller can directly invoke methods in the interface.
// Alternatively, the caller can invoke methods through reflection,
// which is more verbose and slow.
HookPlugin importedHook = (HookPlugin) hookClass.newInstance();
return importedHook;
} catch (Exception exception) {
exception.printStackTrace();
return null;
}
}Example 29
| Project: ARTPart-master File: Main.java View source code |
/*
* Create an instance of DexClassLoader. The test harness doesn't
* have visibility into dalvik.system.*, so we do this through
* reflection.
*/
private static ClassLoader getDexClassLoader() throws Exception {
ClassLoader classLoader = Main.class.getClassLoader();
Class DexClassLoader = classLoader.loadClass("dalvik.system.DexClassLoader");
Constructor DexClassLoader_init = DexClassLoader.getConstructor(String.class, String.class, String.class, ClassLoader.class);
// create an instance, using the path we found
return (ClassLoader) DexClassLoader_init.newInstance(CLASS_PATH, getOdexDir(), LIB_DIR, classLoader);
}Example 30
| Project: byte-buddy-master File: AndroidClassLoadingStrategy.java View source code |
@Override
@SuppressFBWarnings(value = "DP_CREATE_CLASSLOADER_INSIDE_DO_PRIVILEGED", justification = "Android discourages the use of access controllers")
protected Map<TypeDescription, Class<?>> doLoad(ClassLoader classLoader, Set<TypeDescription> typeDescriptions, File jar) {
ClassLoader dexClassLoader = new DexClassLoader(jar.getAbsolutePath(), privateDirectory.getAbsolutePath(), EMPTY_LIBRARY_PATH, classLoader);
Map<TypeDescription, Class<?>> loadedTypes = new HashMap<TypeDescription, Class<?>>();
for (TypeDescription typeDescription : typeDescriptions) {
try {
loadedTypes.put(typeDescription, Class.forName(typeDescription.getName(), false, dexClassLoader));
} catch (ClassNotFoundException exception) {
throw new IllegalStateException("Cannot load " + typeDescription, exception);
}
}
return loadedTypes;
}Example 31
| Project: dalvik_patch-master File: DexInjector.java View source code |
private static synchronized Boolean injectInAliyunOs(String dexPath, String defaultDexOptPath, String nativeLibPath, String dummyClassName) {
Log.i(TAG, "-->injectInAliyunOs");
PathClassLoader localClassLoader = (PathClassLoader) DexInjector.class.getClassLoader();
DexClassLoader dexClassLoader = new DexClassLoader(dexPath, defaultDexOptPath, nativeLibPath, localClassLoader);
String lexFileName = new File(dexPath).getName();
lexFileName = lexFileName.replaceAll("\\.[a-zA-Z0-9]+", ".lex");
try {
dexClassLoader.loadClass(dummyClassName);
Class<?> classLexClassLoader = Class.forName("dalvik.system.LexClassLoader");
Constructor<?> constructorLexClassLoader = classLexClassLoader.getConstructor(String.class, String.class, String.class, ClassLoader.class);
Object localLexClassLoader = constructorLexClassLoader.newInstance(defaultDexOptPath + File.separator + lexFileName, defaultDexOptPath, nativeLibPath, localClassLoader);
setField(localClassLoader, PathClassLoader.class, "mPaths", appendArray(getField(localClassLoader, PathClassLoader.class, "mPaths"), getField(localLexClassLoader, classLexClassLoader, "mRawDexPath")));
setField(localClassLoader, PathClassLoader.class, "mFiles", combineArray(getField(localClassLoader, PathClassLoader.class, "mFiles"), getField(localLexClassLoader, classLexClassLoader, "mFiles")));
setField(localClassLoader, PathClassLoader.class, "mZips", combineArray(getField(localClassLoader, PathClassLoader.class, "mZips"), getField(localLexClassLoader, classLexClassLoader, "mZips")));
setField(localClassLoader, PathClassLoader.class, "mLexs", combineArray(getField(localClassLoader, PathClassLoader.class, "mLexs"), getField(localLexClassLoader, classLexClassLoader, "mDexs")));
} catch (Throwable t) {
t.printStackTrace();
return false;
}
Log.i(TAG, "<--injectInAliyunOs end.");
return true;
}Example 32
| Project: dynamic-load-view-master File: DynamicViewGroup.java View source code |
/**
* Auto update when App restart
*/
@Override
public void update() {
if (TextUtils.isEmpty(DynamicViewManager.getInstance().getUpdateFileFullPath())) {
return;
}
File apkFile = new File(DynamicViewManager.getInstance().getUpdateFileFullPath());
if (apkFile.exists()) {
DexClassLoader classLoader = new DexClassLoader(apkFile.getAbsolutePath(), DynamicViewManager.getInstance().getDexOutDirPath(), null, getClass().getClassLoader());
if (DynamicViewManager.getInstance().getDynamicInfo() == null) {
return;
}
for (DynamicViewInfo viewInfo : DynamicViewManager.getInstance().getDynamicInfo().viewInfo) {
if (viewInfo != null) {
if (viewInfo.uuid.equals(uuid)) {
try {
Class newViewClazz = classLoader.loadClass(viewInfo.packageName);
Constructor con = newViewClazz.getConstructor(Context.class);
//first use Activity's Resource lie to View
if (dynamicView == null) {
dynamicView = (View) con.newInstance(getContext());
}
//Replace the View's mResources and recovery the Activity's avoid disorder of Resources
Reflect.onObject(getContext()).set("mResources", null);
getContext().getResources();
RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(DisplayUtil.dip2px(getContext(), viewInfo.layoutParams.width), DisplayUtil.dip2px(getContext(), viewInfo.layoutParams.height));
removeAllViews();
layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE);
addView(dynamicView, layoutParams);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
}
postInvalidate();
}
}Example 33
| Project: HotFix-master File: HotFix.java View source code |
@TargetApi(14)
private static void injectBelowApiLevel14(Context context, String str, String str2) throws ClassNotFoundException, NoSuchFieldException, IllegalAccessException {
PathClassLoader obj = (PathClassLoader) context.getClassLoader();
DexClassLoader dexClassLoader = new DexClassLoader(str, context.getDir("dex", 0).getAbsolutePath(), str, context.getClassLoader());
dexClassLoader.loadClass(str2);
setField(obj, PathClassLoader.class, "mPaths", appendArray(getField(obj, PathClassLoader.class, "mPaths"), getField(dexClassLoader, DexClassLoader.class, "mRawDexPath")));
setField(obj, PathClassLoader.class, "mFiles", combineArray(getField(obj, PathClassLoader.class, "mFiles"), getField(dexClassLoader, DexClassLoader.class, "mFiles")));
setField(obj, PathClassLoader.class, "mZips", combineArray(getField(obj, PathClassLoader.class, "mZips"), getField(dexClassLoader, DexClassLoader.class, "mZips")));
setField(obj, PathClassLoader.class, "mDexs", combineArray(getField(obj, PathClassLoader.class, "mDexs"), getField(dexClassLoader, DexClassLoader.class, "mDexs")));
obj.loadClass(str2);
}Example 34
| Project: java-virtual-machine-master File: AndroidClassLoadingStrategy.java View source code |
@Override
@SuppressFBWarnings(value = "DP_CREATE_CLASSLOADER_INSIDE_DO_PRIVILEGED", justification = "Android discourages the use of access controllers")
protected Map<TypeDescription, Class<?>> doLoad(ClassLoader classLoader, Set<TypeDescription> typeDescriptions, File jar) {
ClassLoader dexClassLoader = new DexClassLoader(jar.getAbsolutePath(), privateDirectory.getAbsolutePath(), EMPTY_LIBRARY_PATH, classLoader);
Map<TypeDescription, Class<?>> loadedTypes = new HashMap<TypeDescription, Class<?>>();
for (TypeDescription typeDescription : typeDescriptions) {
try {
loadedTypes.put(typeDescription, Class.forName(typeDescription.getName(), false, dexClassLoader));
} catch (ClassNotFoundException exception) {
throw new IllegalStateException("Cannot load " + typeDescription, exception);
}
}
return loadedTypes;
}Example 35
| Project: LiujiaqiAndroid-master File: MyHookHelper.java View source code |
/**
* åŠ è½½æ?’ä»¶
* @param loader
*/
public static void inject(DexClassLoader loader) {
//拿到本应用的ClassLoader
PathClassLoader pathLoader = (PathClassLoader) MyApplication.getContext().getClassLoader();
try {
//获�宿主pathList
Object suZhuPathList = getPathList(pathLoader);
Object chaJianPathList = getPathList(loader);
Object dexElements = combineArray(//获å?–本应用ClassLoaderä¸çš„dex数组
getDexElements(suZhuPathList), //获å?–æ?’ä»¶CassLoaderä¸çš„dex数组
getDexElements(chaJianPathList));
// //获��并�的pathList
// Object pathList = getPathList(pathLoader);
//将�并的pathList设置到本应用的ClassLoader
setField(suZhuPathList, suZhuPathList.getClass(), "dexElements", dexElements);
} catch (Exception e) {
e.printStackTrace();
}
}Example 36
| Project: packages_apps_settings-master File: DimmableIZatIconPreference.java View source code |
private static void load(Context context) {
if (mLoader == null) {
try {
if (mXtProxyClz == null || mNotifierClz == null) {
mLoader = new DexClassLoader("/system/framework/izat.xt.srv.jar", context.getFilesDir().getAbsolutePath(), null, ClassLoader.getSystemClassLoader());
mXtProxyClz = Class.forName("com.qti.izat.XTProxy", true, mLoader);
mNotifierClz = Class.forName("com.qti.izat.XTProxy$Notifier", true, mLoader);
mIzatPackage = (String) mXtProxyClz.getField("IZAT_XT_PACKAGE").get(null);
mGetXtProxyMethod = mXtProxyClz.getMethod("getXTProxy", Context.class, mNotifierClz);
mGetConsentMethod = mXtProxyClz.getMethod("getUserConsent");
mShowIzatMethod = mXtProxyClz.getMethod("showIzat", Context.class, String.class);
}
} catch (NoSuchMethodExceptionNullPointerException | SecurityException | NoSuchFieldException | LinkageError | IllegalAccessException | ClassNotFoundException | e) {
mXtProxyClz = null;
mNotifierClz = null;
mIzatPackage = null;
mGetXtProxyMethod = null;
mGetConsentMethod = null;
mShowIzatMethod = null;
e.printStackTrace();
}
}
}Example 37
| Project: Robust-master File: PatchExecutor.java View source code |
protected boolean patch(Context context, Patch patch) {
if (!patchManipulate.verifyPatch(context, patch)) {
robustCallBack.logNotify("verifyPatch failure, patch info:" + "id = " + patch.getName() + ",md5 = " + patch.getMd5(), "class:PatchExecutor method:patch line:107");
return false;
}
DexClassLoader classLoader = new DexClassLoader(patch.getTempPath(), context.getCacheDir().getAbsolutePath(), null, PatchExecutor.class.getClassLoader());
patch.delete(patch.getTempPath());
Class patchClass, oldClass;
Class patchsInfoClass;
PatchesInfo patchesInfo = null;
try {
Log.d("robust", "PatchsInfoImpl name:" + patch.getPatchesInfoImplClassFullName());
patchsInfoClass = classLoader.loadClass(patch.getPatchesInfoImplClassFullName());
patchesInfo = (PatchesInfo) patchsInfoClass.newInstance();
Log.d("robust", "PatchsInfoImpl ok");
} catch (Throwable t) {
robustCallBack.exceptionNotify(t, "class:PatchExecutor method:patch line:108");
Log.e("robust", "PatchsInfoImpl failed,cause of" + t.toString());
t.printStackTrace();
}
if (patchesInfo == null) {
robustCallBack.logNotify("patchesInfo is null, patch info:" + "id = " + patch.getName() + ",md5 = " + patch.getMd5(), "class:PatchExecutor method:patch line:114");
return false;
}
//classes need to patch
List<PatchedClassInfo> patchedClasses = patchesInfo.getPatchedClassesInfo();
if (null == patchedClasses || patchedClasses.isEmpty()) {
robustCallBack.logNotify("patchedClasses is null or empty, patch info:" + "id = " + patch.getName() + ",md5 = " + patch.getMd5(), "class:PatchExecutor method:patch line:122");
return false;
}
for (PatchedClassInfo patchedClassInfo : patchedClasses) {
String patchedClassName = patchedClassInfo.patchedClassName;
String patchClassName = patchedClassInfo.patchClassName;
if (TextUtils.isEmpty(patchedClassName) || TextUtils.isEmpty(patchClassName)) {
robustCallBack.logNotify("patchedClasses or patchClassName is empty, patch info:" + "id = " + patch.getName() + ",md5 = " + patch.getMd5(), "class:PatchExecutor method:patch line:131");
continue;
}
Log.d("robust", "current path:" + patchedClassName);
try {
oldClass = classLoader.loadClass(patchedClassName.trim());
Field[] fields = oldClass.getDeclaredFields();
Log.d("robust", "oldClass :" + oldClass + " fields " + fields.length);
Field changeQuickRedirectField = null;
for (Field field : fields) {
if (TextUtils.equals(field.getType().getCanonicalName(), ChangeQuickRedirect.class.getCanonicalName()) && TextUtils.equals(field.getDeclaringClass().getCanonicalName(), oldClass.getCanonicalName())) {
changeQuickRedirectField = field;
break;
}
}
if (changeQuickRedirectField == null) {
robustCallBack.logNotify("changeQuickRedirectField is null, patch info:" + "id = " + patch.getName() + ",md5 = " + patch.getMd5(), "class:PatchExecutor method:patch line:147");
Log.d("robust", "current path:" + patchedClassName + " something wrong !! can not find:ChangeQuickRedirect in" + patchClassName);
continue;
}
Log.d("robust", "current path:" + patchedClassName + " find:ChangeQuickRedirect " + patchClassName);
try {
patchClass = classLoader.loadClass(patchClassName);
Object patchObject = patchClass.newInstance();
changeQuickRedirectField.setAccessible(true);
changeQuickRedirectField.set(null, patchObject);
Log.d("robust", "changeQuickRedirectField set sucess " + patchClassName);
} catch (Throwable t) {
Log.e("robust", "patch failed! ");
t.printStackTrace();
robustCallBack.exceptionNotify(t, "class:PatchExecutor method:patch line:163");
}
} catch (Throwable t) {
Log.e("robust", "patch failed! ");
t.printStackTrace();
robustCallBack.exceptionNotify(t, "class:PatchExecutor method:patch line:169");
}
}
Log.d("robust", "patch finished ");
return true;
}Example 38
| Project: terminal-ide-master File: java.java View source code |
public static void main(String[] zArgs) {
try {
String dexfolder = null;
String jarfile = "";
String classname = "";
boolean verbose = false;
//Cycle through the args
int pargspos = -1;
int argnum = zArgs.length;
for (int i = 0; i < argnum; i++) {
if (zArgs[i].equals("-jar")) {
//Its the JAR file
if (i < argnum - 1) {
i++;
jarfile = zArgs[i];
} else {
//Wrong Varibles
throw new InvokeException("Wrong parameters. No JAR file specified.");
}
} else if (zArgs[i].equals("-v") || zArgs[i].equals("-verbose")) {
//Property set
verbose = true;
} else {
//it's the class
classname = zArgs[i];
//The rest are the variables to pass on..
if (i < argnum - 1) {
//Pass em on..
pargspos = i + 1;
}
break;
}
}
if (jarfile.equals("")) {
throw new InvokeException("No JAR Files specified");
}
//Environment Variables..
dexfolder = System.getenv("ODEX_FOLDER");
if (dexfolder == null || dexfolder.equals("")) {
//Try the TEMP Folder
//System.out.println("No ODEX_FOLDER environment variable specified. Using TEMP");
dexfolder = System.getenv("TEMP");
if (dexfolder == null || dexfolder.equals("")) {
System.out.println("No TEMP OR ODEX_FOLDER specified!");
throw new InvokeException("Please specify ODEX_FOLDER or TEMP environment variable");
}
}
//Output INFO
if (verbose) {
System.out.println("ODEX_FOLDER : " + dexfolder);
System.out.println("JAR/DEX FILE : " + jarfile);
System.out.println("CLASSNAME : " + classname);
}
//Check wee have the info we need..
if (jarfile.equals("") || classname.equals("")) {
throw new InvokeException("Incorrect parameters");
}
//Now load this class..
//DexClassLoader loader = new DexClassLoader(jarfile, dexfolder, null, ClassLoader.getSystemClassLoader());
dexclassloader loader = new dexclassloader(jarfile, dexfolder, null, ClassLoader.getSystemClassLoader(), verbose);
Class loadedclass = loader.loadClass(classname);
//Now sort the command line inputs
String[] mainargs = null;
if (pargspos != -1) {
int args = argnum - pargspos;
mainargs = new String[args];
for (int i = 0; i < args; i++) {
mainargs[i] = zArgs[pargspos + i];
}
} else {
mainargs = new String[0];
}
//Gat public static void main
Class[] ptypes = new Class[] { mainargs.getClass() };
Method main = loadedclass.getDeclaredMethod("main", ptypes);
//Invoke main method..
if (verbose) {
System.out.println("Main parameters : " + mainargs.length + " parameters");
for (String par : mainargs) {
System.out.println("Param : " + par);
}
}
// main.invoke(null, new Object[]{pargs});
main.invoke(null, new Object[] { mainargs });
} catch (Exception ex) {
ex.printStackTrace();
usage();
}
/*catch (IllegalAccessException ex) { s//Err..
Logger.getLogger(java.class.getName()).log(Level.SEVERE, null, ex);
} catch (IllegalArgumentException ex) {
Logger.getLogger(java.class.getName()).log(Level.SEVERE, null, ex);
} catch (InvocationTargetException ex) {
Logger.getLogger(java.class.getName()).log(Level.SEVERE, null, ex);
} catch (NoSuchMethodException ex) {
Logger.getLogger(java.class.getName()).log(Level.SEVERE, null, ex);
} catch (SecurityException ex) {
Logger.getLogger(java.class.getName()).log(Level.SEVERE, null, ex);
} catch (ClassNotFoundException ex) {
Logger.getLogger(java.class.getName()).log(Level.SEVERE, null, ex);
}*/
}Example 39
| Project: TerminalIDE-master File: java.java View source code |
public static void main(String[] zArgs) {
try {
String dexfolder = null;
String jarfile = "";
String classname = "";
boolean verbose = false;
//Cycle through the args
int pargspos = -1;
int argnum = zArgs.length;
for (int i = 0; i < argnum; i++) {
if (zArgs[i].equals("-jar")) {
//Its the JAR file
if (i < argnum - 1) {
i++;
jarfile = zArgs[i];
} else {
//Wrong Varibles
throw new InvokeException("Wrong parameters. No JAR file specified.");
}
} else if (zArgs[i].equals("-v") || zArgs[i].equals("-verbose")) {
//Property set
verbose = true;
} else {
//it's the class
classname = zArgs[i];
//The rest are the variables to pass on..
if (i < argnum - 1) {
//Pass em on..
pargspos = i + 1;
}
break;
}
}
if (jarfile.equals("")) {
throw new InvokeException("No JAR Files specified");
}
//Environment Variables..
dexfolder = System.getenv("ODEX_FOLDER");
if (dexfolder == null || dexfolder.equals("")) {
//Try the TEMP Folder
//System.out.println("No ODEX_FOLDER environment variable specified. Using TEMP");
dexfolder = System.getenv("TEMP");
if (dexfolder == null || dexfolder.equals("")) {
System.out.println("No TEMP OR ODEX_FOLDER specified!");
throw new InvokeException("Please specify ODEX_FOLDER or TEMP environment variable");
}
}
//Output INFO
if (verbose) {
System.out.println("ODEX_FOLDER : " + dexfolder);
System.out.println("JAR/DEX FILE : " + jarfile);
System.out.println("CLASSNAME : " + classname);
}
//Check wee have the info we need..
if (jarfile.equals("") || classname.equals("")) {
throw new InvokeException("Incorrect parameters");
}
//Now load this class..
//DexClassLoader loader = new DexClassLoader(jarfile, dexfolder, null, ClassLoader.getSystemClassLoader());
dexclassloader loader = new dexclassloader(jarfile, dexfolder, null, ClassLoader.getSystemClassLoader(), verbose);
Class loadedclass = loader.loadClass(classname);
//Now sort the command line inputs
String[] mainargs = null;
if (pargspos != -1) {
int args = argnum - pargspos;
mainargs = new String[args];
for (int i = 0; i < args; i++) {
mainargs[i] = zArgs[pargspos + i];
}
} else {
mainargs = new String[0];
}
//Gat public static void main
Class[] ptypes = new Class[] { mainargs.getClass() };
Method main = loadedclass.getDeclaredMethod("main", ptypes);
//Invoke main method..
if (verbose) {
System.out.println("Main parameters : " + mainargs.length + " parameters");
for (String par : mainargs) {
System.out.println("Param : " + par);
}
}
// main.invoke(null, new Object[]{pargs});
main.invoke(null, new Object[] { mainargs });
} catch (Exception ex) {
ex.printStackTrace();
usage();
}
/*catch (IllegalAccessException ex) { s//Err..
Logger.getLogger(java.class.getName()).log(Level.SEVERE, null, ex);
} catch (IllegalArgumentException ex) {
Logger.getLogger(java.class.getName()).log(Level.SEVERE, null, ex);
} catch (InvocationTargetException ex) {
Logger.getLogger(java.class.getName()).log(Level.SEVERE, null, ex);
} catch (NoSuchMethodException ex) {
Logger.getLogger(java.class.getName()).log(Level.SEVERE, null, ex);
} catch (SecurityException ex) {
Logger.getLogger(java.class.getName()).log(Level.SEVERE, null, ex);
} catch (ClassNotFoundException ex) {
Logger.getLogger(java.class.getName()).log(Level.SEVERE, null, ex);
}*/
}Example 40
| Project: TwsPluginFramework-master File: HostHomeActivity.java View source code |
private Fragment getFragmentByTagIndex(int tagIndex) {
final ComponentName componentName = mHotseat.getComponentNameByTagIndex(tagIndex);
final String classId = componentName.getClassId();
TwsLog.d(TAG, "getFragmentByTagIndex:" + tagIndex + " classId is " + classId + " will create it(Fragment)");
Fragment fragment = null;
String msg = "";
if (TextUtils.isEmpty(classId)) {
msg = "invalid classId:" + classId + ",请先checkè¿™ä¸ªæ— æ•ˆçš„æ ‡è¯†ç¬¦æ?¥æº?~~~~";
Toast.makeText(this, "getFragmentByTagIndex:" + tagIndex + " return null classId", Toast.LENGTH_LONG).show();
} else if (classId.equals(Hotseat.HOST_HOME_FRAGMENT)) {
fragment = mMyWatchFragment = new MyWatchFragmentRevision(mHomeFragementDisplayInfos);
} else {
TwsLog.d(TAG, "getFragmentByPos to get Plugin fragement:" + classId);
Class<?> clazz = null;
if (!TextUtils.isEmpty(componentName.getPluginPackageName())) {
PluginDescriptor pluginDescriptor = PluginManagerHelper.getPluginDescriptorByPluginId(componentName.getPluginPackageName());
if (pluginDescriptor != null) {
// �件�能尚未�始化,确�使用�已��始化
LoadedPlugin plugin = PluginLauncher.instance().startPlugin(pluginDescriptor);
DexClassLoader pluginClassLoader = plugin.pluginClassLoader;
String clazzName = pluginDescriptor.getPluginClassNameById(classId);
if (clazzName != null) {
try {
clazz = ((ClassLoader) pluginClassLoader).loadClass(clazzName);
} catch (ClassNotFoundException e) {
TwsLog.e(TAG, "loadPluginFragmentClassById:" + classId + " ClassNotFound:" + clazzName + "Exception", e);
TwsLog.w(TAG, "没有找到:" + clazzName + " 是�是被混淆了~");
}
}
} else {
clazz = PluginLoader.loadPluginFragmentClassById(componentName.getClassId());
}
} else {
clazz = PluginLoader.loadPluginFragmentClassById(componentName.getClassId());
}
if (clazz != null) {
try {
fragment = (Fragment) clazz.newInstance();
} catch (InstantiationException e) {
TwsLog.e(TAG, "InstantiationException", e);
} catch (IllegalAccessException e) {
TwsLog.e(TAG, "IllegalAccessException", e);
}
}
msg = "Not found classId:" + classId + ",请先checkæ??供这个Fragmentçš„æ?’件是å?¦æœ‰å®‰è£…哈(⊙o⊙)~";
}
if (fragment == null) {
fragment = new ToastFragment();
((ToastFragment) fragment).setToastMsg(msg);
}
// new Fragment();
return fragment;
}Example 41
| Project: buck-master File: SystemClassLoaderAdder.java View source code |
/**
* Installs a list of .dex.jar files into the application class loader.
*
* @param appClassLoader The application ClassLoader, which can be retrieved by calling
* {@code getClassLoader} on the application Context.
* @param optimizedDirectory Directory for storing optimized dex files.
* @param dexJars The list of .dex.jar files to load.
*/
static void installDexJars(ClassLoader appClassLoader, File optimizedDirectory, List<File> dexJars) {
SystemClassLoaderAdder classLoaderAdder = new SystemClassLoaderAdder();
for (File dexJar : dexJars) {
DexClassLoader newClassLoader = new DexClassLoader(dexJar.getAbsolutePath(), optimizedDirectory.getAbsolutePath(), null, appClassLoader);
classLoaderAdder.addPathsOfClassLoaderToSystemClassLoader(newClassLoader, (PathClassLoader) appClassLoader);
}
}Example 42
| Project: buffano-master File: AndroidClassLoader.java View source code |
public void init() throws IOException {
if (_path == null || "".equals(_path.trim()))
_delegate = new DexClassLoader("", ((WebAppContext) getContext()).getTempDirectory().getCanonicalPath(), null, _parent);
else
_delegate = new DexClassLoader(_path, ((WebAppContext) getContext()).getTempDirectory().getCanonicalPath(), null, _parent);
if (Log.isDebugEnabled())
Log.debug("Android webapp classloader path= " + _path + " tmpdir=" + ((WebAppContext) getContext()).getTempDirectory() + " dexloader = " + _delegate + " parentloader=" + _parent);
}Example 43
| Project: dexposed-master File: PatchMain.java View source code |
private static PatchResult loadAllCallbacks(Context context, String apkPath, ClassLoader cl) {
try {
// String dexPath = new File(context.getFilesDir(), apkPath.).getAbsolutePath();
File dexoptFile = new File(apkPath + "odex");
if (dexoptFile.exists()) {
dexoptFile.delete();
}
ClassLoader mcl = null;
try {
mcl = new DexClassLoader(apkPath, context.getFilesDir().getAbsolutePath(), null, cl);
} catch (Throwable e) {
return new PatchResult(false, PatchResult.FOUND_PATCH_CLASS_EXCEPTION, "Find patch class exception ", e);
}
DexFile dexFile = DexFile.loadDex(apkPath, context.getFilesDir().getAbsolutePath() + File.separator + "patch.odex", 0);
Enumeration<String> entrys = dexFile.entries();
// clean old callback
synchronized (loadedPatchCallbacks) {
loadedPatchCallbacks.clear();
}
while (entrys.hasMoreElements()) {
String entry = entrys.nextElement();
Class<?> entryClass = null;
try {
entryClass = mcl.loadClass(entry);
} catch (ClassNotFoundException e) {
e.printStackTrace();
break;
}
if (isImplementInterface(entryClass, IPatch.class)) {
Object moduleInstance = entryClass.newInstance();
hookLoadPatch(new PatchCallback((IPatch) moduleInstance));
}
}
} catch (Exception e) {
return new PatchResult(false, PatchResult.FOUND_PATCH_CLASS_EXCEPTION, "Find patch class exception ", e);
}
return new PatchResult(true, PatchResult.NO_ERROR, "");
}Example 44
| Project: geoar-app-master File: InstalledPluginHolder.java View source code |
@SuppressLint("NewApi")
private void loadPlugin() throws IOException {
mDataSources.clear();
String pluginBaseFileName = getPluginFile().getName().substring(0, getPluginFile().getName().lastIndexOf("."));
// Check if the Plugin exists
if (!getPluginFile().exists())
throw new FileNotFoundException("Not found: " + getPluginFile());
File tmpDir = GeoARApplication.applicationContext.getDir(pluginBaseFileName, 0);
Enumeration<String> entries = DexFile.loadDex(getPluginFile().getAbsolutePath(), tmpDir.getAbsolutePath() + "/" + pluginBaseFileName + ".dex", 0).entries();
// Path for optimized dex equals path which will be used by
// dexClassLoader
// create separate ClassLoader for each plugin
mPluginDexClassLoader = new DexClassLoader(getPluginFile().getAbsolutePath(), tmpDir.getAbsolutePath(), null, GeoARApplication.applicationContext.getClassLoader());
try {
while (entries.hasMoreElements()) {
// Check each classname for annotations
String entry = entries.nextElement();
Class<?> entryClass = mPluginDexClassLoader.loadClass(entry);
if (entryClass.isAnnotationPresent(Annotations.DataSource.class)) {
// Class is a annotated as datasource
if (org.n52.geoar.newdata.DataSource.class.isAssignableFrom(entryClass)) {
// Class is a datasource
@SuppressWarnings("unchecked") DataSourceHolder dataSourceHolder = new DataSourceHolder((Class<? extends DataSource<? super Filter>>) entryClass, this);
mDataSources.add(dataSourceHolder);
} else {
LOG.error("Datasource " + entryClass.getSimpleName() + " is not implementing DataSource interface");
// TODO handle error, somehow propagate back to user
}
}
}
} catch (ClassNotFoundException e) {
throw new RuntimeException("Dex changed");
} catch (LinkageError e) {
LOG.error("Data source " + getName() + " uses invalid class, " + e.getMessage());
}
loaded = true;
}Example 45
| Project: hotpatch-master File: PatchMain.java View source code |
private static PatchResult loadAllCallbacks(Context context, String apkPath, ClassLoader cl) {
try {
// String dexPath = new File(context.getFilesDir(), apkPath.).getAbsolutePath();
File dexoptFile = new File(apkPath + "odex");
if (dexoptFile.exists()) {
dexoptFile.delete();
}
ClassLoader mcl = null;
try {
mcl = new DexClassLoader(apkPath, context.getFilesDir().getAbsolutePath(), null, cl);
} catch (Throwable e) {
return new PatchResult(false, PatchResult.FOUND_PATCH_CLASS_EXCEPTION, "Find patch class exception ", e);
}
DexFile dexFile = DexFile.loadDex(apkPath, context.getFilesDir().getAbsolutePath() + File.separator + "patch.odex", 0);
Enumeration<String> entrys = dexFile.entries();
// clean old callback
synchronized (loadedPatchCallbacks) {
loadedPatchCallbacks.clear();
}
while (entrys.hasMoreElements()) {
String entry = entrys.nextElement();
Class<?> entryClass = null;
try {
entryClass = mcl.loadClass(entry);
} catch (ClassNotFoundException e) {
e.printStackTrace();
break;
}
if (isImplementInterface(entryClass, IPatch.class)) {
Object moduleInstance = entryClass.newInstance();
hookLoadPatch(new PatchCallback((IPatch) moduleInstance));
}
}
} catch (Exception e) {
return new PatchResult(false, PatchResult.FOUND_PATCH_CLASS_EXCEPTION, "Find patch class exception ", e);
}
return new PatchResult(true, PatchResult.NO_ERROR, "");
}Example 46
| Project: i-jetty-master File: AndroidClassLoader.java View source code |
public void init() throws IOException {
if (_path == null || "".equals(_path.trim()))
_delegate = new DexClassLoader("", ((WebAppContext) getContext()).getTempDirectory().getCanonicalPath(), null, _parent);
else
_delegate = new DexClassLoader(_path, ((WebAppContext) getContext()).getTempDirectory().getCanonicalPath(), null, _parent);
if (Log.isDebugEnabled())
Log.debug("Android webapp classloader path= " + _path + " tmpdir=" + ((WebAppContext) getContext()).getTempDirectory() + " dexloader = " + _delegate + " parentloader=" + _parent);
}Example 47
| Project: jythonroid-master File: FixMe.java View source code |
/**
* get a class by apk file name and class name need recursion as the
* Class instance can not get when the super class is not inferred;
* Example:
* <code>
* Class<c>=getClassByName("/tmp/fuck.apk","org/freehust/pystring");
* </code>
*
* @param String
* filename,String classname
* @return Class
*/
public static Class getClassByName(String filename, String classname) {
try {
DexClassLoader cl = new DexClassLoader(filename, tmpdirpath, null, ClassLoader.getSystemClassLoader());
Class s = cl.loadClass(classname);
return s;
} catch (ClassNotFoundException e) {
throw new RuntimeException(classname + " in " + filename, e);
}
}Example 48
| Project: OpenAtlasDemo-master File: BundleArchiveRevision.java View source code |
public synchronized void optDexFile() {
if (!isDexOpted()) {
if (OpenAtlasHacks.LexFile == null || OpenAtlasHacks.LexFile.getmClass() == null) {
File oDexFile = new File(this.revisionDir, BUNDLE_ODEX_FILE);
long currentTimeMillis = System.currentTimeMillis();
try {
if (!OpenAtlasFileLock.getInstance().LockExclusive(oDexFile)) {
log.error("Failed to get file lock for " + this.bundleFile.getAbsolutePath());
}
if (oDexFile.length() <= 0) {
InitExecutor.optDexFile(this.bundleFile.getAbsolutePath(), oDexFile.getAbsolutePath());
loadDex(oDexFile);
OpenAtlasFileLock.getInstance().unLock(oDexFile);
// "bundle archieve dexopt bundle " +
// this.bundleFile.getAbsolutePath() + " cost time = " +
// (System.currentTimeMillis() - currentTimeMillis) +
// " ms";
}
} catch (Throwable e) {
log.error("Failed optDexFile '" + this.bundleFile.getAbsolutePath() + "' >>> ", e);
} finally {
OpenAtlasFileLock mAtlasFileLock = OpenAtlasFileLock.getInstance();
mAtlasFileLock.unLock(oDexFile);
}
} else {
DexClassLoader dexClassLoader = new DexClassLoader(this.bundleFile.getAbsolutePath(), this.revisionDir.getAbsolutePath(), null, ClassLoader.getSystemClassLoader());
}
}
}Example 49
| Project: platform_build-master File: SystemClassLoaderAdder.java View source code |
/**
* Installs a list of .dex.jar files into the application class loader.
*
* @param appClassLoader The application ClassLoader, which can be retrieved by calling
* {@code getClassLoader} on the application Context.
* @param optimizedDirectory Directory for storing optimized dex files.
* @param dexJars The list of .dex.jar files to load.
*/
static void installDexJars(ClassLoader appClassLoader, File optimizedDirectory, List<File> dexJars) {
SystemClassLoaderAdder classLoaderAdder = new SystemClassLoaderAdder();
for (File dexJar : dexJars) {
DexClassLoader newClassLoader = new DexClassLoader(dexJar.getAbsolutePath(), optimizedDirectory.getAbsolutePath(), null, appClassLoader);
classLoaderAdder.addPathsOfClassLoaderToSystemClassLoader(newClassLoader, (PathClassLoader) appClassLoader);
}
}Example 50
| Project: ShareFV-master File: AndroidClassLoader.java View source code |
public void init() throws IOException {
if (_path == null || "".equals(_path.trim()))
_delegate = new DexClassLoader("", ((WebAppContext) getContext()).getTempDirectory().getCanonicalPath(), null, _parent);
else
_delegate = new DexClassLoader(_path, ((WebAppContext) getContext()).getTempDirectory().getCanonicalPath(), null, _parent);
if (Log.isDebugEnabled())
Log.debug("Android webapp classloader path= " + _path + " tmpdir=" + ((WebAppContext) getContext()).getTempDirectory() + " dexloader = " + _delegate + " parentloader=" + _parent);
}Example 51
| Project: test4XXX-master File: PatchMain.java View source code |
private static PatchResult loadAllCallbacks(Context context, String apkPath, ClassLoader cl) {
try {
// String dexPath = new File(context.getFilesDir(), apkPath.).getAbsolutePath();
File dexoptFile = new File(apkPath + "odex");
if (dexoptFile.exists()) {
dexoptFile.delete();
}
ClassLoader mcl = null;
try {
mcl = new DexClassLoader(apkPath, context.getFilesDir().getAbsolutePath(), null, cl);
} catch (Throwable e) {
return new PatchResult(false, PatchResult.FOUND_PATCH_CLASS_EXCEPTION, "Find patch class exception ", e);
}
DexFile dexFile = DexFile.loadDex(apkPath, context.getFilesDir().getAbsolutePath() + File.separator + "patch.odex", 0);
Enumeration<String> entrys = dexFile.entries();
// clean old callback
synchronized (loadedPatchCallbacks) {
loadedPatchCallbacks.clear();
}
while (entrys.hasMoreElements()) {
String entry = entrys.nextElement();
Class<?> entryClass = null;
try {
entryClass = mcl.loadClass(entry);
} catch (ClassNotFoundException e) {
e.printStackTrace();
break;
}
if (isImplementInterface(entryClass, IPatch.class)) {
Object moduleInstance = entryClass.newInstance();
hookLoadPatch(new PatchCallback((IPatch) moduleInstance));
}
}
} catch (Exception e) {
return new PatchResult(false, PatchResult.FOUND_PATCH_CLASS_EXCEPTION, "Find patch class exception ", e);
}
return new PatchResult(true, PatchResult.NO_ERROR, "");
}Example 52
| Project: WeChatMomentStat-Android-master File: Task.java View source code |
public void initSnsReader() {
File outputAPKFile = new File(Config.EXT_DIR + "/wechat.apk");
if (!outputAPKFile.exists())
copyAPKFromAssets();
try {
Config.initWeChatVersion("6.3.13.64_r4488992");
DexClassLoader cl = new DexClassLoader(outputAPKFile.getAbsolutePath(), context.getDir("outdex", 0).getAbsolutePath(), null, ClassLoader.getSystemClassLoader());
Class SnsDetailParser = null;
Class SnsDetail = null;
Class SnsObject = null;
SnsDetailParser = cl.loadClass(Config.SNS_XML_GENERATOR_CLASS);
SnsDetail = cl.loadClass(Config.PROTOCAL_SNS_DETAIL_CLASS);
SnsObject = cl.loadClass(Config.PROTOCAL_SNS_OBJECT_CLASS);
snsReader = new SnsReader(SnsDetail, SnsDetailParser, SnsObject);
} catch (Throwable e) {
Log.e("wechatmomentstat", "exception", e);
}
}Example 53
| Project: ZeusHotfix-master File: HotfixLoaderUtil.java View source code |
/**
* �始化补�框架
*
* @param applicationProxy
* @param context
* @return trueè¡¨æ˜ŽåŠ è½½äº†è¡¥ä¸?框架, falseè¡¨æ˜Žæ²¡æœ‰åŠ è½½è¡¥ä¸?框架
*/
protected static Application attachBaseContext(Application applicationProxy, final Context context) {
Util.createDir(Util.getInsideHotfixPath(context));
Util.createDir(Util.getSdcardHotfixPath(context));
//åˆ¤æ–æ˜¯å?¦æ˜¯ä¸»è¿›ç¨‹
boolean isMainProcess = true;
if (!context.getPackageName().equals(getCurProcessName(context))) {
isMainProcess = false;
}
final String pathInfo = readPathInfo(context, isMainProcess);
//当å‰?Resouces指å?‘çš„apk为补ä¸?文件夹å?³å½“å‰?å·²ç»?åŠ è½½è¿‡è¡¥ä¸?了,防æ¢è®¤ä¸ºå¤šæ¬¡è°ƒç”¨ï¼Œæˆ–者如果补ä¸?apkä¸?å˜åœ¨ï¼Œç›´æŽ¥é€€å‡º
if (Util.isEmpty(pathInfo) || context.getPackageResourcePath().equals(Util.getHotfixApkPath(context, pathInfo)) || !Util.fileExists(Util.getHotfixApkPath(context, pathInfo))) {
return loadApplication(applicationProxy, context);
}
HotfixMeta HotfixMeta = getHotfixMeta(context, pathInfo);
HotfixMeta currentMeta = getCurrentApkMeta(context);
//æ ¡éªŒé…?置信æ?¯æ˜¯å?¦æ”¯æŒ?åŠ è½½è¡¥ä¸?
if (HotfixMeta == null || currentMeta == null || HotfixMeta.getVersion() < 1 || HotfixMeta.getVersionCode() < 1 || //如果补ä¸?çš„version codeå°?于当å‰?版本则ä¸?åŠ è½½è¡¥ä¸?
HotfixMeta.getVersion() != currentMeta.getVersion() || currentMeta.getVersionCode() > HotfixMeta.getVersionCode()) {
//è¡¥ä¸?文件æ?Ÿå??或者补ä¸?版本比宿主还低,这时清ç?†æ¸…ç?†è¡¥ä¸?
if (isMainProcess) {
new Thread(new Runnable() {
@Override
public void run() {
//清空补�目录下所有文件和文件夹
Util.deleteFilesInDirectory(Util.getSdcardHotfixPath(context));
Util.deleteFilesInDirectory(Util.getInsideHotfixPath(context));
}
}).start();
}
return loadApplication(applicationProxy, context);
}
//如果优化å?Žçš„odex文件ä¸?å˜åœ¨ï¼Œåˆ™åŽ»ä¼˜åŒ–odex文件,且当å‰?ä¸?åŠ è½½è¡¥ä¸?,防æ¢å‡ºçްanr
if (!new File(Util.getInsideHotfixVersionPath(context, pathInfo)).exists()) {
new Thread(new Runnable() {
@Override
public void run() {
new DexClassLoader(Util.getHotfixApkPath(context, pathInfo), Util.getInsideHotfixVersionPath(context, pathInfo), "", context.getClassLoader().getParent());
}
}).start();
return loadApplication(applicationProxy, context);
}
ApplicationInfo applicationInfo = context.getApplicationInfo();
Object packageInfo = Util.getField(context, "mPackageInfo");
try {
//设置当�的ClassLoader为补�apk创建的ClassLoader
DexClassLoader dexClassLoader = new DexClassLoader(Util.getHotfixApkPath(context, pathInfo), Util.getInsideHotfixVersionPath(context, pathInfo), Util.getNativeLibPath(context, pathInfo), context.getClassLoader().getParent());
Util.setField(packageInfo, "mClassLoader", dexClassLoader);
// 设置mResDir为补�apk的路径,如果mResources为null,则系统会使用该地�创建一个Resources
Util.setField(packageInfo, "mResDir", Util.getHotfixApkPath(context, pathInfo));
// 设置mAppDir为补�apk的路径,它影�context.getPackageCodePath()结果
Util.setField(packageInfo, "mAppDir", Util.getHotfixApkPath(context, pathInfo));
//设置mLibDirå½±å“?å˜æ”¾so文件路径地å?€
Util.setField(packageInfo, "mLibDir", Util.getNativeLibPath(context, pathInfo));
//设置mResources为null,以便系统使用之�设置的mResDir创建新的Resources
Util.setField(packageInfo, "mResources", null);
applicationInfo.sourceDir = Util.getHotfixApkPath(context, pathInfo);
applicationInfo.publicSourceDir = Util.getHotfixApkPath(context, pathInfo);
applicationInfo.nativeLibraryDir = Util.getNativeLibPath(context, pathInfo);
} catch (Throwable e) {
e.printStackTrace();
}
// 获�mActivityThread
Object activityThread = Util.getField(packageInfo, "mActivityThread");
// 设置mResources�数
Class<? extends Object> packInfoClass = packageInfo.getClass();
Class[] arrayOfClass = new Class[1];
arrayOfClass[0] = activityThread.getClass();
// 让系统自己设置Resources,该Resources为补�apk的Resources
try {
packInfoClass.getDeclaredMethod("getResources", arrayOfClass).invoke(packageInfo, new Object[] { activityThread });
} catch (Exception e) {
}
String versionName = HotfixMeta.getVersionName();
int versionCode = HotfixMeta.getVersionCode();
// 获�sPackageManager
Object packageManager;
try {
packageManager = activityThread.getClass().getMethod("getPackageManager", new Class[0]).invoke(null, new Object[0]);
//å› ä¸ºpackageManager是IBinder接å?£å¯¹è±¡ï¼Œè¿™é‡Œå?¯ä»¥è®¾ç½®åЍæ€?代ç?†
Object packageManagerPoxy = Proxy.newProxyInstance(applicationProxy.getClass().getClassLoader(), packageManager.getClass().getInterfaces(), new PackageManagerInvocation(packageManager, context, versionCode, versionName, pathInfo));
Util.setField(activityThread, "sPackageManager", packageManagerPoxy);
Util.setField(applicationProxy.getPackageManager(), "mPM", packageManagerPoxy);
} catch (Exception exception1) {
exception1.printStackTrace();
}
final boolean finalIsMainProcess = isMainProcess;
new Thread(new Runnable() {
@Override
public void run() {
//é™?低线程优先级防æ¢é˜»å¡žUI线程
Process.setThreadPriority(Process.THREAD_PRIORITY_LOWEST);
//进行ç¾å??æ ¡éªŒï¼Œæ ¡éªŒå¤±è´¥åˆ™æ?€æ»è¿›ç¨‹
try {
Signature[] hotfixSignature = Util.getApkSignature(Util.getHotfixApkPath(context, pathInfo), context);
Signature[] currentSignature = Util.getPackageSignature(context.getPackageName(), context);
if (!hotfixSignature[0].equals(currentSignature[0])) {
Process.killProcess(Process.myPid());
}
} catch (Exception e) {
Process.killProcess(Process.myPid());
}
if (finalIsMainProcess) {
//记录主进程当�使用补�版本
Util.writeString(Util.getOtherPathInfoPath(context, HOTFIX_NEW_PATHINFO_PATH), pathInfo);
//如果当å‰?åŠ è½½çš„è¡¥ä¸?版本与其他进程的补ä¸?版本ä¸?一致,则é‡?å?¯å…¶ä»–进程
if (Util.fileExists(Util.getOtherPathInfoPath(context, HOTFIX_OLD_PATHINFO_PATH))) {
String oldPathInfo = Util.readString(Util.getOtherPathInfoPath(context, HOTFIX_OLD_PATHINFO_PATH));
if (Util.isEmpty(oldPathInfo) && !pathInfo.equals(oldPathInfo)) {
Util.resetPackagerOtherProcess(context);
}
}
//ä¸»è¿›ç¨‹åˆ™æ¸…é™¤å…¶ä»–æ— æ•ˆçš„è¡¥ä¸?以释放å˜å‚¨ç©ºé—´
clearOldHotfix(context, pathInfo);
} else {
//记录é?žä¸»è¿›ç¨‹ä½¿ç”¨çš„版本,这个值这个时候是ç‰äºŽä¸»è¿›ç¨‹åŠ è½½çš„è¡¥ä¸?的版本
//如果主进程使用新版本补�之�就会读这个值,如果�一致就会���主进程
Util.writeString(Util.getOtherPathInfoPath(context, HOTFIX_OLD_PATHINFO_PATH), pathInfo);
}
}
}).start();
return loadApplication(applicationProxy, context);
}Example 54
| Project: Small-master File: ReflectAccelerator.java View source code |
public static boolean expandDexPathList(ClassLoader cl, String[] dexPaths, DexFile[] dexFiles) {
ZipFile[] zips = null;
try {
/*
* see https://android.googlesource.com/platform/libcore/+/android-2.3_r1/dalvik/src/main/java/dalvik/system/DexClassLoader.java
*/
if (sDexClassLoader_mFiles_field == null) {
sDexClassLoader_mFiles_field = getDeclaredField(cl.getClass(), "mFiles");
sDexClassLoader_mPaths_field = getDeclaredField(cl.getClass(), "mPaths");
sDexClassLoader_mZips_field = getDeclaredField(cl.getClass(), "mZips");
sDexClassLoader_mDexs_field = getDeclaredField(cl.getClass(), "mDexs");
}
if (sDexClassLoader_mFiles_field == null || sDexClassLoader_mPaths_field == null || sDexClassLoader_mZips_field == null || sDexClassLoader_mDexs_field == null) {
return false;
}
int N = dexPaths.length;
Object[] files = new Object[N];
Object[] paths = new Object[N];
zips = new ZipFile[N];
for (int i = 0; i < N; i++) {
String path = dexPaths[i];
files[i] = new File(path);
paths[i] = path;
zips[i] = new ZipFile(path);
}
expandArray(cl, sDexClassLoader_mFiles_field, files, true);
expandArray(cl, sDexClassLoader_mPaths_field, paths, true);
expandArray(cl, sDexClassLoader_mZips_field, zips, true);
expandArray(cl, sDexClassLoader_mDexs_field, dexFiles, true);
} catch (Exception e) {
e.printStackTrace();
if (zips != null) {
for (ZipFile zipFile : zips) {
try {
zipFile.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
return false;
}
return true;
}Example 55
| Project: ACDD-master File: BundleArchiveRevision.java View source code |
public synchronized void optDexFile() {
if (!isDexOpted()) {
if (OpenAtlasHacks.LexFile == null || OpenAtlasHacks.LexFile.getmClass() == null) {
File oDexFile = new File(this.revisionDir, BUNDLE_ODEX_FILE);
long currentTimeMillis = System.currentTimeMillis();
try {
if (!OpenAtlasFileLock.getInstance().LockExclusive(oDexFile)) {
log.error("Failed to get file lock for " + this.bundleFile.getAbsolutePath());
}
if (oDexFile.length() <= 0) {
InitExecutor.optDexFile(this.bundleFile.getAbsolutePath(), oDexFile.getAbsolutePath());
loadDex(oDexFile);
OpenAtlasFileLock.getInstance().unLock(oDexFile);
// "bundle archieve dexopt bundle " +
// this.bundleFile.getAbsolutePath() + " cost time = " +
// (System.currentTimeMillis() - currentTimeMillis) +
// " ms";
}
} catch (Throwable e) {
log.error("Failed optDexFile '" + this.bundleFile.getAbsolutePath() + "' >>> ", e);
} finally {
OpenAtlasFileLock mAtlasFileLock = OpenAtlasFileLock.getInstance();
mAtlasFileLock.unLock(oDexFile);
}
} else {
DexClassLoader dexClassLoader = new DexClassLoader(this.bundleFile.getAbsolutePath(), this.revisionDir.getAbsolutePath(), null, ClassLoader.getSystemClassLoader());
}
}
}Example 56
| Project: android-runtime-master File: DexFactory.java View source code |
public Class<?> resolveClass(String name, String className, String[] methodOverrides, String[] implementedInterfaces, boolean isInterface) throws ClassNotFoundException, IOException {
String fullClassName = className.replace("$", "_");
if (!isInterface) {
fullClassName += CLASS_NAME_LOCATION_SEPARATOR + name;
}
// try to get pre-generated binding classes
try {
if (logger.isEnabled()) {
logger.write("getting pre-generated proxy class with name: " + fullClassName.replace("-", "_"));
}
Class<?> pregeneratedClass = classLoader.loadClass(fullClassName.replace("-", "_"));
if (logger.isEnabled()) {
logger.write("Pre-generated class found: " + fullClassName.replace("-", "_"));
}
return pregeneratedClass;
} catch (Exception e) {
}
//
Class<?> existingClass = this.injectedDexClasses.get(fullClassName);
if (existingClass != null) {
return existingClass;
}
String classToProxy = this.getClassToProxyName(className);
String dexFilePath = classToProxy;
if (!isInterface) {
dexFilePath += CLASS_NAME_LOCATION_SEPARATOR + name;
}
File dexFile = this.getDexFile(dexFilePath);
// generate dex file
if (dexFile == null) {
long startGenTime = System.nanoTime();
if (logger.isEnabled()) {
logger.write("generating proxy in place");
}
dexFilePath = this.generateDex(name, classToProxy, methodOverrides, implementedInterfaces, isInterface);
dexFile = new File(dexFilePath);
long stopGenTime = System.nanoTime();
totalGenTime += stopGenTime - startGenTime;
if (logger.isEnabled()) {
logger.write("Finished inplace gen took: " + (stopGenTime - startGenTime) / 1000000.0 + "ms");
logger.write("TotalGenTime: " + totalGenTime / 1000000.0 + "ms");
}
}
// creates jar file from already generated dex file
String jarFilePath = dexFile.getPath().replace(".dex", ".jar");
File jarFile = new File(jarFilePath);
if (!jarFile.exists()) {
FileOutputStream jarFileStream = new FileOutputStream(jarFile);
ZipOutputStream out = new ZipOutputStream(jarFileStream);
out.putNextEntry(new ZipEntry("classes.dex"));
byte[] dexData = new byte[(int) dexFile.length()];
FileInputStream fi = new FileInputStream(dexFile);
fi.read(dexData, 0, dexData.length);
fi.close();
out.write(dexData);
out.closeEntry();
out.close();
}
//
Class<?> result = null;
DexFile df = null;
try {
// use DexFile instead of DexClassLoader to allow class loading
// within the default class loader
// Note: According to the official documentation, DexFile should not
// be directly used.
// However, this is the only viable way to get our dynamic classes
// loaded within the system class loader
df = DexFile.loadDex(jarFilePath, new File(this.odexDir, fullClassName).getAbsolutePath(), 0);
result = df.loadClass(fullClassName, classLoader);
} catch (IOException e) {
e.printStackTrace();
DexClassLoader dexClassLoader = new DexClassLoader(jarFilePath, this.odexDir.getAbsolutePath(), null, classLoader);
result = dexClassLoader.loadClass(fullClassName);
}
this.injectedDexClasses.put(fullClassName, result);
return result;
}Example 57
| Project: AndroidStudyDemo-master File: ProxyApplication.java View source code |
//这是context 赋值
@Override
protected void attachBaseContext(Context base) {
super.attachBaseContext(base);
try {
//创建两个文件夹payload_odex,payload_lib �有的,�写的文件目录
File odex = this.getDir("payload_odex", MODE_PRIVATE);
File libs = this.getDir("payload_lib", MODE_PRIVATE);
odexPath = odex.getAbsolutePath();
libPath = libs.getAbsolutePath();
apkFileName = odex.getAbsolutePath() + "/payload.apk";
File dexFile = new File(apkFileName);
if (!dexFile.exists()) {
//在payload_odex文件夹内,创建payload.apk
dexFile.createNewFile();
// 读�程�classes.dex文件
byte[] dexdata = this.readDexFileFromApk();
// 分离出解壳å?Žçš„apk文件已用于动æ€?åŠ è½½
this.splitPayLoadFromDex(dexdata);
}
// é…?置动æ€?åŠ è½½çŽ¯å¢ƒ
Object currentActivityThread = RefInvokeUtil.invokeStaticMethod("android.app.ActivityThread", "currentActivityThread", new Class[] {}, //获�主线程对象 http://blog.csdn.net/myarrow/article/details/14223493
new Object[] {});
//当å‰?apk的包å??
String packageName = this.getPackageName();
//下�两��是太�解
HashMap mPackages = (HashMap) RefInvokeUtil.getFieldOjbect("android.app.ActivityThread", currentActivityThread, "mPackages");
WeakReference wr = (WeakReference) mPackages.get(packageName);
//åˆ›å»ºè¢«åŠ å£³apkçš„DexClassLoader对象 åŠ è½½apk内的类和本地代ç ?(c/c++代ç ?)
DexClassLoader dLoader = new DexClassLoader(apkFileName, odexPath, libPath, (ClassLoader) RefInvokeUtil.getFieldOjbect("android.app.LoadedApk", wr.get(), "mClassLoader"));
//base.getClassLoader(); 是ä¸?是就ç‰å?ŒäºŽ (ClassLoader) RefInvokeUtilUtil.getFieldOjbect()? 有空验è¯?下//?
//把当å‰?进程的DexClassLoader 设置æˆ?äº†è¢«åŠ å£³apkçš„DexClassLoader ----有点c++ä¸è¿›ç¨‹çŽ¯å¢ƒçš„æ„?æ€?~~
RefInvokeUtil.setFieldOjbect("android.app.LoadedApk", "mClassLoader", wr.get(), dLoader);
} catch (Exception e) {
e.printStackTrace();
}
}Example 58
| Project: dexknife-wj-master File: DexProtector.java View source code |
/**
* åŠ è½½åŠ å¯†å?Žçš„dex文件
*
* @param dexInput åŠ å¯†çš„dex文件的输入æµ?
* @return ClassLoader
*/
public ClassLoader loadEncryptDex(String[] dexName) {
try {
//通过å??射修改ActivityThreadä¸LoadedApkçš„ClassLoaderå—æ®µ
ClassLoader appClassLoader = ClassLoader.getSystemClassLoader();
String pahts = "";
for (int i = 0; i < dexName.length; i++) {
// 优先系统的
pahts += createEncryptDexLoader(context.getAssets().open("jiagu_data.bin/" + dexName[i]), dexName[i], appClassLoader) + ":";
}
// �过优化的dex输出目录
File odexDir = context.getDir("apktoolplus_odex", Context.MODE_PRIVATE);
// libs目录
String libPath = context.getApplicationInfo().nativeLibraryDir;
// åˆ›å»ºç±»åŠ è½½å™¨ï¼ŒåŠ è½½è§£å¯†å?Žçš„dex文件
ClassLoader dexClassLoader;
if (appClassLoader != null) {
dexClassLoader = new DexClassLoader(pahts, odexDir.getAbsolutePath(), libPath, appClassLoader);
} else {
dexClassLoader = new DexClassLoader(pahts, odexDir.getAbsolutePath(), libPath, context.getClassLoader());
}
// 修改当�ClassLoader为自定义ClassLoader
setAppClassLoader(dexClassLoader);
// åˆ é™¤è§£å¯†å?Žçš„dex文件
deleteDir(context.getDir("apktoolplus_dex", Context.MODE_PRIVATE));
return dexClassLoader;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}Example 59
| Project: ghostcommander-supath-master File: CA.java View source code |
/**
* CreateExternalAdapter Tries to load an adapter class from foreign package
* @param String type - adapter type, also the suffix of the plugin application
* @param String class_name - the adapter class name to be loaded
* @param int dialog_id - resource ID to show dialog if the class can't be loaded
*/
public static CommanderAdapter CreateExternalAdapter(Context ctx, String type, String class_name) {
try {
File dex_f = ctx.getDir(type, Context.MODE_PRIVATE);
if (dex_f == null || !dex_f.exists()) {
Log.w(TAG, "app.data storage is not accessable, trying to use the SD card");
File sd = Environment.getExternalStorageDirectory();
// nowhere to store the dex :(
if (sd == null)
return null;
dex_f = new File(sd, "temp");
if (!dex_f.exists())
dex_f.mkdir();
}
ApplicationInfo ai = ctx.getPackageManager().getApplicationInfo("com.ghostsq.commander." + type, 0);
Log.i(TAG, type + " package is " + ai.sourceDir);
ClassLoader pcl = ctx.getClass().getClassLoader();
DexClassLoader cl = new DexClassLoader(ai.sourceDir, dex_f.getAbsolutePath(), null, pcl);
//
Class<?> adapterClass = cl.loadClass("com.ghostsq.commander." + type + "." + class_name);
Log.i(TAG, "Class has been loaded " + adapterClass.toString());
try {
File[] list = dex_f.listFiles();
for (int i = 0; i < list.length; i++) list[i].delete();
} catch (Exception e) {
Log.w(TAG, "Can't remove the plugin's .dex: ", e);
}
if (adapterClass != null) {
Constructor<?> constr = null;
try {
constr = adapterClass.getConstructor(Context.class);
} catch (Exception e) {
e.printStackTrace();
}
if (constr != null)
return (CommanderAdapter) constr.newInstance(ctx);
else
return (CommanderAdapter) adapterClass.newInstance();
}
} catch (Throwable e) {
Log.e(TAG, "This class can't be created: " + type, e);
}
return null;
}Example 60
| Project: openxface-android-master File: XPluginLoader.java View source code |
/**
* 动æ€?从jar文件ä¸è¯»å?–æ?’ä»¶é…?ç½®
*
* @param ctx
* @param jarPath
* jar文件的文件夹
* @return
*/
private void loadPluginFromJar(XExtensionContext ctx) {
// �数检查
if (null == mJarFolder || null == mWriteableDir || !new File(mWriteableDir).exists() || !new File(mWriteableDir).exists()) {
return;
}
if (!mJarLoaderMap.isEmpty()) {
// 通过这里ä¿?è¯?引擎å?¯åЍ å?ªåŠ è½½ä¸€æ¬¡
for (XEntry value : mJarLoaderMap.values()) {
loadPluginFromMap(ctx, value.mLoader, value.mPluginDescription);
}
return;
}
File[] files = new File(mJarFolder).listFiles(new ModuleFilter());
for (File jar : files) {
try {
DexClassLoader cl = new DexClassLoader(jar.getAbsolutePath(), mWriteableDir, null, ctx.getSystemContext().getContext().getClassLoader());
JarFile jarFile = new JarFile(jar);
Manifest manifest = jarFile.getManifest();
String pluginDes = manifest.getMainAttributes().getValue(PLUGIN_JAR_ENTRY_TAG);
if (null == pluginDes) {
continue;
}
Class<?> libProviderClazz = cl.loadClass(pluginDes);
XIPluginDescription obj = (XIPluginDescription) libProviderClazz.newInstance();
HashMap<String, String> map = obj.getPluginDesciption();
loadPluginFromMap(ctx, cl, map);
mJarLoaderMap.put(jar.getAbsolutePath(), new XEntry(cl, map));
} catch (ClassNotFoundException e) {
handleLoadExceptionFromJar(e, jar, " Load class dynamicly error.");
} catch (IllegalAccessException e) {
handleLoadExceptionFromJar(e, jar, " lllegal access error when instance plugin.");
} catch (InstantiationException e) {
handleLoadExceptionFromJar(e, jar, " instance plugin error.");
} catch (IOException e) {
handleLoadExceptionFromJar(e, jar, "init jar package error.");
}
}
}Example 61
| Project: tinker-master File: SystemClassLoaderAdder.java View source code |
private static void install(ClassLoader loader, List<File> additionalClassPathEntries, File optimizedDirectory) 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 = ShareReflectUtil.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);
//edit by zhangshaowen
String outputPathName = SharePatchFileUtil.optimizedPathFor(additionalEntry, optimizedDirectory);
//for below 4.0, we must input jar or zip
extraDexs[index] = DexFile.loadDex(entryPath, outputPathName, 0);
}
pathField.set(loader, path.toString());
ShareReflectUtil.expandFieldArray(loader, "mPaths", extraPaths);
ShareReflectUtil.expandFieldArray(loader, "mFiles", extraFiles);
ShareReflectUtil.expandFieldArray(loader, "mZips", extraZips);
try {
ShareReflectUtil.expandFieldArray(loader, "mDexs", extraDexs);
} catch (Exception e) {
}
}Example 62
| Project: appcan-android-master File: ThirdPluginMgr.java View source code |
// å› ä¸ºä¹‹å‰?çš„æ–¹æ³•æ— æ³•æ›¿æ?¢å?进程的classloader,故改æˆ?以下的方å¼?。由于æ¯?一个进程åˆ?始化的时候都会åˆ?始化一次他的application,而且默认的classloader是和applicationçš„classloaderä¸€æ ·çš„
// 故在applicationåˆ?始化的时候,替æ?¢æŽ‰applicationçš„classloader。之å‰?å?ªæœ‰åœ¨ä¸»è¿›ç¨‹ä¸æ‰?替æ?¢æŽ‰applicationçš„loader,所以å?è¿›ç¨‹è¿˜æ˜¯æ— æ³•åŠ è½½åŠ¨æ€?æ?’ä»¶
private void initClassLoader() {
try {
pluginJars = mContext.getAssets().list(dexJar);
if (pluginJars != null && pluginJars.length > 0) {
// create the dexPath
int PluginCount = pluginJars.length;
String dexPath = libsParentDir + File.separator + dexJar;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < PluginCount; i++) {
sb.append(dexPath).append(File.separator).append(pluginJars[i]).append(File.pathSeparator);
}
dexPath = sb.toString();
// create the optPath
String optPath = libsParentDir + File.separator + optFile;
File dirFile = new File(optPath);
if (!dirFile.exists()) {
dirFile.mkdirs();
}
String libPath = libsParentDir + File.separator + dexLib;
// create the dexclassloader
DexClassLoader dexCl = new DexClassLoader(dexPath, optPath, libPath, mContext.getClassLoader());
replaceCurrentClassLoader(dexCl);
}
/*
* Field mMainThread =
* Activity.class.getDeclaredField("mMainThread");
* mMainThread.setAccessible(true); Object mainThread =
* mMainThread.get((EBrowserActivity) context); Class threadClass =
* mainThread.getClass(); Field mPackages =
* threadClass.getDeclaredField("mPackages");
* mPackages.setAccessible(true); WeakReference<?> ref; Map<String,
* ?> map = (Map<String, ?>) mPackages.get(mainThread); ref =
* (WeakReference<?>) map.get(context.getPackageName()); Object apk
* = ref.get(); Class apkClass = apk.getClass();
*
* Field mClassLoader = apkClass.getDeclaredField("mClassLoader");
* mClassLoader.setAccessible(true); mClassLoader.set(apk, dexCl);
*/
} catch (Exception e) {
e.printStackTrace();
}
}Example 63
| Project: CSipSimple-master File: VideoCaptureDeviceInfoAndroid.java View source code |
// Returns a handle to HTC front facing camera.
// The caller is responsible to release it on completion.
private Camera AllocateEVOFrontFacingCamera() throws SecurityException, NoSuchMethodException, ClassNotFoundException, IllegalArgumentException, IllegalAccessException, InvocationTargetException {
String classPath = null;
File file = new File("/system/framework/com.htc.hardware.twinCamDevice.jar");
classPath = "com.htc.hardware.twinCamDevice.FrontFacingCamera";
boolean exists = file.exists();
if (!exists) {
file = new File("/system/framework/com.sprint.hardware.twinCamDevice.jar");
classPath = "com.sprint.hardware.twinCamDevice.FrontFacingCamera";
exists = file.exists();
}
if (!exists) {
return null;
}
String dexOutputDir = "";
if (context != null) {
dexOutputDir = context.getFilesDir().getAbsolutePath();
File mFilesDir = new File(dexOutputDir, "dexfiles");
if (!mFilesDir.exists()) {
// Log.e("*WEBRTCN*", "Directory doesn't exists");
if (!mFilesDir.mkdirs()) {
// Log.e("*WEBRTCN*", "Unable to create files directory");
}
}
}
dexOutputDir += "/dexfiles";
DexClassLoader loader = new DexClassLoader(file.getAbsolutePath(), dexOutputDir, null, ClassLoader.getSystemClassLoader());
Method method = ((ClassLoader) loader).loadClass(classPath).getDeclaredMethod("getFrontFacingCamera", (Class[]) null);
Camera camera = (Camera) method.invoke((Object[]) null, (Object[]) null);
return camera;
}Example 64
| Project: CSipSimple-old-master File: VideoCaptureDeviceInfoAndroid.java View source code |
// Returns a handle to HTC front facing camera.
// The caller is responsible to release it on completion.
private Camera AllocateEVOFrontFacingCamera() throws SecurityException, NoSuchMethodException, ClassNotFoundException, IllegalArgumentException, IllegalAccessException, InvocationTargetException {
String classPath = null;
File file = new File("/system/framework/com.htc.hardware.twinCamDevice.jar");
classPath = "com.htc.hardware.twinCamDevice.FrontFacingCamera";
boolean exists = file.exists();
if (!exists) {
file = new File("/system/framework/com.sprint.hardware.twinCamDevice.jar");
classPath = "com.sprint.hardware.twinCamDevice.FrontFacingCamera";
exists = file.exists();
}
if (!exists) {
return null;
}
String dexOutputDir = "";
if (context != null) {
dexOutputDir = context.getFilesDir().getAbsolutePath();
File mFilesDir = new File(dexOutputDir, "dexfiles");
if (!mFilesDir.exists()) {
// Log.e("*WEBRTCN*", "Directory doesn't exists");
if (!mFilesDir.mkdirs()) {
// Log.e("*WEBRTCN*", "Unable to create files directory");
}
}
}
dexOutputDir += "/dexfiles";
DexClassLoader loader = new DexClassLoader(file.getAbsolutePath(), dexOutputDir, null, ClassLoader.getSystemClassLoader());
Method method = ((ClassLoader) loader).loadClass(classPath).getDeclaredMethod("getFrontFacingCamera", (Class[]) null);
Camera camera = (Camera) method.invoke((Object[]) null, (Object[]) null);
return camera;
}Example 65
| Project: DroidFix-master File: DroidFix.java View source code |
private static void install(ClassLoader loader, List<File> additionalClassPathEntries, File optimizedDirectory, boolean isHotfix) throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException, InvocationTargetException, NoSuchMethodException, InstantiationException {
Field pathListField = findField(loader, "pathList");
Object dexPathList = pathListField.get(loader);
Field dexElement = findField(dexPathList, "dexElements");
Class<?> elementType = dexElement.getType().getComponentType();
//DexClassLoader dexClassLoader=new DexClassLoader(additionalClassPathEntries.get(0).getAbsolutePath(),optimizedDirectory.getAbsolutePath(),"",null);
Method loadDex = findMethod(dexPathList, "loadDexFile", File.class, File.class);
loadDex.setAccessible(true);
Object dex = loadDex.invoke(null, additionalClassPathEntries.get(0), optimizedDirectory);
Constructor<?> constructor = elementType.getConstructor(File.class, boolean.class, File.class, DexFile.class);
constructor.setAccessible(true);
Object element = constructor.newInstance(new File(""), false, additionalClassPathEntries.get(0), dex);
Object[] newEles = new Object[1];
newEles[0] = element;
expandFieldArray(dexPathList, "dexElements", newEles, isHotfix);
}Example 66
| Project: dynamic-load-apk-master File: DLPluginManager.java View source code |
/**
* prepare plugin runtime env, has DexClassLoader, Resources, and so on.
*
* @param packageInfo
* @param dexPath
* @return
*/
private DLPluginPackage preparePluginEnv(PackageInfo packageInfo, String dexPath) {
DLPluginPackage pluginPackage = mPackagesHolder.get(packageInfo.packageName);
if (pluginPackage != null) {
return pluginPackage;
}
DexClassLoader dexClassLoader = createDexClassLoader(dexPath);
AssetManager assetManager = createAssetManager(dexPath);
Resources resources = createResources(assetManager);
// create pluginPackage
pluginPackage = new DLPluginPackage(dexClassLoader, resources, packageInfo);
mPackagesHolder.put(packageInfo.packageName, pluginPackage);
return pluginPackage;
}Example 67
| Project: neembuunow-master File: ak.java View source code |
private static void f(Context paramContext) throws ak.a {
try {
arrayOfByte1 = an.a(ao.a());
arrayOfByte2 = an.a(arrayOfByte1, ao.b());
localFile1 = paramContext.getCacheDir();
if (localFile1 == null) {
localFile1 = paramContext.getDir("dex", 0);
if (localFile1 == null) {
throw new a();
}
}
} catch (ap localap) {
byte[] arrayOfByte1;
byte[] arrayOfByte2;
File localFile1;
throw new a(localap);
File localFile2 = File.createTempFile("ads", ".jar", localFile1);
FileOutputStream localFileOutputStream = new FileOutputStream(localFile2);
localFileOutputStream.write(arrayOfByte2, 0, arrayOfByte2.length);
localFileOutputStream.close();
DexClassLoader localDexClassLoader = new DexClassLoader(localFile2.getAbsolutePath(), localFile1.getAbsolutePath(), null, paramContext.getClassLoader());
Class localClass1 = localDexClassLoader.loadClass(b(arrayOfByte1, ao.c()));
Class localClass2 = localDexClassLoader.loadClass(b(arrayOfByte1, ao.i()));
Class localClass3 = localDexClassLoader.loadClass(b(arrayOfByte1, ao.g()));
Class localClass4 = localDexClassLoader.loadClass(b(arrayOfByte1, ao.k()));
Class localClass5 = localDexClassLoader.loadClass(b(arrayOfByte1, ao.e()));
d = localClass1.getMethod(b(arrayOfByte1, ao.d()), new Class[0]);
e = localClass2.getMethod(b(arrayOfByte1, ao.j()), new Class[0]);
String str1 = b(arrayOfByte1, ao.h());
Class[] arrayOfClass1 = new Class[1];
arrayOfClass1[0] = Context.class;
f = localClass3.getMethod(str1, arrayOfClass1);
String str2 = b(arrayOfByte1, ao.l());
Class[] arrayOfClass2 = new Class[2];
arrayOfClass2[0] = MotionEvent.class;
arrayOfClass2[1] = DisplayMetrics.class;
g = localClass4.getMethod(str2, arrayOfClass2);
String str3 = b(arrayOfByte1, ao.f());
Class[] arrayOfClass3 = new Class[1];
arrayOfClass3[0] = Context.class;
h = localClass5.getMethod(str3, arrayOfClass3);
String str4 = localFile2.getName();
localFile2.delete();
new File(localFile1, str4.replace(".jar", ".dex")).delete();
return;
} catch (FileNotFoundException localFileNotFoundException) {
throw new a(localFileNotFoundException);
} catch (IOException localIOException) {
throw new a(localIOException);
} catch (ClassNotFoundException localClassNotFoundException) {
throw new a(localClassNotFoundException);
} catch (an.a locala) {
throw new a(locala);
} catch (NoSuchMethodException localNoSuchMethodException) {
throw new a(localNoSuchMethodException);
} catch (NullPointerException localNullPointerException) {
throw new a(localNullPointerException);
}
}Example 68
| Project: NoTauLabsNag-master File: OPTelemetryService.java View source code |
/**
* Load the UAVObjects from a JAR file. This method must be called in the
* service context.
* @return True if success, False otherwise
*/
public boolean loadUavobjects(String jar, UAVObjectManager objMngr) {
final String JAR_DIR = "jars";
final String DEX_DIR = "optimized_dex";
File jarsDir = getDir(JAR_DIR, MODE_WORLD_READABLE);
if (jarsDir.exists())
deleteDirectoryContents(jarsDir);
copyAssets(JAR_DIR, jar);
Log.d(TAG, "Starting dex loader");
File dexDir = getDir(DEX_DIR, Context.MODE_WORLD_READABLE);
// Necessary to get dexOpt to run
if (dexDir.exists())
deleteDirectoryContents(dexDir);
String classpath = new File(jarsDir, jar).getAbsolutePath();
// does this help?
Thread.currentThread().setContextClassLoader(getClass().getClassLoader());
DexClassLoader loader = new DexClassLoader(classpath, dexDir.getAbsolutePath(), null, getClassLoader());
Log.d(TAG, "Done dex loader");
try {
Class<?> initClass = loader.loadClass("org.openpilot_nonag.uavtalk.uavobjects.UAVObjectsInitialize");
Method initMethod = initClass.getMethod("register", UAVObjectManager.class);
initMethod.invoke(null, objMngr);
} catch (ClassNotFoundException e1) {
e1.printStackTrace();
return false;
} catch (IllegalAccessException e1) {
e1.printStackTrace();
return false;
} catch (NoSuchMethodException e1) {
e1.printStackTrace();
return false;
} catch (IllegalArgumentException e) {
e.printStackTrace();
return false;
} catch (InvocationTargetException e) {
e.printStackTrace();
return false;
}
return true;
}Example 69
| Project: atlas-master File: BundleArchiveRevision.java View source code |
public synchronized void optDexFile() {
if (isDexOpted()) {
return;
}
if (AtlasHacks.LexFile != null && AtlasHacks.LexFile.getmClass() != null) {
//yunos
// TODO: need also cover logic of filelocks for YunOS.
new DexClassLoader(bundleFile.getAbsolutePath(), revisionDir.getAbsolutePath(), null, ClassLoader.getSystemClassLoader());
isDexOptDone = true;
return;
}
File odexFile = new File(revisionDir, BUNDLE_ODEX_FILE);
long START = 0;
START = System.currentTimeMillis();
try {
if (AtlasFileLock.getInstance().LockExclusive(odexFile) == false) {
Log.e("Framework", "Failed to get file lock for " + bundleFile.getAbsolutePath());
}
if (dexFile == null) {
dexFile = com.taobao.android.runtime.RuntimeUtils.loadDex(RuntimeVariables.androidApplication, bundleFile.getAbsolutePath(), odexFile.getAbsolutePath(), 0);
//dexFile = DexFile.loadDex(bundleFile.getAbsolutePath(), odexFile.getAbsolutePath(), 0);
}
//9月份版本明天�布先�集�
// isDexOptDone = checkDexValid(dexFile);
isDexOptDone = true;
} catch (IOException e) {
if (odexFile.exists()) {
odexFile.delete();
}
Log.e("Framework", "Failed optDexFile '" + bundleFile.getAbsolutePath() + "' >>> ", e);
AtlasMonitor.getInstance().trace(AtlasMonitor.CONTAINER_DEXOPT_FAIL, false, "0", e == null ? "" : e.getMessage(), bundleFile.getName());
} finally {
AtlasFileLock.getInstance().unLock(odexFile);
}
Log.e("Framework", "bundle archieve dexopt bundle " + bundleFile.getAbsolutePath() + " cost time = " + (System.currentTimeMillis() - START) + " ms");
return;
}Example 70
| Project: android-sdk-sources-for-api-level-23-master File: MultiDex.java View source code |
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);
}Example 71
| Project: appinventor-sources-master File: ReplForm.java View source code |
/**
* This is a nasty hack. For loading external component's dex file so that they can be accessible for
* kawa to load it, when required. This assumes classloader checks class via delegation through the parent
* classloaders. For multiple dex files, we just cascade the classloaders in the hierarchy
*/
public void loadComponents() {
// Store the loaded dex files in the private storage of the App for stable optimization
File dexOutput = activeForm.$context().getDir("componentDexs", activeForm.$context().MODE_PRIVATE);
File componentFolder = new File(REPL_COMP_DIR);
checkComponentDir();
// Current Thread Class Loader
ClassLoader parentClassLoader = Thread.currentThread().getContextClassLoader();
for (File compFolder : componentFolder.listFiles()) {
if (compFolder.isDirectory()) {
File component = new File(compFolder.getPath() + File.separator + "classes.jar");
File loadComponent = new File(compFolder.getPath() + File.separator + compFolder.getName() + ".jar");
component.renameTo(loadComponent);
if (loadComponent.exists() && !loadedExternalDexs.contains(loadComponent.getName())) {
loadedExternalDexs.add(loadComponent.getName());
DexClassLoader dexCloader = new DexClassLoader(loadComponent.getAbsolutePath(), dexOutput.getAbsolutePath(), null, parentClassLoader);
parentClassLoader = dexCloader;
Thread.currentThread().setContextClassLoader(parentClassLoader);
}
}
}
}Example 72
| Project: attentive-ui-master File: MonkeySourceNetworkViews.java View source code |
/**
* Get the ID class for the given package.
* This will cause issues if people reload a package with different
* resource identifiers, but don't restart the Monkey server.
*
* @param packageName The package that we want to retrieve the ID class for
* @return The ID class for the given package
*/
private static Class<?> getIdClass(String packageName, String sourceDir) throws ClassNotFoundException {
// This kind of reflection is expensive, so let's only do it
// if we need to
Class<?> klass = sClassMap.get(packageName);
if (klass == null) {
DexClassLoader classLoader = new DexClassLoader(sourceDir, "/data/local/tmp", null, ClassLoader.getSystemClassLoader());
klass = classLoader.loadClass(packageName + ".R$id");
sClassMap.put(packageName, klass);
}
return klass;
}Example 73
| Project: ContextEngine-master File: ContextEngineCore.java View source code |
private boolean loadClass(String componentName, String dex, String packagename) {
final File optimizedDexOutputPath = context.getDir("outdex", Context.MODE_PRIVATE);
File dexInternalStoragePath;
// if (dex == null)
// dexInternalStoragePath = new File(context.getDir("dex",
// Context.MODE_PRIVATE),
// "classes.dex");
// else
dexInternalStoragePath = new File(context.getDir("dex", Context.MODE_PRIVATE), dex);
DexClassLoader cl = new DexClassLoader(dexInternalStoragePath.getAbsolutePath(), optimizedDexOutputPath.getAbsolutePath(), null, context.getClassLoader());
Class<?> contextClass = null;
Class<?>[] parameterTypes = { Context.class };
try {
// Load the Class
contextClass = cl.loadClass(packagename.concat("." + componentName));
Constructor<?> contextConstructor = contextClass.getConstructor(parameterTypes);
Component context = (Component) contextConstructor.newInstance(this.context);
activeContexts.put(componentName, context);
return true;
} catch (ClassNotFoundException cnfe) {
Log.e(LOG_TAG, "Component does not exist!");
return false;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}Example 74
| Project: dexmaker-master File: DexMaker.java View source code |
private ClassLoader generateClassLoader(File result, File dexCache, ClassLoader parent) {
try {
return (ClassLoader) Class.forName("dalvik.system.DexClassLoader").getConstructor(String.class, String.class, String.class, ClassLoader.class).newInstance(result.getPath(), dexCache.getAbsolutePath(), null, parent);
} catch (ClassNotFoundException e) {
throw new UnsupportedOperationException("load() requires a Dalvik VM", e);
} catch (InvocationTargetException e) {
throw new RuntimeException(e.getCause());
} catch (InstantiationException e) {
throw new AssertionError();
} catch (NoSuchMethodException e) {
throw new AssertionError();
} catch (IllegalAccessException e) {
throw new AssertionError();
}
}Example 75
| Project: fastdex-master File: MultiDex.java View source code |
private static void install(ClassLoader loader, List<? extends 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<? extends 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);
}Example 76
| Project: platform_development-master File: MonkeySourceNetworkViews.java View source code |
/**
* Get the ID class for the given package.
* This will cause issues if people reload a package with different
* resource identifiers, but don't restart the Monkey server.
*
* @param packageName The package that we want to retrieve the ID class for
* @return The ID class for the given package
*/
private static Class<?> getIdClass(String packageName, String sourceDir) throws RemoteException, ClassNotFoundException {
// This kind of reflection is expensive, so let's only do it
// if we need to
Class<?> klass = sClassMap.get(packageName);
if (klass == null) {
DexClassLoader classLoader = new DexClassLoader(sourceDir, "/data/local/tmp", null, ClassLoader.getSystemClassLoader());
klass = classLoader.loadClass(packageName + ".R$id");
sClassMap.put(packageName, klass);
}
return klass;
}Example 77
| Project: RocooFix-master File: RocooFix.java View source code |
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 = RocooUtils.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());
RocooUtils.expandFieldArray(loader, "mPaths", extraPaths);
RocooUtils.expandFieldArray(loader, "mFiles", extraFiles);
RocooUtils.expandFieldArray(loader, "mZips", extraZips);
RocooUtils.expandFieldArray(loader, "mDexs", extraDexs);
}Example 78
| Project: ApkLauncher-master File: ApkPackageManager.java View source code |
public ClassLoader createClassLoader(Context baseContext, String apkPath, String libPath, String targetPackageName, boolean force) {
ClassLoader cl = ApkPackageManager.getClassLoader(targetPackageName);
if (null == cl || force) {
if (mClassLoaderFactory != null) {
cl = mClassLoaderFactory.createClassLoader(this, baseContext, apkPath, libPath, targetPackageName);
} else {
String optPath = getOptDir().getPath();
cl = new DexClassLoader(apkPath, optPath, libPath, baseContext.getClassLoader());
// cl = new TargetClassLoader(apkPath, optPath, libPath, baseContext.getClassLoader(), targetPackageName, baseContext);
}
ApkPackageManager.putClassLoader(targetPackageName, (cl));
}
return cl;
}Example 79
| Project: koala--Android-Plugin-Runtime--master File: PluginManagerImpl.java View source code |
/**
* 真æ£å®‰è£…æ?’件的代ç ?ï¼Œæ ¸å¿ƒæ–¹æ³•
*
* @param info
* æ?’ä»¶ä¿¡æ?¯
*/
private void realInstallPluin(PluginInfo info) {
try {
Plugin plugin = new Plugin();
plugin.mPluginInfo = info;
PackageInfo packageInfo = info.mPackageInfo;
packageInfo.applicationInfo.uid = Process.myUid();
packageInfo.applicationInfo.sourceDir = info.apkPath;
packageInfo.applicationInfo.publicSourceDir = info.apkPath;
packageInfo.applicationInfo.dataDir = mContext.getDir(info.packageName, 0).getAbsolutePath();
packageInfo.applicationInfo.flags &= ApplicationInfo.FLAG_HAS_CODE;
Object realPackageInfo = null;
try {
realPackageInfo = (Object) getPackageInfo.invoke(mActivityThread, new Object[] { packageInfo.applicationInfo, null });
} catch (Exception e) {
realPackageInfo = (Object) getPackageInfo.invoke(mActivityThread, new Object[] { packageInfo.applicationInfo });
}
plugin.mRealPackageInfo = realPackageInfo;
// 本地库的路径
StringBuilder sb = new StringBuilder();
int size = info.nativeLibraryPaths.size();
for (int j = 0; j < size; j++) {
sb.append(info.nativeLibraryPaths.get(j));
if (j < size - 1) {
sb.append(":");
}
}
// 实例化�件的classloader
DexClassLoader classLoader = new DexClassLoader(info.apkPath, mDexoutputPath, sb.toString(), mOriginalClassLoader);
mClassLoader.set(realPackageInfo, classLoader);
plugin.mClassLoader = classLoader;
// 调用Application
plugin.mApplication = (Application) makeApplication.invoke(realPackageInfo, false, null);
if (plugin.mApplication instanceof PluginApplication) {
PluginApplication pa = (PluginApplication) plugin.mApplication;
pa.setPluginName(plugin.mPluginInfo.packageName);
}
plugin.mApplication.onCreate();
Context context = plugin.mApplication.getApplicationContext();
LocalBroadcastManager lbm = new LocalBroadcastManager(context);
plugin.mLocalBroadCastManagers.put(context, lbm);
// 注册manifest里�的receiver
ArrayList<PackageParser.Activity> receivers = info.mPackageObj.receivers;
for (int i = 0; i < receivers.size(); i++) {
android.content.pm.PackageParser.Activity receiver = receivers.get(i);
String receiverName = receiver.className;
BroadcastReceiver broadcastreceiver = (BroadcastReceiver) plugin.mClassLoader.loadClass(receiverName).newInstance();
ArrayList<ActivityIntentInfo> intentinfos = receiver.intents;
for (int j = 0; j < intentinfos.size(); j++) {
IntentFilter filter = intentinfos.get(j);
lbm.registerReceiver(broadcastreceiver, filter);
mContext.registerReceiver(mReceiver, filter);
mHasRegisterReceiver = true;
}
}
// 注册contentprovider
ArrayList<PackageParser.Provider> providers = info.mPackageObj.providers;
for (int i = 0; i < providers.size(); i++) {
android.content.pm.PackageParser.Provider provider = providers.get(i);
String providerName = provider.className;
ContentProvider localProvider = (ContentProvider) plugin.mClassLoader.loadClass(providerName).newInstance();
localProvider.attachInfo(plugin.mApplication, provider.info);
IContentProvider realProvier = localProvider.getIContentProvider();
String names[] = PATTERN_SEMICOLON.split(provider.info.authority);
for (int j = 0; j < names.length; j++) {
plugin.mProviderMap.put(names[i], realProvier);
}
}
// æ?喜,æ?’件安装了
plugin.mPluginInfo.isInstalled = true;
mPlugins.put(info.packageName, plugin);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}Example 80
| Project: pirateplayer-master File: QtActivity.java View source code |
// this function is used to load and start the loader
private void loadApplication(Bundle loaderParams) {
try {
final int errorCode = loaderParams.getInt(ERROR_CODE_KEY);
if (errorCode != 0) {
if (errorCode == INCOMPATIBLE_MINISTRO_VERSION) {
downloadUpgradeMinistro(loaderParams.getString(ERROR_MESSAGE_KEY));
return;
}
// fatal error, show the error and quit
AlertDialog errorDialog = new AlertDialog.Builder(QtActivity.this).create();
errorDialog.setMessage(loaderParams.getString(ERROR_MESSAGE_KEY));
errorDialog.setButton(getResources().getString(android.R.string.ok), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
errorDialog.show();
return;
}
// add all bundled Qt libs to loader params
ArrayList<String> libs = new ArrayList<String>();
if (m_activityInfo.metaData.containsKey("android.app.bundled_libs_resource_id"))
libs.addAll(Arrays.asList(getResources().getStringArray(m_activityInfo.metaData.getInt("android.app.bundled_libs_resource_id"))));
String libName = null;
if (m_activityInfo.metaData.containsKey("android.app.lib_name")) {
libName = m_activityInfo.metaData.getString("android.app.lib_name");
//main library contains main() function
loaderParams.putString(MAIN_LIBRARY_KEY, libName);
}
loaderParams.putStringArrayList(BUNDLED_LIBRARIES_KEY, libs);
loaderParams.putInt(NECESSITAS_API_LEVEL_KEY, NECESSITAS_API_LEVEL);
// load and start QtLoader class
m_classLoader = new // .jar/.apk files
DexClassLoader(// .jar/.apk files
loaderParams.getString(DEX_PATH_KEY), // directory where optimized DEX files should be written.
getDir("outdex", Context.MODE_PRIVATE).getAbsolutePath(), // libs folder (if exists)
loaderParams.containsKey(LIB_PATH_KEY) ? loaderParams.getString(LIB_PATH_KEY) : null, // parent loader
getClassLoader());
@SuppressWarnings("rawtypes") Class // load QtLoader class
loaderClass = m_classLoader.loadClass(loaderParams.getString(LOADER_CLASS_NAME_KEY));
// create an instance
Object qtLoader = loaderClass.newInstance();
Method perpareAppMethod = qtLoader.getClass().getMethod("loadApplication", Activity.class, ClassLoader.class, Bundle.class);
if (!(Boolean) perpareAppMethod.invoke(qtLoader, this, m_classLoader, loaderParams))
throw new Exception("");
QtApplication.setQtActivityDelegate(qtLoader);
QtActivity.QtActivityInstance = this;
// now load the application library so it's accessible from this class loader
if (libName != null)
System.loadLibrary(libName);
Method startAppMethod = qtLoader.getClass().getMethod("startApplication");
if (!(Boolean) startAppMethod.invoke(qtLoader))
throw new Exception("");
} catch (Exception e) {
e.printStackTrace();
AlertDialog errorDialog = new AlertDialog.Builder(QtActivity.this).create();
if (m_activityInfo != null && m_activityInfo.metaData.containsKey("android.app.fatal_error_msg"))
errorDialog.setMessage(m_activityInfo.metaData.getString("android.app.fatal_error_msg"));
else
errorDialog.setMessage("Fatal error, your application can't be started.");
errorDialog.setButton(getResources().getString(android.R.string.ok), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
errorDialog.show();
}
}Example 81
| Project: ZeusPlugin-master File: PluginManager.java View source code |
/**
* 安装�始的内置�件
*/
private static void installInitPlugins() {
HashMap<String, PluginManifest> installedList = getInstalledPlugin();
HashMap<String, Integer> defaultList = getDefaultPlugin();
for (String key : defaultList.keySet()) {
int installVersion = -1;
int defaultVersion = defaultList.get(key);
if (installedList.containsKey(key)) {
installVersion = installedList.get(key).getVersion();
}
ZeusPlugin plugin = getPlugin(key);
if (defaultVersion > installVersion) {
boolean ret = plugin.installAssetPlugin();
//æ??å‰?å°†dex文件优化为odex或者opt文件
if (ret) {
try {
new DexClassLoader(PluginUtil.getAPKPath(key), PluginUtil.getDexCacheParentDirectPath(), null, mBaseClassLoader.getParent());
} catch (Throwable e) {
e.printStackTrace();
}
}
}
}
}Example 82
| Project: android-15-master File: ConnectivityService.java View source code |
private NetworkStateTracker makeWimaxStateTracker() {
//Initialize Wimax
DexClassLoader wimaxClassLoader;
Class wimaxStateTrackerClass = null;
Class wimaxServiceClass = null;
Class wimaxManagerClass;
String wimaxJarLocation;
String wimaxLibLocation;
String wimaxManagerClassName;
String wimaxServiceClassName;
String wimaxStateTrackerClassName;
NetworkStateTracker wimaxStateTracker = null;
boolean isWimaxEnabled = mContext.getResources().getBoolean(com.android.internal.R.bool.config_wimaxEnabled);
if (isWimaxEnabled) {
try {
wimaxJarLocation = mContext.getResources().getString(com.android.internal.R.string.config_wimaxServiceJarLocation);
wimaxLibLocation = mContext.getResources().getString(com.android.internal.R.string.config_wimaxNativeLibLocation);
wimaxManagerClassName = mContext.getResources().getString(com.android.internal.R.string.config_wimaxManagerClassname);
wimaxServiceClassName = mContext.getResources().getString(com.android.internal.R.string.config_wimaxServiceClassname);
wimaxStateTrackerClassName = mContext.getResources().getString(com.android.internal.R.string.config_wimaxStateTrackerClassname);
log("wimaxJarLocation: " + wimaxJarLocation);
wimaxClassLoader = new DexClassLoader(wimaxJarLocation, new ContextWrapper(mContext).getCacheDir().getAbsolutePath(), wimaxLibLocation, ClassLoader.getSystemClassLoader());
try {
wimaxManagerClass = wimaxClassLoader.loadClass(wimaxManagerClassName);
wimaxStateTrackerClass = wimaxClassLoader.loadClass(wimaxStateTrackerClassName);
wimaxServiceClass = wimaxClassLoader.loadClass(wimaxServiceClassName);
} catch (ClassNotFoundException ex) {
loge("Exception finding Wimax classes: " + ex.toString());
return null;
}
} catch (Resources.NotFoundException ex) {
loge("Wimax Resources does not exist!!! ");
return null;
}
try {
log("Starting Wimax Service... ");
Constructor wmxStTrkrConst = wimaxStateTrackerClass.getConstructor(new Class[] { Context.class, Handler.class });
wimaxStateTracker = (NetworkStateTracker) wmxStTrkrConst.newInstance(mContext, mHandler);
Constructor wmxSrvConst = wimaxServiceClass.getDeclaredConstructor(new Class[] { Context.class, wimaxStateTrackerClass });
wmxSrvConst.setAccessible(true);
IBinder svcInvoker = (IBinder) wmxSrvConst.newInstance(mContext, wimaxStateTracker);
wmxSrvConst.setAccessible(false);
ServiceManager.addService(WimaxManagerConstants.WIMAX_SERVICE, svcInvoker);
} catch (Exception ex) {
loge("Exception creating Wimax classes: " + ex.toString());
return null;
}
} else {
loge("Wimax is not enabled or not added to the network attributes!!! ");
return null;
}
return wimaxStateTracker;
}Example 83
| Project: cnAndroidDocs-master File: ConnectivityService.java View source code |
/**
* Loads external WiMAX library and registers as system service, returning a
* {@link NetworkStateTracker} for WiMAX. Caller is still responsible for
* invoking {@link NetworkStateTracker#startMonitoring(Context, Handler)}.
*/
private static NetworkStateTracker makeWimaxStateTracker(Context context, Handler trackerHandler) {
// Initialize Wimax
DexClassLoader wimaxClassLoader;
Class wimaxStateTrackerClass = null;
Class wimaxServiceClass = null;
Class wimaxManagerClass;
String wimaxJarLocation;
String wimaxLibLocation;
String wimaxManagerClassName;
String wimaxServiceClassName;
String wimaxStateTrackerClassName;
NetworkStateTracker wimaxStateTracker = null;
boolean isWimaxEnabled = context.getResources().getBoolean(com.android.internal.R.bool.config_wimaxEnabled);
if (isWimaxEnabled) {
try {
wimaxJarLocation = context.getResources().getString(com.android.internal.R.string.config_wimaxServiceJarLocation);
wimaxLibLocation = context.getResources().getString(com.android.internal.R.string.config_wimaxNativeLibLocation);
wimaxManagerClassName = context.getResources().getString(com.android.internal.R.string.config_wimaxManagerClassname);
wimaxServiceClassName = context.getResources().getString(com.android.internal.R.string.config_wimaxServiceClassname);
wimaxStateTrackerClassName = context.getResources().getString(com.android.internal.R.string.config_wimaxStateTrackerClassname);
if (DBG)
log("wimaxJarLocation: " + wimaxJarLocation);
wimaxClassLoader = new DexClassLoader(wimaxJarLocation, new ContextWrapper(context).getCacheDir().getAbsolutePath(), wimaxLibLocation, ClassLoader.getSystemClassLoader());
try {
wimaxManagerClass = wimaxClassLoader.loadClass(wimaxManagerClassName);
wimaxStateTrackerClass = wimaxClassLoader.loadClass(wimaxStateTrackerClassName);
wimaxServiceClass = wimaxClassLoader.loadClass(wimaxServiceClassName);
} catch (ClassNotFoundException ex) {
loge("Exception finding Wimax classes: " + ex.toString());
return null;
}
} catch (Resources.NotFoundException ex) {
loge("Wimax Resources does not exist!!! ");
return null;
}
try {
if (DBG)
log("Starting Wimax Service... ");
Constructor wmxStTrkrConst = wimaxStateTrackerClass.getConstructor(new Class[] { Context.class, Handler.class });
wimaxStateTracker = (NetworkStateTracker) wmxStTrkrConst.newInstance(context, trackerHandler);
Constructor wmxSrvConst = wimaxServiceClass.getDeclaredConstructor(new Class[] { Context.class, wimaxStateTrackerClass });
wmxSrvConst.setAccessible(true);
IBinder svcInvoker = (IBinder) wmxSrvConst.newInstance(context, wimaxStateTracker);
wmxSrvConst.setAccessible(false);
ServiceManager.addService(WimaxManagerConstants.WIMAX_SERVICE, svcInvoker);
} catch (Exception ex) {
loge("Exception creating Wimax classes: " + ex.toString());
return null;
}
} else {
loge("Wimax is not enabled or not added to the network attributes!!! ");
return null;
}
return wimaxStateTracker;
}Example 84
| Project: frameworks_base_disabled-master File: ConnectivityService.java View source code |
private NetworkStateTracker makeWimaxStateTracker() {
//Initialize Wimax
DexClassLoader wimaxClassLoader;
Class wimaxStateTrackerClass = null;
Class wimaxServiceClass = null;
Class wimaxManagerClass;
String wimaxJarLocation;
String wimaxLibLocation;
String wimaxManagerClassName;
String wimaxServiceClassName;
String wimaxStateTrackerClassName;
NetworkStateTracker wimaxStateTracker = null;
boolean isWimaxEnabled = mContext.getResources().getBoolean(com.android.internal.R.bool.config_wimaxEnabled);
if (isWimaxEnabled) {
try {
wimaxJarLocation = mContext.getResources().getString(com.android.internal.R.string.config_wimaxServiceJarLocation);
wimaxLibLocation = mContext.getResources().getString(com.android.internal.R.string.config_wimaxNativeLibLocation);
wimaxManagerClassName = mContext.getResources().getString(com.android.internal.R.string.config_wimaxManagerClassname);
wimaxServiceClassName = mContext.getResources().getString(com.android.internal.R.string.config_wimaxServiceClassname);
wimaxStateTrackerClassName = mContext.getResources().getString(com.android.internal.R.string.config_wimaxStateTrackerClassname);
log("wimaxJarLocation: " + wimaxJarLocation);
wimaxClassLoader = new DexClassLoader(wimaxJarLocation, new ContextWrapper(mContext).getCacheDir().getAbsolutePath(), wimaxLibLocation, ClassLoader.getSystemClassLoader());
try {
wimaxManagerClass = wimaxClassLoader.loadClass(wimaxManagerClassName);
wimaxStateTrackerClass = wimaxClassLoader.loadClass(wimaxStateTrackerClassName);
wimaxServiceClass = wimaxClassLoader.loadClass(wimaxServiceClassName);
} catch (ClassNotFoundException ex) {
loge("Exception finding Wimax classes: " + ex.toString());
return null;
}
} catch (Resources.NotFoundException ex) {
loge("Wimax Resources does not exist!!! ");
return null;
}
try {
log("Starting Wimax Service... ");
Constructor wmxStTrkrConst = wimaxStateTrackerClass.getConstructor(new Class[] { Context.class, Handler.class });
wimaxStateTracker = (NetworkStateTracker) wmxStTrkrConst.newInstance(mContext, mHandler);
Constructor wmxSrvConst = wimaxServiceClass.getDeclaredConstructor(new Class[] { Context.class, wimaxStateTrackerClass });
wmxSrvConst.setAccessible(true);
IBinder svcInvoker = (IBinder) wmxSrvConst.newInstance(mContext, wimaxStateTracker);
wmxSrvConst.setAccessible(false);
ServiceManager.addService(WimaxManagerConstants.WIMAX_SERVICE, svcInvoker);
} catch (Exception ex) {
loge("Exception creating Wimax classes: " + ex.toString());
return null;
}
} else {
loge("Wimax is not enabled or not added to the network attributes!!! ");
return null;
}
return wimaxStateTracker;
}Example 85
| Project: property-db-master File: ConnectivityService.java View source code |
/**
* Loads external WiMAX library and registers as system service, returning a
* {@link NetworkStateTracker} for WiMAX. Caller is still responsible for
* invoking {@link NetworkStateTracker#startMonitoring(Context, Handler)}.
*/
private static NetworkStateTracker makeWimaxStateTracker(Context context, Handler trackerHandler) {
// Initialize Wimax
DexClassLoader wimaxClassLoader;
Class wimaxStateTrackerClass = null;
Class wimaxServiceClass = null;
Class wimaxManagerClass;
String wimaxJarLocation;
String wimaxLibLocation;
String wimaxManagerClassName;
String wimaxServiceClassName;
String wimaxStateTrackerClassName;
NetworkStateTracker wimaxStateTracker = null;
boolean isWimaxEnabled = context.getResources().getBoolean(com.android.internal.R.bool.config_wimaxEnabled);
if (isWimaxEnabled) {
try {
wimaxJarLocation = context.getResources().getString(com.android.internal.R.string.config_wimaxServiceJarLocation);
wimaxLibLocation = context.getResources().getString(com.android.internal.R.string.config_wimaxNativeLibLocation);
wimaxManagerClassName = context.getResources().getString(com.android.internal.R.string.config_wimaxManagerClassname);
wimaxServiceClassName = context.getResources().getString(com.android.internal.R.string.config_wimaxServiceClassname);
wimaxStateTrackerClassName = context.getResources().getString(com.android.internal.R.string.config_wimaxStateTrackerClassname);
if (DBG)
log("wimaxJarLocation: " + wimaxJarLocation);
wimaxClassLoader = new DexClassLoader(wimaxJarLocation, new ContextWrapper(context).getCacheDir().getAbsolutePath(), wimaxLibLocation, ClassLoader.getSystemClassLoader());
try {
wimaxManagerClass = wimaxClassLoader.loadClass(wimaxManagerClassName);
wimaxStateTrackerClass = wimaxClassLoader.loadClass(wimaxStateTrackerClassName);
wimaxServiceClass = wimaxClassLoader.loadClass(wimaxServiceClassName);
} catch (ClassNotFoundException ex) {
loge("Exception finding Wimax classes: " + ex.toString());
return null;
}
} catch (Resources.NotFoundException ex) {
loge("Wimax Resources does not exist!!! ");
return null;
}
try {
if (DBG)
log("Starting Wimax Service... ");
Constructor wmxStTrkrConst = wimaxStateTrackerClass.getConstructor(new Class[] { Context.class, Handler.class });
wimaxStateTracker = (NetworkStateTracker) wmxStTrkrConst.newInstance(context, trackerHandler);
Constructor wmxSrvConst = wimaxServiceClass.getDeclaredConstructor(new Class[] { Context.class, wimaxStateTrackerClass });
wmxSrvConst.setAccessible(true);
IBinder svcInvoker = (IBinder) wmxSrvConst.newInstance(context, wimaxStateTracker);
wmxSrvConst.setAccessible(false);
ServiceManager.addService(WimaxManagerConstants.WIMAX_SERVICE, svcInvoker);
} catch (Exception ex) {
loge("Exception creating Wimax classes: " + ex.toString());
return null;
}
} else {
loge("Wimax is not enabled or not added to the network attributes!!! ");
return null;
}
return wimaxStateTracker;
}Example 86
| Project: platform_dalvik-master File: DexClassLoaderHelper.java View source code |
/**
* Creates and returns DexClassLoader instance with its classpath
* set to {@code pathHolder}.
*
* @param pathHolder {@code non-null;} location of jar archive containing dex
* classes canned into a working PathHolder instance.
* @return dex class loader instance with its classpath set to location
* indicated by {@code pathHolder}
*/
public ClassLoader getDexClassLoader(PathHolder pathHolder) {
ClassLoader myLoader = DexClassLoaderHelper.class.getClassLoader();
return new DexClassLoader(pathHolder.getJarFilePath(), pathHolder.getDirLocation(), null, myLoader);
}Example 87
| Project: android-libcore64-master File: Support_ClassLoader.java View source code |
@Override
public ClassLoader getClassLoader(URL url, ClassLoader parent) {
return new DexClassLoader(url.getPath(), tmp.getAbsolutePath(), null, parent);
}Example 88
| Project: android_libcore-master File: Support_ClassLoader.java View source code |
@Override
public ClassLoader getClassLoader(URL url, ClassLoader parent) {
return new DexClassLoader(url.getPath(), tmp.getAbsolutePath(), null, parent);
}Example 89
| Project: android_platform_libcore-master File: Support_ClassLoader.java View source code |
@Override
public ClassLoader getClassLoader(URL url, ClassLoader parent) {
return new DexClassLoader(url.getPath(), tmp.getAbsolutePath(), null, parent);
}Example 90
| Project: cw-omnibus-master File: ThingsLoaderThunk.java View source code |
private void loadThunk() throws ClassNotFoundException, IllegalAccessException, InstantiationException {
DexClassLoader dcl = new DexClassLoader(apkPath.getAbsolutePath(), cachePath.getAbsolutePath(), null, getClass().getClassLoader());
Class<ThingsLoader> clazz = (Class<ThingsLoader>) dcl.loadClass(classname);
extImpl = clazz.newInstance();
}Example 91
| Project: ApkLauncher_legacy-master File: StubActivity.java View source code |
private ClassLoader onCreateClassLoader(String apkPath, String libPath) {
ClassLoader c = new DexClassLoader(apkPath, getDir("apk_code_cache", 0).getPath(), libPath, mRealBaseContext.getClassLoader());
Log.d(TAG, "new classloader for apk: " + c);
return c;
}