Android NDK cmake JNI static library - android

Because of security concerns I would like to link all libraries statically including my native library containing JNI_OnLoad function. I've read that it's possible to link JNI library statically (http://docs.oracle.com/javase/8/docs/technotes/guides/jni/spec/invocation.html#library_version) but I fail to do it with Android Studio. Is it possible?
Here's what I have currently.
In Java code:
System.loadLibrary("testlibrary");
In cmake makefile:
add_library( testlibrary
STATIC
${mysources} )
target_link_libraries(testlibrary)
In C++ file:
extern "C" {
EXPORT
JNIEXPORT jint JNICALL JNI_OnLoad_testlibrary(JavaVM *vm, void *reserved) {
...
return JNI_VERSION_1_8;
}
When built with Android Studio application fails because it tries to find *.so library file:
java.lang.UnsatisfiedLinkError:
dalvik.system.PathClassLoader[DexPathList[[zip file
"/data/app/xxx-1/base.apk"],nativeLibraryDirectories=[/vendor/lib,
/system/lib]]] couldn't find "libtestlibrary.so"

System.loadLibrary("testlibrary");
This line tries to load libtestlibrary.so, and obviously it wasn't built and packed into APK, since library with this name is static one:
add_library( testlibrary
STATIC
${mysources} )
Here you've described target libtestlibrary.a, that is not loadable, and can only be linked against loadable .so. So to achieve desired result you should declare testlibrary as shared one, and then link it against another static libraries. As result you'll get one, monolitic shared library, that can be loaded into program address space. E.g
add_library(testlibrary SHARED ${mysources})
add_library(lib1 STATIC ${lib1_src})
add_library(lib2 STATIC ${lib2_src})
...
target_link_libraries(testlibrary lib1 lib2 ...)

Related

Android - use generated C files with JNI

I am trying to create an application using C files.
In fact, the C files were generated from matlab (~20 files, with .c and .h), and I didn't modify those files.
To use those files with JNI, I create an other C file which is using JNI : native-lib.c.
So the C files generated by matlab are used through native-lib.c (I used a tuto found on the web to write this file).
I have this architecture for the c files :
src/
-- jni/
---- native-lib.c
---- include/
-------- All the c files generated from matlab
And this is native-lib.c (that I simplify here):
#include <jni.h>
#include "include/function1.h"
JNIEXPORT jint JNICALL
My_project_function1(JNIEnv* env, jobject obj, Function1_Args args) {
int x = function1(args);
return x;
}
etc...
To build the C library I use this file : CMakeList.txt :
cmake_minimum_required(VERSION 3.4.1)
add_library(native-lib SHARED src/jni/native-lib.c)
include_directories(src/jni/include)
find_library(log-lib log)
target_link_libraries(native-lib ${log-lib})
But this file CMakeList.txt doesn't work ! All the files in the folder include/ are not included in the project (only native-lib.c is recognize).
So I want to include the files of the include/ folder WITHOUT modify them (without adding JNIEXPORT, JNICALL, etc...).
I almost never use C, and I know nothing about the C generation. So I don't know how to do, and I don't understand most of the answers found on the web :(
Is someone understand why CMakeList.txt doesn't work? Do you have a solution to solve my problem ?
Thanks !
I am not familiar with CMake, however, You probably want to either add the src/jni/include folder as a second library source and static link to native-lib, or add the contents of src/jni/include directly to the arguments of add_library(native-lib SHARED ...). Please note that include_directories are for #include paths and not for src locations.
Finally I found a solution to my problem :
It is very simple in fact :
cmake_minimum_required(VERSION 3.4.1)
file(GLOB sources_c
"src/jni/include/*.h"
"src/jni/include/*.c"
"src/jni/native-lib.c"
)
add_library(native-lib SHARED ${sources_c})
find_library(log-lib log)
target_link_libraries(native-lib ${log-lib})
I just put all the C files in the variable sources_c with file(GLOB sources_c ...).
And, in CMakeList.txt, it seems that there is any distinction between pure C files and JNI-C files (C files with, JNIEXPORT, ect ...).
I hope it will help !

Android NDK CMake linking issues

I'm quite new with NDK + Gradle + CMake integration and I'm trying to understand why linking doesn't export symbols as intended.
I have a static library built by a CMakeLists.txt which is not the main CMakeLists.txt.
The scripts does something like:
# main CMakeLists.txt
add_subdirectory(${LIBS}/foo libs}
add_library(native SHARED native.cpp)
# omitting standard android libraries
target_link_libraries(native foo ${android-lib} ${log-lib})
while CMakeLists.txt inside ${libs}/foo is the following:
# misc configuration of ${SRC}
add_library(foo STATIC ${SRC})
The script works fine, it's able to link libnative.so and I'm able to find the generated libfoo.a. Everything seems fine.
I then try to define a native method in foo.cpp contained in foo library:
extern "C" JNIEXPORT void JNICALL Java_com_mypackage_Controls_onTap(JNIEnv*, jobject, int x, int y) {
// log something
}
But I'm not able to call the native method defined in foo library. I get an UnsatisfiedLinkError at runtime. If, instead, I move (directly by copying and pasting) the method to native.cpp then everything goes fine.
So basically:
Java -> method in native.cpp works
Java -> method in native.cpp -> method defined in foo library works
Java -> method in foo library doesn't work (UnsatisfiedLinkError)
I tried to inspect the exported functions with nm and it looks like that foo.a correctly exports the native function as I can see
00011060 T Java_com_mypackage_Controls_onTap
But this entry disappears from libnative.so. If, instead, I define the method directly in native.cpp then I can see it correctly with nm also on libnative.so.
In addition calling any method in foo library from native.cpp works as intended so the library is effectively statically linked.
I am not able to understand the reason behind this, the approach should be fine, visibility should be correct as specified by JNIEXPORT macro so I'm really groping in the dark (and Gradle doesn't provide any output of compilation phase so I can't understand what's happening, but the build.ninja file seems correct)
This behavior, even if unpleasant, is correct. The linker drops any object "files" (in your case, foo.o) from used static libraries, unless they are "pinned" by one of the objects in the shared lib (in your case, native.o). There are three ways to solve the problem:
compile foo.cpp as part of libnative.so instead of a
static lib.
reference Java_com_mypackage_Controls_onTap or any other
external symbol from foo.cpp in native.cpp
use SET(native -Wl,--whole-archive foo -Wl,--no-whole-archive) (see https://stackoverflow.com/a/17477559/192373)

How to link crypto shared library in Android JNI

I am writing a wrapper to use some functions of crypto.
I build crypto lib from openssl-android with Android-NDK. Now i have the libcrypto.so that i need, but i donĀ“t know how to link it with my wrapper.
My project tree is like this
(proj root)
|
|->(src)
|->(src)-> com.package
|->(src)-> com.package->NativeCipher.java
|
|->(jni)
|->(jni)->Android.mk
|->(jni)->NativeCipher.c
NativeCipher.java
public class NativeCipher {
static {
System.loadLibrary("crypto");
System.loadLibrary("NativeCipher");
}
public static native byte[] AESEncrypt(byte[] in, byte[] key);
}
NativeCipher.c
#include <string.h>
#include <jni.h>
#include <aes.h>
jbyteArray Java_com_package_NativeCipher_AESEncrypt(JNIEnv* env, jobject this, jbyteArray in, jbyteArray key)
{
// All my code here
}
I need to use the functions of #include that crypto provides.
However, i don't know what to do with the .so files that NDK generates and how to make the Android.mk file to build.
Thanks in advance, i tried to be as specific as posible.
Native libraries go to the libs/armeabi or libs/armeabi-v7a of your Android project. You might want to rename the OpenSSL library though, because the system already has a libcrypto.so. As for your own JNI wrapper, just take the shared library sample from the NDK and modify to use your own files.

How to create dll using android

I am new to Android application development.I want develop a dll using android. Is it possible to develop and integrate to android app. Please tell me the solution. If it is possible please tell me the solution one by one.
As for me I once made a note for myself about NDK. Here it is:
Required applicaitions:
1. Eclipse
2. CDT+Sequoyah plug-ins
3. Android ADT
4. Android NDK
Configuration:
1. Install Eclipse, ADT, CDT and Sequoyah plug-ins
2. In the Eclipse -> Window -> Preferences -> Android -> Native Development put NDK location
Steps:
1. Create new Android Project
2. Create Java class for working with native libraries (NativeLibrary.java)
3. In the class NativeLibrary.java define interface for native methods
4. Right click on Project -> Android Tools -> Add Native Support. Define name of the library.
5. Build the project
6. Go to PROJECT_HOME/bin
7. Create C header file with the command javah -jni <packagename>.NativeLibrary
8. Move this file to PROJECT_HOME/jni folder
9. Implement methods from the header file in the generated cpp file. Do not forget to include the moved header in this file.
10. In java classes create new object of NativeLibrary class and call its methods.
11. Build project.
UPDATE: Step by step without plugins
Required applications - this is what you need to develop native applications. In my case I use Eclipse + Android ADT plugin + Android CDT plugin + Sequoyah plugin. You can install them using Eclipse - > Install new software
Then you should download Android NDK. Also you should export PATH to it.
For the configuration: you should define only path to your NDK in Eclipse -> Window -> Preferences -> Android -> Native Development
You are not obliged to use these plugins but it is easier to develop with them. However, Sequoyah contains errors (or it's sometimes not properly configured for my computer)
After that you can create new Android project. Then you can create java class that defines native methods. In my case this is NativeLibrary.java. Here it is:
package com.testpack.nativetest;
public class NativeLibrary {
public native static int add(int a, int b);
static {
System.loadLibrary("nativ");
}
}
After that build your Android project. After that go to your bin/classes (I don't know but before it was just bin directory) directory:
cd ~/programming/android/workspace/NativeTest/bin/classes
And run the following command:
javah -jni com.testpack.nativetest.NativeLibrary
This command should produce com_testpack_nativetest_NativeLibrary.h header in your bin/classes directory. It should look like:
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class com_testpack_nativetest_NativeLibrary */
#ifndef _Included_com_testpack_nativetest_NativeLibrary
#define _Included_com_testpack_nativetest_NativeLibrary
#ifdef __cplusplus
extern "C" {
#endif
/*
* Class: com_testpack_nativetest_NativeLibrary
* Method: add
* Signature: (II)I
*/
JNIEXPORT jint JNICALL Java_com_testpack_nativetest_NativeLibrary_add
(JNIEnv *, jclass, jint, jint);
#ifdef __cplusplus
}
#endif
#endif
Create jni directory in your project and Run the following command. It will move this header to jni directory.
mv com_testpack_nativetest_NativeLibrary.h ../../jni
After that in jni directory create .c file. In my case it is nativ.c, copy the definition of the function from .h file and generate code:
#include "com_testpack_nativetest_NativeLibrary.h"
JNIEXPORT jint JNICALL Java_com_testpack_nativetest_NativeLibrary_add
(JNIEnv *env, jclass obj, jint a, jint b) {
return a+b;
}
Then in jni directory you should create a make file Android.mk Here it is. Simply change the source (nativ.c) and the name of your library (nativ).
LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)
LOCAL_MODULE := nativ
LOCAL_SRC_FILES := nativ.c
include $(BUILD_SHARED_LIBRARY)
Go to the PROJECT_HOME directory. In my case this is
cd ~/programming/android/workspace/NativeTest
and run ndk-build. That's all. After that you can test it in your activity:
package com.testpack.nativetest;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
public class NativeTestActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Log.d("TEST:", "Result 5+4=" + NativeLibrary.add(5, 4));
}
}
With plugins it is a bit easier to develop. But I think you should test it by yourself how to do this.
You can check out the Android NDK, here http://developer.android.com/sdk/ndk/index.html.
The NDK can be used to create linux equvalent .so, of the windows .dll files.

how to use libssl.so in an android project?

I did build the libssl.so from openssl project with Android NDK under the mac os x shell and now I would like someone to tell me how i can use it in Eclispe and in my android project ?
Is it ok if I drag and drop the file in the project root directory ??
How can I access the library function from the code ??
I saw this example :
// load the library - name matches jni/Android.mk
static {
System.loadLibrary("ndkfoo");
}
// declare the native code function - must match ndkfoo.c
private native String invokeNativeFunction();
...
file ndkfoo.c :
jstring Java_com_mindtherobot_samples_ndkfoo_NdkFooActivity_invokeNativeFunction(JNIEnv* env, jobject javaThis) {
return (*env)->NewStringUTF(env, "Hello from native code!");
}
But the libssl.so has it own functions list and they not named with my java class name i guess...
Any idea ?
to link .so file to yr project, u need to right click project->properties->Java Build Path->Library->Android 2.* -> Native Library location ->Edit -> browse to .so file folder path

Categories

Resources