Android系统实现DroidPlugin插件机制

360手机助手使用的 DroidPlugin,它是360手机助手团队在Android系统上实现了一种插件机制。它可以在无需安装、修改的情况下运行APK文件,此机制对改进大型APP的架构,实现多团队协作开发具有一定的好处。

它是一种新的插件机制,一种免安装的运行机制

github地址:https://github.com/DroidPluginTeam/DroidPlugin

参考博客:http://blog.csdn.net/hejjunlin/article/details/52124397

DroidPlugin的的基本原理:

  共享进程:为android提供一个进程运行多个apk的机制,通过API欺骗机制瞒过系统

  占坑:通过预先占坑的方式实现不用在manifest注册,通过一带多的方式实现服务管理

  Hook机制:动态代理实现函数hook,Binder代理绕过部分系统服务限制,IO重定向(先获取原始Object-->Read,然后动态代理Hook Object后-->Write回去,达到瞒天过海的目的)

public abstract class Hook {

 private boolean mEnable = false;//能否hook

 protected Context mHostContext;//宿主context,外部传入
 protected BaseHookHandle mHookHandles;

 public void setEnable(boolean enable, boolean reInstallHook) {
  this.mEnable = enable;
 }

 public final void setEnable(boolean enable) {
  setEnable(enable, false);
 }

 public boolean isEnable() {
  return mEnable;
 }


 protected Hook(Context hostContext) {
  mHostContext = hostContext;
  mHookHandles = createHookHandle();
 }

 protected abstract BaseHookHandle createHookHandle();//用于子类创建Hook机制


 protected abstract void onInstall(ClassLoader classLoader) throws Throwable;//插件安装

 protected void onUnInstall(ClassLoader classLoader) throws Throwable {//插件卸载

 }
}

public class HookedMethodHandler {//Hook方法

 private static final String TAG = HookedMethodHandler.class.getSimpleName();
 protected final Context mHostContext;
 /**
  * 调用方法的时候会到AppOpsService进行判断uid(宿主apk)和插件的包名是否匹配,此处是不匹配的
  * 此时就可以经过转换欺骗系统让程序认为是宿主apk调过来的(这样的前提就需要宿主把所有的权限都申请了)
  * 因为系统只会去检测宿主apk
  * **/
 private Object mFakedResult = null;//用于欺骗系统
 private boolean mUseFakedResult = false;

 public HookedMethodHandler(Context hostContext) {
  this.mHostContext = hostContext;
 }


 public synchronized Object doHookInner(Object receiver, Method method, Object[] args) throws Throwable {
  long b = System.currentTimeMillis();
  try {
   mUseFakedResult = false;
   mFakedResult = null;
   boolean suc = beforeInvoke(receiver, method, args);
   Object invokeResult = null;
   if (!suc) {//false执行原始方法
    invokeResult = method.invoke(receiver, args);
   }
   afterInvoke(receiver, method, args, invokeResult);
   if (mUseFakedResult) {//true返回欺骗结果,false返回正常的调用方法
    return mFakedResult;
   } else {
    return invokeResult;
   }
  } finally {
   long time = System.currentTimeMillis() - b;
   if (time > 5) {
    Log.i(TAG, "doHookInner method(%s.%s) cost %s ms", method.getDeclaringClass().getName(), method.getName(), time);
   }
  }
 }

 public void setFakedResult(Object fakedResult) {
  this.mFakedResult = fakedResult;
  mUseFakedResult = true;
 }

 /**
  * 在某个方法被调用之前执行,如果返回true,则不执行原始的方法,否则执行原始方法
  */
 protected boolean beforeInvoke(Object receiver, Method method, Object[] args) throws Throwable {
  return false;
 }

 protected void afterInvoke(Object receiver, Method method, Object[] args, Object invokeResult) throws Throwable {
 }

 public boolean isFakedResult() {
  return mUseFakedResult;
 }

 public Object getFakedResult() {
  return mFakedResult;
 }
}

abstract class BinderHook extends Hook implements InvocationHandler {

 private Object mOldObj;

 public BinderHook(Context hostContext) {
  super(hostContext);
 }

 @Override
 public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
  try {
   if (!isEnable()) {//如果不能Hook,执行原方法
    return method.invoke(mOldObj, args);
   }
   HookedMethodHandler hookedMethodHandler = mHookHandles.getHookedMethodHandler(method);
   if (hookedMethodHandler != null) {
    return hookedMethodHandler.doHookInner(mOldObj, method, args);
   } else {
    return method.invoke(mOldObj, args);
   }
  } catch (InvocationTargetException e) {
   Throwable cause = e.getTargetException();
   if (cause != null && MyProxy.isMethodDeclaredThrowable(method, cause)) {
    throw cause;
   } else if (cause != null) {
    RuntimeException runtimeException = !TextUtils.isEmpty(cause.getMessage()) ? new RuntimeException(cause.getMessage()) : new RuntimeException();
    runtimeException.initCause(cause);
    throw runtimeException;
   } else {
    RuntimeException runtimeException = !TextUtils.isEmpty(e.getMessage()) ? new RuntimeException(e.getMessage()) : new RuntimeException();
    runtimeException.initCause(e);
    throw runtimeException;
   }
  } catch (IllegalArgumentException e) {
   try {
    StringBuilder sb = new StringBuilder();
    sb.append(" DROIDPLUGIN{");
    if (method != null) {
     sb.append("method[").append(method.toString()).append("]");
    } else {
     sb.append("method[").append("NULL").append("]");
    }
    if (args != null) {
     sb.append("args[").append(Arrays.toString(args)).append("]");
    } else {
     sb.append("args[").append("NULL").append("]");
    }
    sb.append("}");

    String message = e.getMessage() + sb.toString();
    throw new IllegalArgumentException(message, e);
   } catch (Throwable e1) {
    throw e;
   }
  } catch (Throwable e) {
   if (MyProxy.isMethodDeclaredThrowable(method, e)) {
    throw e;
   } else {
    RuntimeException runtimeException = !TextUtils.isEmpty(e.getMessage()) ? new RuntimeException(e.getMessage()) : new RuntimeException();
    runtimeException.initCause(e);
    throw runtimeException;
   }
  }
 }

 abstract Object getOldObj() throws Exception;

 void setOldObj(Object mOldObj) {
  this.mOldObj = mOldObj;
 }

 public abstract String getServiceName();//具体Hook哪一个service

 /**
  * 先调用ServiceManagerCacheBinderHook的onInstall()方法更新一下service cache
  * 然后生成一个新的代理对象放到mProxiedObjCache里。这样下次不管是从cache里取,还是直接通过binder调用,就都会返回我们的代理对象。
  * **/
 @Override
 protected void onInstall(ClassLoader classLoader) throws Throwable {
  new ServiceManagerCacheBinderHook(mHostContext, getServiceName()).onInstall(classLoader);
  mOldObj = getOldObj();
  Class<?> clazz = mOldObj.getClass();//得到class
  List<Class<?>> interfaces = Utils.getAllInterfaces(clazz);
  Class[] ifs = interfaces != null && interfaces.size() > 0 ? interfaces.toArray(new Class[interfaces.size()]) : new Class[0];
  //用原始对象的classloader传入动态代理,得到代理对象
  Object proxiedObj = MyProxy.newProxyInstance(clazz.getClassLoader(), ifs, this);
  MyServiceManager.addProxiedObj(getServiceName(), proxiedObj);
 }
}

结论就是读取插件apk,和宿主的uid对比,然后进行包替换,在利用binder代理Hook,启动插件,这概括很是大概,不过涉及太复杂

然后是使用了,结束和使用都很多资料,很详细,不过自己研究了一翻记录下心得,也能加深理解和印象

public class MainActivity extends AppCompatActivity {

 private String filepath = null, packageName = "cn.liuzhen.plugin";
 private TextView tv_val;
 private Context context;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  context = MainActivity.this;
  tv_val = (TextView)findViewById(R.id.tv_val);
  filepath = Environment.getExternalStorageDirectory().getAbsolutePath().concat("/test.apk");
 }

 public void click(View view) {
  if (filepath == null){
   Toast.makeText(context,"filepath is null",Toast.LENGTH_SHORT).show();
   return;
  }
  String result = null;
  int code = -1;
  try {
   switch (view.getId()) {
    case R.id.btn_install:
     code = PluginManager.getInstance().installPackage(filepath, PackageManagerCompat.INSTALL_REPLACE_EXISTING);
     result = "install";
     switch (code) {
      case PluginManager.INSTALL_FAILED_NO_REQUESTEDPERMISSION:
       result = "安装失败,文件请求的权限太多";
       break;
      case PackageManagerCompat.INSTALL_FAILED_NOT_SUPPORT_ABI:
       result = "宿主不支持插件的abi环境,可能宿主运行时为64位,但插件只支持32位";
       break;
      case PackageManagerCompat.INSTALL_SUCCEEDED:
       result = "安装完成";
       break;
     }
     break;
    case R.id.btn_del:
     PluginManager.getInstance().deletePackage(packageName, 0);
     result = "del";
     break;
    case R.id.btn_open:
     PackageManager pm = getPackageManager();
     Intent intent = pm.getLaunchIntentForPackage("cn.liuzhen.plugin");
     if (intent == null){
      result = "intent is null";
     }else
      startActivity(intent);
     break;
   }

  } catch (RemoteException e) {
   result = "安装失败 "+e.getMessage();
  }
  tv_val.setText(result);
 }

}

运行程序成功,然后把运行的apk复制一份,我上面的名称是写死的,test.apk,然后放在根目录,点击安装,显示成功后在点击打开,就能见到跳转到插件界面了,插件化通了。

接下来就是看自己怎么设计和开发了,什么东西也不能随便使用,得好好考虑,个人觉得插件化不宜大范围使用,适合小菜单的集成,毕竟都是反射的,而且还得考虑好安全问题。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持鸟哥教程(niaoge.com)。

声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:notice#niaoge.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。