您的位置:首页 > 其它

插件化开发---DroidPlugin对Servie的管理

2017-02-06 19:20 393 查看
Service分为两种形式:以startService启动的服务和用bindService绑定的服务;由于这两个过程大体相似,这里以稍复杂的bindService为例分析Service组件的工作原理。

绑定Service的过程是通过Context类的bindService完成的,这个方法需要三个参数:第一个参数代表想要绑定的Service的Intent,第二个参数是一个ServiceConnetion,我们可以通过这个对象接收到Service绑定成功或者失败的回调;第三个参数则是绑定时候的一些FLAG

Context的具体实现在ContextImpl类,ContextImpl中的bindService方法直接调用了bindServiceCommon方法,此方法源码如下:

/** @hide */
@Override
public boolean bindServiceAsUser(Intent service, ServiceConnection conn, int flags,
UserHandle user) {
return bindServiceCommon(service, conn, flags, user);
}

private boolean bindServiceCommon(Intent service, ServiceConnection conn, int flags,
UserHandle user) {
IServiceConnection sd;
if (conn == null) {
throw new IllegalArgumentException("connection is null");
}
if (mPackageInfo != null) {
sd = mPackageInfo.getServiceDispatcher(conn, getOuterContext(),
mMainThread.getHandler(), flags);
} else {
throw new RuntimeException("Not supported in system context");
}
validateServiceIntent(service);
try {
IBinder token = getActivityToken();
if (token == null && (flags&BIND_AUTO_CREATE) == 0 && mPackageInfo != null
&& mPackageInfo.getApplicationInfo().targetSdkVersion
< android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
flags |= BIND_WAIVE_PRIORITY;
}
service.prepareToLeaveProcess();
int res = ActivityManagerNative.getDefault().bindService(
mMainThread.getApplicationThread(), getActivityToken(),
service, service.resolveTypeIfNeeded(getContentResolver()),
sd, flags, user.getIdentifier());
if (res < 0) {
throw new SecurityException(
"Not allowed to bind to service " + service);
}
return res != 0;
} catch (RemoteException e) {
return false;
}
}


大致观察就能发现这个方法最终通过ActivityManagerNative借助AMS进而完成Service的绑定过程,在跟踪AMS的bindService源码之前,我们关注一下这个方法开始处创建的sd变量。这个变量的类型是IServiceConnection,如果读者还有印象,我们在 广播的管理 一文中也遇到过类似的处理方式——IIntentReceiver;所以,这个IServiceConnection与IApplicationThread以及IIntentReceiver相同,都是ActivityThread给AMS提供的用来与之进行通信的Binder对象;这个接口的实现类为LoadedApk.ServiceDispatcher。

bindService这个方法相当简单,只是做了一些参数校检之后直接调用了ActivityServices类的bindServiceLocked方法:

int bindServiceLocked(IApplicationThread caller, IBinder token, Intent service,
String resolvedType, IServiceConnection connection, int flags,
String callingPackage, int userId) throws TransactionTooLargeException {
final ProcessRecord callerApp = mAm.getRecordForAppLocked(caller);
// 参数校检,略

ServiceLookupResult res =
retrieveServiceLocked(service, resolvedType, callingPackage,
Binder.getCallingPid(), Binder.getCallingUid(), userId, true, callerFg);
// 结果校检, 略
ServiceRecord s = res.record;

final long origId = Binder.clearCallingIdentity();

try {
// ... 不关心, 略

mAm.startAssociationLocked(callerApp.uid, callerApp.processName,
s.appInfo.uid, s.name, s.processName);

AppBindRecord b = s.retrieveAppBindingLocked(service, callerApp);
ConnectionRecord c = new ConnectionRecord(b, activity,
connection, flags, clientLabel, clientIntent);
IBinder binder = connection.asBinder();
ArrayList<ConnectionRecord> clist = s.connections.get(binder);

// 对connection进行处理, 方便存取,略
clist.add(c);

if ((flags&Context.BIND_AUTO_CREATE) != 0) {
s.lastActivity = SystemClock.uptimeMillis();
if (bringUpServiceLocked(s, service.getFlags(), callerFg, false) != null) {
return 0;
}
}

// 与BIND_AUTO_CREATE不同的启动FLAG,原理与后续相同,略

} finally {
Binder.restoreCallingIdentity(origId);
}

return 1;
}


这个方法比较长,我这里省去了很多无关代码,只列出关键逻辑;首先它通过retrieveServiceLocked方法获取到了intent匹配到的需要bind到的Service组件res;然后把ActivityThread传递过来的IServiceConnection使用ConnectionRecord进行了包装,方便接下来使用;最后如果启动的FLAG为BIND_AUTO_CREATE,那么调用bringUpServiceLocked开始创建Service,

在bringUpServiceLocked方法中进行判断,如果Service所在的进程已经启动,那么直接调用realStartServiceLocked方法来真正启动Service组件;如果Service所在的进程还没有启动,那么先在AMS中记下这个要启动的Service组件,然后通过startProcessLocked启动新的进程。

