Android jni 集成 Address Sanitizer

Address Sanitizer

該工具是google開源,用於對c++中的代碼進行質量檢測。

具體介紹:https://developer.android.google.cn/ndk/guides/asan?hl=zh_cn

按照官方的文檔集成,會遇到一些問題,比如對應so找不到等。所以踩了一些坑。記錄一下。

集成

整體思路如下:

對於debug版本,集成Address Sanitizer,便於在開發期間發現問題。

對於release版本,不進行集成,並避免對應的一些so添加到release中去。

將對應所需資源拷貝到工程目錄下

google的集成文檔中需要添加一些so文件,但是並沒有提供對應so下載。通過github等找了一份。

具體下載地址如下:https://download.csdn.net/download/lisdye2/12464858

將該文件包含目錄放到對應的工程目錄下。和src同級。

build.gradle中添加配置

debug {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'

            // 添加c層代碼檢測 https://developer.android.com/ndk/guides/asan
            sourceSets.debug.jniLibs.srcDir "sanitizer/jniLibs"
            sourceSets.debug.resources.srcDir("sanitizer")
            sourceSets.debug.resources.filter.exclude("sanitizer/jniLibs/**")
            externalNativeBuild {
                cmake {
                    arguments "-DSANITIZER=TRUE"
                }
            }
        }

CMakeLists.txt中添加配置

if (SANITIZER)
    target_compile_options(native-lib PUBLIC -fsanitize=address -fno-omit-frame-pointer)
    set_target_properties(native-lib PROPERTIES LINK_FLAGS -fsanitize=address)
endif()

其中native-lib表示對應的so文件名稱,根據需求替換

運行

運行時,加入了Address Sanitizer會影響執行的效率。如果遇見地址錯誤等,會崩潰,並拋出異常堆棧。如下爲堆棧的起始,具體內容很長。

==29443==ERROR: AddressSanitizer: stack-buffer-overflow on address 0x0071f1395248 at pc 0x0071e6ed2234 bp 0x0071f1395210 sp 0x0071f1395208

...

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章