SlideShare a Scribd company logo
Android JNI/NDK
Android JNI
● Why JNI?
● What is NDK?
● Why NDK?
● Deep into JNI world.
Why JNI?
Android is put together of about equal part Java and C.
we need an easy way to bridge between these two totally different worlds
.Java offers Java Native Interface
(JNI) as a framework connecting the world of Java to the native code.
More About JNI
JNI is part of Dalvik VM, which allows native code to access java
environment. Like accessing java objects and its methods, members etc.
JNI also facilitates accessing and invoking of native methods from Java
code.
JNI Comes with Primitive and reference types.
Primitive types can be manipulated directly as these are equivalent to native
c.c++ data types
But you need special helper functions to manipulate JNI reference types.
What is NDK?
NDK is a toolchain
Cross-compiler, linker, what you need to build for ARM, x86, MIPS, etc.
NDK provides a way to bundle lib.so into your APK
The native library needs to be loadable in a secure way.
NDK "standardizes" various native platforms
It provides headers for libc, libm, libz, lliibblloogg, lliibbjjnniiggrraahhiiccss,
OpenGL/OpenSL ES,
JNI headers, minimal C++ support headers, and Android native app APIs
NDK in Action
Why NDK/JNI?
For performance
Sometimes, native code still runs faster.
For legacy support
You may have that C/C++ code you’d like to use in your app.
For access to low-level libraries
I n a rare case when there is no Java API to do something.
For cross-platform development
But Adding JNI to your app will make it more complex.
Build Process
Deep Into JNI world
Loading Native Libraries and
Registering Native Methods
Native code is usually compiled into a shared library and loaded before the
native methods can be called.
All the Native methods are declared with native keyword in java.
static {
//use either of the two methods below
System.loadLibrary(“nativelib");
System.load("/data/data/cookbook.chapter2/lib/ libNative.so");
}
Registering Native Methods
 JNIEnv Interface Pointer:
Every native method defined in native code at JNI must accept two input
parameters, the first one being a pointer to JNIEnv. The JNIEnv interface pointer is
pointing to thread-local data, which in turn points to a JNI function table shared by
all threads. This can be illustrated using the following diagram:
JNIEnv
Gateway to access all predefined JNI functions.
Access Java Fields
Invoke Java Methods.
It points to the thread’s local data, so it cannot be shared.
It can be accessible only by java threads.
Native threads must call AttachCurrentThread to attach itself to VM and to
obtain the JNIEnv interface pointer.
RegisterNatives :
 Two ways:
 1. Using Javah tool.
 2. Using RegisterNative function.
Using RegisterNative Method
Prototype:
jint RegisterNatives(JNIEnv *env, jclass clazz, const JNINativeMethod
*methods, jint nMethods);
The clazz argument is a reference to the class in which the native method is
to be registered. The methods argument is an array of the JNINativeMethod
data structure.
JNINativeMethod is defined as follows:
typedef struct {
char *name;
char *signature;
void *fnPtr;
} JNINativeMethod;
name indicates the native method name, signature is the descriptor of the
method's input argument data type and return value data type, and fnPtr is the
function pointer pointing to the native method.
The last argument, nMethods of RegisterNatives, indicates the number of
methods to register. The function returns zero to indicate success, and a
negative value otherwise.
JNI_OnLoad
 Invoke when the native library is loaded.
 It is the right and safe place to register the native methods before their
execution.
 JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM* pVm, void* reserved)
 {
 JNIEnv* env;
 if ((*pVm)->GetEnv(pVm, (void **)&env, JNI_VERSION_1_6)) {
 return -1;
 }
 // Get jclass with env->FindClass.
 // Register methods with env->RegisterNatives.
 return JNI_VERSION_1_6;
 }
JNI Datatypes
Manipulating strings in JNI
 Strings are somewhat complicated in JNI, mainly because Java strings and C strings are internally
different.
 Java programming language uses UTF-16 to represent strings. If a character cannot fit in a 16-bit code
value, a pair of code values named surrogate pair is used
 C strings are simply an array of bytes terminated by a null character
 The Unicode Standard is a character coding system designed to support the
worldwide interchange, processing, and display of the written texts of the
diverse languages and technical disciplines of the modern world. In addition, it
supports classical and historical texts of many written languages.
 Few JNI String Functions:
 jstring NewStringUTF(JNIEnv *env, const char *bytes);
 void GetStringUTFRegion(JNIEnv *env, jstring str, jsize start, jsize len, char
*buf);
 void ReleaseStringUTFChars(JNIEnv *env, jstring string, const char *utf);
 const jbyte * GetStringUTFChars(JNIEnv *env, jstring string, jboolean
*isCopy);
Manipulating Objects in JNI
jobject AllocObject(JNIEnv *env, jclass clazz);
jobject NewObject(JNIEnv *env, jclass clazz,jmethodID
methodID, ...);
jobject NewObjectA(JNIEnv *env, jclass clazz,jmethodID
methodID, jvalue *args);
jobject NewObjectV(JNIEnv *env, jclass clazz,jmethodID
methodID, va_list args);
 The clazz argument is a reference to the Java class of which we want to create