我们先看Service进程已经启动的情况,也即realStartServiceLocked分支:

private final void realStartServiceLocked(ServiceRecord r,
ProcessRecord app, boolean execInFg) throws RemoteException {

// 略。。

boolean created = false;
try {
synchronized (r.stats.getBatteryStats()) {
r.stats.startLaunchedLocked();
}
mAm.ensurePackageDexOpt(r.serviceInfo.packageName);
app.forceProcessStateUpTo(ActivityManager.PROCESS_STATE_SERVICE);
app.thread.scheduleCreateService(r, r.serviceInfo,
mAm.compatibilityInfoForPackageLocked(r.serviceInfo.applicationInfo),
app.repProcState);
r.postNotification();
created = true;
} catch (DeadObjectException e) {
mAm.appDiedLocked(app);
throw e;
} finally {
// 略。。
}

requestServiceBindingsLocked(r, execInFg);

// 不关心,略。。
}


这个方法首先调用了app.thread的scheduleCreateService方法,我们知道,这是一个IApplicationThread对象,它是App所在进程提供给AMS的用来与App进程进行通信的Binder对象,这个Binder的Server端在ActivityThread的ApplicationThread类,因此,我们跟踪ActivityThread类,这个方法的实现如下:

public final void scheduleCreateService(IBinder token,
ServiceInfo info, CompatibilityInfo compatInfo, int processState) {
updateProcessState(processState, false);
CreateServiceData s = new CreateServiceData();
s.token = token;
s.info = info;
s.compatInfo = compatInfo;

sendMessage(H.CREATE_SERVICE, s);
}


它不过是转发了一个消息给ActivityThread的H这个Handler,H类收到这个消息之后,直接调用了ActivityThread类的handleCreateService方法,如下:

private void handleCreateService(CreateServiceData data) {
unscheduleGcIdler();

LoadedApk packageInfo = getPackageInfoNoCheck(
data.info.applicationInfo, data.compatInfo);
Service service = null;
try {
java.lang.ClassLoader cl = packageInfo.getClassLoader();
service = (Service) cl.loadClass(data.info.name).newInstance();
} catch (Exception e) {
}

try {
ContextImpl context = ContextImpl.createAppContext(this, packageInfo);
context.setOuterContext(service);

Application app = packageInfo.makeApplication(false, mInstrumentation);
service.attach(context, this, data.info.name, data.token, app,
ActivityManagerNative.getDefault());
service.onCreate();
mServices.put(data.token, service);
try {
ActivityManagerNative.getDefault().serviceDoneExecuting(
data.token, SERVICE_DONE_EXECUTING_ANON, 0, 0);
} catch (RemoteException e) {
// nothing to do.
}
} catch (Exception e) {
}
}


看到这段代码,是不是似曾相识?!没错,这里与Activity组件的创建过程如出一辙!所以这里就不赘述了,可以参阅 Activity生命周期管理。

需要注意的是,这里Service类的创建过程与Activity是略微有点不同的,虽然都是通过ClassLoader通过反射创建,但是Activity却把创建过程委托给了Instrumentation类,而Service则是直接进行。

OK,现在ActivityThread里面的handleCreateService方法成功创建出了Service对象,并且调用了它的onCreate方法;到这里我们的Service已经启动成功。scheduleCreateService这个Binder调用过程结束,代码又回到了AMS进程的realStartServiceLocked方法

app.thread.scheduleCreateService(r, r.serviceInfo,
mAm.compatibilityInfoForPackageLocked(r.serviceInfo.applicationInfo),
app.repProcState);
......
......

requestServiceBindingsLocked(r, execInFg);


这个方法在完成scheduleCreateService这个binder调用之后,执行了一个requestServiceBindingsLocked方法;看方法名好像于「绑定服务」有关,它简单地执行了一个遍历然后调用了另外一个方法:

private final boolean requestServiceBindingLocked(ServiceRecord r, IntentBindRecord i,
boolean execInFg, boolean rebind) throws TransactionTooLargeException {
if (r.app == null || r.app.thread == null) {
return false;
}
if ((!i.requested || rebind) && i.apps.size() > 0) {
try {
bumpServiceExecutingLocked(r, execInFg, "bind");
r.app.forceProcessStateUpTo(ActivityManager.PROCESS_STATE_SERVICE);
r.app.thread.scheduleBindService(r, i.intent.getIntent(), rebind,
r.app.repProcState);
// 不关心,略。。
}
return true;
}


可以看到,这里又通过IApplicationThread这个Binder进行了一次IPC调用,我们跟踪ActivityThread类里面的ApplicationThread的scheduleBindService方法,发现这个方法不过通过Handler转发了一次消息,真正的处理代码在handleBindService里面:

rivate void handleBindService(BindServiceData data) {
Service s = mServices.get(data.token);
if (s != null) {
try {
data.intent.setExtrasClassLoader(s.getClassLoader());
data.intent.prepareToEnterProcess();
try {
if (!data.rebind) {
IBinder binder = s.onBind(data.intent);
ActivityManagerNative.getDefault().publishService(
data.token, data.intent, binder);
} else {
s.onRebind(data.intent);
ActivityManagerNative.getDefault().serviceDoneExecuting(
data.token, SERVICE_DONE_EXECUTING_ANON, 0, 0);
}
ensureJitEnabled();
} catch (RemoteException ex) {
}
} catch (Exception e) {
}
}
}


我们要Bind的Service终于在这里完成了绑定!绑定之后又通过ActivityManagerNative这个Binder进行一次IPC调用,我们查看AMS的publishService方法,这个方法简单第调用了publishServiceLocked方法,源码如下:

void publishServiceLocked(ServiceRecord r, Intent intent, IBinder service) {
final long origId = Binder.clearCallingIdentity();
try {
if (r != null) {
Intent.FilterComparison filter
= new Intent.FilterComparison(intent);
IntentBindRecord b = r.bindings.get(filter);
if (b != null && !b.received) {
b.binder = service;
b.requested = true;
b.received = true;
for (int conni=r.connections.size()-1; conni>=0; conni--) {
ArrayList<ConnectionRecord> clist = r.connections.valueAt(conni);
for (int i=0; i<clist.size(); i++) {
ConnectionRecord c = clist.get(i);
if (!filter.equals(c.binding.intent.intent)) {
continue;
}
try {
c.conn.connected(r.name, service);
} catch (Exception e) {
}
}
}
}

serviceDoneExecutingLocked(r, mDestroyingServices.contains(r), false);
}
} finally {
Binder.restoreCallingIdentity(origId);
}
}


还记得我们之前提到的那个IServiceConnection吗?在bindServiceLocked方法里面,我们把这个IServiceConnection放到了一个ConnectionRecord的List中存放在ServiceRecord里面,这里所做的就是取出已经被Bind的这个Service对应的IServiceConnection对象,然后调用它的connected方法;我们说过,这个IServiceConnection也是一个Binder对象,它的Server端在LoadedApk.ServiceDispatcher里面。

最后提一点,以上我们分析了Service所在进程已经存在的情况,如果Service所在进程不存在,那么会调用startProcessLocked方法创建一个新的进程,并把需要启动的Service放在一个队列里面;创建进程的过程通过Zygote fork出来,进程创建成功之后会调用ActivityThread的main方法,在这个main方法里面间接调用到了AMS的attachApplication方法,在AMS的attachApplication里面会检查刚刚那个待启动Service队列里面的内容,并执行Service的启动操作;之后的启动过程与进程已经存在的情况下相同;可以自行分析。

Service的插件化思路

可以注册一个真正的Service组件ProxyService,让这个ProxyService承载一个真正的Service组件所具备的能力(进程优先级等);当启动插件的服务比如PluginService的时候,我们统一启动这个ProxyService,当这个ProxyService运行起来之后,再在它的onStartCommand等方法里面进行分发,执行PluginService的onStartCommond等对应的方法;我们把这种方案形象地称为「代理分发技术」

注册代理Service

我们需要一个货真价实的Service组件来承载进程优先级等功能,因此需要在AndroidManifest.xml中声明一个或者多个(用以支持多进程)这样的Sevice:

<service
android:name="com.weishu.upf.service_management.app.ProxyService"
android:process="plugin01"/>


加载Service

我们可以在ProxyService里面把任务转发给真正要启动的插件Service组件,要完成这个过程肯定需要创建一个对应的插件Service对象,比如PluginService;但是通常情况下插件存在与单独的文件之中,正常的方式是无法创建这个PluginService对象的,宿主程序默认的ClassLoader无法加载插件中对应的这个类;所以,要创建这个对应的PluginService对象,必须先完成插件的加载过程,让这个插件中的所有类都可以被正常访问;

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);

}


/**
* 解析Apk文件中的 <service>, 并存储起来
* 主要是调用PackageParser类的generateServiceInfo方法
* @param apkFile 插件对应的apk文件
* @throws Exception 解析出错或者反射调用出错, 均会抛出异常
*/
public void preLoadServices(File apkFile) throws Exception {
Class<?> packageParserClass = Class.forName("android.content.pm.PackageParser");
Method parsePackageMethod = packageParserClass.getDeclaredMethod("parsePackage", File.class, int.class);

Object packageParser = packageParserClass.newInstance();

// 首先调用parsePackage获取到apk对象对应的Package对象
Object packageObj = parsePackageMethod.invoke(packageParser, apkFile, PackageManager.GET_SERVICES);

// 读取Package对象里面的services字段
// 接下来要做的就是根据这个List<Service> 获取到Service对应的ServiceInfo
Field servicesField = packageObj.getClass().getDeclaredField("services");
List services = (List) servicesField.get(packageObj);

// 调用generateServiceInfo 方法, 把PackageParser.Service转换成ServiceInfo
Class<?> packageParser$ServiceClass = Class.forName("android.content.pm.PackageParser$Service");
Class<?> packageUserStateClass = Class.forName("android.content.pm.PackageUserState");
Class<?> userHandler = Class.forName("android.os.UserHandle");
Method getCallingUserIdMethod = userHandler.getDeclaredMethod("getCallingUserId");
int userId = (Integer) getCallingUserIdMethod.invoke(null);
Object defaultUserState = packageUserStateClass.newInstance();

// 需要调用 android.content.pm.PackageParser#generateActivityInfo(android.content.pm.ActivityInfo, int, android.content.pm.PackageUserState, int)
Method generateReceiverInfo = packageParserClass.getDeclaredMethod("generateServiceInfo",
packageParser$ServiceClass, int.class, packageUserStateClass, int.class);

// 解析出intent对应的Service组件
for (Object service : services) {
ServiceInfo info = (ServiceInfo) generateReceiverInfo.invoke(packageParser, service, 0, defaultUserState, userId);
mServiceInfoMap.put(new ComponentName(info.packageName, info.name), info);
}
}


