四、反编译工具Dedexer
Dedexer是目前在网上能找到的唯一一个反编译dex文件的开源工具[ ]。Dedexer下载后需要编译才能使用。如果你用过ant编译java程序,那么编译Dedexer是一件非常简单的工作。注意目前Dedexer的最新版本是1.5,只能使用junit4.5编译。下面以linux环境为例,讲一下Dedexer的编译使用过程。
下载ddx1.5.zip后,解压缩会产生一个dedexer目录,其中包含build.xml文件。我们需要根据本机的环境配置build.xml的内容,注意下面的粗体部分是我本机的配置。
<property name="home" value="/home/danny/myproject/dedex/dedexer"/>
<property name="junit-home" value="/home/danny/myproject/dedex"/>
<!-- Directories derived from the source tree root -->
<property name="classdir" value="${home}/classes"/>
<property name="src" value="${home}/sources"/>
<property name="testbase" value="${home}/testfiles"/>
<!-- Directories derived from the JUnit base -->
<property name="junit_jar" value="${junit-home}/junit-4.5.jar"/>
环境配置好之后可以开始编译了。当然要保证你已经安装好了ant编译工具。执行ant。
Buildfile: build.xml
init:
[mkdir] Created dir: /home/danny/myproject/dedex/dedexer/classes
compile:
[javac] Compiling 48 source files to /home/danny/myproject/dedex/dedexer/classes
[javac] Note: /home/danny/myproject/dedex/dedexer/sources/hu/uw/pallergabor/dedexer/Annotation.java uses unchecked or unsafe operations.
[javac] Note: Recompile with -Xlint:unchecked for details.
package:
[jar] Building jar: /home/danny/myproject/dedex/dedexer/ddx.jar
BUILD SUCCESSFUL
Total time: 3 seconds
好了,编译dedexer成功,只用了3秒种,生成了ddx.jar文件。我习惯修改一下它的文件名,加上版本号。用来反编译的命令如下:
Processing hello/world/R$string
Processing hello/world/R$layout
Processing hello/world/hello
Processing hello/world/R$attr
Processing hello/world/R
Processing hello/world/R$drawable
dedexer为每个class文件生成了一个后缀为ddx的文件。不出所料,有6个ddx文件。
R$attr.ddx R.ddx R$drawable.ddx R$layout.ddx R$string.ddx hello.ddx
看一下我们所关心的hello.ddx的内容。
.super android/app/Activity
.source hello.java
.method public <init>()V
.line 7
invoke-direct {v0},android/app/Activity/<init> ; <init>()V
return-void
.end method
.method public onCreate(Landroid/os/Bundle;)V
.line 11
invoke-super {v2,v3},android/app/Activity/onCreate ; onCreate(Landroid/os/Bundle;)V
.line 13
new-instance v0,android/widget/TextView
invoke-direct {v0,v2},android/widget/TextView/<init> ; <init>(Landroid/content/Context;)V
.line 14
const-string v1,"hello, OPhone"
invoke-virtual {v0,v1},android/widget/TextView/setText ; setText(Ljava/lang/CharSequence;)V
.line 15
invoke-virtual {v2,v0},hello/world/hello/setContentView ; setContentView(Landroid/view/View;)V
.line 16
return-void
.end method
从反编译的结果来看,代码的可读性仍然比较差,但比dexdump相比要好一些。我们能够看到“hello, OPhone”字符串是通过invoke-virtual {v0, v1}, android/widget/TextView/setText调用的。
dedexer与dexdump相比至少有3个优点。一,不需要在android模拟器中运行。二,把dex文件按照java源代码package的目录结构建好了目录,每个class文件对应一个ddx文件。不像dexdump那样把所有的结果都放在一起。三,按照Dedexer作者的说法,可以把 Dedexer作为一个像jasmin那样的反编译引擎,目前好多强大的java反编译工具都是以jasmin作为反编译引擎的。
五、结束语
本文简单介绍了apk文件的结构和内容,并介绍了反编译工具Dedexer的用法。也希望我在这里抛砖引玉,让更多的高手了解apk文件的结构,熟悉Dedexer这个反编译引擎,将来写出威力更高,可读性更强的dex反编译工具。