an instance object. It cannot be an array class, which has its own set of JNI
functions.
 methodID is the constructor method ID, which can be obtained using the
GetMethodID JNI function.
Manipulating Classes in JNI
jclass FindClass(JNIEnv *env, const char *name);
 Majorly used method when writing JNI code.
 Must pass full path of class.
 If you have to call this method for finding the most used class in JNI, it is
better to Cache it.
Accessing Java Static and Instance
fileds in Native code
 jfieldID data type: jfieldID is a regular C pointer pointing to a data structure
with details hidden from developers. We should not confuse it with jobject or
its subtypes. jobject is a reference type corresponding to Object in Java,
while jfieldID doesn't have such a corresponding type in Java. However, JNI
provides functions to convert the java.lang.reflect.Field instance to jfieldID
and vice versa.
 Field descriptor: It refers to the modified UTF-8 string used to represent the
field data type. The following table summarizes the Java field types and its
corresponding field descriptors:
Accessing static fields
 JNI provides three functions to access static fields of a Java class. They
have the following prototypes:
jfieldID GetStaticFieldID(JNIEnv *env, jclass clazz,
const char *name, const char *sig);
<NativeType> GetStatic<Type>Field(JNIEnv
*env,jclass clazz, jfieldID fieldID);
void SetStatic<Type>Field(JNIEnv *env, jclass clazz,
jfieldID fieldID,<NativeType> value);
Accessing instance field
 Accessing instance fields is similar to accessing static fields. JNI also
provides the following three functions for us:
jfieldID GetFieldID(JNIEnv *env, jclass clazz, const
char *name, const char *sig);
<NativeType> Get<Type>Field(JNIEnv *env,jobject
obj, jfieldID fieldID);
void Set<Type>Field(JNIEnv *env, jobject obj, jfieldID
fieldID, <NativeType> value);
Calling static and instance methods
from the native code
 jmethodID data type: Similar to jfieldID, jmethodID is a regular C pointer
pointing to a data structure with details hidden from the developers. JNI
provides functions to convert the java.lang.reflect.Method instance to
jmethodID and vice versa.
 Method descriptor: This is a modified UTF-8 string used to represent the
input (input arguments) data types and output (return type) data type of the
method. Method descriptors are formed by grouping all field descriptors of its
input arguments inside a "()", and appending the field descriptor of the return
type. If the return type is void, we should use "V". If there's no input
arguments, we should simply use "()", followed by the field descriptor of the
return type. For constructors, "V" should be used to represent the return
type. The following table lists a few Java methods and their corresponding
method descriptors:
Calling static methods:
 JNI provides four sets of functions for native code to call Java methods.
Their prototypes are as follows:
jmethodID GetStaticMethodID(JNIEnv *env, jclass
clazz, const char *name, const char *sig);
<NativeType> CallStatic<Type>Method(JNIEnv *env,
jclass clazz, jmethodID methodID, ...);
<NativeType> CallStatic<Type>MethodA(JNIEnv
*env, jclass clazz, jmethodID methodID, jvalue *args);
<NativeType> CallStatic<Type>MethodV(JNIEnv
*env, jclass clazz,jmethodID methodID, va_list args);
Calling instance methods:
 Calling instance methods from the native code is similar to calling static methods.
JNI also provides four sets of functions as follows:
jmethodID GetMethodID(JNIEnv *env, jclass clazz, const
char *name, const char *sig);
<NativeType> Call<Type>Method(JNIEnv *env, jobject obj,
jmethodID methodID, ...);
<NativeType> Call<Type>MethodA(JNIEnv *env,jobject
obj, jmethodID methodID, jvalue *args);
<NativeType> Call<Type>MethodV(JNIEnv *env, jobject
obj, jmethodID methodID, va_list args);
Checking errors and handling
exceptions in JNI
 JNI functions can fail because of system constraint (for example, lack of
memory) or invalid arguments (for example, passing a native UTF-8 string
when the function is expecting a UTF-16 string).
 Check for errors and exceptions: Many JNI functions return a special value
to indicate failure. For example, the FindClass function returns NULL to
indicate it failed to load the class. Many other functions do not use the return
value to signal failure; instead an exception is thrown.
 jboolean ExceptionCheck(JNIEnv *env);
 jthrowable ExceptionOccurred(JNIEnv *env);
 void ExceptionDescribe(JNIEnv *env);
Throw exceptions in the native
code:
 JNI provides two functions to throw an exception from native code. They
have the following prototypes:
jint Throw(JNIEnv *env, jthrowable obj);
jint ThrowNew(JNIEnv *env, jclass clazz, const char
*message);
 The first function accepts a reference to a jthrowable object and throws the