拦截startService等调用过程

要手动控制Service组件的生命周期,需要拦截startService,stopService等调用,并且把启动插件Service全部重定向为启动ProxyService(保留原始插件Service信息);这个拦截过程需要Hook ActvityManagerNative,我们对这种技术应该是轻车熟路了

public static void hookActivityManagerNative() throws ClassNotFoundException,
NoSuchMethodException, InvocationTargetException,
IllegalAccessException, NoSuchFieldException {

Class<?> activityManagerNativeClass = Class.forName("android.app.ActivityManagerNative");

Field gDefaultField = activityManagerNativeClass.getDeclaredField("gDefault");
gDefaultField.setAccessible(true);

Object gDefault = gDefaultField.get(null);

// gDefault是一个 android.util.Singleton对象; 我们取出这个单例里面的字段
Class<?> singleton = Class.forName("android.util.Singleton");
Field mInstanceField = singleton.getDeclaredField("mInstance");
mInstanceField.setAccessible(true);

// ActivityManagerNative 的gDefault对象里面原始的 IActivityManager对象
Object rawIActivityManager = mInstanceField.get(gDefault);

// 创建一个这个对象的代理对象, 然后替换这个字段, 让我们的代理对象帮忙干活
Class<?> iActivityManagerInterface = Class.forName("android.app.IActivityManager");
Object proxy = Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
new Class<?>[] { iActivityManagerInterface }, new IActivityManagerHandler(rawIActivityManager));
mInstanceField.set(gDefault, proxy);
}


我们在收到startService,stopService之后可以进行具体的操作,对于startService来说,就是直接替换启动的插件Service为ProxyService等待后续处理,

if ("startService".equals(method.getName())) {
// API 23:
// public ComponentName startService(IApplicationThread caller, Intent service,
//        String resolvedType, int userId) throws RemoteException
// 找到参数里面的第一个Intent 对象
Pair<Integer, Intent> integerIntentPair = foundFirstIntentOfArgs(args);
Intent newIntent = new Intent();
// 代理Service的包名, 也就是我们自己的包名
String stubPackage = UPFApplication.getContext().getPackageName();
// 这里我们把启动的Service替换为ProxyService, 让ProxyService接收生命周期回调
ComponentName componentName = new ComponentName(stubPackage, ProxyService.class.getName());
newIntent.setComponent(componentName);
// 把我们原始要启动的TargetService先存起来
newIntent.putExtra(AMSHookHelper.EXTRA_TARGET_INTENT, integerIntentPair.second);

// 替换掉Intent, 达到欺骗AMS的目的
args[integerIntentPair.first] = newIntent;
Log.v(TAG, "hook method startService success");
return method.invoke(mBase, args);
}


分发Service

Hook ActivityManagerNative之后,所有的插件Service的启动都被重定向了到了我们注册的ProxyService,这样可以保证我们的插件Service有一个真正的Service组件作为宿主;但是要执行特定插件Service的任务,我们必须把这个任务分发到真正要启动的Service上去;以onStart为例,在启动ProxyService之后,会收到ProxyService的onStart回调,我们可以在这个方法里面把具体的任务交给原始要启动的插件Service组件:

@Override
public void onStart(Intent intent, int startId) {
Log.d(TAG, "onStart() called with " + "intent = [" + intent + "], startId = [" + startId + "]");

// 分发Service
ServiceManager.getInstance().onStart(intent, startId);
super.onStart(intent, startId);
}


匹配过程

上文中我们把启动插件Service重定向为启动ProxyService,现在ProxyService已经启动,因此必须把控制权交回原始的PluginService;在加载插件的时候,我们存储了插件中所有的Service组件的信息,因此,只需要根据Intent里面的Component信息就可以取出对应的PluginService。

private ServiceInfo selectPluginService(Intent pluginIntent) {
for (ComponentName componentName : mServiceInfoMap.keySet()) {
if (componentName.equals(pluginIntent.getComponent())) {
return mServiceInfoMap.get(componentName);
}
}
return null;
}


