Java Native Interface Application Notes

Total Page:16

File Type:pdf, Size:1020Kb

Java Native Interface Application Notes Java Native Interface Application Notes Da Ke 4/5/2009 ECE 480 Spring 2009, Design Team 3 Department of Electrical and Computer Engineering Michigan State University Abstract Java is one of most widely used programming language today due to its openness, ability to scale up and portability. The language is design to have a simpler object model and fewer low-level facilities like pointer methods in C/C++. Sometime this could impose a limitation on what a program can do. This application note will explore various ways of implementation that will allow Java to interact with some programs that are written in lower level language. Keywords: Java, JVM, JNI, Linux, Windows, Operating System, Native interface, Native code Introduction Most modern high level programming languages today are capable of handling what once consider trivial tasks for developers like memory management. However, this doesn't come without cost. A Java application does not interact with underlying system infrastructure directly instead it first compile source code to bytecode and run on Java virtual machine which itself is an application that run on top of the operating system. The Java virtual machine acts like a mediator between the application and the operating system. Most modern implementations of Java Virtual Machine does include several interfaces and libraries that we can utilize to allow Java applications to perform some system level tasks and even speed up the execution of the program by handing over some more resource-intense operations to programs that are runs natively on the machine. Objective This application note will explain different approaches to implement system level functions using Java Programming Language. The goal is for the reader with basic understanding of Java to understand different ways of interacting with operating system in Java and what are the trade-offs. Background The ability to access system resource is essential for programs that are design to be flexible and expandable. In an embedded environment where system resource is both limited and considerably slower than conventional computing environment. It’s extremely important for an application to effectively manage and utilize system resource to both improve the performance and stability. The Java Programming Language is designed to create applications across many different platforms. By utilize different Java libraries to communicate Java application directly with the system and native programs, one will find the run time efficiency of Java application can be greatly optimized. Approaches Java Native Interface (JNI) Java Native Interface is a native programming interface for Java Programming Language. It allows Java code runs inside of a Java Virtual Machine (JVM) to interoperate with applications or libraries that is written in some other lower level programming languages such as C, C++ and assembly. With JNI developers are able to utilize existing libraries written in other languages and incorporate these existing functionalities into their Java application. JNI for C/C++ Program Most modern java compiler provides an interface library jni.h that allows C/C++ program to access and manipulate Java objects. This is all done by C/C++ memory pointers. As shown in Figure 1, the JNI is implemented using direct memory mapping. Therefore, the usage and allocation of memory is effectively managed by the JVM. JNI allows the programmer to pass different Java objects as parameters to C/C++ program and gets the return value from the native program converts it back to the java object. Figure 1: JNI Pointers and Functions Figure 2: Java Native Interface illustration in C/C++ Example Program in C I’ll go through a simple example of how to create a C function and interface with Java application using JNI. There are 5 steps to do this as you can see from Figure 2: 1. Write the Java Code This is a simple Java program with a native method declared – the Do_thing1 method. The program will call Do_thing1 method when it gets executed. 2. Compile the Java Code This step is very simple all you need to do is run your favorite Java compiler. Make sure it supports JNI. The command to do this under GNU/Linux is: javac Example1.java 3. Create the header (.h) File If your Java compiler is equipped with JNI support, you should be able to generate a general C/C++ header file that contains information that JNI needs to identify a C/C++ program. You need to make sure your Java source code was successfully compiled. To generate the JNI header file under GNU/Linux just run: javah –jni Example1 4. Implement the Native Method In this step you will need to either port your original native code into JNI compatible form or start implementing a new one. For our example, I’ll try to keep it simple. In the header file generated by javah in previous step you will find: This is a declaration of the native method with two parameters. The first parameter JNIEnv is a pointer that allows your native code to access parameters passed in from the Java application. The second parameter jobject is a reference to current instance of Java’s class. Now we need to provide an implementation of to this native method. This is a very simple function that just prints out string “This is Example1” using C standard I/O library. When the Java application gets execute, this module will be print out the string. 5. Create a Shared Library In step 1, we loaded the native library named example1, the file name that JVM expected for the shared library will be different depend of operating system. For example, under most Linux/Unix systems the JVM will expect library name libexample1.so for the above example while the Microsoft Windows will expect example1.dll To compile the native application under Linux: gcc -o libexample1.so -shared -Wl,-soname,libexample1.so –I /path/to/your/jdk/lib/include –I /path/to/your/jdk/lib/include/linux Example1.c - static –lc It’s important to set the correct environmental variable so that JVM knows where to find the shared library. To do this under Linux: LD_LIBRARY_PATH=`pwd` export LD_LIBRARY_PATH Where the `pwd` is command that printing out the current working directory. You need to change this accordingly. After the Environmental variable is set you should be able to run you Java application with native method. Alternative Approach: Java Runtime Object Java also provides another simple and easy interface to interact with operating system – the Runtime object. The Runtime object is a special object that associated with current Java application. It’s able to send commands as a string to system command shell. The command shell is different across different operating system therefore most of the commands will not be usable if operating system is changed. Nevertheless, it’s an easy and effective way to execute a native application. Figure 3: Java Runtime Command Execution Illustration As you can see from above figure, using Runtime object is much simpler compare to JNI. There are a lot fewer steps involve. However, the communication between the native process and Java application is somewhat limited - data transfer in between are restricted to String, I/O Exception and Interrupt. To launch an external process, first you need to create a Process object and attach it to the new Process created by Runtime object from the command string that user specify: In order to get output produce by the external process, you will need a BufferedReader object. You can choose to output the string captured from external process: You can also implement the Exception handler in this block of code. If there is an exception occurred while getting the output from the external process that’s usually an indication that the process had failed to launch. Conclusion A Java application with system-specific implementation usually scarifies the portability of the application in exchange for the efficiency of the program. However, there are different ways to go around that. For example, you can provide different implementations of native code for various platforms and let Java Virtual Machine decide which implementation to use. This way we will have a relative more efficient application, and still able take advantage of many great features provides by Java. References: JNI Design (Sun Microsystem): http://java.sun.com/j2se/1.5.0/docs/guide/jni/spec/design.html Java Runtime Object Reference (Sun Microsystem): http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Runtime.html JNI in Wikipedia: http://en.wikipedia.org/wiki/Java_Native_Interface .
Recommended publications
  • Jeannie: Granting Java Native Interface Developers Their Wishes
    Jeannie: Granting Java Native Interface Developers Their Wishes Martin Hirzel Robert Grimm IBM Watson Research Center New York University [email protected] [email protected] Abstract higher-level languages and vice versa. For example, a Java Higher-level languages interface with lower-level languages project can reuse a high-performance C library for binary such as C to access platform functionality, reuse legacy li- decision diagrams (BDDs) through the Java Native Inter- braries, or improve performance. This raises the issue of face [38] (JNI), which is the standard FFI for Java. how to best integrate different languages while also recon- FFI designs aim for productivity, safety, portability, and ciling productivity, safety, portability, and efficiency. This efficiency. Unfortunately, these goals are often at odds. For paper presents Jeannie, a new language design for integrat- instance, Sun’s original FFI for Java, the Native Method In- ing Java with C. In Jeannie, both Java and C code are nested terface [52, 53] (NMI), directly exposed Java objects as C within each other in the same file and compile down to JNI, structs and thus provided simple and fast access to object the Java platform’s standard foreign function interface. By fields. However, this is unsafe, since C code can violate Java combining the two languages’ syntax and semantics, Jean- types, notably by storing an object of incompatible type in a nie eliminates verbose boiler-plate code, enables static error field. Furthermore, it constrains garbage collectors and just- detection across the language boundary, and simplifies dy- in-time compilers, since changes to the data representation namic resource management.
    [Show full text]
  • Binary and Hexadecimal
    Binary and Hexadecimal Binary and Hexadecimal Introduction This document introduces the binary (base two) and hexadecimal (base sixteen) number systems as a foundation for systems programming tasks and debugging. In this document, if the base of a number might be ambiguous, we use a base subscript to indicate the base of the value. For example: 45310 is a base ten (decimal) value 11012 is a base two (binary) value 821716 is a base sixteen (hexadecimal) value Why do we need binary? The binary number system (also called the base two number system) is the native language of digital computers. No matter how elegantly or naturally we might interact with today’s computers, phones, and other smart devices, all instructions and data are ultimately stored and manipulated in the computer as binary digits (also called bits, where a bit is either a 0 or a 1). CPUs (central processing units) and storage devices can only deal with information in this form. In a computer system, absolutely everything is represented as binary values, whether it’s a program you’re running, an image you’re viewing, a video you’re watching, or a document you’re writing. Everything, including text and images, is represented in binary. In the “old days,” before computer programming languages were available, programmers had to use sequences of binary digits to communicate directly with the computer. Today’s high level languages attempt to shield us from having to deal with binary at all. However, there are a few reasons why it’s important for programmers to understand the binary number system: 1.
    [Show full text]
  • JNI – C++ Integration Made Easy
    JNI – C++ integration made easy Evgeniy Gabrilovich Lev Finkelstein [email protected] [email protected] Abstract The Java Native Interface (JNI) [1] provides interoperation between Java code running on a Java Virtual Machine and code written in other programming languages (e.g., C++ or assembly). The JNI is useful when existing libraries need to be integrated into Java code, or when portions of the code are implemented in other languages for improved performance. The Java Native Interface is extremely flexible, allowing Java methods to invoke native methods and vice versa, as well as allowing native functions to manipulate Java objects. However, this flexibility comes at the expense of extra effort for the native language programmer, who has to explicitly specify how to connect to various Java objects (and later to disconnect from them, to avoid resource leak). We suggest a template-based framework that relieves the C++ programmer from most of this burden. In particular, the proposed technique provides automatic selection of the right functions to access Java objects based on their types, automatic release of previously acquired resources when they are no longer necessary, and overall simpler interface through grouping of auxiliary functions. Introduction The Java Native Interface1 is a powerful framework for seamless integration between Java and other programming languages (called “native languages” in the JNI terminology). A common case of using the JNI is when a system architect wants to benefit from both worlds, implementing communication protocols in Java and computationally expensive algorithmic parts in C++ (the latter are usually compiled into a dynamic library, which is then invoked from the Java code).
    [Show full text]
  • T U M a Digital Wallet Implementation for Anonymous Cash
    Technische Universität München Department of Informatics Bachelor’s Thesis in Information Systems A Digital Wallet Implementation for Anonymous Cash Oliver R. Broome Technische Universität München Department of Informatics Bachelor’s Thesis in Information Systems A Digital Wallet Implementation for Anonymous Cash Implementierung eines digitalen Wallets for anonyme Währungen Author Oliver R. Broome Supervisor Prof. Dr.-Ing. Georg Carle Advisor Sree Harsha Totakura, M. Sc. Date October 15, 2015 Informatik VIII Chair for Network Architectures and Services I conrm that this thesis is my own work and I have documented all sources and material used. Garching b. München, October 15, 2015 Signature Abstract GNU Taler is a novel approach to digital payments with which payments are performed with cryptographically generated representations of actual currencies. The main goal of GNU Taler is to allow taxable anonymous payments to non-anonymous merchants. This thesis documents the implementation of the Android version of the GNU Taler wallet, which allows users to create new Taler-based funds and perform payments with them. Zusammenfassung GNU Taler ist ein neuartiger Ansatz für digitales Bezahlen, bei dem Zahlungen mit kryptographischen Repräsentationen von echten Währungen getätigt werden. Das Hauptziel von GNU Taler ist es, versteuerbare, anonyme Zahlungen an nicht-anonyme Händler zu ermöglichen. Diese Arbeit dokumentiert die Implementation der Android-Version des Taler-Portemonnaies, der es Benutzern erlaubt, neues Taler-Guthaben zu erzeugen und mit ihnen Zahlungen zu tätigen. I Contents 1 Introduction 1 1.1 GNU Taler . .2 1.2 Goals of the thesis . .2 1.3 Outline . .3 2 Implementation prerequisites 5 2.1 Native libraries . .5 2.1.1 Libgcrypt .
    [Show full text]
  • Exposing Native Device Apis to Web Apps
    Exposing Native Device APIs to Web Apps Arno Puder Nikolai Tillmann Michał Moskal San Francisco State University Microsoft Research Microsoft Research Computer Science One Microsoft Way One Microsoft Way Department Redmond, WA 98052 Redmond, WA 98052 1600 Holloway Avenue [email protected] [email protected] San Francisco, CA 94132 [email protected] ABSTRACT language of the respective platform, HTML5 technologies A recent survey among developers revealed that half plan to gain traction for the development of mobile apps [12, 4]. use HTML5 for mobile apps in the future. An earlier survey A recent survey among developers revealed that more than showed that access to native device APIs is the biggest short- half (52%) are using HTML5 technologies for developing mo- coming of HTML5 compared to native apps. Several dif- bile apps [22]. HTML5 technologies enable the reuse of the ferent approaches exist to overcome this limitation, among presentation layer and high-level logic across multiple plat- them cross-compilation and packaging the HTML5 as a na- forms. However, an earlier survey [21] on cross-platform tive app. In this paper we propose a novel approach by using developer tools revealed that access to native device APIs a device-local service that runs on the smartphone and that is the biggest shortcoming of HTML5 compared to native acts as a gateway to the native layer for HTML5-based apps apps. Several different approaches exist to overcome this running inside the standard browser. WebSockets are used limitation. Besides the development of native apps for spe- for bi-directional communication between the web apps and cific platforms, popular approaches include cross-platform the device-local service.
    [Show full text]
  • Nacldroid: Native Code Isolation for Android Applications
    NaClDroid: Native Code Isolation for Android Applications Elias Athanasopoulos1, Vasileios P. Kemerlis2, Georgios Portokalidis3, and Angelos D. Keromytis4 1 Vrije Universiteit Amsterdam, The Netherlands [email protected] 2 Brown University, Providence, RI, USA [email protected] 3 Stevens Institute of Technology, Hoboken, NJ, USA [email protected] 4 Columbia University, New York, NY, USA [email protected] Abstract. Android apps frequently incorporate third-party libraries that contain native code; this not only facilitates rapid application develop- ment and distribution, but also provides new ways to generate revenue. As a matter of fact, one in two apps in Google Play are linked with a library providing ad network services. However, linking applications with third-party code can have severe security implications: malicious libraries written in native code can exfiltrate sensitive information from a running app, or completely modify the execution runtime, since all native code is mapped inside the same address space with the execution environment, namely the Dalvik/ART VM. We propose NaClDroid, a framework that addresses these problems, while still allowing apps to include third-party code. NaClDroid prevents malicious native-code libraries from hijacking Android applications using Software Fault Isolation. More specifically, we place all native code in a Native Client sandbox that prevents uncon- strained reads, or writes, inside the process address space. NaClDroid has little overhead; for native code running inside the NaCl sandbox the slowdown is less than 10% on average. Keywords: SFI, NaCl, Android 1 Introduction Android is undoubtedly the most rapidly growing platform for mobile devices, with estimates predicting one billion Android-based smartphones shipping in 2017 [12].
    [Show full text]
  • Developing and Benchmarking Native Linux Applications on Android
    Developing and Benchmarking Native Linux Applications on Android Leonid Batyuk, Aubrey-Derrick Schmidt, Hans-Gunther Schmidt, Ahmet Camtepe, and Sahin Albayrak Technische Universit¨at Berlin, 10587 Berlin, Germany {aubrey.schmidt,leonid.batyuk,hans-gunther.schmidt,ahmet.camtepe, sahin.albayrak}@dai-labor.de http://www.dai-labor.de Abstract. Smartphones get increasingly popular where more and more smartphone platforms emerge. Special attention was gained by the open source platform Android which was presented by the Open Handset Al- liance (OHA) hosting members like Google, Motorola, and HTC. An- droid uses a Linux kernel and a stripped-down userland with a custom Java VM set on top. The resulting system joins the advantages of both environments, while third-parties are intended to develop only Java ap- plications at the moment. In this work, we present the benefit of using native applications in Android. Android includes a fully functional Linux, and using it for heavy computational tasks when developing applications can bring in substantional performance increase. We present how to develop native applications and software components, as well as how to let Linux appli- cations and components communicate with Java programs. Additionally, we present performance measurements of native and Java applications executing identical tasks. The results show that native C applications can be up to 30 times as fast as an identical algorithm running in Dalvik VM. Java applications can become a speed-up of up to 10 times if utilizing JNI. Keywords: software, performance, smartphones, android, C, Java. 1 Introduction With the growing customer interest in smartphones the number of available platforms increases steadily.
    [Show full text]
  • Cloud Native Trail Map 2
    1. CONTAINERIZATION • Commonly done with Docker containers • Any size application and dependencies (even PDP-11 code running on an emulator) can be containerized • Over time, you should aspire towards splitting suitable applications and writing future functionality as microservices CLOUD NATIVE TRAIL MAP 2. CI/CD • Setup Continuous Integration/Continuous Delivery (CI/CD) so The Cloud Native Landscape l.cncf.io that changes to your source code automatically result in a new has a large number of options. This Cloud container being built, tested, and deployed to staging and Native Trail Map is a recommended process eventually, perhaps, to production for leveraging open source, cloud native • Setup automated rollouts, roll backs and testing technologies. At each step, you can choose • Argo is a set of Kubernetes-native tools for a vendor-supported offering or do it yourself, deploying and running jobs, applications, and everything after step #3 is optional workflows, and events using GitOps based on your circumstances. 3. ORCHESTRATION & paradigms such as continuous and progressive delivery and MLops CNCF Incubating APPLICATION DEFINITION HELP ALONG THE WAY • Kubernetes is the market-leading orchestration solution • You should select a Certified Kubernetes Distribution, 4. OBSERVABILITY & ANALYSIS Hosted Platform, or Installer: cncf.io/ck A. Training and Certification • Helm Charts help you define, install, and upgrade • Pick solutions for monitoring, logging and tracing Consider training offerings from CNCF even the most complex Kubernetes application • Consider CNCF projects Prometheus for monitoring, and then take the exam to become a Fluentd for logging and Jaeger for Tracing Certified Kubernetes Administrator or a • For tracing, look for an OpenTracing-compatible Certified Kubernetes Application Developer implementation like Jaeger cncf.io/training CNCF Graduated CNCF Graduated B.
    [Show full text]
  • Rockbox User Manual
    The Rockbox Manual for Ipod Classic rockbox.org December 27, 2020 2 Rockbox https://www.rockbox.org/ Open Source Jukebox Firmware Rockbox and this manual is the collaborative effort of the Rockbox team and its contributors. See the appendix for a complete list of contributors. c 2003–2020 The Rockbox Team and its contributors, c 2004 Christi Alice Scarborough, c 2003 José Maria Garcia-Valdecasas Bernal & Peter Schlenker. Version 3.15p10. Built using pdfLATEX. Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.2 or any later version published by the Free Software Foundation; with no Invariant Sec- tions, no Front-Cover Texts, and no Back-Cover Texts. A copy of the license is included in the section entitled “GNU Free Documentation License”. The Rockbox manual (version 3.15p10) Ipod Classic Contents 3 Contents 1. Introduction 12 1.1. Welcome..................................... 12 1.2. Getting more help............................... 12 1.3. Naming conventions and marks........................ 13 2. Installation 14 2.1. Before Starting................................. 14 2.2. Installing Rockbox............................... 15 2.2.1. Automated Installation........................ 15 2.2.2. Manual Installation.......................... 17 2.2.3. Finishing the install.......................... 19 2.2.4. Enabling Speech Support (optional)................. 19 2.3. Running Rockbox................................ 19 2.4. Updating Rockbox............................... 19 2.5. Uninstalling Rockbox............................. 20 2.5.1. Automatic Uninstallation....................... 20 2.5.2. Manual Uninstallation......................... 20 2.6. Troubleshooting................................. 20 3. Quick Start 21 3.1. Basic Overview................................. 21 3.1.1. The player’s controls.......................... 21 3.1.2. Turning the player on and off....................
    [Show full text]
  • Defeating Kernel Native API Hookers by Direct Kiservicetable Restoration
    Defeating Kernel Native API Hookers by Direct KiServiceTable Restoration Tan Chew Keong Vice-President SIG2 www.security.org.sg IT Security... the Gathering. By enthusiasts for enthusiasts! Outline • User-space API calls and Native APIs • Redirecting the execution path of Native APIs • Locating and restoring the KiServiceTable • Defeating Native API hooking rootkits and security tools. IT Security... the Gathering. By enthusiasts for enthusiasts! User-space API calls • User-space Win32 applications requests for system services by calling APIs exported by various DLLs. • For example, to write to an open file, pipe or device, the WriteFile API, exported by kernel32.dll is used. IT Security... the Gathering. By enthusiasts for enthusiasts! User-space API calls • WriteFile API will in turn call the native API NtWriteFile/ZwWriteFile that is exported by ntdll.dll • In ntdll.dll, both NtWriteFile and ZwWriteFile points to the same code. • Actual work is actually performed in kernel- space, hence NtWriteFile/ZwWritefile in ntdll.dll contains only minimal code to transit into kernel code using software interrupt INT 0x2E IT Security... the Gathering. By enthusiasts for enthusiasts! User-space API calls • In Win2k, NtWriteFile/ZwWriteFile in ntdll.dll disassembles to MOV EAX, 0EDh LEA EDX, DWORD PTR SS:[ESP+4] INT 2E RETN 24 • 0xED is the system service number that will be used to index into the KiServiceTable to locate the kernel function that handles the call. IT Security... the Gathering. By enthusiasts for enthusiasts! User-space API calls Application WriteFile() kernel32.dll Nt/ZwWriteFile() mov eax, system service num ntdll.dll lea edx, pointer to parameters int 0x2E ntoskrnl.exe NtWriteFile() IT Security..
    [Show full text]
  • X86 Assembly Language Reference Manual
    x86 Assembly Language Reference Manual Part No: 817–5477–11 March 2010 Copyright ©2010 Oracle and/or its affiliates. All rights reserved. This software and related documentation are provided under a license agreement containing restrictions on use and disclosure and are protected by intellectual property laws. Except as expressly permitted in your license agreement or allowed by law, you may not use, copy, reproduce, translate, broadcast, modify, license, transmit, distribute, exhibit, perform, publish, or display any part, in any form, or by any means. Reverse engineering, disassembly, or decompilation of this software, unless required by law for interoperability, is prohibited. The information contained herein is subject to change without notice and is not warranted to be error-free. If you find any errors, please report them to us in writing. If this is software or related software documentation that is delivered to the U.S. Government or anyone licensing it on behalf of the U.S. Government, the following notice is applicable: U.S. GOVERNMENT RIGHTS Programs, software, databases, and related documentation and technical data delivered to U.S. Government customers are “commercial computer software” or “commercial technical data” pursuant to the applicable Federal Acquisition Regulation and agency-specific supplemental regulations. As such, the use, duplication, disclosure, modification, and adaptation shall be subject to the restrictions and license terms setforth in the applicable Government contract, and, to the extent applicable by the terms of the Government contract, the additional rights set forth in FAR 52.227-19, Commercial Computer Software License (December 2007). Oracle USA, Inc., 500 Oracle Parkway, Redwood City, CA 94065.
    [Show full text]
  • Design of the RISC-V Instruction Set Architecture
    Design of the RISC-V Instruction Set Architecture Andrew Waterman Electrical Engineering and Computer Sciences University of California at Berkeley Technical Report No. UCB/EECS-2016-1 http://www.eecs.berkeley.edu/Pubs/TechRpts/2016/EECS-2016-1.html January 3, 2016 Copyright © 2016, by the author(s). All rights reserved. Permission to make digital or hard copies of all or part of this work for personal or classroom use is granted without fee provided that copies are not made or distributed for profit or commercial advantage and that copies bear this notice and the full citation on the first page. To copy otherwise, to republish, to post on servers or to redistribute to lists, requires prior specific permission. Design of the RISC-V Instruction Set Architecture by Andrew Shell Waterman A dissertation submitted in partial satisfaction of the requirements for the degree of Doctor of Philosophy in Computer Science in the Graduate Division of the University of California, Berkeley Committee in charge: Professor David Patterson, Chair Professor Krste Asanovi´c Associate Professor Per-Olof Persson Spring 2016 Design of the RISC-V Instruction Set Architecture Copyright 2016 by Andrew Shell Waterman 1 Abstract Design of the RISC-V Instruction Set Architecture by Andrew Shell Waterman Doctor of Philosophy in Computer Science University of California, Berkeley Professor David Patterson, Chair The hardware-software interface, embodied in the instruction set architecture (ISA), is arguably the most important interface in a computer system. Yet, in contrast to nearly all other interfaces in a modern computer system, all commercially popular ISAs are proprietary.
    [Show full text]