插件化中加载so库解决方案

简介

先简单介绍下,我们知道jninative层与java层交互的桥梁,有了jni,我们可以通过动态或静态的方式去加载so,从而读取so库中的native逻辑。

常用架构

当我们需要将native代码打包成so库时,我们需要使用ndk-build等命令去生成对应的架构so库,常用的架构如下:
armeabi,armeabi-v7a,x86,mips,arm64-v8a,mips64,x86_64

外部加载与内部加载

  • 打包在apk中的情况,不需要开发者自己去判断ABI,Android系统在安装APK的时候,不会安装APK里面全部的so库文件,而是会根据当前CPU类型支持的ABI,从APK里面拷贝最合适的so库,并保存在APP的内部存储路径的libs 下面。
  • 动态加载外部so的情况下,需要我们判断ABI类型来加载相应的so,Android系统不会帮我们处理。

加载so的两种方式

  • System.load
    参数必须为库文件的绝对路径
    使用注意:只能将so放到内部进行绝对路径加载,而不能放置于sd卡,否则会抛异常
  • System.loadLibrary
    参数为库文件名,不包含库文件的扩展名

插件中so加载问题定位

小编写的《实战插件化-MPlugin》使用到了如下加载so方式

    // 步骤1:加载生成的so库文件
    // 注意要跟so库文件名相同
    static {
        System.loadLibrary("hello_jni");
    }

    // 步骤2:定义在JNI中实现的方法
    public native String getFromJNI();

如果仅仅是使用addDexPath方法将插件dex插入到宿主dexElements中,那么插件apk中存在加载so的话,是会抛经典的UnsatisfiedLinkError异常
通过阅读android7.0源码我们发现,当我们调用System.loadLibrary("hello_jni")方法时,会进入如下源码层

System.java
public static void loadLibrary(String libname) {
       Runtime.getRuntime().loadLibrary0(VMStack.getCallingClassLoader(), libname);
}