创建以及分发

可以看到,系统也是通过反射创建出了对应的Service对象,然后也创建了对应的Context,并给Service注入了活力。如果我们模拟系统创建Context这个过程,势必需要进行一系列反射调用,那么我们何不直接反射handleCreateService方法呢?

现在我们已经创建出了对应的PluginService,并且拥有至关重要的Context对象;接下来就可以把消息分发给原始的PluginService组件了,这个分发的过程很简单,直接执行消息对应的回调(onStart, onDestroy等)即可;因此,完整的startService分发过程如下:

public void onStart(Intent proxyIntent, int startId) {

Intent targetIntent = proxyIntent.getParcelableExtra(AMSHookHelper.EXTRA_TARGET_INTENT);
ServiceInfo serviceInfo = selectPluginService(targetIntent);

if (serviceInfo == null) {
Log.w(TAG, "can not found service : " + targetIntent.getComponent());
return;
}
try {

if (!mServiceMap.containsKey(serviceInfo.name)) {
// service还不存在, 先创建
proxyCreateService(serviceInfo);
}
Service service = mServiceMap.get(serviceInfo.name);
service.onStart(targetIntent, startId);
} catch (Exception e) {
e.printStackTrace();
}
}


、、、、、、、、、、、、、、、、、、、、、代码区、、、、、、、、、、、、、、、、、、、、、、、



配置文件

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.weishu.upf.service_management.app">
<application
android:allowBackup="true"
android:name="com.weishu.upf.service_management.app.UPFApplication"
android:label="@string/app_name"
android:icon="@mipmap/ic_launcher">

<activity android:name="com.weishu.upf.service_management.app.MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<service android:name="com.weishu.upf.service_management.app.ProxyService" android:process="plugin01"/>
</application>
</manifest>


UPFApplication

package com.weishu.upf.service_management.app;

import java.io.File;

import android.app.Application;
import android.content.Context;

import com.weishu.upf.service_management.app.hook.AMSHookHelper;
import com.weishu.upf.service_management.app.hook.BaseDexClassLoaderHookHelper;

/**
* 这个类只是为了方便获取全局Context的.
*/
public class UPFApplication extends Application {

private static Context sContext;

@Override
protected void attachBaseContext(Context base) {
super.attachBaseContext(base);
sContext = base;

try {
// 拦截startService, stopService等操作
AMSHookHelper.hookActivityManagerNative();
Utils.extractAssets(base, "test.jar");
File apkFile = getFileStreamPath("test.jar");
File odexFile = getFileStreamPath("test.odex");

// Hook ClassLoader, 让插件中的类能够被成功加载
BaseDexClassLoaderHookHelper.patchClassLoader(getClassLoader(), apkFile, odexFile);
// 解析插件中的Service组件
ServiceManager.getInstance().preLoadServices(apkFile);
} catch (Exception e) {
throw new RuntimeException("hook failed");
}
}

public static Context getContext() {
return sContext;
}
}


AMSHookHelper.hookActivityManagerNative();

AMSHookHelper

package com.weishu.upf.service_management.app.hook;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Proxy;

public class AMSHookHelper {

public static final String EXTRA_TARGET_INTENT = "extra_target_intent";

/**
* Hook AMS
* <p/>
* 主要完成的操作是  "把真正要启动的Activity临时替换为在AndroidManifest.xml中声明的替身Activity"
* <p/>
* 进而骗过AMS
*
* @throws ClassNotFoundException
* @throws NoSuchMethodException
* @throws InvocationTargetException
* @throws IllegalAccessException
* @throws NoSuchFieldException
*/
public static void hookActivityManagerNative() throws ClassNotFoundException,
NoSuchMethodException, InvocationTargetException,
IllegalAccessException, NoSuchFieldException {

//        17package android.util;
//        18
//        19/**
//         20 * Singleton helper class for lazily initialization.
//         21 *
//         22 * Modeled after frameworks/base/include/utils/Singleton.h
//         23 *
//         24 * @hide
//         25 */
//        26public abstract class Singleton<T> {
//            27    private T mInstance;
//            28
//                    29    protected abstract T create();
//            30
//                    31    public final T get() {
//                32        synchronized (this) {
//                    33            if (mInstance == null) {
//                        34                mInstance = create();
//                        35            }
//                    36            return mInstance;
//                    37        }
//                38    }
//            39}
//        40

Class<?> activityManagerNativeClass = Class.forName("android.app.ActivityManagerNative");

Field gDefaultField = activityManagerNativeClass.getDeclaredField("gDefault");
gDefaultField.setAccessible(true);

Object gDefault = gDefaultField.get(null);

// gDefault是一个 android.util.Singleton对象; 我们取出这个单例里面的字段
Class<?> singleton = Class.forName("android.util.Singleton");
Field mInstanceField = singleton.getDeclaredField("mInstance");
mInstanceField.setAccessible(true);

// ActivityManagerNative 的gDefault对象里面原始的 IActivityManager对象
Object rawIActivityManager = mInstanceField.get(gDefault);

// 创建一个这个对象的代理对象, 然后替换这个字段, 让我们的代理对象帮忙干活
Class<?> iActivityManagerInterface = Class.forName("android.app.IActivityManager");
Object proxy = Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
new Class<?>[] { iActivityManagerInterface }, new IActivityManagerHandler(rawIActivityManager));
mInstanceField.set(gDefault, proxy);
}

}