exception, while the second function accepts a reference to an exception
class. It will create an exception object of the clazz class with the message
argument and throw it.
Extended Error Check
 Using CheckJNI

Android also offers a mode called CheckJNI, where the JavaVM and JNIEnv
function table pointers are switched to tables of functions that perform an
extended series of checks before calling the standard implementation.
 List of Errors that CheckJNI tool can catch:
 Arrays: attempting to allocate a negative-sized array.
 Bad pointers: passing a bad jarray/jclass/jobject/jstring to a JNI call, or passing a NULL
pointer to a JNI call with a non-nullable argument.
 Class names: passing anything but the “java/lang/String” style of class name to a JNI call.
 Critical calls: making a JNI call between a “critical” get and its corresponding release.
 Direct ByteBuffers: passing bad arguments to NewDirectByteBuffer.
 Exceptions: making a JNI call while there’s an exception pending.
 JNIEnv*s: using a JNIEnv* from the wrong thread.
 jfieldIDs: using a NULL jfieldID, or using a jfieldID to set a field to a value of the wrong
type (trying to assign a StringBuilder to a String field, say), or using a jfieldID for a static
field to set an instance field or vice versa, or using a jfieldID from one class with instances
of another class.
Enabling CheckJNI
 Enable CheckJNI:
 For Production Builds
 adb shell setprop debug.checkjni 1
 For Engineering Builds:
 adb shell stop
 adb shell setprop dalvik.vm.checkjni true
 adb shell start
Memory Issues
 Using Libc Debug Mode
 adb shell setprop libc.debug.malloc 1
 adb shell stop
 adb shell start
 Supported libc debug mode values are
 1: Perform leak detection.
 5: Fill allocated memory to detect overruns.
 10: Fill memory and add sentinel to detect overruns.
Further Reading
 Native Threads usage
 More about references
 JNI Graphics using OpenGL
 Audio using OpenSL apis.
 http://developer.android.com/training/articles/perf-jni.html
Questions??

More Related Content

What's hot

Java IO
Java IOJava IO
Java IO
UTSAB NEUPANE
 
Delegates and events in C#
Delegates and events in C#Delegates and events in C#
Delegates and events in C#
Dr.Neeraj Kumar Pandey
 
C# in depth
C# in depthC# in depth
C# in depth
Arnon Axelrod
 
Presentation on Android application life cycle and saved instancestate
Presentation on Android application life cycle and saved instancestatePresentation on Android application life cycle and saved instancestate
Presentation on Android application life cycle and saved instancestate
Osahon Gino Ediagbonya
 
C# Basics
C# BasicsC# Basics
C# Basics
Sunil OS
 
Jsp ppt
Jsp pptJsp ppt
Jsp ppt
Vikas Jagtap
 
Android contentprovider
Android contentproviderAndroid contentprovider
Android contentproviderKrazy Koder
 
Java Tokens
Java  TokensJava  Tokens
JQuery selectors
JQuery selectors JQuery selectors
JQuery selectors
chandrashekher786
 
Build RESTful API Using Express JS
Build RESTful API Using Express JSBuild RESTful API Using Express JS
Build RESTful API Using Express JS
Cakra Danu Sedayu
 
Android service, aidl - day 1
Android service, aidl - day 1Android service, aidl - day 1
Android service, aidl - day 1Utkarsh Mankad
 
Spring JDBCTemplate
Spring JDBCTemplateSpring JDBCTemplate
Spring JDBCTemplateGuo Albert
 
java.io - streams and files
java.io - streams and filesjava.io - streams and files
java.io - streams and files
Marcello Thiry
 
Interface in java
Interface in javaInterface in java
Interface in java
PhD Research Scholar
 
JSON: The Basics
JSON: The BasicsJSON: The Basics
JSON: The Basics
Jeff Fox
 

What's hot (20)

Java IO
Java IOJava IO
Java IO
 
Delegates and events in C#
Delegates and events in C#Delegates and events in C#
Delegates and events in C#
 
C# in depth
C# in depthC# in depth
C# in depth
 
Presentation on Android application life cycle and saved instancestate
Presentation on Android application life cycle and saved instancestatePresentation on Android application life cycle and saved instancestate
Presentation on Android application life cycle and saved instancestate
 
C# Basics
C# BasicsC# Basics
C# Basics
 
Jsp ppt
Jsp pptJsp ppt
Jsp ppt
 
Android contentprovider
Android contentproviderAndroid contentprovider
Android contentprovider
 
Java Tokens
Java  TokensJava  Tokens
Java Tokens
 
JQuery selectors
JQuery selectors JQuery selectors
JQuery selectors
 
Build RESTful API Using Express JS
Build RESTful API Using Express JSBuild RESTful API Using Express JS
Build RESTful API Using Express JS
 
Android service, aidl - day 1
Android service, aidl - day 1Android service, aidl - day 1
Android service, aidl - day 1
 
