[关闭]
@asce1885 2015-08-04T06:46:47.000000Z 字数 10716 阅读 382

Android平台免Root无侵入AOP框架Dexposed使用详解

Android


阿里巴巴无线事业部最近开源的Android平台下的无侵入运行期AOP框架Dexposed,该框架基于AOP思想,支持经典的AOP使用场景,可应用于日志记录,性能统计,安全控制,事务处理,异常处理等方面。

针对Android平台,Dexposed支持函数级别的在线热更新,例如对已经发布在应用市场上的宿主APK,当我们从crash统计平台上发现某个函数调用有bug,导致经常性crash,这时,可以在本地开发一个补丁APK,并发布到服务器中,宿主APK下载这个补丁APK并集成后,就可以很容易修复这个crash。

Dexposed是基于久负盛名的开源Xposed框架实现的一个Android平台上功能强大的无侵入式运行时AOP框架。

Dexposed的AOP实现是完全非侵入式的,没有使用任何注解处理器,编织器或者字节码重写器。集成Dexposed框架很简单,只需要在应用初始化阶段加载一个很小的JNI库就可以,这个加载操作已经封装在DexposedBridge函数库里面的canDexposed函数中,源码如下所示:

  1. /**
  2. * Check device if can run dexposed, and load libs auto.
  3. */
  4. public synchronized static boolean canDexposed(Context context) {
  5. if (!DeviceCheck.isDeviceSupport(context)) {
  6. return false;
  7. }
  8. //load xposed lib for hook.
  9. return loadDexposedLib(context);
  10. }
  11. private static boolean loadDexposedLib(Context context) {
  12. // load xposed lib for hook.
  13. try {
  14. if (android.os.Build.VERSION.SDK_INT > 19){
  15. System.loadLibrary("dexposed_l");
  16. } else if (android.os.Build.VERSION.SDK_INT == 10
  17. || android.os.Build.VERSION.SDK_INT == 9 ||
  18. android.os.Build.VERSION.SDK_INT > 14){
  19. System.loadLibrary("dexposed");
  20. }
  21. return true;
  22. } catch (Throwable e) {
  23. return false;
  24. }
  25. }

Dexposed实现的hooking,不仅可以hook应用中的自定义函数,也可以hook应用中调用的Android框架的函数。Android开发者将从这一点得到很多好处,因为我们严重依赖于Android SDK的版本碎片化。

基于动态类加载技术,运行中的app可以加载一小段经过编译的Java AOP代码,在不需要重启app的前提下实现修改目标app的行为。

典型的使用场景

如何集成

集成方式很简单,只需要将一个jar包加入项目的libs文件夹中,同时将两个so文件添加到jniLibs中对应的ABI目录中即可。Gradle依赖如下所示:

  1. buildscript {
  2. repositories {
  3. mavenCentral()
  4. }
  5. dependencies {
  6. classpath 'com.android.tools.build:gradle:0.10.+'
  7. classpath 'com.nabilhachicha:android-native-dependencies:0.1'
  8. }
  9. }
  10. ...
  11. native_dependencies {
  12. artifact 'com.taobao.dexposed:dexposed_l:0.2+:armeabi'
  13. artifact 'com.taobao.dexposed:dexposed:0.2+:armeabi'
  14. }
  15. dependencies {
  16. compile files('libs/dexposedbridge.jar')
  17. }

其中,native_dependencies是一个第三方插件,使用方法可参考《如何在Android Gradle中添加原生so文件依赖》。当然,我们也可以直接把需要用到的so文件直接拷贝到jniLibs目录中,这样的话,可以把上面的native_dependencies代码段注释掉。

同时应该在应用初始化的地方(尽可能早的添加)添加初始化Dexposed的代码,例如在MyApplication中添加:

  1. public class MyApplication extends Application {
  2. private boolean mIsSupported = false; // 设备是否支持dexposed
  3. private boolean mIsLDevice = false; // 设备Android系统是否是Android 5.0及以上
  4. @Override
  5. public void onCreate() {
  6. super.onCreate();
  7. // check device if support and auto load libs
  8. mIsSupported = DexposedBridge.canDexposed(this);
  9. mIsLDevice = Build.VERSION.SDK_INT >= 21;
  10. }
  11. public boolean isSupported() {
  12. return mIsSupported;
  13. }
  14. public boolean isLDevice() {
  15. return mIsLDevice;
  16. }
  17. }