IActivityManagerHandler

package com.weishu.upf.service_management.app.hook;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

import android.content.ComponentName;
import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;
import android.util.Pair;

import com.weishu.upf.service_management.app.ProxyService;
import com.weishu.upf.service_management.app.ServiceManager;
import com.weishu.upf.service_management.app.UPFApplication;

/**
* @author weishu
* @dete 16/1/7.
*/
/* package */ class IActivityManagerHandler implements InvocationHandler {

private static final String TAG = "IActivityManagerHandler";

Object mBase;

public IActivityManagerHandler(Object base) {
mBase = base;
}

@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

if ("startService".equals(method.getName())) {
// 只拦截这个方法
// API 23:
// public ComponentName startService(IApplicationThread caller, Intent service,
//        String resolvedType, int userId) throws RemoteException

// 找到参数里面的第一个Intent 对象
Pair<Integer, Intent> integerIntentPair = foundFirstIntentOfArgs(args);
Intent newIntent = new Intent();

// 代理Service的包名, 也就是我们自己的包名
String stubPackage = UPFApplication.getContext().getPackageName();

// 这里我们把启动的Service替换为ProxyService, 让ProxyService接收生命周期回调
ComponentName componentName = new ComponentName(stubPackage, ProxyService.class.getName());
newIntent.setComponent(componentName);

// 把我们原始要启动的TargetService先存起来
newIntent.putExtra(AMSHookHelper.EXTRA_TARGET_INTENT, integerIntentPair.second);

// 替换掉Intent, 达到欺骗AMS的目的
args[integerIntentPair.first] = newIntent;

Log.v(TAG, "hook method startService success");
return method.invoke(mBase, args);

}

//     public int stopService(IApplicationThread caller, Intent service,
// String resolvedType, int userId) throws RemoteException
if ("stopService".equals(method.getName())) {
Intent raw = foundFirstIntentOfArgs(args).second;
if (!TextUtils.equals(UPFApplication.getContext().getPackageName(), raw.getComponent().getPackageName())) {
// 插件的intent才做hook
Log.v(TAG, "hook method stopService success");
return ServiceManager.getInstance().stopService(raw);
}
}

return method.invoke(mBase, args);
}

private Pair<Integer, Intent> foundFirstIntentOfArgs(Object... args) {
int index = 0;

for (int i = 0; i < args.length; i++) {
if (args[i] instanceof Intent) {
index = i;
break;
}
}
return Pair.create(index, (Intent) args[index]);
}
}


Utils.extractAssets(base, “test.jar”);

Utils

package com.weishu.upf.service_management.app;

import java.io.Closeable;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import android.content.Context;
import android.content.res.AssetManager;

/**
* @author weishu
* @date 16/3/29
*/
public class Utils {

/**
* 把Assets里面得文件复制到 /data/data/files 目录下
*
* @param context
* @param sourceName
*/
public static void extractAssets(Context context, String sourceName) {
AssetManager am = context.getAssets();
InputStream is = null;
FileOutputStream fos = null;
try {
is = am.open(sourceName);
File extractFile = context.getFileStreamPath(sourceName);
fos = new FileOutputStream(extractFile);
byte[] buffer = new byte[1024];
int count = 0;
while ((count = is.read(buffer)) > 0) {
fos.write(buffer, 0, count);
}
fos.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
closeSilently(is);
closeSilently(fos);
}

}

// --------------------------------------------------------------------------
private static void closeSilently(Closeable closeable) {
if (closeable == null) {
return;
}
try {
closeable.close();
} catch (Throwable e) {
// ignore
}
}

private static File sBaseDir;

}


BaseDexClassLoaderHookHelper.patchClassLoader(getClassLoader(), apkFile, odexFile);

BaseDexClassLoaderHookHelper

package com.weishu.upf.service_management.app.hook;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Array;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;

import dalvik.system.DexClassLoader;
import dalvik.system.DexFile;

/**
* 由于应用程序使用的ClassLoader为PathClassLoader
* 最终继承自 BaseDexClassLoader
* 查看源码得知,这个BaseDexClassLoader加载代码根据一个叫做
* dexElements的数组进行, 因此我们把包含代码的dex文件插入这个数组
* 系统的classLoader就能帮助我们找到这个类
*
* 这个类用来进行对于BaseDexClassLoader的Hook
* 类名太长, 不要吐槽.
* @author weishu
* @date 16/3/28
*/
public final class BaseDexClassLoaderHookHelper {

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); }
}


MainActivity