Runtime.java
synchronized void loadLibrary0(ClassLoader loader, String libname) {
        if (libname.indexOf((int)File.separatorChar) != -1) {
            throw new UnsatisfiedLinkError(
    "Directory separator should not appear in library name: " + libname);
        }
        String libraryName = libname;
        if (loader != null) {
            String filename = loader.findLibrary(libraryName);
            if (filename == null) {
                throw new UnsatisfiedLinkError(loader + " couldn't find \"" +
                                               System.mapLibraryName(libraryName) + "\"");
            }
            String error = doLoad(filename, loader);
            if (error != null) {
                throw new UnsatisfiedLinkError(error);
            }
            return;
        }

而通过如上源码我们会发现当filenamenull时,会抛出经典的UnsatisfiedLinkError异常,所以我们继续看loader.findLibrary(libraryName)这个方法,源码如下:

BaseDexClassLoader.java
@Override
public String findLibrary(String name) {
    return pathList.findLibrary(name);
}

DexPathList.java
public String findLibrary(String libraryName) {
    String fileName = System.mapLibraryName(libraryName);
    for (Element element : nativeLibraryPathElements) {
        String path = element.findNativeLibrary(fileName);
        if (path != null) {
            return path;
        }
    }
    return null;
}

通过如上源码我们大概知道了,System.loadLibrary是通过BaseDexClassLoader中的nativeLibraryPathElements数组来遍历查询子element来获得librarypath,所以我们定位到nativeLibraryPathElements,再来看nativeLibraryPathElements是如何生成的,继续往下看源码

DexPathList.java
public DexPathList(ClassLoader definingContext, String dexPath,
            String librarySearchPath, File optimizedDirectory) {
                                              ········
        ArrayList<IOException> suppressedExceptions = new ArrayList<IOException>();
        this.dexElements = makeDexElements(splitDexPath(dexPath), optimizedDirectory,
                                           suppressedExceptions, definingContext);
        this.nativeLibraryDirectories = splitPaths(librarySearchPath, false);
        this.systemNativeLibraryDirectories =
                splitPaths(System.getProperty("java.library.path"), true);
        List<File> allNativeLibraryDirectories = new ArrayList<>(nativeLibraryDirectories);
        allNativeLibraryDirectories.addAll(systemNativeLibraryDirectories);

        this.nativeLibraryPathElements = makePathElements(allNativeLibraryDirectories,
                                                          suppressedExceptions,
                                                          definingContext);
                                              ········
}

通过如上源码我们可以知道原来dexElementsnativeLibraryPathElements是分开的,所以这就是为什么我们明明将插件apk中的dex插入到宿主apk的dexElements中去运行插件apk,而插件apk中因为加载了so从而导致抛出经典的UnsatisfiedLinkError异常。

解决方案

  • 第一种方式:通过DexClassLoader去load取插件apk,我们知道DexClassLoader 中还可以传入libraryPath,该参数就是允许你指定so加载路径,所以实现方式如下:
String librarySearchPath = "/data/data/mplugindemo.shengyuan.com.mplugindemo/mplugin_demo/lib/";
DexClassLoader loader = new DexClassLoader(dexPath, mContext.getCacheDir().getAbsolutePath(),librarySearchPath, mContext.getClassLoader());

然后获得如上loader对象后,如果你的so加载逻辑是在fragment中,而只是为了将插件中的fragment载入到宿主容器中显示,如上方式就可以了,但是如果你是希望去启动插件Activity,由插件Activity去加载so的话,还需要将LoadedApk中的mClassLoader对象替换成如上loader对象。(不建议使用,因为当你使用插件apk跳转到下一个页面的时候,会抛出找不到第三方公共库的异常,除非你重写startActivity,然后load插件dex中的class来启动对应的activity页面)

  • 第二种方式:可以参考小编之前的《剖析ClassLoader深入热修复原理》文章中提到的,在 PathClassLoaderBootClassLoader 之间插入一个 自定义的MyClassLoader,然后在MyClassLoader中重写findLibrary方法
  • 第三种方式:通过如上阅读定位我们知道,核心点在nativeLibraryPathElements数组,因为我们知道nativeLibraryPathElements数组是通过makePathElements方法构建生成的,所以我们可以通过反射去调用makePathElements方法,将librarySearchPath路径传入,从而获得新的nativeLibraryPathElements数组,然后将新旧合并。
    实现方式如下:
 public static void insertNativeLibraryPathElements(File soDirFile,Context context){
        PathClassLoader pathClassLoader = (PathClassLoader) context.getClassLoader();
        Object pathList = getPathList(pathClassLoader);
        if(pathList != null) {
            Field nativeLibraryPathElementsField = null;
            try {

                Method makePathElements;
                Object invokeMakePathElements;
                boolean isNewVersion = Build.VERSION.SDK_INT > Build.VERSION_CODES.N_MR1;
                //调用makePathElements
                makePathElements = isNewVersion?pathList.getClass().getDeclaredMethod("makePathElements", List.class):pathList.getClass().getDeclaredMethod("makePathElements", List.class,List.class,ClassLoader.class);
                makePathElements.setAccessible(true);
                ArrayList<IOException> suppressedExceptions = new ArrayList<>();
                List<File> nativeLibraryDirectories = new ArrayList<>();
                nativeLibraryDirectories.add(soDirFile);
                List<File> allNativeLibraryDirectories = new ArrayList<>(nativeLibraryDirectories);
                //获取systemNativeLibraryDirectories
                Field systemNativeLibraryDirectoriesField = pathList.getClass().getDeclaredField("systemNativeLibraryDirectories");
                systemNativeLibraryDirectoriesField.setAccessible(true);
                List<File> systemNativeLibraryDirectories = (List<File>) systemNativeLibraryDirectoriesField.get(pathList);
                Log.i("insertNativeLibrary","systemNativeLibraryDirectories "+systemNativeLibraryDirectories);
                allNativeLibraryDirectories.addAll(systemNativeLibraryDirectories);
                invokeMakePathElements = isNewVersion?makePathElements.invoke(pathClassLoader, allNativeLibraryDirectories):makePathElements.invoke(pathClassLoader, allNativeLibraryDirectories,suppressedExceptions,pathClassLoader);
                Log.i("insertNativeLibrary","makePathElements "+invokeMakePathElements);

                nativeLibraryPathElementsField = pathList.getClass().getDeclaredField("nativeLibraryPathElements");
                nativeLibraryPathElementsField.setAccessible(true);
                Object list = nativeLibraryPathElementsField.get(pathList);
                Log.i("insertNativeLibrary","nativeLibraryPathElements "+list);
                Object dexElementsValue = combineArray(list, invokeMakePathElements);
                //把组合后的nativeLibraryPathElements设置到系统中
                nativeLibraryPathElementsField.set(pathList,dexElementsValue);
            } catch (NoSuchFieldException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
        }
    }

注意

需要先解压插件apk,提取apk中的so库,根据Build.CPU_ABI来判断当前适用的so架构,然把对应架构的so库复制到宿主apk对应的data so目录下(/data/data/mplugindemo.shengyuan.com.mplugindemo/mplugin168/lib/arm64-v8a
已在android7.0、8.0验证通过
实例地址:https://github.com/3332523marco/MPlugin

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,847评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,208评论 1 292
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,587评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,942评论 0 205
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,332评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,587评论 1 218
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,853评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,568评论 0 198
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,273评论 1 242
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,542评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,033评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,373评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,031评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,073评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,830评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,628评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,537评论 2 269