SlideShare una empresa de Scribd logo
1 de 36
Descargar para leer sin conexión
Native code in Android
applications
My projects using NDK
Yumm
Low memory overhead for image decoding
Hudriks Math
cocos2d-x; cross-platform: iOS and Android
Secure Video Player
Critical DRM code; cross-platform code (iOS/Android/Linux/OS X/Windows);
high-performance
Overview
Your Java Application
Java code

/libs/armeabi/

Android Runtime
Core Libraries (Java)
JVM (Dalvik)

Libraries
OpenSL ES

SQLite

OpenGL

Linux Platform

Media
Android NDK

•

Documentation

•

Toolchain - ndk-build, gcc/clang, gdbserver, …

•

NDK framework headers

•

Build system
NDK frameworks
android-4 (1.6)
•

dl, zlib, math, log

•

OpenGL ES 1.x

android-14 (4.0)
android-5 (2.0)
•

OpenMAX

OpenGL ES 2.0

android-8 (2.2)
•

•

JNI Graphics - java Bitmaps on low level

android-9 (2.3)
•

EGL

•

OpenSL ES - audio library

•

Native Applications - native activity, etc

android-18 (4.3)
•

OpenGL ES 3.0
Compilation process
source

.c/.c++
.o
.o

objects
compiler

.o
.o
.o

shared library
linker

.so

static library
.a (archive)

.so
.o
.o
.o
Application structure
•

jni/ (source code)
•

Android.mk

•

[Application.mk]

•

module1/
•

•

Android.mk

libs/armeabi/libnative.so - compiled shared library
CPU specific
•

Application Binary Interface (ABI):
• armeabi - at least ARMv5TE
• armeabi-v7a - Thumb-2; VFP hardware FPU; NEON
• x86
• mips

•

Application.mk:
• APP_ABI := all
• APP_ABI := armeabi armeabi-v7a
Java Native Interface
JNI in C and C++
#include <jni.h>

C
struct JNINativeInterface {	
	 jclass
(*FindClass)(JNIEnv*, const char*);	
}	
typedef const struct JNINativeInterface* JNIEnv;	
!

JNIEnv* env;	
(*env)->FindClass(env, “classname”);
JNI in C and C++
C++
struct _JNIEnv {	
jclass FindClass(const char* name)	
{ return functions->FindClass(this, name); }	
}	

!

JNIEnv* env;	
env->FindClass(“classname”);
Mapping native functions
libnative.so

Java.class

- function_1()

- function_1()

- function_2()

- function_2()

- function_3()

- function_3()

- function_4()

- function_4()

- function_5()

- function_5()
Mapping native functions
.java
public native static int testNative(int a, int b);

.c
jint Java_com_example_jnibasics_NativeDemo_testNative(JNIEnv *env, jclass obj, jint a, jint b)

package name

javah
> javah com.example.jnibasics.NativeDemo
Mapping native functions
jint RegisterNatives(JNIEnv *env, jclass clazz, const
JNINativeMethod *methods, jint nMethods);
typedef struct {
char *name;
char *signature;
void *fnPtr;
} JNINativeMethod;

jint addVals(JNIEnv *env, jclass obj, jint a, jint b) {…}
Mapping native functions
static JNINativeMethod sMethods[] = {	
{"testNative", "(II)I", (void*)addVals}	
};

jint JNI_OnLoad(JavaVM* vm, void* reserved) {	
JNIEnv *env = NULL;	
jclass klass;	
	
if((*vm)->GetEnv(vm, (void**)&env, JNI_VERSION_1_6) != JNI_OK)	
return -1;	

!

klass = (*env)->FindClass(env, “com/example/jnibasics/NativeDemo”);	
 	
(*env)->RegisterNatives(env, klass, gMethods, 1);	

	

!

	

return JNI_VERSION_1_6;	
}
Loading .so from Java
	
	
	
	
	
	
	

static {	
static {	
	
System.loadLibrary("Dependency");	
	
System.loadLibrary("JNIBasics");	
	
System.loadLibrary("JNIBasics");	
}
}

JNIBasics