package com.weishu.upf.service_management.app;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;

/**
* @author weishu
* @date 16/5/9
*/
public class MainActivity extends Activity implements View.OnClickListener {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

setContentView(R.layout.main);
findViewById(R.id.startService1).setOnClickListener(this);
findViewById(R.id.startService2).setOnClickListener(this);
findViewById(R.id.stopService1).setOnClickListener(this);
findViewById(R.id.stopService2).setOnClickListener(this);

}

@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.startService1:
startService(new Intent().setComponent(
new ComponentName("com.weishu.upf.demo.app2", "com.weishu.upf.demo.app2.TargetService1")));

break;
case R.id.startService2:
startService(new Intent().setComponent(
new ComponentName("com.weishu.upf.demo.app2", "com.weishu.upf.demo.app2.TargetService2")));
break;

case R.id.stopService1:
stopService(new Intent().setComponent(
new ComponentName("com.weishu.upf.demo.app2", "com.weishu.upf.demo.app2.TargetService1")));
break;

case R.id.stopService2:
stopService(new Intent().setComponent(
new ComponentName("com.weishu.upf.demo.app2", "com.weishu.upf.demo.app2.TargetService2")));
break;
}
}
}


ProxyService

package com.weishu.upf.service_management.app;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

/**
* @author weishu
* @date 16/5/10
*/
public class ProxyService extends Service {

private static final String TAG = "ProxyService";

@Override
public void onCreate() {
Log.d(TAG, "onCreate() called");
super.onCreate();
}

@Override
public void onStart(Intent intent, int startId) {
Log.d(TAG, "onStart() called with " + "intent = [" + intent + "], startId = [" + startId + "]");

// 分发Service
ServiceManager.getInstance().onStart(intent, startId);
super.onStart(intent, startId);
}

@Override
public IBinder onBind(Intent intent) {
// TODO: 16/5/11 bindService实现
return null;
}

@Override
public void onDestroy() {
Log.d(TAG, "onDestroy() called");
super.onDestroy();
}
}


ServiceManager

package com.weishu.upf.service_management.app;

import java.io.File;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ServiceInfo;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;

import com.weishu.upf.service_management.app.hook.AMSHookHelper;

