java2smali python 粘合脚本

用于学习smali 语法而写的

 

# encoding=utf-8
'''
将java文件转换为smali文件
'''
import os
import sys
from glob import glob
import subprocess
DX_FILE = None
BAKSMALI = None
javafile = None
outsmali = None


def run_cmd(cmd):
    print(cmd)
    res = subprocess.Popen(cmd,shell=True,
                          stdout=subprocess.PIPE,
                          stderr=subprocess.PIPE,
                          env = {'JAVA_HOME':'/Library/Java/JavaVirtualMachines/jdk1.8.0_241.jdk/Contents/Home',
                                'PATH':'/Library/Java/JavaVirtualMachines/jdk1.8.0_241.jdk/Contents/Home/bin'
                                
                          }
                          )
    t= res.stdout.read()
    print(t.decode())
    t= res.stderr.read()
    print(t.decode())
   


def make_java():
    '''
    javac smaliTest.java
    '''
    run_cmd('javac %s' % javafile)


def class_to_dex():
    '''
    dx.jar form android-sdk\build-tools\23.0.1\lib
    java -jar dx.jar --dex --output=smaliTest.dex smaliTest.class
    '''
    cmd = 'java -jar {dx_jar} --dex --output={dx_path} {class_flie}'.format(
        dx_jar=DX_FILE, dx_path=javafile.split('.')[0]+'.dex', 
        class_flie=javafile.split('.')[0]+'.class'
    )
    run_cmd(cmd)


def dex_to_smali():
    '''
    baksmali.jar form android-sdk\platform-tools\
    https://bitbucket.org/JesusFreke/smali/downloads/?tab=downloads
    java -jar baksmali.jar smaliTest.dex

    '''
    cmd = 'java -jar {bs} d {dx_path}'.format(bs=BAKSMALI,
        dx_path=javafile.split('.')[0]+'.dex')
    run_cmd(cmd)


def check_env():
    global DX_FILE, BAKSMALI
    from pprint import pprint as pt
    print('check android sdk')
    t = os.environ.get('ANDROID_HOME')
    if not t:
        print('not fond android sdk.')
        sys.exit(-1)

    _dx_path = os.path.join(t, 'build-tools', '*', 'lib', 'dx.jar')
    path = glob(_dx_path)
    if len(path) < 1:
        print('not fond dx.jar file')
        sys.exit(-1)
    DX_FILE = path[0]

    _baksmali_path = os.path.join(
        t, 'build-tools', 'platform-tools', 'baksmali.jar')
    path = glob(_baksmali_path)
    if len(path) < 1:
        path = glob('./baksmali*.jar')
        if len(path) < 1:
            print('not fond dx.jar file')
            sys.exit(-1)
    BAKSMALI = path[0]
    print(DX_FILE)
    run_cmd('java -version')


if __name__ == "__main__":
    check_env()
    if len(sys.argv) >= 2:
        javafile = sys.argv[1]
        run_cmd('echo "%s"' % javafile)
        outsmali = javafile.split('.')[0]+'.smali'
    else:
        print('没有java文件')
        sys.exit(0)

    if len(sys.argv) >= 3:
        outsmali = sys.argv[2]

    make_java()
    class_to_dex()
    dex_to_smali()

  其中java home 写死在里面,可以用命令 /usr/libexec/java_home -V 查看系统安装的java

      其次要注意android sdk 对应的jdk 和其他jar要对应的jdk,这里用的是jdk8

      还要注意baksmali 等的参数可能会随着版本变更。

      最后。。。。smali文件会出现在out目录下。

 

posted @ 2020-02-02 15:48  apuyuseng  阅读(346)  评论(0编辑  收藏  举报