ARM assembly in Android Apps(1)

来源:互联网 发布:linux tmp 权限不够 编辑:程序博客网 时间:2024/06/10 10:59

一直在想,能不能用NDK编译ARM汇编语言程序,修改了ndk/samples中的hello-jni程序,增加了一个汇编语言函数,获取SP,LR,PC的值


思路:

开始时,不知道如何用汇编语言编写函数,因此用C语言实现了一个函数,然后编译一下,生成汇编语言代码,参考这些代码实现自己的汇编语言函数。


汇编源码文件asm_operations.s:

.text
.align 4
.global read_registers
.type read_registers, %function
read_registers:
str sp, [r0]
str lr, [r1]
str pc, [r2]

bx lr

.size read_registers, .-read_registers   

实现函数void read_registers(int* arg0, int* arg1, int* arg2)


在C语言源码文件hello-jni.c中调用函数read_registers:

#include <string.h>
#include <jni.h>


#include <stdio.h>
#include <android/log.h>


extern void read_registers(int* arg0, int* arg1, int* arg2);

jstring
Java_com_example_hellojni_HelloJni_stringFromJNI( JNIEnv* env,
                                                  jobject thiz )
{
int eSP = 0;
int eLR = 0;
int ePC = 0;


read_registers(&eSP, &eLR, &ePC);


// int __android_log_print(int prio, const char *tag,  const char *fmt, ...)


__android_log_print(ANDROID_LOG_INFO, "hello_jni", "eSP is: 0x%8x\n", eSP);
__android_log_print(ANDROID_LOG_INFO, "hello_jni", "eLR is: 0x%8x\n", eLR);
__android_log_print(ANDROID_LOG_INFO, "hello_jni", "ePC is: 0x%8x\n", ePC);



    return (*env)->NewStringUTF(env, "Hello from JNI 002!");
}


修改原来的Android.mk文件:

LOCAL_PATH := $(call my-dir)

include $(CLEAR_VARS)

LOCAL_ARM_MODE := arm

LOCAL_LDLIBS := -llog


LOCAL_MODULE    := hello-jni
LOCAL_SRC_FILES := hello-jni.c asm_operations.s


include $(BUILD_SHARED_LIBRARY)


程序编译后,在Android设备上执行,通过logcat查看log信息:

02-03 23:25:52.973  7271  7271 I hello_jni: eSP is: 0xbeb50568
02-03 23:25:52.973  7271  7271 I hello_jni: eLR is: 0x4caafc7c
02-03 23:25:52.973  7271  7271 I hello_jni: ePC is: 0x4caafd50

原创粉丝点击