基本用法

对于某个函数而言,有三个注入点可供选择:函数执行前注入(before),函数执行后注入(after),替换函数执行的代码段(replace),分别对应于抽象类XC_MethodHook及其子类XC_MethodReplacement中的函数:

  1. public abstract class XC_MethodHook extends XCallback {
  2. /**
  3. * Called before the invocation of the method.
  4. * <p>Can use {@link MethodHookParam#setResult(Object)} and {@link MethodHookParam#setThrowable(Throwable)}
  5. * to prevent the original method from being called.
  6. */
  7. protected void beforeHookedMethod(MethodHookParam param) throws Throwable {}
  8. /**
  9. * Called after the invocation of the method.
  10. * <p>Can use {@link MethodHookParam#setResult(Object)} and {@link MethodHookParam#setThrowable(Throwable)}
  11. * to modify the return value of the original method.
  12. */
  13. protected void afterHookedMethod(MethodHookParam param) throws Throwable {}
  14. }
  1. public abstract class XC_MethodReplacement extends XC_MethodHook {
  2. @Override
  3. protected final void beforeHookedMethod(MethodHookParam param) throws Throwable {
  4. try {
  5. Object result = replaceHookedMethod(param);
  6. param.setResult(result);
  7. } catch (Throwable t) {
  8. param.setThrowable(t);
  9. }
  10. }
  11. protected final void afterHookedMethod(MethodHookParam param) throws Throwable {
  12. }
  13. /**
  14. * Shortcut for replacing a method completely. Whatever is returned/thrown here is taken
  15. * instead of the result of the original method (which will not be called).
  16. */
  17. protected abstract Object replaceHookedMethod(MethodHookParam param) throws Throwable;
  18. }

可以看到这三个注入回调函数都有一个类型为MethodHookParam的参数,这个参数包含了一些很有用的信息:

MethodHookParam代码如下所示:

  1. public static class MethodHookParam extends XCallback.Param {
  2. /** Description of the hooked method */
  3. public Member method;
  4. /** The <code>this</code> reference for an instance method, or null for static methods */
  5. public Object thisObject;
  6. /** Arguments to the method call */
  7. public Object[] args;
  8. private Object result = null;
  9. private Throwable throwable = null;
  10. /* package */ boolean returnEarly = false;
  11. /** Returns the result of the method call */
  12. public Object getResult() {
  13. return result;
  14. }
  15. /**
  16. * Modify the result of the method call. In a "before-method-call"
  17. * hook, prevents the call to the original method.
  18. * You still need to "return" from the hook handler if required.
  19. */
  20. public void setResult(Object result) {
  21. this.result = result;
  22. this.throwable = null;
  23. this.returnEarly = true;
  24. }
  25. /** Returns the <code>Throwable</code> thrown by the method, or null */
  26. public Throwable getThrowable() {
  27. return throwable;
  28. }
  29. /** Returns true if an exception was thrown by the method */
  30. public boolean hasThrowable() {
  31. return throwable != null;
  32. }
  33. /**
  34. * Modify the exception thrown of the method call. In a "before-method-call"
  35. * hook, prevents the call to the original method.
  36. * You still need to "return" from the hook handler if required.
  37. */
  38. public void setThrowable(Throwable throwable) {
  39. this.throwable = throwable;
  40. this.result = null;
  41. this.returnEarly = true;
  42. }
  43. /** Returns the result of the method call, or throws the Throwable caused by it */
  44. public Object getResultOrThrowable() throws Throwable {
  45. if (throwable != null)
  46. throw throwable;
  47. return result;
  48. }
  49. }

例子一:AOP编程

AOP(Aspect Oriented Programming),也就是面向方面编程,是通过预编译方式和运行期动态代理实现程序功能的统一维护的一种技术。利用AOP可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高程序的可重用性,同时提高了开发的效率。

AOP一般应用在日志记录,性能统计,安全控制,事务处理,异常处理等方面,它的主要意图是将日志记录,性能统计,安全控制,事务处理,异常处理等代码从业务逻辑代码中划分出来,通过对这些行为的分离,我们希望可以将它们独立到非业务逻辑的方法中,进而改变这些行为的时候不影响业务逻辑的代码。

