More Specifically JNI Justin Catterson.  ADA  C++  Java  Ruby  Python  Haskell  Perl  etc. What is a Foreign Function Interface? Simply an interface.

Slides:



Advertisements
Similar presentations
What is a Computer Program? For a computer to be able to do anything (multiply, play a song, run a word processor), it must be given the instructions.
Advertisements

Connecting to Databases. relational databases tables and relations accessed using SQL database -specific functionality –transaction processing commit.
Introduction to .NET Framework
Tahir Nawaz Introduction to.NET Framework. .NET – What Is It? Software platform Language neutral In other words:.NET is not a language (Runtime and a.
COM vs. CORBA.
The Interface Definition Language for Fail-Safe C Kohei Suenaga, Yutaka Oiwa, Eijiro Sumii, Akinori Yonezawa University of Tokyko.
Introduction To Java Objectives For Today â Introduction To Java â The Java Platform & The (JVM) Java Virtual Machine â Core Java (API) Application Programming.
Inlining Java Native Calls at Runtime (CASCON 2005 – 4 th Workshop on Compiler Driven Performance) Levon Stepanian, Angela Demke Brown Computer Systems.
This work is licensed under the Creative Commons Attribution 4.0 International License. To view a copy of this license, visit
The road to reliable, autonomous distributed systems
Java Native Interface Modified from CS587x Lecture Department of Computer Science Iowa State University.
George Blank University Lecturer. CS 602 Java and the Web Object Oriented Software Development Using Java Chapter 4.
1 Tuesday, November 07, 2006 “If anything can go wrong, it will.” -Murphy’s Law.
JETT 2003 Java.compareTo(C++). JAVA Java Platform consists of 4 parts: –Java Language –Java API –Java class format –Java Virtual Machine.
Administrivia No class next Monday (May 2) Enjoy extra time on P3. ;-) Reading 3 available “Reflections on Trusting Trust”, Ken Thompson No written summary.
Java Native Interface (JNI). JNI Linking Java and C code.
Asst.Prof.Dr.Ahmet Ünveren SPRING Computer Engineering Department Asst.Prof.Dr.Ahmet Ünveren SPRING Computer Engineering Department.
Session-02. Objective In this session you will learn : What is Class Loader ? What is Byte Code Verifier? JIT & JAVA API Features of Java Java Environment.
Lecture 1: Overview of Java. What is java? Developed by Sun Microsystems (James Gosling) A general-purpose object-oriented language Based on C/C++ Designed.
File System. NET+OS 6 File System Architecture Design Goals File System Layer Design Storage Services Layer Design RAM Services Layer Design Flash Services.
Introduction to Java Programming. Contents 1. Java, etc. 2. Java's Advantages 3. Java's Disadvantages 4. Types of Java Code 5. Java Bytecodes 6. Steps.
Embedded Java Research Geoffrey Beers Peter Jantz December 18, 2001.
JAVA v.s. C++ Programming Language Comparison By LI LU SAMMY CHU By LI LU SAMMY CHU.
Principles of Computer Programming (using Java) Review Haidong Xue Summer 2011, at GSU.
CSC 142 A 1 CSC 142 Introduction to Java [Reading: chapter 0]
Introduction to Java CSIS 3701: Advanced Object Oriented Programming.
Java Native Interface CS587x Lecture Department of Computer Science Iowa State University.
Programming Fundamentals 2: Background/ F II Objectives – –give a non-technical overview of Java Semester 2, Background.
What is Android NDK ● A toolset that lets you embed in you app native source code ● C, C++(recently supported December 2010) and assembly(?) ● It is supported.
COM vs. CORBA Computer Science at Azusa Pacific University September 19, 2015 Azusa Pacific University, Azusa, CA 91702, Tel: (800) Department.
Java Virtual Machine Java Virtual Machine A Java Virtual Machine (JVM) is a set of computer software programs and data structures that use.
Types for Programs and Proofs Lecture 1. What are types? int, float, char, …, arrays types of procedures, functions, references, records, objects,...
Java Introduction Lecture 1. Java Powerful, object-oriented language Free SDK and many resources at
Introduction to Java CSIS 3701: Advanced Object Oriented Programming.
1 Module Objective & Outline Module Objective: After completing this Module, you will be able to, appreciate java as a programming language, write java.
Rutgers University Excellence Campaign 2/20/2004 Java Native Interface Tutorial Xiaolin Li Rutgers.
Java Introduction to JNI Prepared by Humaira Siddiqui.
By Noorez Kassam Welcome to JNI. Why use JNI ? 1. You already have significantly large and tricky code written in another language and you would rather.
Algorithm Programming Bar-Ilan University תשס"ח by Moshe Fresko.
BLU-ICE and the Distributed Control System Constraints for Software Development Strategies Timothy M. McPhillips Stanford Synchrotron Radiation Laboratory.
Introduction and Features of Java. What is java? Developed by Sun Microsystems (James Gosling) A general-purpose object-oriented language Based on C/C++
Netprog: Java Intro1 Crash Course in Java. Netprog: Java Intro2 Why Java? Network Programming in Java is very different than in C/C++ –much more language.
1 Compiler Construction (CS-636) Muhammad Bilal Bashir UIIT, Rawalpindi.
1 Introduction to Java. 2 What is Java? A programming language. A platform –A virtual machine (JVM) definition. –Runtime environments in diverse hardware.
© Janice Regan, CMPT 300, May CMPT 300 Introduction to Operating Systems Memory: Relocation.
Android JNI and JAR Library JNI Library 1. JNI *.c sources file must include jni header file jni.h #include 2. In Make file CFLAGS must add -I $(NDK_INC)/
We will talking about story of JAVA language. By Kristsada Songpartom.
Buffer Overflow Proofing of Code Binaries By Ramya Reguramalingam Graduate Student, Computer Science Advisor: Dr. Gopal Gupta.
Core Java Introduction Byju Veedu Ness Technologies httpdownload.oracle.com/javase/tutorial/getStarted/intro/definition.html.
PRIOR TO WEB SERVICES THE OTHER TECHNOLOGIES ARE:.
Java Basics Opening Discussion zWhat did we talk about last class? zWhat are the basic constructs in the programming languages you are familiar.
Slide Advanced Programming 2004, based on LY Stefanus's slides Native Methods.
Computer Organization and Design Pointers, Arrays and Strings in C Montek Singh Sep 18, 2015 Lab 5 supplement.
How to execute Program structure Variables name, keywords, binding, scope, lifetime Data types – type system – primitives, strings, arrays, hashes – pointers/references.
Efficient Software-Based Fault Isolation Authors: Robert Wahbe Steven Lucco Thomas E. Anderson Susan L. Graham Presenter: Gregory Netland.
Spring 2006 Special Topics in Computer Engineering: Java Intro 1 Crash Course in Java Based on notes from D. Hollinger Based in part on notes from J.J.
Java and C# - Some Commonalities Compile into machine-independent, language- independent code which runs in a managed execution environment Garbage Collection.
SESSION 1 Introduction in Java. Objectives Introduce classes and objects Starting with Java Introduce JDK Writing a simple Java program Using comments.
Sung-Dong Kim, Dept. of Computer Engineering, Hansung University Java - Introduction.
File-System Management
Object Oriented Programming in
Efficient Software-Based Fault Isolation
Types for Programs and Proofs
Day 12 Threads.
Introduction Enosis Learning.
CMPE419 Mobile Application Development
Introduction Enosis Learning.
Units with – James tedder
Units with – James tedder
CMPE419 Mobile Application Development
Presentation transcript:

More Specifically JNI Justin Catterson

 ADA  C++  Java  Ruby  Python  Haskell  Perl  etc. What is a Foreign Function Interface? Simply an interface which allows languages to interact with one another

 Reuse of Legacy Code  Add libraries to language (Object Oriented)  Performance

Released in 1997 Used to call native methods Used to embed a Java Virtual Machine into native applications Suns JDK contains over 600,00 lines of native C code

 Software Security  Loss of Portability  Mapping is not easy  Only supports C/C++ can do Ada, Fortran, COBOL but it is more difficult  Strong knowledge in both Java and C  Overhead?

When to use  Java API doesn’t support certain features required by application  Want to access an existing library  Implement time-critical sections in a low level language  Multiple processes are taking up too much memory When NOT to use  When you could communicate with native language through TCP/IP connection  Could connect to database using JDBC  Distributed object technology such as Java IDL API

 Binary Compatibility  Little overhead  Native methods full use of JVM  Not the only FFI available for Java

 Make control flow as simplistic as possible  Keep native code minimal (Error checking)  Isolate native code (“Porting layer”)

1. Add to the system variable path the location of your JDK bin (ie. C:\Program Files (x86)\Java\jdk1.6.0_20\bin) 2. Write java class with at least one method declared native (ie. Public native void hello() ) 3. Add call to System.loadLibrary (ie. Static { System.loadLibrary(“hello”);} 4. Compile java code using javac

5. Create header file for the c using javah 6. Write native method for hello 7. with microsoft visual studio, execute the vcvarsall.bat in the vc directory of visual studio 8. Compile native file into a dll (using cl -Iinclude - Iinclude\win32 -MD -LD hello.cpp - Fejnihello.dll) –l is where the include and include\win32 directories are from the jdk 9. Run the java program

jni

1. JNIEnv pointer contains the location of the function table 2. If method is (java static), the method belongs to the java class that contains the native function

public class C { public static native int atol(String str); } JNIExport jint JNICALL Java_C_atol(JNIEnv *env, jclass cls, jstring str) { const char *cstr = env->GetStringUTFChars(str, 0); if (cstr == NULL) { return 0; // out of memory } int result = atol(cstr); env->ReleaseStringUTFChars(str, cstr); return result; }

1. Write the Java code 2. Compile java 3. Write C++ 4. Compile C++ 5. run the exe (Ensure you have the JVM dll directory in the system variable path)

cToJava

 s/guide/jni/spec/functions.html s/guide/jni/spec/functions.html

 Typically accepted C and C++ is faster than Java  Is it expensive to make the call through JNI?

Run benchmark tests to measure execution time between two algorithms in Java and C++ 1. HeapSort ( Memory ) 2. Discrete Fast Fourier Transform ( Heavy Math)

 Check java’s performance for mathematical computations  If you are interested in learning more  rSystems/fft.pdf rSystems/fft.pdf

 Array sizes of 250, 1000, and To check the impact of array sizes on Java and JNI  Vary number of iterations to check start-up cost

Not expensive enough to not use Still has cost associated pending the JIT ns per call + 25 to 30ns for each argument (Dawid Kurzyniec and Vaidy Sunderam)

 JVM memory and native memory space transfer (hash map store recently accessed fieldids and methods)  Arrays primary concern ( Try to avoid passing them)  Pending VM may make copy

1. Primitive 2. Reference

Java Language TypeNative TypeDescription booleanjbooleanUnsigned 8 bits bytejbyteSigned 8 bits CharjcharUnsigned 16 bits shortjshortSigned 16bits intjintSigned 32 bits longjlongSigned 64 bits floatjfloat32 bits doublejdouble64 bits

All JNI objects inherit from jObject Treated as pointers

1. Local 2. Global 3. Weak

 Content that is created from a native method will only exist during the execution of the native method. Memory corruptions Or system crashes Attempted to use invalid Local address  jstring  MyNewString(JNIEnv *env, jchar *chars, jint len)  {  static jclass stringClass = NULL;  jmethodID cid;  jcharArray elemArr;  jstring result;  if (stringClass == NULL) {  stringClass = (*env)->FindClass(env,  "java/lang/String");  if (stringClass == NULL) {  return NULL; /* exception thrown */  }}  /* It is wrong to use the cached stringClass here,  because it may be invalid. */  cid = (*env)->GetMethodID(env, stringClass,  " ", "([C)V"); ...  elemArr = (*env)->NewCharArray(env, len); ...  result = (*env)->NewObject(env, stringClass, cid, elemArr);  (*env)->DeleteLocalRef(env, elemArr);  return result;  }

 Exists until the programmer deletes the object  No GC jstring MyNewString(JNIEnv *env, jchar *chars, jint len) { static jclass stringClass = NULL;... if (stringClass == NULL) { jclass localRefCls = (*env)->FindClass(env, "java/lang/String"); if (localRefCls == NULL) { return NULL; /* exception thrown */ } /* Create a global reference */ stringClass = (*env)->NewGlobalRef(env, localRefCls); /* The local reference is no longer useful */ (*env)->DeleteLocalRef(env, localRefCls); /* Is the global reference created successfully? */ if (stringClass == NULL) { return NULL; /* out of memory exception thrown */ }... } NewGlobalRe f

 Similar to Global references  Valid across native methods and threads  Don’t care if object gets GC JNIEXPORT void JNICALL Java_mypkg_MyCls_f(JNIEnv *env, jobject self) { static jclass myCls2 = NULL; if (myCls2 == NULL) { jclass myCls2Local = (*env)->FindClass(env, "mypkg/MyCls2"); if (myCls2Local == NULL) { return; /* can’t find class */ } myCls2 = NewWeakGlobalRef(env, myCls2Local); if (myCls2 == NULL) { return; /* out of memory */ }... /* use myCls2 */ }

 JNIenv pointer cannot cache must pass pointer associated with the specific thread  Local references valid only for thread that created it, pass global references  Synchronization use MoniterEnter/MoniterExit

 Safety Guarantees  Safe Language + Unsafe Language = unsafe  C code is unsafe, you may read/write to any memory address  C code can pass objects of wrong type back to Java and therefore violate Java's type checks  Memory Mangement ( calls to release)

 Private? Constants?  From references, C can see private data and change the values of constants  Interface pointers, this is how C can use Java’s functions. C can overwrite the entries in the function table.  Array Index out of bounds, accidently read/write directly to Java’s heap

 Safe interoperation (Remote Prodecure Calls)  Ccured (pointer arithmetic solutions)  SafeJNI (wrap JNI api calls)  Jeannie

 Place components in different address space  Significant overhead

 Internal safety for C code  Separates pointers by usage  Helps remove array index out of bounds errors

 Real-Time Embedded  Use Java for upper levels (UI, threading, networking)  Have C++/C interface with hardware and signaling, support already exists

C  Hardware sensors  Platform operations  3D libraries Android (JavaME) -- Linux

 Use JNI to expand language libraries/ use legacy programs  JNI useful for embedded systems  Java can be easily abused using JNI  Keep native methods in the same “package”

 1] Sheng Liang (June 1999). The Java Native Interface Programmer’s Guide and Specification. Retrieved from  [2] Gang Tan; Andrew W. Appel; Srimat Chakradhar; Anand Raghunathan; Srivaths Ravi; Daniel Wang (2006). Safe Java Native Interface. Retrieved from  [3] Scott Stricker(March 2002). Java Programming with JNI.  Retrieved from  [4] Dawid Kurzyniec; Vaidy Sunderam. Efficient Cooperation between Java and Native  Codes - JNI Performance Benchmark.  Retrieved from  [5] Demetrius L. Davis. To JNI or not to JNI?  Retrieved from   [6] Preetham Chandrian (August 2011). Efficient Java Native Interface for Android based Mobile Devices.  Retrieved from