Android Threading
Android ThreadingAndroid Threading
Android Threading
 
Input output streams
Input output streamsInput output streams
Input output streams
 
Spring JDBCTemplate
Spring JDBCTemplateSpring JDBCTemplate
Spring JDBCTemplate
 
Android adapters
Android adaptersAndroid adapters
Android adapters
 
Introduction to Angularjs
Introduction to AngularjsIntroduction to Angularjs
Introduction to Angularjs
 
java.io - streams and files
java.io - streams and filesjava.io - streams and files
java.io - streams and files
 
Interface in java
Interface in javaInterface in java
Interface in java
 
JSON: The Basics
JSON: The BasicsJSON: The Basics
JSON: The Basics
 
Android Services
Android ServicesAndroid Services
Android Services
 

Viewers also liked

Understanding the Dalvik bytecode with the Dedexer tool
Understanding the Dalvik bytecode with the Dedexer toolUnderstanding the Dalvik bytecode with the Dedexer tool
Understanding the Dalvik bytecode with the Dedexer tool
Gabor Paller
 
Dancing with dalvik
Dancing with dalvikDancing with dalvik
Dancing with dalvik
Thomas Richards
 
Garbage Collection of Java VM
Garbage Collection of Java VMGarbage Collection of Java VM
Garbage Collection of Java VM
Yongqiang Li
 
Let's talk about jni
Let's talk about jniLet's talk about jni
Let's talk about jni
Yongqiang Li
 
LinkedIn - Disassembling Dalvik Bytecode
LinkedIn - Disassembling Dalvik BytecodeLinkedIn - Disassembling Dalvik Bytecode
LinkedIn - Disassembling Dalvik BytecodeAlain Leon
 
Inside Android's Dalvik VM - NEJUG Nov 2011
Inside Android's Dalvik VM - NEJUG Nov 2011Inside Android's Dalvik VM - NEJUG Nov 2011
Inside Android's Dalvik VM - NEJUG Nov 2011
Doug Hawkins
 
Android internals 05 - Dalvik VM (rev_1.1)
Android internals 05 - Dalvik VM (rev_1.1)Android internals 05 - Dalvik VM (rev_1.1)
Android internals 05 - Dalvik VM (rev_1.1)
Egor Elizarov
 
Understanding the Dalvik Virtual Machine
Understanding the Dalvik Virtual MachineUnderstanding the Dalvik Virtual Machine
Understanding the Dalvik Virtual Machine
National Cheng Kung University
 
Google ART (Android RunTime)
Google ART (Android RunTime)Google ART (Android RunTime)
Google ART (Android RunTime)
Niraj Solanke
 
How to implement a simple dalvik virtual machine
How to implement a simple dalvik virtual machineHow to implement a simple dalvik virtual machine
How to implement a simple dalvik virtual machine
Chun-Yu Wang
 

Viewers also liked (10)

Understanding the Dalvik bytecode with the Dedexer tool
Understanding the Dalvik bytecode with the Dedexer toolUnderstanding the Dalvik bytecode with the Dedexer tool
Understanding the Dalvik bytecode with the Dedexer tool
 
Dancing with dalvik
Dancing with dalvikDancing with dalvik
Dancing with dalvik
 
Garbage Collection of Java VM
Garbage Collection of Java VMGarbage Collection of Java VM
Garbage Collection of Java VM
 
Let's talk about jni
Let's talk about jniLet's talk about jni
Let's talk about jni
 
LinkedIn - Disassembling Dalvik Bytecode
LinkedIn - Disassembling Dalvik BytecodeLinkedIn - Disassembling Dalvik Bytecode
LinkedIn - Disassembling Dalvik Bytecode
 
Inside Android's Dalvik VM - NEJUG Nov 2011
Inside Android's Dalvik VM - NEJUG Nov 2011Inside Android's Dalvik VM - NEJUG Nov 2011
Inside Android's Dalvik VM - NEJUG Nov 2011
 
Android internals 05 - Dalvik VM (rev_1.1)
Android internals 05 - Dalvik VM (rev_1.1)Android internals 05 - Dalvik VM (rev_1.1)
Android internals 05 - Dalvik VM (rev_1.1)
 
Understanding the Dalvik Virtual Machine
Understanding the Dalvik Virtual MachineUnderstanding the Dalvik Virtual Machine
Understanding the Dalvik Virtual Machine
 
Google ART (Android RunTime)
Google ART (Android RunTime)Google ART (Android RunTime)
Google ART (Android RunTime)
 
How to implement a simple dalvik virtual machine
How to implement a simple dalvik virtual machineHow to implement a simple dalvik virtual machine
How to implement a simple dalvik virtual machine
 

Similar to Android JNI

Getting started with the JNI
Getting started with the JNIGetting started with the JNI
Getting started with the JNI
Kirill Kounik
 
Using the Android Native Development Kit (NDK)
Using the Android Native Development Kit (NDK)Using the Android Native Development Kit (NDK)
Using the Android Native Development Kit (NDK)
DroidConTLV
 
JNA - Let's C what it's worth
JNA - Let's C what it's worthJNA - Let's C what it's worth
JNA - Let's C what it's worth
Idan Sheinberg
 
NDK Primer (AnDevCon Boston 2014)
NDK Primer (AnDevCon Boston 2014)NDK Primer (AnDevCon Boston 2014)
NDK Primer (AnDevCon Boston 2014)
Ron Munitz
 
C++ programming with jni
C++ programming with jniC++ programming with jni
C++ programming with jni
Peter Hagemeyer
 
NDK Primer (Wearable DevCon 2014)
NDK Primer (Wearable DevCon 2014)NDK Primer (Wearable DevCon 2014)
NDK Primer (Wearable DevCon 2014)
Ron Munitz
 
Introduction to the Android NDK
Introduction to the Android NDKIntroduction to the Android NDK
Introduction to the Android NDK
BeMyApp
 
Android and cpp
Android and cppAndroid and cpp
Android and cpp
Joan Puig Sanz
 
Android ndk
Android ndkAndroid ndk
Android ndk
Khiem-Kim Ho Xuan
 
Unit 1 of java part 2 basic introduction
Unit 1 of java part 2 basic introduction Unit 1 of java part 2 basic introduction
Unit 1 of java part 2 basic introduction
AKR Education
 
Developing android apps with java 8
Developing android apps with java 8Developing android apps with java 8
Developing android apps with java 8
Jorge Castillo Pérez
 
Java OOP Concepts 1st Slide
Java OOP Concepts 1st SlideJava OOP Concepts 1st Slide
Java OOP Concepts 1st Slide
sunny khan
 
College Project - Java Disassembler - Description
College Project - Java Disassembler - DescriptionCollege Project - Java Disassembler - Description
College Project - Java Disassembler - Description
Ganesh Samarthyam
 
Using the android ndk - DroidCon Paris 2014
Using the android ndk - DroidCon Paris 2014Using the android ndk - DroidCon Paris 2014
Using the android ndk - DroidCon Paris 2014
Paris Android User Group
 
Cross Platform App Development with C++
Cross Platform App Development with C++Cross Platform App Development with C++
Cross Platform App Development with C++
Joan Puig Sanz
 
java basic .pdf
java basic .pdfjava basic .pdf
java basic .pdf
Satish More
 
02 basic java programming and operators
02 basic java programming and operators02 basic java programming and operators
02 basic java programming and operators
Danairat Thanabodithammachari
 
Std 12 Computer Chapter 7 Java Basics (Part 1)
Std 12 Computer Chapter 7 Java Basics (Part 1)Std 12 Computer Chapter 7 Java Basics (Part 1)
Std 12 Computer Chapter 7 Java Basics (Part 1)
Nuzhat Memon
 

Similar to Android JNI (20)

Getting started with the JNI
Getting started with the JNIGetting started with the JNI
Getting started with the JNI
 
Using the Android Native Development Kit (NDK)
Using the Android Native Development Kit (NDK)Using the Android Native Development Kit (NDK)
Using the Android Native Development Kit (NDK)
 
JNA - Let's C what it's worth
JNA - Let's C what it's worthJNA - Let's C what it's worth
JNA - Let's C what it's worth
 
NDK Primer (AnDevCon Boston 2014)
NDK Primer (AnDevCon Boston 2014)NDK Primer (AnDevCon Boston 2014)
NDK Primer (AnDevCon Boston 2014)
 
C++ programming with jni
C++ programming with jniC++ programming with jni
C++ programming with jni
 
NDK Primer (Wearable DevCon 2014)
NDK Primer (Wearable DevCon 2014)NDK Primer (Wearable DevCon 2014)
NDK Primer (Wearable DevCon 2014)
 
Introduction to the Android NDK
Introduction to the Android NDKIntroduction to the Android NDK
Introduction to the Android NDK
 
Dacj 4 1-c
Dacj 4 1-cDacj 4 1-c
Dacj 4 1-c
 
Android and cpp
Android and cppAndroid and cpp
Android and cpp
 
Android ndk
Android ndkAndroid ndk
Android ndk
 
CS2309 JAVA LAB MANUAL
CS2309 JAVA LAB MANUALCS2309 JAVA LAB MANUAL
CS2309 JAVA LAB MANUAL
 
Unit 1 of java part 2 basic introduction
Unit 1 of java part 2 basic introduction Unit 1 of java part 2 basic introduction
Unit 1 of java part 2 basic introduction
 
Developing android apps with java 8
Developing android apps with java 8Developing android apps with java 8
Developing android apps with java 8
 
Java OOP Concepts 1st Slide
Java OOP Concepts 1st SlideJava OOP Concepts 1st Slide
Java OOP Concepts 1st Slide
 
