---
title: "Android 6.0下报错: UnsatisfiedLinkError: dlopen failed ... text relocations"
author: "OliveExcel"
date: "2015-10-17T18:28:30Z"
tags: []
categories: ["移动开发"]
slug: "android-6-0-unsatisfiedlinkerror-dlopen-failed-text-relocations"
draft: true
lastmod: "2016-06-17T11:39:25Z"
id: 2249768
url: "https://oliveexcel.iteye.com/blog/2249768"
---

**20160617更新:**

**使用Android 6.0的NDK重新编译so文件, 即可解决问题.**

 

**===================================================================**

 

**20151017内容:**

**首先贴一下这个问题的官方答复:**

https://code.google.com/p/android-developer-preview/issues/detail?id=3028

 

**先介绍一下这个问题的背景 (没兴趣看的, 可以直接跳到下文的问题解决方案):**

1\. 这个问题出现在loadLibrary()的过程中.

2\. 在Android 6.0之前, text reloactions问题, 会在编译的过程中, 作为warning报出来, log大致如下:

ActivityManager: WARNING: linker: libdvm.so has text relocations. This is wasting memory and is a security risk. Please fix.

    在Android 6.0中, 原来的warning被升级为error了. 因此, 同样的库文件, 在Android 6.0前的环境运行, 不报错, 6.0下就会crash掉.

3\. **text reloactions**又被称为**TEXTREL**, 它与PIC相关, 先说PIC:

PIC: Position Independent Code, 指一段代码, 在加载到内存后, 其物理地址与代码本身是无关的.

为什么要使用PIC:

**1. 效率相关**: 使用PIC后, 代码可以被加载到内存的任意位置, 即不存在某段代码始终对应特定物理地址的情况, 这样的方式, 适用于共享对象的加载.

换个说法, 使用PIC的共享对象, 在内存中是真正"共享"的; 而未使用PIC的共享对象, 在被不同进程加载的过程中, 会产生多个copy, 从而引入效率问题.

**2. 安全相关**: 使用PIC后, 特定代码被加载的内存地址不确定, 这样可以避免某些内存地址敏感的攻击. RedHat有一篇相关的文章: https://securityblog.redhat.com/2012/11/28/position-independent-executables-pie

回到**TEXTREL**, 它实际上是源码中存在"特定代码映射特定地址". 加载代码时, 必须将其加载到特定物理地址, 导致调用这些代码时, 必需增加一个relocation的过程.

 

**解决方案:**

**方案一 (官方推荐):**

1\. 在[这里](https://code.google.com/p/android-developer-preview/issues/detail?id=3028 "官方推荐: TEXTREL问题解决方案")有Google的同事推荐的方案

2\. 以下是解决步骤:

操作步骤: https://wiki.gentoo.org/wiki/Hardened/Textrels\_Guide

**这里面东西好多你不会想看我再写一次的所以自己看吧**

一句概括要做的: 通过scanelf / objdump定位存在TEXTREL问题的文件, 以及关键代码在文件中的偏移量, 然后根据偏移量对应的特征 (函数名 / hard code的绝对地址等), 定位到代码所在.

**方案二 (简单但会影响程序效率):** 

在mk脚本中, 对LOCAL\_CFLAGS, 增加-fPIC参数, 同时按需求配置链接库的参数. 此方案的参考源是[这里](http://stackoverflow.com/questions/30498776/position-independent-executables-and-android-lollipop "StackOverflow: PIE in Android 5.X").

 

=====================================================================

 

**相关参考资料:**

1\. TEXTREL问题的官方回复: https://code.google.com/p/android-developer-preview/issues/detail?id=3028

2\. TEXTREL问题分析定位: https://wiki.gentoo.org/wiki/Hardened/Textrels\_Guide

3\. Android 5.0安全性增强描述文档: https://source.android.com/devices/tech/security/enhancements/enhancements50.html

4\. PIC的wiki: https://en.wikipedia.org/wiki/Position-independent\_code

5\. Oracle关于PIC的描述: https://docs.oracle.com/cd/E19683-01/816-1386/chapter4-29405/index.html

6\. RedHat关于PIE的描述: https://securityblog.redhat.com/2012/11/28/position-independent-executables-pie/

7\. StackOverflow上对Android 5.0 PIE问题的解决方案: http://stackoverflow.com/questions/30498776/position-independent-executables-and-android-lollipop