Dependency
Demo
References
jobject gObject = NULL;	
!
void function(JNIEnv* jobject obj) {	
	 gObject = (*env)->NewGlobalRef(env, obj);	
}	
!
void finish(JNIEnv* env) {	
	 (*env)->DeleteGlobalRef(env, gObject);	
}
Calling Java methods from
native
jclass clz = (*env)->FindClass(env, “com/example/jnibasics/NativeDemo");	

!
jmethodID method = (*env)->GetMethodID(env, clz, 	
	 	 "methodName", “(II)Ljava/lang/String;");	

!
jstring result = (*env)->CallObjectMethod(env, obj, method, 5, 6);
Accessing java strings
jstring jstr;	
const char* str;	
!

str = (*env)->GetStringUTFChars(env, jstr, NULL);	
!

...	
!

(*env)->ReleaseStringUTFChars(env, jstr, str);
Further reading
•

Attaching Java threads

•

Creating new Java objects from native code

•

Distinguish between virtual and non virtual methods

•

Exception handling

•

Accessing Java arrays
Using native code
Performance
•

Most applications don’t need native code!

•

Only for extensive calculations: games, rich media

•

Take advantage of NEON CPU instructions

•

Avoiding Java Garbage Collection
Cross-platform architecture
platform dependant
libraries
(network, UI, etc)

Application
(Java/UIKit)
platform independent
code
(no JNI)

external interface
(JNI/Objective-C)
Cross-platform examples

VLC
Security
1.
2.
3.
4.

Register as a developer (£60 per year)
Add device UUID to dev account
Generate Provisioning Profile
Sign APK with developer’s certificate

!

or Submit to Apple Store
or Jailbreak device

Binary is encrypted
Decryption is on OS level

Self-signed APK
or not-signed at all

Decompiled Objective C:

Decompiled Java:

class structures
assembly code

readable code
Demo

DISCLAIMER: For educational purposes only;
I’m not encouraging to hack somebody else’s applications;
Summary
•

Always obfuscate Java code!

•

Never save passwords, use session key or hash
instead

•

Never keep encryption keys in clear data in memory

•

Keep all critical code in native
Further protection

•

Hide non-public symbols from .so files

•

Strip debug information into separate files

•

Expose only high-level APIs to Java
Tips
•

Debugging native code is tricky
•
•

•

Linux or OSX as dev platform
Use ARM DS-5 Community Edition in Eclipse

Android fragmentation
•

separate .so files for different version
Questions?

Dmitry Matyukhin
dmitry@fancygames.net

Más contenido relacionado

La actualidad más candente

Fixing the Java Serialization Mess
Fixing the Java Serialization Mess Fixing the Java Serialization Mess
Fixing the Java Serialization Mess
Salesforce Engineering
 
Building a java tracer
Building a java tracerBuilding a java tracer
Building a java tracer
rahulrevo
 

La actualidad más candente (20)

HexRaysCodeXplorer: make object-oriented RE easier
HexRaysCodeXplorer: make object-oriented RE easierHexRaysCodeXplorer: make object-oriented RE easier
HexRaysCodeXplorer: make object-oriented RE easier
 
Static code analysis: what? how? why?
Static code analysis: what? how? why?Static code analysis: what? how? why?
Static code analysis: what? how? why?
 
Making Java more dynamic: runtime code generation for the JVM
Making Java more dynamic: runtime code generation for the JVMMaking Java more dynamic: runtime code generation for the JVM
Making Java more dynamic: runtime code generation for the JVM
 
NDK Primer (Wearable DevCon 2014)
NDK Primer (Wearable DevCon 2014)NDK Primer (Wearable DevCon 2014)
NDK Primer (Wearable DevCon 2014)
 
Flutter 是什麼?用 Flutter 會省到時間嗎? @ GDG Devfest2020
Flutter 是什麼?用 Flutter 會省到時間嗎? @ GDG Devfest2020Flutter 是什麼?用 Flutter 會省到時間嗎? @ GDG Devfest2020
Flutter 是什麼?用 Flutter 會省到時間嗎? @ GDG Devfest2020
 
core java
core javacore java
core java
 
Java 10, Java 11 and beyond
Java 10, Java 11 and beyondJava 10, Java 11 and beyond
Java 10, Java 11 and beyond
 
Java Deserialization Vulnerabilities - The Forgotten Bug Class
Java Deserialization Vulnerabilities - The Forgotten Bug ClassJava Deserialization Vulnerabilities - The Forgotten Bug Class
Java Deserialization Vulnerabilities - The Forgotten Bug Class
 
C++ programming with jni
C++ programming with jniC++ programming with jni
C++ programming with jni
 
Tips and tricks for building high performance android apps using native code
Tips and tricks for building high performance android apps using native codeTips and tricks for building high performance android apps using native code
Tips and tricks for building high performance android apps using native code
 
Building High Performance Android Applications in Java and C++
Building High Performance Android Applications in Java and C++Building High Performance Android Applications in Java and C++
Building High Performance Android Applications in Java and C++
 
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
 
Fixing the Java Serialization Mess
Fixing the Java Serialization Mess Fixing the Java Serialization Mess
Fixing the Java Serialization Mess
 
The definitive guide to java agents
The definitive guide to java agentsThe definitive guide to java agents
The definitive guide to java agents
 
Inc0gnito 2015 Android DEX Analysis Technique
Inc0gnito 2015 Android DEX Analysis TechniqueInc0gnito 2015 Android DEX Analysis Technique
Inc0gnito 2015 Android DEX Analysis Technique
 
Building a java tracer
Building a java tracerBuilding a java tracer
Building a java tracer
 
JVM Mechanics: When Does the JVM JIT & Deoptimize?
JVM Mechanics: When Does the JVM JIT & Deoptimize?JVM Mechanics: When Does the JVM JIT & Deoptimize?
JVM Mechanics: When Does the JVM JIT & Deoptimize?
 
C++ Advanced Features
C++ Advanced FeaturesC++ Advanced Features
C++ Advanced Features
 
Java concurrency
Java concurrencyJava concurrency
Java concurrency
 
C++ Advanced Features
C++ Advanced FeaturesC++ Advanced Features
C++ Advanced Features
 

Destacado

1.1 memahami gelombang (b)
1.1 memahami gelombang (b)1.1 memahami gelombang (b)
1.1 memahami gelombang (b)
Amb Jerome
 
Parish Leadership 2014: Insurance and Risk Management
Parish Leadership 2014: Insurance and Risk ManagementParish Leadership 2014: Insurance and Risk Management
Parish Leadership 2014: Insurance and Risk Management
Anglican Diocese of Toronto
 
07-02-2013 eraikune-boma
07-02-2013 eraikune-boma07-02-2013 eraikune-boma
07-02-2013 eraikune-boma
Eraikune
 
06 salida 23_03_2013
06 salida 23_03_201306 salida 23_03_2013
06 salida 23_03_2013
chouffe
 
Rapport: Utprøving av iPad i alternative opplæringarenaer
Rapport: Utprøving av iPad i alternative opplæringarenaerRapport: Utprøving av iPad i alternative opplæringarenaer
Rapport: Utprøving av iPad i alternative opplæringarenaer
Frode Kyrkjebø
 
The JOBS Act Implementation Update
The JOBS Act Implementation UpdateThe JOBS Act Implementation Update
The JOBS Act Implementation Update
MarketNexus Media
 

Destacado (20)

Madeleine H Vedel CV 2015
Madeleine H Vedel CV 2015Madeleine H Vedel CV 2015
Madeleine H Vedel CV 2015
 
Solidos cristalinos hcsc
Solidos cristalinos hcscSolidos cristalinos hcsc
Solidos cristalinos hcsc
 
SOLOPRENEUR
SOLOPRENEURSOLOPRENEUR
SOLOPRENEUR
 
Industria Petroquímica Mexicana. Problemática, Diagnóstico y Propuestas de So...
Industria Petroquímica Mexicana. Problemática, Diagnóstico y Propuestas de So...Industria Petroquímica Mexicana. Problemática, Diagnóstico y Propuestas de So...
Industria Petroquímica Mexicana. Problemática, Diagnóstico y Propuestas de So...
 
Eso1128
Eso1128Eso1128
Eso1128
 
Spsbe 18-04-15 - should i move my network folders to office 365
Spsbe   18-04-15 - should i move my network folders to office 365Spsbe   18-04-15 - should i move my network folders to office 365
Spsbe 18-04-15 - should i move my network folders to office 365
 
1.1 memahami gelombang (b)
1.1 memahami gelombang (b)1.1 memahami gelombang (b)
1.1 memahami gelombang (b)
 
Competencia Imperfecta
Competencia ImperfectaCompetencia Imperfecta
Competencia Imperfecta
 
Oracle - Simplificación y Administración de TI
Oracle - Simplificación y Administración de TIOracle - Simplificación y Administración de TI
Oracle - Simplificación y Administración de TI
 
Parish Leadership 2014: Insurance and Risk Management
Parish Leadership 2014: Insurance and Risk ManagementParish Leadership 2014: Insurance and Risk Management
Parish Leadership 2014: Insurance and Risk Management
 
The 9 Criteria for Brand Essence (TM)
The 9 Criteria for Brand Essence (TM)The 9 Criteria for Brand Essence (TM)
The 9 Criteria for Brand Essence (TM)
 
Tca
TcaTca
Tca
 
Contrato ventas Marelli
Contrato ventas MarelliContrato ventas Marelli
Contrato ventas Marelli
 
07-02-2013 eraikune-boma
07-02-2013 eraikune-boma07-02-2013 eraikune-boma
07-02-2013 eraikune-boma
 
06 salida 23_03_2013
06 salida 23_03_201306 salida 23_03_2013
06 salida 23_03_2013
 
N20
N20N20
N20
 
Rapport: Utprøving av iPad i alternative opplæringarenaer
Rapport: Utprøving av iPad i alternative opplæringarenaerRapport: Utprøving av iPad i alternative opplæringarenaer
Rapport: Utprøving av iPad i alternative opplæringarenaer
 
The JOBS Act Implementation Update
The JOBS Act Implementation UpdateThe JOBS Act Implementation Update
The JOBS Act Implementation Update
 
New Age Cleaning Solutions, Kolkata, Cleaning Machine and Garden Equipment
New Age Cleaning Solutions, Kolkata, Cleaning Machine and Garden EquipmentNew Age Cleaning Solutions, Kolkata, Cleaning Machine and Garden Equipment
New Age Cleaning Solutions, Kolkata, Cleaning Machine and Garden Equipment
 
Gramática del Curso 1 Inglés
Gramática del Curso 1 InglésGramática del Curso 1 Inglés
Gramática del Curso 1 Inglés
 

Similar a Native code in Android applications

Vk.amberfog.com gtug part1_introduction2_javaandroid_gtug
Vk.amberfog.com gtug part1_introduction2_javaandroid_gtugVk.amberfog.com gtug part1_introduction2_javaandroid_gtug
Vk.amberfog.com gtug part1_introduction2_javaandroid_gtug
ketan_patel25
 
Module, AMD, RequireJS
Module, AMD, RequireJSModule, AMD, RequireJS
Module, AMD, RequireJS
偉格 高
 

Similar a Native code in Android applications (20)

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)
 
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
 
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)
 