College Project - Java Disassembler - Description
College Project - Java Disassembler - DescriptionCollege Project - Java Disassembler - Description
College Project - Java Disassembler - Description
 
Using the android ndk - DroidCon Paris 2014
Using the android ndk - DroidCon Paris 2014Using the android ndk - DroidCon Paris 2014
Using the android ndk - DroidCon Paris 2014
 
Cross Platform App Development with C++
Cross Platform App Development with C++Cross Platform App Development with C++
Cross Platform App Development with C++
 
java basic .pdf
java basic .pdfjava basic .pdf
java basic .pdf
 
02 basic java programming and operators
02 basic java programming and operators02 basic java programming and operators
02 basic java programming and operators
 
Std 12 Computer Chapter 7 Java Basics (Part 1)
Std 12 Computer Chapter 7 Java Basics (Part 1)Std 12 Computer Chapter 7 Java Basics (Part 1)
Std 12 Computer Chapter 7 Java Basics (Part 1)
 

Recently uploaded

How to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptxHow to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptx
danishmna97
 
UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5
DianaGray10
 
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex ProofszkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
Alex Pruden
 
20240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 202420240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 2024
Matthew Sinclair
 
National Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practicesNational Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practices
Quotidiano Piemontese
 
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
Neo4j
 
Removing Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software FuzzingRemoving Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software Fuzzing
Aftab Hussain
 
Free Complete Python - A step towards Data Science
Free Complete Python - A step towards Data ScienceFree Complete Python - A step towards Data Science
Free Complete Python - A step towards Data Science
RinaMondal9
 
20240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 202420240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 2024
Matthew Sinclair
 
Climate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing DaysClimate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing Days
Kari Kakkonen
 
Video Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the FutureVideo Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the Future
Alpen-Adria-Universität
 
GridMate - End to end testing is a critical piece to ensure quality and avoid...
GridMate - End to end testing is a critical piece to ensure quality and avoid...GridMate - End to end testing is a critical piece to ensure quality and avoid...
GridMate - End to end testing is a critical piece to ensure quality and avoid...
ThomasParaiso2
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
Laura Byrne
 
Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1
DianaGray10
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
Guy Korland
 
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptxSecstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
nkrafacyberclub
 
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
名前 です男
 
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
Neo4j
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
Alan Dix
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
Kari Kakkonen
 

Recently uploaded (20)

How to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptxHow to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptx
 
UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5
 
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex ProofszkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
 
20240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 202420240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 2024
 
National Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practicesNational Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practices
 
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
 
Removing Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software FuzzingRemoving Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software Fuzzing
 
Free Complete Python - A step towards Data Science
Free Complete Python - A step towards Data ScienceFree Complete Python - A step towards Data Science
Free Complete Python - A step towards Data Science
 
20240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 202420240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 2024
 
Climate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing DaysClimate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing Days
 
Video Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the FutureVideo Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the Future
 
GridMate - End to end testing is a critical piece to ensure quality and avoid...
GridMate - End to end testing is a critical piece to ensure quality and avoid...GridMate - End to end testing is a critical piece to ensure quality and avoid...
GridMate - End to end testing is a critical piece to ensure quality and avoid...
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
 
Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
 
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptxSecstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
 
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
 
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
 