/**
* @author weishu
* @date 16/5/10
*/
public final class ServiceManager {

private static final String TAG = "ServiceManager";

private static volatile ServiceManager sInstance;

private Map<String, Service> mServiceMap = new HashMap<String, Service>();

// 存储插件的Service信息
private Map<ComponentName, ServiceInfo> mServiceInfoMap = new HashMap<ComponentName, ServiceInfo>();

public synchronized static ServiceManager getInstance() {
if (sInstance == null) {
sInstance = new ServiceManager();
}
return sInstance;
}

/**
* 启动某个插件Service; 如果Service还没有启动, 那么会创建新的插件Service
* @param proxyIntent
* @param startId
*/
public void onStart(Intent proxyIntent, int startId) {

Intent targetIntent = proxyIntent.getParcelableExtra(AMSHookHelper.EXTRA_TARGET_INTENT);
ServiceInfo serviceInfo = selectPluginService(targetIntent);

if (serviceInfo == null) {
Log.w(TAG, "can not found service : " + targetIntent.getComponent());
return;
}
try {

if (!mServiceMap.containsKey(serviceInfo.name)) {
// service还不存在, 先创建
proxyCreateService(serviceInfo);
}

Service service = mServiceMap.get(serviceInfo.name);
service.onStart(targetIntent, startId);
} catch (Exception e) {
e.printStackTrace();
}
}

/**
* 停止某个插件Service, 当全部的插件Service都停止之后, ProxyService也会停止
* @param targetIntent
* @return
*/
public int stopService(Intent targetIntent) {
ServiceInfo serviceInfo = selectPluginService(targetIntent);
if (serviceInfo == null) {
Log.w(TAG, "can not found service: " + targetIntent.getComponent());
return 0;
}
Service service = mServiceMap.get(serviceInfo.name);
if (service == null) {
Log.w(TAG, "can not runnning, are you stopped it multi-times?");
return 0;
}
service.onDestroy();
mServiceMap.remove(serviceInfo.name);
if (mServiceMap.isEmpty()) {
// 没有Service了, 这个没有必要存在了
Log.d(TAG, "service all stopped, stop proxy");
Context appContext = UPFApplication.getContext();
appContext.stopService(new Intent().setComponent(new ComponentName(appContext.getPackageName(), ProxyService.class.getName())));
}
return 1;
}

/**
* 选择匹配的ServiceInfo
* @param pluginIntent 插件的Intent
* @return
*/
private ServiceInfo selectPluginService(Intent pluginIntent) { for (ComponentName componentName : mServiceInfoMap.keySet()) { if (componentName.equals(pluginIntent.getComponent())) { return mServiceInfoMap.get(componentName); } } return null; }

/**
* 通过ActivityThread的handleCreateService方法创建出Service对象
* @param serviceInfo 插件的ServiceInfo
* @throws Exception
*/
private void proxyCreateService(ServiceInfo serviceInfo) throws Exception {
IBinder token = new Binder();

// 创建CreateServiceData对象, 用来传递给ActivityThread的handleCreateService 当作参数
Class<?> createServiceDataClass = Class.forName("android.app.ActivityThread$CreateServiceData");
Constructor<?> constructor = createServiceDataClass.getDeclaredConstructor();
constructor.setAccessible(true);
Object createServiceData = constructor.newInstance();

// 写入我们创建的createServiceData的token字段, ActivityThread的handleCreateService用这个作为key存储Service
Field tokenField = createServiceDataClass.getDeclaredField("token");
tokenField.setAccessible(true);
tokenField.set(createServiceData, token);

// 写入info对象
// 这个修改是为了loadClass的时候, LoadedApk会是主程序的ClassLoader, 我们选择Hook BaseDexClassLoader的方式加载插件
serviceInfo.applicationInfo.packageName = UPFApplication.getContext().getPackageName();
Field infoField = createServiceDataClass.getDeclaredField("info");
infoField.setAccessible(true);
infoField.set(createServiceData, serviceInfo);

// 写入compatInfo字段
// 获取默认的compatibility配置
Class<?> compatibilityClass = Class.forName("android.content.res.CompatibilityInfo");
Field defaultCompatibilityField = compatibilityClass.getDeclaredField("DEFAULT_COMPATIBILITY_INFO");
Object defaultCompatibility = defaultCompatibilityField.get(null);
Field compatInfoField = createServiceDataClass.getDeclaredField("compatInfo");
compatInfoField.setAccessible(true);
compatInfoField.set(createServiceData, defaultCompatibility);

Class<?> activityThreadClass = Class.forName("android.app.ActivityThread");
Method currentActivityThreadMethod = activityThreadClass.getDeclaredMethod("currentActivityThread");
Object currentActivityThread = currentActivityThreadMethod.invoke(null);

// private void handleCreateService(CreateServiceData data) {
Method handleCreateServiceMethod = activityThreadClass.getDeclaredMethod("handleCreateService", createServiceDataClass);
handleCreateServiceMethod.setAccessible(true);

handleCreateServiceMethod.invoke(currentActivityThread, createServiceData);

// handleCreateService创建出来的Service对象并没有返回, 而是存储在ActivityThread的mServices字段里面, 这里我们手动把它取出来
Field mServicesField = activityThreadClass.getDeclaredField("mServices");
mServicesField.setAccessible(true);
Map mServices = (Map) mServicesField.get(currentActivityThread);
Service service = (Service) mServices.get(token);

// 获取到之后, 移除这个service, 我们只是借花献佛
mServices.remove(token);

// 将此Service存储起来
mServiceMap.put(serviceInfo.name, service);
}

/**
* 解析Apk文件中的 <service>, 并存储起来
* 主要是调用PackageParser类的generateServiceInfo方法
* @param apkFile 插件对应的apk文件
* @throws Exception 解析出错或者反射调用出错, 均会抛出异常
*/
public void preLoadServices(File apkFile) throws Exception {
Class<?> packageParserClass = Class.forName("android.content.pm.PackageParser");
Method parsePackageMethod = packageParserClass.getDeclaredMethod("parsePackage", File.class, int.class);

Object packageParser = packageParserClass.newInstance();

// 首先调用parsePackage获取到apk对象对应的Package对象
Object packageObj = parsePackageMethod.invoke(packageParser, apkFile, PackageManager.GET_SERVICES);

// 读取Package对象里面的services字段
// 接下来要做的就是根据这个List<Service> 获取到Service对应的ServiceInfo
Field servicesField = packageObj.getClass().getDeclaredField("services");
List services = (List) servicesField.get(packageObj);

// 调用generateServiceInfo 方法, 把PackageParser.Service转换成ServiceInfo
Class<?> packageParser$ServiceClass = Class.forName("android.content.pm.PackageParser$Service");
Class<?> packageUserStateClass = Class.forName("android.content.pm.PackageUserState");
Class<?> userHandler = Class.forName("android.os.UserHandle");
Method getCallingUserIdMethod = userHandler.getDeclaredMethod("getCallingUserId");
int userId = (Integer) getCallingUserIdMethod.invoke(null);
Object defaultUserState = packageUserStateClass.newInstance();

// 需要调用 android.content.pm.PackageParser#generateActivityInfo(android.content.pm.ActivityInfo, int, android.content.pm.PackageUserState, int)
Method generateReceiverInfo = packageParserClass.getDeclaredMethod("generateServiceInfo",
packageParser$ServiceClass, int.class, packageUserStateClass, int.class);

// 解析出intent对应的Service组件
for (Object service : services) {
ServiceInfo info = (ServiceInfo) generateReceiverInfo.invoke(packageParser, service, 0, defaultUserState, userId);
mServiceInfoMap.put(new ComponentName(info.packageName, info.name), info);
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: