Activity外掛化原理第一種方案:Hook Instrumentation

顧林海發表於2019-01-30

人生一切難題,知識給你答案

溫馨提示:閱讀本文需要15-20分鐘(一大波程式碼)
公眾號:顧林海(每天更新優質文章)


今天,我們來解決一個問題:

Activity外掛化原理第一種方案:Hook Instrumentation

人生一切難題,知識給你答案。


Activity的外掛化解決的一個根本性問題就是外掛中的Activity並沒有在宿主的AndroidManifest.xml中進行註冊,也就是說我們需要啟動一個未註冊的Activity,因此需要對Activity的啟動過程有個瞭解。

啟動Activity時會請求AMS建立Activity,這裡的AMS指的是ActivityManagerService,AMS所屬的程式與宿主(發起者)不屬於同一個程式,AMS位於SystemServer程式中。

未命名檔案 (5).png

應用程式程式與AMS之間的通訊是通過Binder來實現的,AMS要管理所有APP的啟動請求,因此我們不能在SystemServer程式中進行相應的Hook,那麼我們只能在應用程式中進行相應的Hook。

如果我們啟動一個未註冊的Activity,AMS會去檢查AndroidManifest中是否註冊了該Activity,如果未註冊會報錯。

未命名檔案 (6).png

為了讓AMS驗證通過,需要啟動一個預先在AndroidManifest中註冊的Activity,我們稱之為佔坑,在啟動外掛Activity時替換為佔坑Activity,達到一個欺上瞞下的作用,當AMS驗證通過之後,需要將啟動的佔坑Activity替換為外掛Activity。

未命名檔案 (8).png

總結下來Activity的外掛化需要做兩件事:

  • 將請求啟動的外掛Activity替換為佔坑Activity。
  • 繞過AMS驗證後,將佔坑Activity替換為外掛Activity。

什麼時候將外掛Activity替換為佔坑Activity?又是什麼時候還原外掛Activity?這需要我們對Activity的啟動流程有個相應的認識。

我們在Activity中呼叫startActivity方法如下:

    @Override
    public void startActivity(Intent intent) {
        this.startActivity(intent, null);
    }
    
        @Override
    public void startActivity(Intent intent, @Nullable Bundle options) {
        if (options != null) {
           startActivityForResult(intent, -1, options);
        } else {
           startActivityForResult(intent, -1);
        }
    }
複製程式碼

呼叫startActivityForResult方法:

    public void startActivityForResult(@RequiresPermission Intent intent, int requestCode,
            @Nullable Bundle options) {
        if (mParent == null) {
            //Activity啟動
            options = transferSpringboardActivityOptions(options);
            Instrumentation.ActivityResult ar =
                mInstrumentation.execStartActivity(
                    this, mMainThread.getApplicationThread(), mToken, this,
                    intent, requestCode, options);
            if (ar != null) {
                mMainThread.sendActivityResult(
                    mToken, mEmbeddedID, requestCode, ar.getResultCode(),
                    ar.getResultData());
            }
            if (requestCode >= 0) {
                mStartedActivity = true;
            }

            cancelInputsAndStartExitTransition(options);
            windows.
        } else {
            if (options != null) {
                mParent.startActivityFromChild(this, intent, requestCode, options);
            } else {
                mParent.startActivityFromChild(this, intent, requestCode);
            }
        }
    }

複製程式碼

startActivityForResult方法中通過呼叫mInstrumentation的execStartActivity方法來啟動Activity,這個mInstrumentation是Activity的成員變數,在ActivityThread的performLaunchActivity方法中通過Activity的attach方法傳入,同時Activity的建立也是在performLaunchActivity方法中建立的,通過mInstrumentation.newActivity。

//:/frameworks/base/core/java/android/app/ActivityThread.java
private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
    ...
    try {
        java.lang.ClassLoader cl = appContext.getClassLoader();
        activity = mInstrumentation.newActivity(
                    cl, component.getClassName(), r.intent);
        StrictMode.incrementExpectedActivityCount(activity.getClass());
        r.intent.setExtrasClassLoader(cl);
        r.intent.prepareToEnterProcess();
        if (r.state != null) {
            r.state.setClassLoader(cl);
        }
    }
    ...
    activity.attach(appContext, this, getInstrumentation(), r.token,
                        r.ident, app, r.intent, r.activityInfo, title, r.parent,
                        r.embeddedID, r.lastNonConfigurationInstances, config,
                        r.referrer, r.voiceInteractor, window, r.configCallback);
    ...
}
複製程式碼

