### Install specific NDK version with sdkmanager Source: https://github.com/android/ndk-samples/wiki/Configure-NDK-Path Example of installing a specific side-by-side NDK version (21.1.6273396) from the canary channel (channel=3). The installed location will be $SDK/ndk/21.1.6273396. ```bash ${sdk}/tools/bin/sdkmanager --channel=3 --install "ndk;21.1.6273396" ``` -------------------------------- ### sdkmanager generic NDK install command Source: https://github.com/android/ndk-samples/wiki/Configure-NDK-Path Generic syntax for installing NDKs with the sdkmanager command line tool. Use --install with an ndk-selection value and --channel to specify the release channel (0=stable, 1=beta, 3=canary). The tool may be located under tools/bin depending on your SDK version. ```bash ${sdk}/cmdline-tools/latest/bin/sdkmanager --install "ndk-selection" --channel=${channel} ``` -------------------------------- ### List available NDK versions with sdkmanager Source: https://github.com/android/ndk-samples/wiki/Configure-NDK-Path Lists available NDK versions using the sdkmanager --list option. Useful for checking which NDK versions are available before installing. ```bash ${sdk}/tools/bin/sdkmanager --list ``` -------------------------------- ### Failure message output Source: https://github.com/android/ndk-samples/blob/main/unit-test/README.md Example output when the test fails, showing the assertion error and expected vs actual values. ```text java.lang.AssertionError: /path/to/ndk-samples/unit-test/app/src/main/cpp/adder_test.cpp:6 Expected equality of these values: 4 add(1,2) Which is: 3 ``` -------------------------------- ### CMakeLists.txt for exceptions sample Source: https://github.com/android/ndk-samples/blob/main/exceptions/app/src/main/cpp/CMakeLists.txt CMake configuration for the exceptions sample. Requires CMake 3.22.1 or higher, uses the AppLibrary module, and links against the base package and the log library. ```cmake cmake_minimum_required(VERSION 3.22.1) project(exceptions LANGUAGES CXX) include(AppLibrary) find_package(base CONFIG REQUIRED) add_app_library( exceptions SHARED native-lib.cpp exception_helper.cpp ) target_link_libraries( exceptions PRIVATE base::base log ) ``` -------------------------------- ### Load orderfile and inspect with nm Source: https://github.com/android/ndk-samples/blob/main/orderfile/README.md Commands to move the generated orderfile into the CMake source directory and inspect the shared library's symbol layout with nm. ```bash mv demo.orderfile app/src/main/cpp nm -n liborderfiledemo.so ``` -------------------------------- ### CMakeLists.txt for camera-utils library Source: https://github.com/android/ndk-samples/blob/main/camera/camera-utils/src/main/cpp/CMakeLists.txt CMake configuration for the camera-utils static library. Requires CMake 3.22.1 or later and C++ language support. Includes the AppLibrary module and defines the camera-utils library with camera_utils.cpp as its source. Exposes the include directory and links against the log library. ```cmake cmake_minimum_required(VERSION 3.22.1) project(CameraCommon LANGUAGES CXX) include(AppLibrary) add_app_library(camera-utils STATIC camera_utils.cpp ) target_include_directories(camera-utils PUBLIC include) target_link_libraries(camera-utils PUBLIC log) ``` -------------------------------- ### Set up orthographic projection matrix with glm::ortho Source: https://github.com/android/ndk-samples/blob/main/endless-tunnel/README.md C++ code showing how to set up the projection matrix for the normalized 2D coordinate system. It uses glm::ortho with the screen aspect ratio and a range of 0 to 1 for Y, then combines it with a model matrix for rendering. ```cpp glm::mat4 modelMat, mat; // set up projection matrix float aspect = SceneManager::GetInstance()->GetScreenAspect(); glm::mat4 orthoMat = glm::ortho(0.0f, aspect, 0.0f, 1.0f); // ... (set up modelMat as needed) // determine final matrix for rendering mat = orthoMat * modelMat; // render something mShader->RenderSimpleGeom(&mat, mGeom); ``` -------------------------------- ### Generate orderfile with adb and llvm-profdata Source: https://github.com/android/ndk-samples/blob/main/orderfile/README.md Commands to extract the raw profile from the device and generate an orderfile using llvm-profdata. Requires an optimization flag other than -O0 for profile instrumentation to work. ```bash adb shell "run-as com.example.orderfiledemo sh -c 'cat /data/user/0/com.example.orderfiledemo/cache/demo.profraw' | cat > /data/local/tmp/demo.profraw" adb pull /data/local/tmp/demo.profraw . /toolchains/llvm/prebuilt//bin/llvm-profdata merge demo.profraw -o demo.profdata /toolchains/llvm/prebuilt//bin/llvm-profdata order demo.profdata -o demo.orderfile ``` -------------------------------- ### Load native library in Kotlin and Java Source: https://github.com/android/ndk-samples/blob/main/orderfile/README.md Kotlin and Java equivalents for loading the native library. The Kotlin version uses a companion object with an init block, while the Java version uses a static initializer. ```kotlin # Kotlin companion object { init { System.loadLibrary("orderfiledemo") } } # Java static { System.loadLibrary("orderfiledemo"); } ``` -------------------------------- ### CMakeLists.txt for NativeCodec sample Source: https://github.com/android/ndk-samples/blob/main/native-codec/app/src/main/cpp/CMakeLists.txt CMake configuration for the NativeCodec sample. Sets minimum CMake version 3.22.1, declares a C++ project, includes the AppLibrary module, finds the base package, and defines a shared library 'native-codec-jni' from looper.cpp and native-codec-jni.cpp. Links against base, android, log, mediandk, and OpenMAXAL libraries. ```cmake cmake_minimum_required(VERSION 3.22.1) project(NativeCodec LANGUAGES CXX) include(AppLibrary) find_package(base CONFIG REQUIRED) add_app_library(native-codec-jni SHARED looper.cpp native-codec-jni.cpp ) target_link_libraries(native-codec-jni PRIVATE base::base android log mediandk OpenMAXAL ) ``` -------------------------------- ### Configure CMake build for HelloJniCallback Source: https://github.com/android/ndk-samples/blob/main/hello-jniCallback/app/src/main/cpp/CMakeLists.txt CMake configuration for the HelloJniCallback NDK sample. Requires CMake 3.22.1 or later, includes the AppLibrary module, finds the base package, and builds the shared library hello-jnicallback from hello-jnicallback.cpp, linking against base::base, android, and log. ```cmake cmake_minimum_required(VERSION 3.22.1) project(HelloJniCallback LANGUAGES CXX) include(AppLibrary) find_package(base CONFIG REQUIRED) add_app_library(hello-jnicallback SHARED hello-jnicallback.cpp) target_link_libraries(hello-jnicallback PRIVATE base::base android log ) ``` -------------------------------- ### app/build.gradle - Enable prefab Source: https://github.com/android/ndk-samples/blob/main/unit-test/README.md Enables prefab in build_features to use googletest via prefab. ```Groovy build_features { prefab true } ``` -------------------------------- ### Configure HelloGl2 CMake build with gl2jni Source: https://github.com/android/ndk-samples/blob/main/hello-gl2/app/src/main/cpp/CMakeLists.txt CMake configuration for the HelloGl2 native library. Requires CMake 3.22.1, includes the AppLibrary module, finds the base package, and builds gl2jni as a shared library from gl_code.cpp. Links against base::base, android, log, EGL, and GLESv2. ```cmake cmake_minimum_required(VERSION 3.22.1) project(HelloGl2 LANGUAGES CXX) include(AppLibrary) find_package(base CONFIG REQUIRED) add_app_library(gl2jni SHARED gl_code.cpp) target_link_libraries(gl2jni PRIVATE base::base android log EGL GLESv2 ) ``` -------------------------------- ### app/build.gradle - Add dependencies Source: https://github.com/android/ndk-samples/blob/main/unit-test/README.md Adds junit-gtest and googletest as implementation dependencies. ```Groovy dependencies { implementation 'androidx.test.ext:junit-gtest:1.0.0-alpha01' implementation 'com.android.ndk.thirdparty:googletest:1.11.0-beta-1' } ``` -------------------------------- ### CMakeLists.txt for TexturedTeapotNativeActivity Source: https://github.com/android/ndk-samples/blob/main/teapots/textured-teapot/src/main/cpp/CMakeLists.txt Defines the CMake project, includes AppLibrary, clones stb if missing, builds ndk-helper, and builds the app's shared library with ANativeActivity_onCreate export. ```cmake cmake_minimum_required(VERSION 3.22.1) project(TexturedTeapotNativeActivity LANGUAGES C CXX) include(AppLibrary) get_filename_component(commonDir ${CMAKE_CURRENT_SOURCE_DIR}/../../../../common ABSOLUTE) if((NOT EXISTS ${commonDir}/stb) OR (NOT EXISTS ${commonDir}/stb/stb_image.h)) execute_process(COMMAND git clone https://github.com/nothings/stb.git stb WORKING_DIRECTORY ${commonDir}) endif() # build the ndk-helper library get_filename_component(ndkHelperSrc ${commonDir}/ndk_helper ABSOLUTE) add_subdirectory(${ndkHelperSrc} ndkHelperBin/${CMAKE_BUILD_TYPE}/${ANDROID_ABI}) # now build app's shared lib add_app_library(${PROJECT_NAME} SHARED TeapotNativeActivity.cpp TeapotRenderer.cpp TexturedTeapotRender.cpp Texture.cpp AssetUtil.cpp ) target_include_directories(${PROJECT_NAME} PRIVATE ${commonDir}) target_compile_options(${PROJECT_NAME} PRIVATE -Wno-unused-function) # Export ANativeActivity_onCreate(), # Refer to: https://github.com/android-ndk/ndk/issues/381. set_target_properties(${PROJECT_NAME} PROPERTIES LINK_FLAGS "-u ANativeActivity_onCreate") # add lib dependencies target_link_libraries(${PROJECT_NAME} PRIVATE NdkHelper) ``` -------------------------------- ### CMake configuration for native library and unit tests Source: https://github.com/android/ndk-samples/blob/main/unit-test/app/src/main/cpp/CMakeLists.txt Defines the minimum CMake version, project name, includes AppLibrary, finds required packages (base, googletest, junit-gtest), builds an object library 'adder', a shared library 'unittest' from the adder objects and native-lib.cpp, links base and log, and builds a test library 'app_tests' linking adder objects, googletest, and junit-gtest. ```cmake # For more information about using CMake with Android Studio, read the # documentation: https://d.android.com/studio/projects/add-native-code.html # Sets the minimum version of CMake required to build the native library. cmake_minimum_required(VERSION 3.22.1) project("unittest") include(AppLibrary) find_package(base REQUIRED CONFIG) find_package(googletest REQUIRED CONFIG) find_package(junit-gtest REQUIRED CONFIG) add_app_library(adder OBJECT adder.cpp) add_app_library( unittest SHARED $ native-lib.cpp ) target_link_libraries( # Specifies the target library. unittest PRIVATE base::base log ) add_app_library(app_tests NO_VERSION_SCRIPT SHARED adder_test.cpp) target_link_libraries(app_tests PRIVATE $ googletest::gtest junit-gtest::junit-gtest ) ``` -------------------------------- ### Configure OrderfileDemo CMake build with profile generation or symbol ordering Source: https://github.com/android/ndk-samples/blob/main/orderfile/app/src/main/cpp/CMakeLists.txt CMake configuration for the OrderfileDemo native library. It sets up two mutually exclusive build modes: GENERATE_PROFILES (ON by default) to produce profiles and mapping files, and USE_PROFILE to apply a generated order file for symbol layout. Only one build variable should be uncommented at a time. Profile generation requires an optimization flag other than -O0. ```cmake cmake_minimum_required(VERSION 3.22.1) project(OrderfileDemo CXX) include(AppLibrary) find_package(base CONFIG REQUIRED) # We have setup build variables that you can just comment or uncomment to use. # Make sure to have only one build variable uncommented at a time. # If you want to generate profiles and mapping file, make sure GENERATE_PROFILES is uncommented. # If you want to use your generated order file to layout symbols, uncomment USE_PROFILE. set(GENERATE_PROFILES ON) #set(USE_PROFILE "${CMAKE_SOURCE_DIR}/demo.orderfile") add_app_library(orderfiledemo SHARED orderfile.cpp) target_link_libraries(orderfiledemo PRIVATE base::base log) if(GENERATE_PROFILES) # Generating profiles requires any optimization flag aside from -O0. target_compile_options(orderfiledemo PRIVATE -fprofile-generate -ftemporal-profile -O1) target_link_options(orderfiledemo PRIVATE -fprofile-generate -ftemporal-profile) target_compile_definitions(orderfiledemo PRIVATE GENERATE_PROFILES) elseif(USE_PROFILE) target_compile_options(orderfiledemo PRIVATE) target_link_options(orderfiledemo PRIVATE -Wl,--symbol-ordering-file=${USE_PROFILE} -Wl,--no-warn-symbol-ordering) endif() ``` -------------------------------- ### CMakeLists.txt - Define app_tests library Source: https://github.com/android/ndk-samples/blob/main/unit-test/README.md Creates a shared library for the test, linking against the adder object and googletest/junit-gtest. ```CMake add_library(app_tests SHARED adder_test.cpp) target_link_libraries(app_tests PRIVATE $ googletest::gtest junit-gtest::junit-gtest ) ``` -------------------------------- ### Configure hello-jni CMake build Source: https://github.com/android/ndk-samples/blob/main/hello-jni/app/src/main/cpp/CMakeLists.txt CMake configuration for the hello-jni Android app. Requires CMake 3.22.1, includes the AppLibrary module, finds the base package, and defines a shared library named hello-jni built from hello-jni.cpp. Links against base::base, android, and log libraries. ```cmake cmake_minimum_required(VERSION 3.22.1) project("hello-jni" LANGUAGES CXX) include(AppLibrary) find_package(base CONFIG REQUIRED) add_app_library(hello-jni SHARED hello-jni.cpp ) target_link_libraries(hello-jni PRIVATE base::base android log ) ``` -------------------------------- ### Configure ndk.dir in local.properties Source: https://github.com/android/ndk-samples/wiki/Configure-NDK-Path The local.properties file at the project root stores local settings like SDK and NDK paths. Note that ndk.dir is deprecated from AGP 4.1. ```properties sdk.dir=/Users/ndkPath/dev/sdk ndk.dir=/Users/ndkPath/dev/latest_ndk ``` -------------------------------- ### CMakeLists.txt for SensorGraph native library Source: https://github.com/android/ndk-samples/blob/main/sensor-graph/accelerometer/src/main/cpp/CMakeLists.txt CMake configuration for the SensorGraph native library. Requires CMake 3.22.1, uses the AppLibrary helper and the base package, and links against base, android, GLESv2, and log. ```cmake cmake_minimum_required(VERSION 3.22.1) project(SensorGraph LANGUAGES CXX) include(AppLibrary) find_package(base CONFIG REQUIRED) add_app_library(accelerometergraph SHARED sensorgraph.cpp) target_link_libraries(accelerometergraph PRIVATE base::base android GLESv2 log ) ``` -------------------------------- ### Configure BitmapPlasma CMake build Source: https://github.com/android/ndk-samples/blob/main/bitmap-plasma/app/src/main/cpp/CMakeLists.txt CMake configuration for the BitmapPlasma native library. Requires CMake 3.22.1 and the base package. Defines a shared library 'plasma' from jni.cpp and plasma.cpp, linking against base, android, jnigraphics, log, and m. ```cmake cmake_minimum_required(VERSION 3.22.1) project(BitmapPlasma LANGUAGES CXX) include(AppLibrary) find_package(base CONFIG REQUIRED) add_app_library(plasma SHARED jni.cpp plasma.cpp) target_link_libraries(plasma base::base android jnigraphics log m ) ``` -------------------------------- ### CMakeLists.txt for Gles3Jni Source: https://github.com/android/ndk-samples/blob/main/gles3jni/app/src/main/cpp/CMakeLists.txt CMake configuration for the Gles3Jni native library. It sets the minimum CMake version, declares the project, includes the AppLibrary module, finds the base package, and defines the shared library with its source files and linked libraries. ```cmake cmake_minimum_required(VERSION 3.22.1) project(Gles3Jni LANGUAGES CXX) include(AppLibrary) find_package(base CONFIG REQUIRED) add_app_library(gles3jni SHARED ${GL3STUB_SRC} gles3jni.cpp RendererES2.cpp RendererES3.cpp ) target_link_libraries(gles3jni base::base GLESv3 android EGL log m ) ``` -------------------------------- ### CMakeLists.txt - Find googletest and junit-gtest Source: https://github.com/android/ndk-samples/blob/main/unit-test/README.md Adds find_package calls to locate googletest and junit-gtest as required CONFIG packages. ```CMake find_package(googletest REQUIRED CONFIG) find_package(junit-gtest REQUIRED CONFIG) ``` -------------------------------- ### CMakeLists.txt for native_midi Source: https://github.com/android/ndk-samples/blob/main/native-midi/app/src/main/cpp/CMakeLists.txt CMake configuration for the native_midi Android app. It requires CMake 3.22.1, includes the AppLibrary module, finds the base package, and defines a shared library with sources AppMidiManager.cpp and MainActivity.cpp. Links against base::base, amidi, OpenSLES, android, and log libraries. ```cmake cmake_minimum_required(VERSION 3.22.1) project(native_midi LANGUAGES CXX) include(AppLibrary) find_package(base CONFIG REQUIRED) add_app_library(${PROJECT_NAME} SHARED AppMidiManager.cpp MainActivity.cpp ) target_link_libraries(${PROJECT_NAME} PRIVATE base::base amidi OpenSLES android log ) ``` -------------------------------- ### CMake configuration for native-audio-jni Source: https://github.com/android/ndk-samples/blob/main/native-audio/app/src/main/cpp/CMakeLists.txt Defines the native-audio-jni shared library, links required libraries (base, android, log, OpenSLES), and adds a compile option to suppress deprecation warnings for riscv64 builds. ```cmake cmake_minimum_required(VERSION 3.22.1) project(NativeAudio LANGUAGES CXX) include(AppLibrary) find_package(base CONFIG REQUIRED) add_app_library(native-audio-jni SHARED native-audio-jni.cpp ) # Include libraries needed for native-audio-jni lib target_link_libraries(native-audio-jni PRIVATE base::base android log OpenSLES ) if(ANDROID_ABI STREQUAL riscv64) # This sample uses OpenSLES, which was deprecated in API 26. Our # minSdkVersion is 23, but we also build for riscv64, which isn't a # supported ABI yet and so that configuration is built for the latest API # level supported by the NDK. # # Longer term, this sample should migrate to Oboe. target_compile_options(native-audio-jni PRIVATE -Wno-deprecated-declarations) endif() ``` -------------------------------- ### Coordinate system diagram for 4:3 screen Source: https://github.com/android/ndk-samples/blob/main/endless-tunnel/README.md ASCII diagram showing the four corners of the screen in the normalized 2D coordinate system for a 4:3 aspect ratio. The bottom-left is (0,0), the top-left is (0,1), and the right side is at X = aspect (1.333). ```text (0.000,1.000) (1.333,1.000) +--------------+ | | | | | | | | +--------------+ (0.000,0.000) (1.333,0.000) ``` -------------------------------- ### Configure ndkPath in build.gradle Source: https://github.com/android/ndk-samples/wiki/Configure-NDK-Path Use the android.ndkPath DSL in your app/build.gradle to point to a specific NDK location. Ensure this is removed before distributing source code. ```gradle android { ndkPath "/Users/ndkPath/ndk21" // pointing to your own NDK } ``` -------------------------------- ### adder_test.cpp - Unit test for add function Source: https://github.com/android/ndk-samples/blob/main/unit-test/README.md Contains a googletest unit test that expects add(1,2) to equal 3. ```C++ #include "adder.h" #include "gtest/gtest.h" TEST(adder, adder) { EXPECT_EQ(3, add(1, 2)); } ``` -------------------------------- ### adder.cpp - Implementation of add function Source: https://github.com/android/ndk-samples/blob/main/unit-test/README.md Implements the add function to return the sum of two integers. ```C++ #include "adder.h" int add(int a, int b) { return a + b; } ``` -------------------------------- ### Enable publishNonDefault in lib/build.gradle Source: https://github.com/android/ndk-samples/wiki/Home Enable publishNonDefault in the library's build.gradle file to support debug and release build configurations. ```java android { publishNonDefault true } ``` -------------------------------- ### adder.h - Header for add function Source: https://github.com/android/ndk-samples/blob/main/unit-test/README.md Declares the add function that adds two integers. ```C++ #pragma once int add(int a, int b); ``` -------------------------------- ### Use-after-free error in native-lib.cpp Source: https://github.com/android/ndk-samples/blob/main/sanitizers/README.md This snippet demonstrates a use-after-free error in native code. It is used in the hwasan build variant to trigger a crash and log information about the problem. ```C++ int* foo = new int; *foo = 3; delete foo; *foo = 4; ``` -------------------------------- ### Set ndkPath from ANDROID_NDK_HOME in module Gradle file Source: https://github.com/android/ndk-samples/wiki/Configure-NDK-Path Use this in a module's Gradle file to set the NDK path from the ANDROID_NDK_HOME environment variable. This is useful for CI when building on the command line, as Gradle checks ANDROID_NDK_HOME if no local.properties file exists. Note that ANDROID_NDK_HOME is deprecated. ```groovy ndkPath = System.getenv("ANDROID_NDK_HOME") ``` -------------------------------- ### NativeTests.kt - Test runner wrapper Source: https://github.com/android/ndk-samples/blob/main/unit-test/README.md Kotlin class that runs the native tests using GtestRunner and targets the app_tests library. ```Kotlin package com.example.unittest import androidx.test.ext.junitgtest.GtestRunner import androidx.test.ext.junitgtest.TargetLibrary import org.junit.runner.RunWith @RunWith(GtestRunner::class) @TargetLibrary(libraryName = "app_tests") class NativeTests ``` -------------------------------- ### Configure sanitizers CMake build with SANITIZE option Source: https://github.com/android/ndk-samples/blob/main/sanitizers/app/src/main/cpp/CMakeLists.txt Configures the sanitizers CMake project, defining the library and linking base::base and log. When SANITIZE is set, it maps the ABI to an architecture string and applies the corresponding sanitizer flags. For asan and ubsan, it copies the required runtime library and wrapper script from the NDK into the APK. ```cmake cmake_minimum_required(VERSION 3.22.1) project(sanitizers LANGUAGES CXX) include(AppLibrary) find_package(base CONFIG REQUIRED) add_app_library(sanitizers SHARED native-lib.cpp) target_link_libraries(sanitizers PRIVATE base::base log) if(SANITIZE) # For asan and ubsan, we need to copy some files from the NDK into our APK. get_filename_component(HINT_PATH ${ANDROID_C_COMPILER} DIRECTORY) set(ARCH_STR ${CMAKE_ANDROID_ARCH}) if("${CMAKE_ANDROID_ARCH_ABI}" STREQUAL "arm64-v8a") set(ARCH_STR "aarch64") elseif("${CMAKE_ANDROID_ARCH_ABI}" STREQUAL "armeabi") set(ARCH_STR "arm") elseif("${CMAKE_ANDROID_ARCH_ABI}" STREQUAL "armeabi-v7a") set(ARCH_STR "arm") elseif("${CMAKE_ANDROID_ARCH_ABI}" STREQUAL "x86") set(ARCH_STR "i686") elseif("${CMAKE_ANDROID_ARCH_ABI}" STREQUAL "x86_64") set(ARCH_STR "x86_64") endif() if(${SANITIZE} STREQUAL "hwasan") target_compile_options(sanitizers PUBLIC -fsanitize=hwaddress -fno-omit-frame-pointer) target_link_options(sanitizers PUBLIC -fsanitize=hwaddress) elseif(${SANITIZE} STREQUAL "asan") target_compile_options(sanitizers PUBLIC -fsanitize=address -fno-omit-frame-pointer) target_link_options(sanitizers PUBLIC -fsanitize=address) # Grab libclang_rt.asan-${ARCH_STR}-android.so from the NDK. file(GLOB ASAN_GLOB "${HINT_PATH}/../lib/clang/*/lib/linux") find_file(ASAN NAMES libclang_rt.asan-${ARCH_STR}-android.so PATHS ${ASAN_GLOB}) get_filename_component(ASAN_NAME ${ASAN} NAME) set(ASAN_NAME ${CMAKE_SOURCE_DIR}/../../asan/jniLibs/${CMAKE_ANDROID_ARCH_ABI}/${ASAN_NAME}) add_custom_command( TARGET sanitizers PRE_BUILD COMMAND ${CMAKE_COMMAND} -E copy ${ASAN} ${ASAN_NAME}) # Grab the asan wrapper script from the NDK. find_file(WRAP NAMES asan.sh HINTS ${HINT_PATH}/../../../../../wrap.sh) set(WRAP_NAME ${CMAKE_SOURCE_DIR}/../../asan/resources/lib/${CMAKE_ANDROID_ARCH_ABI}/wrap.sh) add_custom_command( TARGET sanitizers PRE_BUILD COMMAND ${CMAKE_COMMAND} -E copy ${WRAP} ${WRAP_NAME}) elseif(${SANITIZE} STREQUAL "ubsan") target_compile_options(sanitizers PUBLIC -fsanitize=undefined -fno-sanitize-recover=undefined) target_link_options(sanitizers PUBLIC -fsanitize=undefined -fno-sanitize-recover=undefined) # Grab libclang_rt.ubsan_standalone-${ARCH_STR}-android.so from the NDK. file(GLOB UBSAN_GLOB "${HINT_PATH}/../lib/clang/*/lib/linux") find_file(UBSAN NAMES libclang_rt.ubsan_standalone-${ARCH_STR}-android.so PATHS ${UBSAN_GLOB}) get_filename_component(UBSAN_NAME ${UBSAN} NAME) set(UBSAN_NAME ${CMAKE_SOURCE_DIR}/../../ubsan/jniLibs/${CMAKE_ANDROID_ARCH_ABI}/${UBSAN_NAME}) add_custom_command( TARGET sanitizers PRE_BUILD COMMAND ${CMAKE_COMMAND} -E copy ${UBSAN} ${UBSAN_NAME}) endif() endif() ``` -------------------------------- ### Configure CMake targets in build.gradle Source: https://github.com/android/ndk-samples/wiki/Home Specify multiple build targets for CMake in the defaultConfig block of your build.gradle file. ```gradle defaultConfig.externalNativeBuild.cmake.targets "target1", "target2" ``` -------------------------------- ### Configure ndkVersion in build.gradle Source: https://github.com/android/ndk-samples/wiki/Configure-NDK-Path Use the android.ndkVersion DSL in your app/build.gradle file to specify the NDK version for side-by-side support. ```gradle android { ndkVersion "21.1.6273396" } ``` -------------------------------- ### Declare native method runWorkload in Kotlin and Java Source: https://github.com/android/ndk-samples/blob/main/orderfile/README.md Kotlin and Java declarations for the native method runWorkload. The Kotlin version uses external fun, the Java version uses private native. ```kotlin # Kotlin external fun runWorkload(tempDir: String) # Java private native void runWorkload(String tempDir); ``` -------------------------------- ### Signed integer overflow in native-lib.cpp Source: https://github.com/android/ndk-samples/blob/main/sanitizers/README.md This snippet demonstrates a signed integer overflow, which is undefined behavior. It is used in the ubsan build variant to trigger a crash and log information about the problem. ```C++ int k = 0x7fffffff; k += 1; ``` -------------------------------- ### Call runWorkload with cache directory in Kotlin and Java Source: https://github.com/android/ndk-samples/blob/main/orderfile/README.md Kotlin and Java calls to runWorkload with the cache directory path. Note the Java version uses getcacheDir() (lowercase 'c') as shown in the source. ```kotlin # Kotlin runWorkload(applicationContext.cacheDir.toString()) # Java runWorkload(getcacheDir().toString()) ``` -------------------------------- ### Deliberately broken test - EXPECT_EQ(4, add(1,2)) Source: https://github.com/android/ndk-samples/blob/main/unit-test/README.md Shows a modified test that expects 4 instead of 3, which will fail. ```C++ EXPECT_EQ(4, add(1, 2)); ``` -------------------------------- ### Catch RuntimeException in Kotlin Source: https://github.com/android/ndk-samples/blob/main/exceptions/README.md Catch the RuntimeException re-thrown by the native JNI method in Kotlin. This is the Java/Kotlin side of the exception handling workflow. ```Kotlin try { jniMethodThatMightThrow(); } catch (e: java.lang.RuntimeException) { // Handle exception } ``` -------------------------------- ### Implicit android.ndkVersion assignment for default NDK version Source: https://github.com/android/ndk-samples/wiki/Configure-NDK-Path When the default NDK version is triggered (AGP 3.6+), the application behaves as if this android.ndkVersion were set. This is not used when the app specifies ndkVersion or uses ndk.dir in local.properties. ```groovy android.ndkVersion "${the-default-NDK-version}" ``` -------------------------------- ### Catch native exceptions in JNI method Source: https://github.com/android/ndk-samples/blob/main/exceptions/README.md Catch native exceptions in a JNI method and re-throw them as Java RuntimeExceptions using jniThrowRuntimeException. Uncaught native exceptions crash the app, so catch all exceptions as a fail-safe. ```C++ extern "C" JNIEXPORT void JNICALL Java_com_example_exceptions_MainActivity_throwsException(JNIEnv* env, jobject /* this */) { try { might_throw(); } catch (std::exception& e) { jniThrowRuntimeException(env, e.what()); } catch (...) { jniThrowRuntimeException(env, "Catch-all"); } } ```