例如我们可以在应用中所有的Activity.onCreate(Bundle)函数调用之前和之后增加一些相同的处理:

  1. // Target class, method with parameter types, followed by the hook callback (XC_MethodHook).
  2. DexposedBridge.findAndHookMethod(Activity.class, "onCreate", Bundle.class, new XC_MethodHook() {
  3. // To be invoked before Activity.onCreate().
  4. @Override protected void beforeHookedMethod(MethodHookParam param) throws Throwable {
  5. // "thisObject" keeps the reference to the instance of target class.
  6. Activity instance = (Activity) param.thisObject;
  7. // The array args include all the parameters.
  8. Bundle bundle = (Bundle) param.args[0];
  9. Intent intent = new Intent();
  10. // XposedHelpers provide useful utility methods.
  11. XposedHelpers.setObjectField(param.thisObject, "mIntent", intent);
  12. // Calling setResult() will bypass the original method body use the result as method return value directly.
  13. if (bundle.containsKey("return"))
  14. param.setResult(null);
  15. }
  16. // To be invoked after Activity.onCreate()
  17. @Override protected void afterHookedMethod(MethodHookParam param) throws Throwable {
  18. XposedHelpers.callMethod(param.thisObject, "sampleMethod", 2);
  19. }
  20. });

当然也可以替换目标函数原来执行的代码段:

  1. DexposedBridge.findAndHookMethod(Activity.class, "onCreate", Bundle.class, new XC_MethodReplacement() {
  2. @Override protected Object replaceHookedMethod(MethodHookParam param) throws Throwable {
  3. // Re-writing the method logic outside the original method context is a bit tricky but still viable.
  4. ...
  5. }
  6. });

例子二:在线热更新

在线热更新一般用于修复线上严重的,紧急的或者安全性的bug,这里会涉及到两个apk文件,一个我们称为宿主apk,也就是发布到应用市场的apk,一个称为补丁apk。宿主apk出现bug时,通过在线下载的方式从服务器下载到补丁apk,使用补丁apk中的函数替换原来的函数,从而实现在线修复bug的功能。

为了实现这个功能,需要再引入一个名为patchloader的jar包,这个函数库实现了一个热更新框架,宿主apk在发布时会将这个jar包一起打包进apk中,而补丁apk只是在编译时需要这个jar包,但打包成apk时不包含这个jar包,以免补丁apk集成到宿主apk中时发生冲突。因此,补丁apk将会以provided的形式依赖dexposedbridge.jar和patchloader.jar,补丁apk的build.gradle文件中依赖部分脚本如下所示:

  1. dependencies {
  2. provided files('libs/dexposedbridge.jar')
  3. provided files('libs/patchloader.jar')
  4. }

这里我们假设宿主apk的MainActivity.showDialog函数出现问题,需要打补丁,宿主代码如下所示:(类完整路径是com.taobao.dexposed.MainActivity)

  1. package com.taobao.dexposed;
  2. public class MainActivity extends Activity {
  3. private void showDialog() {
  4. AlertDialog.Builder builder = new AlertDialog.Builder(this);
  5. builder.setTitle("Dexposed sample")
  6. .setMessage(
  7. "Please clone patchsample project to generate apk, and copy it to \"/Android/data/com.taobao.dexposed/cache/patch.apk\"")
  8. .setPositiveButton("ok", new DialogInterface.OnClickListener() {
  9. public void onClick(DialogInterface dialog, int whichButton) {
  10. }
  11. }).create().show();
  12. }
  13. }

补丁apk只有一个名为DialogPatch的类,实现了patchloader函数库中的IPatch接口,IPatch接口代码如下所示:

  1. /**
  2. * The interface implemented by hotpatch classes.
  3. */
  4. public interface IPatch {
  5. void handlePatch(PatchParam lpparam) throws Throwable;
  6. }