Android JNI

  • 2. Android JNI ● Why JNI? ● What is NDK? ● Why NDK? ● Deep into JNI world.
  • 3. Why JNI? Android is put together of about equal part Java and C. we need an easy way to bridge between these two totally different worlds .Java offers Java Native Interface (JNI) as a framework connecting the world of Java to the native code.
  • 4. More About JNI JNI is part of Dalvik VM, which allows native code to access java environment. Like accessing java objects and its methods, members etc. JNI also facilitates accessing and invoking of native methods from Java code. JNI Comes with Primitive and reference types. Primitive types can be manipulated directly as these are equivalent to native c.c++ data types But you need special helper functions to manipulate JNI reference types.
  • 5. What is NDK? NDK is a toolchain Cross-compiler, linker, what you need to build for ARM, x86, MIPS, etc. NDK provides a way to bundle lib.so into your APK The native library needs to be loadable in a secure way. NDK "standardizes" various native platforms It provides headers for libc, libm, libz, lliibblloogg, lliibbjjnniiggrraahhiiccss, OpenGL/OpenSL ES, JNI headers, minimal C++ support headers, and Android native app APIs
  • 7. Why NDK/JNI? For performance Sometimes, native code still runs faster. For legacy support You may have that C/C++ code you’d like to use in your app. For access to low-level libraries I n a rare case when there is no Java API to do something. For cross-platform development But Adding JNI to your app will make it more complex.
  • 10. Loading Native Libraries and Registering Native Methods Native code is usually compiled into a shared library and loaded before the native methods can be called. All the Native methods are declared with native keyword in java. static { //use either of the two methods below System.loadLibrary(“nativelib"); System.load("/data/data/cookbook.chapter2/lib/ libNative.so"); }
  • 11. Registering Native Methods  JNIEnv Interface Pointer: Every native method defined in native code at JNI must accept two input parameters, the first one being a pointer to JNIEnv. The JNIEnv interface pointer is pointing to thread-local data, which in turn points to a JNI function table shared by all threads. This can be illustrated using the following diagram:
  • 12. JNIEnv Gateway to access all predefined JNI functions. Access Java Fields Invoke Java Methods. It points to the thread’s local data, so it cannot be shared. It can be accessible only by java threads. Native threads must call AttachCurrentThread to attach itself to VM and to obtain the JNIEnv interface pointer. RegisterNatives :  Two ways:  1. Using Javah tool.  2. Using RegisterNative function.
  • 13. Using RegisterNative Method Prototype: jint RegisterNatives(JNIEnv *env, jclass clazz, const JNINativeMethod *methods, jint nMethods); The clazz argument is a reference to the class in which the native method is to be registered. The methods argument is an array of the JNINativeMethod data structure. JNINativeMethod is defined as follows: typedef struct { char *name; char *signature; void *fnPtr; } JNINativeMethod; name indicates the native method name, signature is the descriptor of the method's input argument data type and return value data type, and fnPtr is the function pointer pointing to the native method. The last argument, nMethods of RegisterNatives, indicates the number of methods to register. The function returns zero to indicate success, and a negative value otherwise.
  • 14. JNI_OnLoad  Invoke when the native library is loaded.  It is the right and safe place to register the native methods before their execution.  JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM* pVm, void* reserved)  {  JNIEnv* env;  if ((*pVm)->GetEnv(pVm, (void **)&env, JNI_VERSION_1_6)) {  return -1;  }  // Get jclass with env->FindClass.  // Register methods with env->RegisterNatives.  return JNI_VERSION_1_6;  }
  • 16. Manipulating strings in JNI  Strings are somewhat complicated in JNI, mainly because Java strings and C strings are internally different.  Java programming language uses UTF-16 to represent strings. If a character cannot fit in a 16-bit code value, a pair of code values named surrogate pair is used  C strings are simply an array of bytes terminated by a null character  The Unicode Standard is a character coding system designed to support the worldwide interchange, processing, and display of the written texts of the diverse languages and technical disciplines of the modern world. In addition, it supports classical and historical texts of many written languages.  Few JNI String Functions:  jstring NewStringUTF(JNIEnv *env, const char *bytes);  void GetStringUTFRegion(JNIEnv *env, jstring str, jsize start, jsize len, char *buf);  void ReleaseStringUTFChars(JNIEnv *env, jstring string, const char *utf);  const jbyte * GetStringUTFChars(JNIEnv *env, jstring string, jboolean *isCopy);
  • 17. Manipulating Objects in JNI jobject AllocObject(JNIEnv *env, jclass clazz); jobject NewObject(JNIEnv *env, jclass clazz,jmethodID methodID, ...); jobject NewObjectA(JNIEnv *env, jclass clazz,jmethodID methodID, jvalue *args); jobject NewObjectV(JNIEnv *env, jclass clazz,jmethodID methodID, va_list args);  The clazz argument is a reference to the Java class of which we want to create an instance object. It cannot be an array class, which has its own set of JNI functions.  methodID is the constructor method ID, which can be obtained using the GetMethodID JNI function.
  • 18. Manipulating Classes in JNI jclass FindClass(JNIEnv *env, const char *name);  Majorly used method when writing JNI code.  Must pass full path of class.  If you have to call this method for finding the most used class in JNI, it is better to Cache it.
  • 19. Accessing Java Static and Instance fileds in Native code  jfieldID data type: jfieldID is a regular C pointer pointing to a data structure with details hidden from developers. We should not confuse it with jobject or its subtypes. jobject is a reference type corresponding to Object in Java, while jfieldID doesn't have such a corresponding type in Java. However, JNI provides functions to convert the java.lang.reflect.Field instance to jfieldID and vice versa.  Field descriptor: It refers to the modified UTF-8 string used to represent the field data type. The following table summarizes the Java field types and its corresponding field descriptors:
  • 20.
  • 21. Accessing static fields  JNI provides three functions to access static fields of a Java class. They have the following prototypes: jfieldID GetStaticFieldID(JNIEnv *env, jclass clazz, const char *name, const char *sig); <NativeType> GetStatic<Type>Field(JNIEnv *env,jclass clazz, jfieldID fieldID); void SetStatic<Type>Field(JNIEnv *env, jclass clazz, jfieldID fieldID,<NativeType> value);
  • 22. Accessing instance field  Accessing instance fields is similar to accessing static fields. JNI also provides the following three functions for us: jfieldID GetFieldID(JNIEnv *env, jclass clazz, const char *name, const char *sig); <NativeType> Get<Type>Field(JNIEnv *env,jobject obj, jfieldID fieldID); void Set<Type>Field(JNIEnv *env, jobject obj, jfieldID fieldID, <NativeType> value);
  • 23. Calling static and instance methods from the native code  jmethodID data type: Similar to jfieldID, jmethodID is a regular C pointer pointing to a data structure with details hidden from the developers. JNI provides functions to convert the java.lang.reflect.Method instance to jmethodID and vice versa.  Method descriptor: This is a modified UTF-8 string used to represent the input (input arguments) data types and output (return type) data type of the method. Method descriptors are formed by grouping all field descriptors of its input arguments inside a "()", and appending the field descriptor of the return type. If the return type is void, we should use "V". If there's no input arguments, we should simply use "()", followed by the field descriptor of the return type. For constructors, "V" should be used to represent the return type. The following table lists a few Java methods and their corresponding method descriptors:
  • 24.
  • 25. Calling static methods:  JNI provides four sets of functions for native code to call Java methods. Their prototypes are as follows: jmethodID GetStaticMethodID(JNIEnv *env, jclass clazz, const char *name, const char *sig); <NativeType> CallStatic<Type>Method(JNIEnv *env, jclass clazz, jmethodID methodID, ...); <NativeType> CallStatic<Type>MethodA(JNIEnv *env, jclass clazz, jmethodID methodID, jvalue *args); <NativeType> CallStatic<Type>MethodV(JNIEnv *env, jclass clazz,jmethodID methodID, va_list args);
  • 26. Calling instance methods:  Calling instance methods from the native code is similar to calling static methods. JNI also provides four sets of functions as follows: jmethodID GetMethodID(JNIEnv *env, jclass clazz, const char *name, const char *sig); <NativeType> Call<Type>Method(JNIEnv *env, jobject obj, jmethodID methodID, ...); <NativeType> Call<Type>MethodA(JNIEnv *env,jobject obj, jmethodID methodID, jvalue *args); <NativeType> Call<Type>MethodV(JNIEnv *env, jobject obj, jmethodID methodID, va_list args);
  • 27. Checking errors and handling exceptions in JNI  JNI functions can fail because of system constraint (for example, lack of memory) or invalid arguments (for example, passing a native UTF-8 string when the function is expecting a UTF-16 string).  Check for errors and exceptions: Many JNI functions return a special value to indicate failure. For example, the FindClass function returns NULL to indicate it failed to load the class. Many other functions do not use the return value to signal failure; instead an exception is thrown.  jboolean ExceptionCheck(JNIEnv *env);  jthrowable ExceptionOccurred(JNIEnv *env);  void ExceptionDescribe(JNIEnv *env);
  • 28. Throw exceptions in the native code:  JNI provides two functions to throw an exception from native code. They have the following prototypes: jint Throw(JNIEnv *env, jthrowable obj); jint ThrowNew(JNIEnv *env, jclass clazz, const char *message);  The first function accepts a reference to a jthrowable object and throws the exception, while the second function accepts a reference to an exception class. It will create an exception object of the clazz class with the message argument and throw it.
  • 29. Extended Error Check  Using CheckJNI  Android also offers a mode called CheckJNI, where the JavaVM and JNIEnv function table pointers are switched to tables of functions that perform an extended series of checks before calling the standard implementation.  List of Errors that CheckJNI tool can catch:  Arrays: attempting to allocate a negative-sized array.  Bad pointers: passing a bad jarray/jclass/jobject/jstring to a JNI call, or passing a NULL pointer to a JNI call with a non-nullable argument.  Class names: passing anything but the “java/lang/String” style of class name to a JNI call.  Critical calls: making a JNI call between a “critical” get and its corresponding release.  Direct ByteBuffers: passing bad arguments to NewDirectByteBuffer.  Exceptions: making a JNI call while there’s an exception pending.  JNIEnv*s: using a JNIEnv* from the wrong thread.  jfieldIDs: using a NULL jfieldID, or using a jfieldID to set a field to a value of the wrong type (trying to assign a StringBuilder to a String field, say), or using a jfieldID for a static field to set an instance field or vice versa, or using a jfieldID from one class with instances of another class.
  • 30. Enabling CheckJNI  Enable CheckJNI:  For Production Builds  adb shell setprop debug.checkjni 1  For Engineering Builds:  adb shell stop  adb shell setprop dalvik.vm.checkjni true  adb shell start
  • 31. Memory Issues  Using Libc Debug Mode  adb shell setprop libc.debug.malloc 1  adb shell stop  adb shell start  Supported libc debug mode values are  1: Perform leak detection.  5: Fill allocated memory to detect overruns.  10: Fill memory and add sentinel to detect overruns.
  • 32. Further Reading  Native Threads usage  More about references  JNI Graphics using OpenGL  Audio using OpenSL apis.  http://developer.android.com/training/articles/perf-jni.html