GOTO Night with Charles Nutter Slides
GOTO Night with Charles Nutter SlidesGOTO Night with Charles Nutter Slides
GOTO Night with Charles Nutter Slides
 
Nodejs Intro Part One
Nodejs Intro Part OneNodejs Intro Part One
Nodejs Intro Part One
 
Visage Android Hands-on Lab (OSCON)
Visage Android Hands-on Lab (OSCON)Visage Android Hands-on Lab (OSCON)
Visage Android Hands-on Lab (OSCON)
 
Js tacktalk team dev js testing performance
Js tacktalk team dev js testing performanceJs tacktalk team dev js testing performance
Js tacktalk team dev js testing performance
 
Introduction to the Android NDK
Introduction to the Android NDKIntroduction to the Android NDK
Introduction to the Android NDK
 
Gradle
GradleGradle
Gradle
 
Java Future S Ritter
Java Future S RitterJava Future S Ritter
Java Future S Ritter
 
Nodejs
NodejsNodejs
Nodejs
 
NodeJS
NodeJSNodeJS
NodeJS
 
introduction to node.js
introduction to node.jsintroduction to node.js
introduction to node.js
 
Android OpenGL ES Game ImageGrabber Final Report
Android OpenGL ES Game ImageGrabber Final ReportAndroid OpenGL ES Game ImageGrabber Final Report
Android OpenGL ES Game ImageGrabber Final Report
 
Nodejs - A-quick-tour-v3
Nodejs - A-quick-tour-v3Nodejs - A-quick-tour-v3
Nodejs - A-quick-tour-v3
 
Vk.amberfog.com gtug part1_introduction2_javaandroid_gtug
Vk.amberfog.com gtug part1_introduction2_javaandroid_gtugVk.amberfog.com gtug part1_introduction2_javaandroid_gtug
Vk.amberfog.com gtug part1_introduction2_javaandroid_gtug
 
Getting Native with NDK
Getting Native with NDKGetting Native with NDK
Getting Native with NDK
 
Nodejs - A quick tour (v6)
Nodejs - A quick tour (v6)Nodejs - A quick tour (v6)
Nodejs - A quick tour (v6)
 
Future of NodeJS
Future of NodeJSFuture of NodeJS
Future of NodeJS
 
Module, AMD, RequireJS
Module, AMD, RequireJSModule, AMD, RequireJS
Module, AMD, RequireJS
 

Último

Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Victor Rentea
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 

Último (20)

Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital Adaptability
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 

Native code in Android applications