DialogPatch类实现IPatch的handlePatch函数,在该函数中通过反射得到宿主APK中com.taobao.dexposed.MainActivity类实例,然后调用dexposedbridge函数库中的DexposedBridge.findAndHookMethod函数,对MainActivity中的showDialog函数进行Hook操作,替换宿主apk中的相应代码,DialogPatch代码如下所示:

  1. public class DialogPatch implements IPatch {
  2. @Override
  3. public void handlePatch(final PatchParam arg0) throws Throwable {
  4. Class<?> cls = null;
  5. try {
  6. cls= arg0.context.getClassLoader()
  7. .loadClass("com.taobao.dexposed.MainActivity");
  8. } catch (ClassNotFoundException e) {
  9. e.printStackTrace();
  10. return;
  11. }
  12. DexposedBridge.findAndHookMethod(cls, "showDialog",
  13. new XC_MethodReplacement() {
  14. @Override
  15. protected Object replaceHookedMethod(MethodHookParam param) throws Throwable {
  16. Activity mainActivity = (Activity) param.thisObject;
  17. AlertDialog.Builder builder = new AlertDialog.Builder(mainActivity);
  18. builder.setTitle("Dexposed sample")
  19. .setMessage("The dialog is shown from patch apk!")
  20. .setPositiveButton("ok", new DialogInterface.OnClickListener() {
  21. public void onClick(DialogInterface dialog, int whichButton) {
  22. }
  23. }).create().show();
  24. return null;
  25. }
  26. });
  27. }
  28. }

最后宿主apk通过调用patchloader函数库提供的PatchMain.load函数来动态加载下载到的补丁apk,加载代码如下所示:

  1. // Run patch apk
  2. public void runPatchApk(View view) {
  3. Log.d("dexposed", "runPatchApk button clicked.");
  4. if (isLDevice) {
  5. showLog("dexposed", "It doesn't support this function on L device.");
  6. return;
  7. }
  8. if (!isSupport) {
  9. Log.d("dexposed", "This device doesn't support dexposed!");
  10. return;
  11. }
  12. File cacheDir = getExternalCacheDir();
  13. if(cacheDir != null){
  14. String fullpath = cacheDir.getAbsolutePath() + File.separator + "patch.apk";
  15. PatchResult result = PatchMain.load(this, fullpath, null);
  16. if (result.isSuccess()) {
  17. Log.e("Hotpatch", "patch success!");
  18. } else {
  19. Log.e("Hotpatch", "patch error is " + result.getErrorInfo());
  20. }
  21. }
  22. showDialog();
  23. }

为便于理解,这里也把load函数体贴出来,更详细内容大家可以看源码:

  1. /**
  2. * Load a runnable patch apk.
  3. *
  4. * @param context the application or activity context.
  5. * @param apkPath the path of patch apk file.
  6. * @param contentMap the object maps that will be used by patch classes.
  7. * @return PatchResult include if success or error detail.
  8. */
  9. public static PatchResult load(Context context, String apkPath, HashMap<String, Object> contentMap) {
  10. if (!new File(apkPath).exists()) {
  11. return new PatchResult(false, PatchResult.FILE_NOT_FOUND, "FILE not found on " + apkPath);
  12. }
  13. PatchResult result = loadAllCallbacks(context, apkPath,context.getClassLoader());
  14. if (!result.isSuccess()) {
  15. return result;
  16. }
  17. if (loadedPatchCallbacks.getSize() == 0) {
  18. return new PatchResult(false, PatchResult.NO_PATCH_CLASS_HANDLE, "No patch class to be handle");
  19. }
  20. PatchParam lpparam = new PatchParam(loadedPatchCallbacks);
  21. lpparam.context = context;
  22. lpparam.contentMap = contentMap;
  23. return PatchCallback.callAll(lpparam);
  24. }

支持的系统版本

Dexposed支持从Android2.3到4.4(除了3.0)的所有dalvid运行时arm架构的设备,稳定性已经经过实践检验。

支持的系统版本:

不支持的系统版本:

测试中的系统版本:

未经测试的系统版本:

使用Dexposed的项目

目前阿里系主流app例如手机淘宝,支付宝,天猫都使用了Dexposed支持在线热更新,而开源项目中,在Github上面能搜到的只有一个XLog项目,它的主要功能是方便的打印函数调用和耗时日志,这也是一个了解Dexposed如何使用的很好的例子。

参考资料

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注