綜上所述Instrumentation提供了execStartActivity方法來啟動Activity,newActivity方法來建立Activity。因此,第一種方案就是用代理Instrumentation來替代Activity的Instrumentation,並在代理Instrumentation的execStartActivity方法中替換為佔坑Activity,在newActivity方法還原外掛Activity。

現在我們基於第一種方案Hook Instrumentation來實現Activity的外掛化。

首先建立佔坑Activity:

public class StubActivity extends AppCompatActivity {

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_stub);
    }
}
複製程式碼

建立外掛Activity:

public class TargetActivity extends AppCompatActivity {

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_target);
    }
}
複製程式碼

並在AndroidManifest.xml中註冊佔坑Activity:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="com.glh.haiproject01">

    <application
        android:name=".MyApplication"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme"
        tools:ignore="AllowBackup,GoogleAppIndexingWarning">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".StubActivity" />
    </application>

</manifest>
複製程式碼

在AndroidManifest.xml中沒有註冊外掛Activity,這時如果啟動外掛Activity會報錯。

最後Hook Instrumentation,將ActivityThread中的成員變數Instrumentation替換成代理的Instrumentation。

建立代理Instrumentation類:

public class InstrumentationProxy extends Instrumentation {

    private Instrumentation mInstrumentation;
    private PackageManager mPackageManager;

    public InstrumentationProxy(Instrumentation instrumentation, PackageManager packageManager) {
        this.mInstrumentation = instrumentation;
        this.mPackageManager = packageManager;
    }

    public ActivityResult execStartActivity(
            Context who, IBinder contextThread, IBinder token, Activity target,
            Intent intent, int requestCode, Bundle options) {

        List<ResolveInfo> resolveInfo = mPackageManager.queryIntentActivities(intent, PackageManager.MATCH_ALL);
        //判斷啟動的外掛Activity是否在AndroidManifest.xml中註冊過
        if (null == resolveInfo || resolveInfo.size() == 0) {
            //儲存目標外掛
            intent.putExtra(HookHelper.REQUEST_TARGET_INTENT_NAME, intent.getComponent().getClassName());
            //設定為佔坑Activity
            intent.setClassName(who, "com.glh.haiproject01.StubActivity");
        }

        try {
            Method execStartActivity = Instrumentation.class.getDeclaredMethod("execStartActivity",
                    Context.class, IBinder.class, IBinder.class, Activity.class,
                    Intent.class, int.class, Bundle.class);
            return (ActivityResult) execStartActivity.invoke(mInstrumentation, who, contextThread, token, target, intent, requestCode, options);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        return null;
    }

    public Activity newActivity(ClassLoader cl, String className, Intent intent) throws InstantiationException,
            IllegalAccessException, ClassNotFoundException {
        String intentName=intent.getStringExtra(HookHelper.REQUEST_TARGET_INTENT_NAME);
        if(!TextUtils.isEmpty(intentName)){
            return super.newActivity(cl,intentName,intent);
        }
        return super.newActivity(cl,className,intent);
    }

}
複製程式碼

代理類InstrumentationProxy的execStartActivity方法先判斷外掛Activity是否在AndroidManifest.xml中註冊過,如果沒有註冊過就需要替換佔坑的Activity,在newActivity方法中還原外掛Activity。

代理類InstrumentationProxy寫完後,需要對ActivityThread的成員變數mInstrumentation進行替換。

public class MyApplication extends Application {

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        hookActivityThreadInstrumentation();
    }


    private void hookActivityThreadInstrumentation(){
        try {
            Class<?> activityThreadClass=Class.forName("android.app.ActivityThread");
            Field activityThreadField=activityThreadClass.getDeclaredField("sCurrentActivityThread");
            activityThreadField.setAccessible(true);
            //獲取ActivityThread物件sCurrentActivityThread
            Object activityThread=activityThreadField.get(null);

            Field instrumentationField=activityThreadClass.getDeclaredField("mInstrumentation");
            instrumentationField.setAccessible(true);
            //從sCurrentActivityThread中獲取成員變數mInstrumentation
            Instrumentation instrumentation= (Instrumentation) instrumentationField.get(activityThread);
            //建立代理物件InstrumentationProxy
            InstrumentationProxy proxy=new InstrumentationProxy(instrumentation,getPackageManager());
            //將sCurrentActivityThread中成員變數mInstrumentation替換成代理類InstrumentationProxy
            instrumentationField.set(activityThread,proxy);
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}
複製程式碼

這時我們在主介面點選跳轉外掛Activity:

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        findViewById(R.id.btn_startActivity).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent(MainActivity.this,TargetActivity.class);
                startActivity(intent);
            }
        });
    }
}
複製程式碼

執行效果:

wq1.gif


838794-506ddad529df4cd4.webp.jpg

相關文章