From 045ba37a2773f31d532c8cd82ec5f4d783d42098 Mon Sep 17 00:00:00 2001 From: Andrei Pangin Date: Sat, 15 Oct 2022 20:23:19 +0100 Subject: [PATCH] Published under GPLv2 per JVMCI license requirements --- .gitignore | 3 + LICENSE | 339 ++++++++++++++++++ MANIFEST.MF | 1 + README.md | 182 ++++++++++ build.sh | 11 + example/one/nalim/bench/JniBench.java | 59 +++ example/one/nalim/bench/jnibench.c | 36 ++ example/one/nalim/example/Cpu.java | 18 + example/one/nalim/example/LibSSL.java | 17 + example/one/nalim/example/Libc.java | 17 + example/one/nalim/example/Mem.java | 17 + example/one/nalim/example/Time.java | 20 ++ src/one/nalim/AArch64CallingConvention.java | 73 ++++ .../nalim/AMD64LinuxCallingConvention.java | 93 +++++ .../nalim/AMD64WindowsCallingConvention.java | 79 ++++ src/one/nalim/Agent.java | 61 ++++ src/one/nalim/CallingConvention.java | 61 ++++ src/one/nalim/Code.java | 37 ++ src/one/nalim/JavaInternals.java | 99 +++++ src/one/nalim/Library.java | 33 ++ src/one/nalim/Link.java | 44 +++ src/one/nalim/Linker.java | 161 +++++++++ 22 files changed, 1461 insertions(+) create mode 100644 .gitignore create mode 100644 LICENSE create mode 100644 MANIFEST.MF create mode 100644 README.md create mode 100644 build.sh create mode 100644 example/one/nalim/bench/JniBench.java create mode 100644 example/one/nalim/bench/jnibench.c create mode 100644 example/one/nalim/example/Cpu.java create mode 100644 example/one/nalim/example/LibSSL.java create mode 100644 example/one/nalim/example/Libc.java create mode 100644 example/one/nalim/example/Mem.java create mode 100644 example/one/nalim/example/Time.java create mode 100644 src/one/nalim/AArch64CallingConvention.java create mode 100644 src/one/nalim/AMD64LinuxCallingConvention.java create mode 100644 src/one/nalim/AMD64WindowsCallingConvention.java create mode 100644 src/one/nalim/Agent.java create mode 100644 src/one/nalim/CallingConvention.java create mode 100644 src/one/nalim/Code.java create mode 100644 src/one/nalim/JavaInternals.java create mode 100644 src/one/nalim/Library.java create mode 100644 src/one/nalim/Link.java create mode 100644 src/one/nalim/Linker.java diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..18b830b --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +/out/ +/.idea/ +*.iml diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..d159169 --- /dev/null +++ b/LICENSE @@ -0,0 +1,339 @@ + GNU GENERAL PUBLIC LICENSE + Version 2, June 1991 + + Copyright (C) 1989, 1991 Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +License is intended to guarantee your freedom to share and change free +software--to make sure the software is free for all its users. This +General Public License applies to most of the Free Software +Foundation's software and to any other program whose authors commit to +using it. (Some other Free Software Foundation software is covered by +the GNU Lesser General Public License instead.) You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +this service if you wish), that you receive source code or can get it +if you want it, that you can change the software or use pieces of it +in new free programs; and that you know you can do these things. + + To protect your rights, we need to make restrictions that forbid +anyone to deny you these rights or to ask you to surrender the rights. +These restrictions translate to certain responsibilities for you if you +distribute copies of the software, or if you modify it. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must give the recipients all the rights that +you have. You must make sure that they, too, receive or can get the +source code. And you must show them these terms so they know their +rights. + + We protect your rights with two steps: (1) copyright the software, and +(2) offer you this license which gives you legal permission to copy, +distribute and/or modify the software. + + Also, for each author's protection and ours, we want to make certain +that everyone understands that there is no warranty for this free +software. If the software is modified by someone else and passed on, we +want its recipients to know that what they have is not the original, so +that any problems introduced by others will not reflect on the original +authors' reputations. + + Finally, any free program is threatened constantly by software +patents. We wish to avoid the danger that redistributors of a free +program will individually obtain patent licenses, in effect making the +program proprietary. To prevent this, we have made it clear that any +patent must be licensed for everyone's free use or not licensed at all. + + The precise terms and conditions for copying, distribution and +modification follow. + + GNU GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License applies to any program or other work which contains +a notice placed by the copyright holder saying it may be distributed +under the terms of this General Public License. The "Program", below, +refers to any such program or work, and a "work based on the Program" +means either the Program or any derivative work under copyright law: +that is to say, a work containing the Program or a portion of it, +either verbatim or with modifications and/or translated into another +language. (Hereinafter, translation is included without limitation in +the term "modification".) Each licensee is addressed as "you". + +Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running the Program is not restricted, and the output from the Program +is covered only if its contents constitute a work based on the +Program (independent of having been made by running the Program). +Whether that is true depends on what the Program does. + + 1. You may copy and distribute verbatim copies of the Program's +source code as you receive it, in any medium, provided that you +conspicuously and appropriately publish on each copy an appropriate +copyright notice and disclaimer of warranty; keep intact all the +notices that refer to this License and to the absence of any warranty; +and give any other recipients of the Program a copy of this License +along with the Program. + +You may charge a fee for the physical act of transferring a copy, and +you may at your option offer warranty protection in exchange for a fee. + + 2. You may modify your copy or copies of the Program or any portion +of it, thus forming a work based on the Program, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) You must cause the modified files to carry prominent notices + stating that you changed the files and the date of any change. + + b) You must cause any work that you distribute or publish, that in + whole or in part contains or is derived from the Program or any + part thereof, to be licensed as a whole at no charge to all third + parties under the terms of this License. + + c) If the modified program normally reads commands interactively + when run, you must cause it, when started running for such + interactive use in the most ordinary way, to print or display an + announcement including an appropriate copyright notice and a + notice that there is no warranty (or else, saying that you provide + a warranty) and that users may redistribute the program under + these conditions, and telling the user how to view a copy of this + License. (Exception: if the Program itself is interactive but + does not normally print such an announcement, your work based on + the Program is not required to print an announcement.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Program, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Program, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Program. + +In addition, mere aggregation of another work not based on the Program +with the Program (or with a work based on the Program) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may copy and distribute the Program (or a work based on it, +under Section 2) in object code or executable form under the terms of +Sections 1 and 2 above provided that you also do one of the following: + + a) Accompany it with the complete corresponding machine-readable + source code, which must be distributed under the terms of Sections + 1 and 2 above on a medium customarily used for software interchange; or, + + b) Accompany it with a written offer, valid for at least three + years, to give any third party, for a charge no more than your + cost of physically performing source distribution, a complete + machine-readable copy of the corresponding source code, to be + distributed under the terms of Sections 1 and 2 above on a medium + customarily used for software interchange; or, + + c) Accompany it with the information you received as to the offer + to distribute corresponding source code. (This alternative is + allowed only for noncommercial distribution and only if you + received the program in object code or executable form with such + an offer, in accord with Subsection b above.) + +The source code for a work means the preferred form of the work for +making modifications to it. For an executable work, complete source +code means all the source code for all modules it contains, plus any +associated interface definition files, plus the scripts used to +control compilation and installation of the executable. However, as a +special exception, the source code distributed need not include +anything that is normally distributed (in either source or binary +form) with the major components (compiler, kernel, and so on) of the +operating system on which the executable runs, unless that component +itself accompanies the executable. + +If distribution of executable or object code is made by offering +access to copy from a designated place, then offering equivalent +access to copy the source code from the same place counts as +distribution of the source code, even though third parties are not +compelled to copy the source along with the object code. + + 4. You may not copy, modify, sublicense, or distribute the Program +except as expressly provided under this License. Any attempt +otherwise to copy, modify, sublicense or distribute the Program is +void, and will automatically terminate your rights under this License. +However, parties who have received copies, or rights, from you under +this License will not have their licenses terminated so long as such +parties remain in full compliance. + + 5. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Program or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Program (or any work based on the +Program), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Program or works based on it. + + 6. Each time you redistribute the Program (or any work based on the +Program), the recipient automatically receives a license from the +original licensor to copy, distribute or modify the Program subject to +these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties to +this License. + + 7. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Program at all. For example, if a patent +license would not permit royalty-free redistribution of the Program by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Program. + +If any portion of this section is held invalid or unenforceable under +any particular circumstance, the balance of the section is intended to +apply and the section as a whole is intended to apply in other +circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system, which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 8. If the distribution and/or use of the Program is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Program under this License +may add an explicit geographical distribution limitation excluding +those countries, so that distribution is permitted only in or among +countries not thus excluded. In such case, this License incorporates +the limitation as if written in the body of this License. + + 9. The Free Software Foundation may publish revised and/or new versions +of the General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + +Each version is given a distinguishing version number. If the Program +specifies a version number of this License which applies to it and "any +later version", you have the option of following the terms and conditions +either of that version or of any later version published by the Free +Software Foundation. If the Program does not specify a version number of +this License, you may choose any version ever published by the Free Software +Foundation. + + 10. If you wish to incorporate parts of the Program into other free +programs whose distribution conditions are different, write to the author +to ask for permission. For software which is copyrighted by the Free +Software Foundation, write to the Free Software Foundation; we sometimes +make exceptions for this. Our decision will be guided by the two goals +of preserving the free status of all derivatives of our free software and +of promoting the sharing and reuse of software generally. + + NO WARRANTY + + 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY +FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN +OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES +PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED +OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS +TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE +PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, +REPAIR OR CORRECTION. + + 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR +REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, +INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING +OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED +TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY +YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER +PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE +POSSIBILITY OF SUCH DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along + with this program; if not, write to the Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + +Also add information on how to contact you by electronic and paper mail. + +If the program is interactive, make it output a short notice like this +when it starts in an interactive mode: + + Gnomovision version 69, Copyright (C) year name of author + Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, the commands you use may +be called something other than `show w' and `show c'; they could even be +mouse-clicks or menu items--whatever suits your program. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the program, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the program + `Gnomovision' (which makes passes at compilers) written by James Hacker. + + , 1 April 1989 + Ty Coon, President of Vice + +This General Public License does not permit incorporating your program into +proprietary programs. If your program is a subroutine library, you may +consider it more useful to permit linking proprietary applications with the +library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. diff --git a/MANIFEST.MF b/MANIFEST.MF new file mode 100644 index 0000000..6f812be --- /dev/null +++ b/MANIFEST.MF @@ -0,0 +1 @@ +Premain-Class: one.nalim.Agent diff --git a/README.md b/README.md new file mode 100644 index 0000000..8b02327 --- /dev/null +++ b/README.md @@ -0,0 +1,182 @@ +# nalim + +Nalim is a library for linking Java methods to native functions using +[JVMCI](https://openjdk.org/jeps/243) (JVM compiler interface). + +Unlike other Java frameworks for native library access, nalim does not +use JNI and therefore does not incur [JNI related overhead](https://stackoverflow.com/a/24747484/3448419). + +When calling a native function with nalim + - a thread does not switch from `in_Java` to `in_native` state and back; + - no memory barrier is involved; + - no JNI handles are created; + - exception checks and safepoint checks are omitted; + - native function can access primitive arrays directly in the heap. + +As a result, native calls become faster comparing to JNI, especially when +a target function is short. In this sense, nalim is similar to +[JNI Critical Natives](https://stackoverflow.com/a/36309652/3448419), +but relies on a standard supported interface. JNI Critical Natives +have been [deprecated](https://bugs.openjdk.org/browse/JDK-8233343) in JDK 16 +and [obsoleted](https://bugs.openjdk.org/browse/JDK-8258192) since JDK 18, +so nalim can serve as a replacement. + +### Examples + +#### 1. Basic usage + +```java +public class Libc { + + @Link + public static native int getuid(); + + @Link + public static native int getgid(); + + static { + Linker.linkClass(Libc.class); + } +} +``` +``` +System.out.println("My user id = " + Libc.getuid()); +``` + +#### 2. Linking by a different name + +```java +public class Mem { + + @Link(name = "malloc") + public static native long allocate(long size); + + @Link(name = "free") + public static native void release(long ptr); + + static { + Linker.linkClass(Mem.class); + } +} +``` + +#### 3. Working with arrays + +```java +@Library("ssl") +public class LibSSL { + + public static byte[] sha256(byte[] data) { + byte[] digest = new byte[32]; + SHA256(data, data.length, digest); + return digest; + } + + @Link + private static native void SHA256(byte[] data, int len, byte[] digest); +} +``` + +#### 4. Inlining raw machine code + +```java +public class Cpu { + + // rdtsc + // shl $0x20,%rdx + // or %rdx,%rax + // ret + @Code({15, 49, 72, -63, -30, 32, 72, 9, -48, -61}) + public static native long rdtsc(); + + static { + Linker.linkClass(Cpu.class); + } +} +``` + +### Running + +#### 1. As an agent + +``` +java -XX:+UnlockExperimentalVMOptions -XX:+EnableJVMCI \ + -javaagent:nalim.jar -cp MainClass +``` + +This is the simplest way to add nalim to your application, +as the agent exports all required JDK internal packages for you. + +The agent optionally accepts a list of classes whose native methods +will be automatically linked at startup: +``` +-javaagent:nalim.jar=com.example.MyLib,com.example.OtherLib +``` + +#### 2. On the classpath + +If not adding nalim as an agent, you'll have to add all required +`--add-exports` manually. + +``` +java -XX:+UnlockExperimentalVMOptions -XX:+EnableJVMCI \ + --add-exports jdk.internal.vm.ci/jdk.vm.ci.code=ALL-UNNAMED \ + --add-exports jdk.internal.vm.ci/jdk.vm.ci.code.site=ALL-UNNAMED \ + --add-exports jdk.internal.vm.ci/jdk.vm.ci.hotspot=ALL-UNNAMED \ + --add-exports jdk.internal.vm.ci/jdk.vm.ci.meta=ALL-UNNAMED \ + --add-exports jdk.internal.vm.ci/jdk.vm.ci.runtime=ALL-UNNAMED \ + -cp nalim.jar:app.jar MainClass +``` + +### Performance + +JMH benchmark for comparing regular JNI calls with nalim calls is available +[here](https://github.com/apangin/nalim/blob/master/example/one/nalim/bench). + +The following results were obtained on Intel Core i7-1280P CPU with JDK 17.0.4.1. + +#### Simple native method + +``` +static native int add(int a, int b); +``` + +``` +Benchmark Mode Cnt Score Error Units +JniBench.add_jni avgt 10 6,535 ± 0,225 ns/op +JniBench.add_nalim avgt 10 0,862 ± 0,035 ns/op +``` + +#### Array processing + +``` +static native long max(long[] array, int length); +``` + +``` +Benchmark (length) Mode Cnt Score Error Units +JniBench.max_jni 10 avgt 10 25,103 ± 0,994 ns/op +JniBench.max_jni 100 avgt 10 55,981 ± 2,930 ns/op +JniBench.max_jni 1000 avgt 10 433,106 ± 1,661 ns/op +JniBench.max_nalim 10 avgt 10 3,477 ± 0,215 ns/op +JniBench.max_nalim 100 avgt 10 38,368 ± 2,348 ns/op +JniBench.max_nalim 1000 avgt 10 420,540 ± 4,049 ns/op +``` + +### Supported platforms + + - **Linux:** amd64 aarch64 + - **macOS:** amd64 aarch64 + - **Windows:** amd64 + +### Limitations + +A native function called with nalim has certain limitations comparing to a regular +JNI function. + +1. It must be `static`. +2. It does not have access to `JNIEnv` and therefore cannot call JNI functions, + in particular, it cannot throw exceptions. +3. Only primitive types and primitive arrays can be passed as arguments. +4. A function must return as soon as possible, since it blocks JVM from reaching + a safepoint. diff --git a/build.sh b/build.sh new file mode 100644 index 0000000..7595554 --- /dev/null +++ b/build.sh @@ -0,0 +1,11 @@ +#!/bin/sh +javac --add-modules jdk.internal.vm.ci \ + --add-exports jdk.internal.vm.ci/jdk.vm.ci.code=ALL-UNNAMED \ + --add-exports jdk.internal.vm.ci/jdk.vm.ci.code.site=ALL-UNNAMED \ + --add-exports jdk.internal.vm.ci/jdk.vm.ci.hotspot=ALL-UNNAMED \ + --add-exports jdk.internal.vm.ci/jdk.vm.ci.meta=ALL-UNNAMED \ + --add-exports jdk.internal.vm.ci/jdk.vm.ci.runtime=ALL-UNNAMED \ + --source 11 --target 11 \ + -d . src/one/nalim/*.java + +jar cfm nalim.jar MANIFEST.MF one diff --git a/example/one/nalim/bench/JniBench.java b/example/one/nalim/bench/JniBench.java new file mode 100644 index 0000000..5d5a769 --- /dev/null +++ b/example/one/nalim/bench/JniBench.java @@ -0,0 +1,59 @@ +package one.nalim.bench; + +import one.nalim.Link; +import one.nalim.Linker; +import org.openjdk.jmh.annotations.*; + +import java.util.concurrent.ThreadLocalRandom; + +@State(Scope.Benchmark) +public class JniBench { + + int a = 123; + int b = 45678; + + @Param({"10", "100", "1000"}) + int length; + + long[] array; + + @Setup + public void setup() { + array = ThreadLocalRandom.current().longs(length).toArray(); + } + + @Benchmark + public long add_jni() { + return add(a, b); + } + + @Benchmark + public long add_nalim() { + return raw_add(a, b); + } + + @Benchmark + public long max_jni() { + return max(array, array.length); + } + + @Benchmark + public long max_nalim() { + return raw_max(array, array.length); + } + + static native int add(int a, int b); + + static native long max(long[] array, int length); + + @Link + static native int raw_add(int a, int b); + + @Link + static native long raw_max(long[] array, int length); + + static { + System.loadLibrary("jnibench"); + Linker.linkClass(JniBench.class); + } +} diff --git a/example/one/nalim/bench/jnibench.c b/example/one/nalim/bench/jnibench.c new file mode 100644 index 0000000..f988550 --- /dev/null +++ b/example/one/nalim/bench/jnibench.c @@ -0,0 +1,36 @@ +#include + +JNIEXPORT jint JNICALL +Java_bench_JniBench_add(JNIEnv* env, jclass unused, jint a, jint b) { + return a + b; +} + +JNIEXPORT jint JNICALL +raw_add(jint a, jint b) { + return a + b; +} + +JNIEXPORT jlong JNICALL +Java_bench_JniBench_max(JNIEnv* env, jclass unused, jlongArray array, jint length) { + jboolean isCopy; + jlong* data = (jlong*) (*env)->GetPrimitiveArrayCritical(env, array, &isCopy); + + jlong max = 1LL << 63; + jint i; + for (i = 0; i < length; i++) { + if (data[i] > max) max = data[i]; + } + + (*env)->ReleasePrimitiveArrayCritical(env, array, data, JNI_ABORT); + return max; +} + +JNIEXPORT jlong JNICALL +raw_max(jlong* data, jint length) { + jlong max = 1LL << 63; + jint i; + for (i = 0; i < length; i++) { + if (data[i] > max) max = data[i]; + } + return max; +} diff --git a/example/one/nalim/example/Cpu.java b/example/one/nalim/example/Cpu.java new file mode 100644 index 0000000..56623f4 --- /dev/null +++ b/example/one/nalim/example/Cpu.java @@ -0,0 +1,18 @@ +package one.nalim.example; + +import one.nalim.Code; +import one.nalim.Linker; + +public class Cpu { + + // rdtsc + // shl $0x20,%rdx + // or %rdx,%rax + // ret + @Code({15, 49, 72, -63, -30, 32, 72, 9, -48, -61}) + public static native long rdtsc(); + + static { + Linker.linkClass(Cpu.class); + } +} diff --git a/example/one/nalim/example/LibSSL.java b/example/one/nalim/example/LibSSL.java new file mode 100644 index 0000000..4d44c1a --- /dev/null +++ b/example/one/nalim/example/LibSSL.java @@ -0,0 +1,17 @@ +package one.nalim.example; + +import one.nalim.Library; +import one.nalim.Link; + +@Library("ssl") +public class LibSSL { + + public static byte[] sha256(byte[] data) { + byte[] digest = new byte[32]; + SHA256(data, data.length, digest); + return digest; + } + + @Link + private static native void SHA256(byte[] data, int len, byte[] digest); +} diff --git a/example/one/nalim/example/Libc.java b/example/one/nalim/example/Libc.java new file mode 100644 index 0000000..83b6d0d --- /dev/null +++ b/example/one/nalim/example/Libc.java @@ -0,0 +1,17 @@ +package one.nalim.example; + +import one.nalim.Link; +import one.nalim.Linker; + +public class Libc { + + @Link + public static native int getuid(); + + @Link + public static native int getgid(); + + static { + Linker.linkClass(Libc.class); + } +} diff --git a/example/one/nalim/example/Mem.java b/example/one/nalim/example/Mem.java new file mode 100644 index 0000000..f921b3b --- /dev/null +++ b/example/one/nalim/example/Mem.java @@ -0,0 +1,17 @@ +package one.nalim.example; + +import one.nalim.Link; +import one.nalim.Linker; + +public class Mem { + + @Link(name = "malloc") + public static native long allocate(long size); + + @Link(name = "free") + public static native void release(long ptr); + + static { + Linker.linkClass(Mem.class); + } +} diff --git a/example/one/nalim/example/Time.java b/example/one/nalim/example/Time.java new file mode 100644 index 0000000..fcbd502 --- /dev/null +++ b/example/one/nalim/example/Time.java @@ -0,0 +1,20 @@ +package one.nalim.example; + +import one.nalim.Link; +import one.nalim.Linker; + +public class Time { + + public static long[] current() { + long[] result = new long[2]; + clock_gettime(0, result); + return result; + } + + @Link + private static native void clock_gettime(int clk_id, long[] tp); + + static { + Linker.linkClass(Time.class); + } +} diff --git a/src/one/nalim/AArch64CallingConvention.java b/src/one/nalim/AArch64CallingConvention.java new file mode 100644 index 0000000..d6ba079 --- /dev/null +++ b/src/one/nalim/AArch64CallingConvention.java @@ -0,0 +1,73 @@ +/* + * Copyright (C) 2022 Andrei Pangin + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ + +package one.nalim; + +import java.nio.ByteBuffer; + +class AArch64CallingConvention extends CallingConvention { + + // AArch64 calling convention: + // Java: x1, x2, x3, x4, x5, x6, x7, x0, stack + // Native: x0, x1, x2, x3, x4, x5, x6, x7, stack + + @Override + public void javaToNative(ByteBuffer buf, Class... types) { + if (types.length >= 8) { + // 8th Java argument clashes with the 1st native arg + buf.putInt(0xaa0003e8); // mov x8, x0 + } + + int index = 0; + for (Class type : types) { + index += moveArg(buf, index, type); + } + } + + @Override + public void emitCall(ByteBuffer buf, long address) { + int a0 = (int) address & 0xffff; + int a1 = (int) (address >>> 16) & 0xffff; + int a2 = (int) (address >>> 32) & 0xffff; + int a3 = (int) (address >>> 48); + + buf.putInt(0xd2800009 | a0 << 5); // movz x9, #0xffff + if (a1 != 0) buf.putInt(0xf2a00009 | a1 << 5); // movk x9, #0xffff, lsl #16 + if (a2 != 0) buf.putInt(0xf2c00009 | a2 << 5); // movk x9, #0xffff, lsl #32 + if (a3 != 0) buf.putInt(0xf2e00009 | a3 << 5); // movk x9, #0xffff, lsl #48 + + buf.putInt(0xd61f0120); // br x9 + } + + private static int moveArg(ByteBuffer buf, int index, Class type) { + if (type == float.class || type == double.class) { + return 0; + } else if (index >= 8 && (type.isPrimitive() || type.isArray())) { + return 0; + } else if (type.isPrimitive()) { + // mov x0, x1 + buf.putInt((type == long.class ? 0xaa0003e0 : 0x2a0003e0) | index | (index + 1) << 16); + return 1; + } else if (type.isArray()) { + // add x0, x1, #offset + buf.putInt(0x91000000 | index | (index + 1) << 5 | arrayBaseOffset(type) << 10); + return 1; + } + throw new IllegalArgumentException("Unsupported argument type: " + type); + } +} diff --git a/src/one/nalim/AMD64LinuxCallingConvention.java b/src/one/nalim/AMD64LinuxCallingConvention.java new file mode 100644 index 0000000..24d1c99 --- /dev/null +++ b/src/one/nalim/AMD64LinuxCallingConvention.java @@ -0,0 +1,93 @@ +/* + * Copyright (C) 2022 Andrei Pangin + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ + +package one.nalim; + +import java.nio.ByteBuffer; + +class AMD64LinuxCallingConvention extends CallingConvention { + + // x64 calling convention (Linux, macOS): + // Java: rsi, rdx, rcx, r8, r9, rdi, stack + // Native: rdi, rsi, rdx, rcx, r8, r9, stack + + private static final int SAVE_LAST_ARG = + 0x4889f8; // mov rax, rdi + + private static final int[] MOVE_INT_ARG = { + 0x89f7, // mov edi, esi + 0x89d6, // mov esi, edx + 0x89ca, // mov edx, ecx + 0x4489c1, // mov ecx, r8d + 0x4589c8, // mov r8d, r9d + 0x4189c1, // mov r9d, eax + }; + + private static final int[] MOVE_LONG_ARG = { + 0x4889f7, // mov rdi, rsi + 0x4889d6, // mov rsi, rdx + 0x4889ca, // mov rdx, rcx + 0x4c89c1, // mov rcx, r8 + 0x4d89c8, // mov r8, r9 + 0x4989c1, // mov r9, rax + }; + + private static final int[] MOVE_ARRAY_ARG = { + 0x488d7e, // lea rdi, [rsi+N] + 0x488d72, // lea rsi, [rdx+N] + 0x488d51, // lea rdx, [rcx+N] + 0x498d48, // lea rcx, [r8+N] + 0x4d8d41, // lea r8, [r9+N] + 0x4c8d48, // lea r9, [rax+N] + }; + + @Override + public void javaToNative(ByteBuffer buf, Class... types) { + if (types.length >= 6) { + // 6th Java argument clashes with the 1st native arg + emit(buf, SAVE_LAST_ARG); + } + + int index = 0; + for (Class type : types) { + index += moveArg(buf, index, type); + } + } + + @Override + public void emitCall(ByteBuffer buf, long address) { + buf.putShort((short) 0xb848).putLong(address); // mov rax, address + buf.putShort((short) 0xe0ff); // jmp rax + } + + private static int moveArg(ByteBuffer buf, int index, Class type) { + if (type == float.class || type == double.class) { + return 0; + } else if (index >= 6 && (type.isPrimitive() || type.isArray())) { + return 0; + } else if (type.isPrimitive()) { + emit(buf, (type == long.class ? MOVE_LONG_ARG : MOVE_INT_ARG)[index]); + return 1; + } else if (type.isArray()) { + emit(buf, MOVE_ARRAY_ARG[index]); + buf.put((byte) arrayBaseOffset(type)); + return 1; + } + throw new IllegalArgumentException("Unsupported argument type: " + type); + } +} diff --git a/src/one/nalim/AMD64WindowsCallingConvention.java b/src/one/nalim/AMD64WindowsCallingConvention.java new file mode 100644 index 0000000..61b491d --- /dev/null +++ b/src/one/nalim/AMD64WindowsCallingConvention.java @@ -0,0 +1,79 @@ +/* + * Copyright (C) 2022 Andrei Pangin + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ + +package one.nalim; + +import java.nio.ByteBuffer; + +class AMD64WindowsCallingConvention extends CallingConvention { + + // x64 calling convention (Windows): + // Java: rdx, r8, r9, rdi, rsi, rcx, stack + // Native: rcx, rdx, r8, r9, stack + + private static final int[] MOVE_INT_ARG = { + 0x89d1, // mov ecx, edx + 0x4489c2, // mov edx, r8d + 0x4589c8, // mov r8d, r9d + 0x4189f9, // mov r9d, edi + }; + + private static final int[] MOVE_LONG_ARG = { + 0x4889d1, // mov rcx, rdx + 0x4c89c2, // mov rdx, r8 + 0x4d89c8, // mov r8, r9 + 0x4989f9, // mov r9, rdi + }; + + private static final int[] MOVE_ARRAY_ARG = { + 0x488d4a, // lea rcx, [rdx+N] + 0x498d50, // lea rdx, [r8+N] + 0x4d8d41, // lea r8, [r9+N] + 0x4c8d4f, // lea r9, [rdi+N] + }; + + @Override + public void javaToNative(ByteBuffer buf, Class... types) { + int index = 0; + for (Class type : types) { + index += moveArg(buf, index, type); + } + } + + @Override + public void emitCall(ByteBuffer buf, long address) { + buf.putShort((short) 0xb848).putLong(address); // mov rax, address + buf.putShort((short) 0xe0ff); // jmp rax + } + + private static int moveArg(ByteBuffer buf, int index, Class type) { + if (type == float.class || type == double.class) { + return 0; + } else if (index >= 4 && (type.isPrimitive() || type.isArray())) { + throw new IllegalArgumentException("At most 4 integer arguments are supported"); + } else if (type.isPrimitive()) { + emit(buf, (type == long.class ? MOVE_LONG_ARG : MOVE_INT_ARG)[index]); + return 1; + } else if (type.isArray()) { + emit(buf, MOVE_ARRAY_ARG[index]); + buf.put((byte) arrayBaseOffset(type)); + return 1; + } + throw new IllegalArgumentException("Unsupported argument type: " + type); + } +} diff --git a/src/one/nalim/Agent.java b/src/one/nalim/Agent.java new file mode 100644 index 0000000..5d023a6 --- /dev/null +++ b/src/one/nalim/Agent.java @@ -0,0 +1,61 @@ +/* + * Copyright (C) 2022 Andrei Pangin + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ + +package one.nalim; + +import java.lang.instrument.Instrumentation; +import java.util.Collections; +import java.util.Map; +import java.util.Optional; +import java.util.Set; + +public class Agent { + + public static void premain(String args, Instrumentation inst) throws Exception { + openJvmciPackages(inst); + + if (args != null) { + for (String className : args.split(",")) { + Linker.linkClass(Class.forName(className)); + } + } + } + + private static void openJvmciPackages(Instrumentation inst) { + Optional jvmciModule = ModuleLayer.boot().findModule("jdk.internal.vm.ci"); + if (jvmciModule.isEmpty()) { + throw new IllegalStateException("JVMCI module not found. Use -XX:+UnlockExperimentalVMOptions -XX:+EnableJVMCI"); + } + + Set unnamed = Set.of( + ClassLoader.getPlatformClassLoader().getUnnamedModule(), + ClassLoader.getSystemClassLoader().getUnnamedModule() + ); + + Map> extraExports = Map.of( + "jdk.vm.ci.code", unnamed, + "jdk.vm.ci.code.site", unnamed, + "jdk.vm.ci.hotspot", unnamed, + "jdk.vm.ci.meta", unnamed, + "jdk.vm.ci.runtime", unnamed + ); + + inst.redefineModule(jvmciModule.get(), Collections.emptySet(), extraExports, + Collections.emptyMap(), Collections.emptySet(), Collections.emptyMap()); + } +} diff --git a/src/one/nalim/CallingConvention.java b/src/one/nalim/CallingConvention.java new file mode 100644 index 0000000..fc920bb --- /dev/null +++ b/src/one/nalim/CallingConvention.java @@ -0,0 +1,61 @@ +/* + * Copyright (C) 2022 Andrei Pangin + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ + +package one.nalim; + +import jdk.vm.ci.meta.JavaKind; +import jdk.vm.ci.runtime.JVMCI; + +import java.nio.ByteBuffer; + +abstract class CallingConvention { + + static CallingConvention getInstance() { + String arch = System.getProperty("os.arch").toLowerCase(); + if (!arch.contains("64")) { + throw new IllegalStateException("Unsupported architecture: " + arch); + } + + if (arch.contains("aarch") || arch.contains("arm")) { + return new AArch64CallingConvention(); + } + + String os = System.getProperty("os.name").toLowerCase(); + if (os.contains("windows")) { + return new AMD64WindowsCallingConvention(); + } else { + return new AMD64LinuxCallingConvention(); + } + } + + abstract void javaToNative(ByteBuffer buf, Class... types); + + abstract void emitCall(ByteBuffer buf, long address); + + protected static int arrayBaseOffset(Class arrayType) { + JavaKind elementKind = JavaKind.fromJavaClass(arrayType.getComponentType()); + return JVMCI.getRuntime().getHostJVMCIBackend().getMetaAccess().getArrayBaseOffset(elementKind); + } + + protected static void emit(ByteBuffer buf, int code) { + if ((code >>> 24) != 0) buf.put((byte) (code >>> 24)); + if ((code >>> 16) != 0) buf.put((byte) (code >>> 16)); + if ((code >>> 8) != 0) buf.put((byte) (code >>> 8)); + if (code != 0) buf.put((byte) code); + } +} diff --git a/src/one/nalim/Code.java b/src/one/nalim/Code.java new file mode 100644 index 0000000..e3d5282 --- /dev/null +++ b/src/one/nalim/Code.java @@ -0,0 +1,37 @@ +/* + * Copyright (C) 2022 Andrei Pangin + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ + +package one.nalim; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * Specifies machine code to be associated with a native method. + */ +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.METHOD) +public @interface Code { + /** + * Machine code for the method implementation. + * Typically, the code should end with a return instruction. + */ + byte[] value(); +} diff --git a/src/one/nalim/JavaInternals.java b/src/one/nalim/JavaInternals.java new file mode 100644 index 0000000..2e051aa --- /dev/null +++ b/src/one/nalim/JavaInternals.java @@ -0,0 +1,99 @@ +/* + * Copyright (C) 2022 Andrei Pangin + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ + +package one.nalim; + +import sun.misc.Unsafe; + +import java.lang.reflect.AccessibleObject; +import java.lang.reflect.Constructor; +import java.lang.reflect.Field; +import java.lang.reflect.Method; + +class JavaInternals { + public static final Unsafe unsafe = getUnsafe(); + + private static final long accessibleOffset = getAccessibleOffset(); + + private static Unsafe getUnsafe() { + try { + return (Unsafe) getPrivateField(Unsafe.class, "theUnsafe").get(null); + } catch (IllegalAccessException e) { + throw new IllegalStateException(e); + } + } + + private static long getAccessibleOffset() { + boolean hasModules = !System.getProperty("java.version").startsWith("1."); + if (hasModules) { + try { + Method m0 = JavaInternals.class.getDeclaredMethod("getAccessibleOffset"); + Method m1 = JavaInternals.class.getDeclaredMethod("getAccessibleOffset"); + m1.setAccessible(true); + + // Work around JDK 17 restrictions on calling setAccessible() + for (long offset = 8; offset < 128; offset++) { + if (unsafe.getByte(m0, offset) == 0 && unsafe.getByte(m1, offset) == 1) { + return offset; + } + } + } catch (Exception e) { + // Fall back to default setAccessible() implementation + } + } + return 0; + } + + public static Field getPrivateField(Class cls, String name) { + try { + Field f = cls.getDeclaredField(name); + setAccessible(f); + return f; + } catch (NoSuchFieldException e) { + throw new IllegalArgumentException(e); + } + } + + public static Method getPrivateMethod(Class cls, String name, Class... params) { + try { + Method m = cls.getDeclaredMethod(name, params); + setAccessible(m); + return m; + } catch (NoSuchMethodException e) { + throw new IllegalArgumentException(e); + } + } + + public static Constructor getPrivateConstructor(Class cls, Class... params) { + try { + Constructor c = cls.getDeclaredConstructor(params); + setAccessible(c); + return c; + } catch (NoSuchMethodException e) { + throw new IllegalArgumentException(e); + } + } + + public static void setAccessible(AccessibleObject ao) { + if (accessibleOffset != 0) { + unsafe.putByte(ao, accessibleOffset, (byte) 1); + } else { + ao.setAccessible(true); + } + } +} diff --git a/src/one/nalim/Library.java b/src/one/nalim/Library.java new file mode 100644 index 0000000..0ad02a1 --- /dev/null +++ b/src/one/nalim/Library.java @@ -0,0 +1,33 @@ +/* + * Copyright (C) 2022 Andrei Pangin + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ + +package one.nalim; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * Specifies the name of the native shared library to load. + */ +@Retention(RetentionPolicy.RUNTIME) +@Target({ElementType.TYPE, ElementType.METHOD}) +public @interface Library { + String value(); +} diff --git a/src/one/nalim/Link.java b/src/one/nalim/Link.java new file mode 100644 index 0000000..871ab17 --- /dev/null +++ b/src/one/nalim/Link.java @@ -0,0 +1,44 @@ +/* + * Copyright (C) 2022 Andrei Pangin + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ + +package one.nalim; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * Denotes a method for linking with the native code. + */ +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.METHOD) +public @interface Link { + /** + * Alternative name of the native function. + * If not specified, Java method name is assumed. + */ + String name() default ""; + + /** + * true, if the target method uses Java calling convention; + * false, if the Linker should generate a prologue + * for translating arguments according to the native ABI. + */ + boolean naked() default false; +} diff --git a/src/one/nalim/Linker.java b/src/one/nalim/Linker.java new file mode 100644 index 0000000..3f8e8ff --- /dev/null +++ b/src/one/nalim/Linker.java @@ -0,0 +1,161 @@ +/* + * Copyright (C) 2022 Andrei Pangin + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ + +package one.nalim; + +import jdk.vm.ci.code.site.DataPatch; +import jdk.vm.ci.code.site.Site; +import jdk.vm.ci.hotspot.HotSpotCompiledCode; +import jdk.vm.ci.hotspot.HotSpotCompiledNmethod; +import jdk.vm.ci.hotspot.HotSpotResolvedJavaMethod; +import jdk.vm.ci.meta.Assumptions; +import jdk.vm.ci.meta.ResolvedJavaMethod; +import jdk.vm.ci.runtime.JVMCI; +import jdk.vm.ci.runtime.JVMCIBackend; +import jdk.vm.ci.runtime.JVMCICompiler; + +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.util.concurrent.ConcurrentHashMap; + +/** + * Links native methods to the provided machine code using JVMCI. + */ +public class Linker { + private static final JVMCIBackend jvmci = JVMCI.getRuntime().getHostJVMCIBackend(); + private static final ConcurrentHashMap nativeLibraries = new ConcurrentHashMap<>(); + private static final CallingConvention callingConvention = CallingConvention.getInstance(); + + static { + loadLibrary("java"); + } + + public static void loadLibrary(String name) { + if (nativeLibraries.putIfAbsent(name, Boolean.TRUE) == null) { + if (name.indexOf('/') >= 0 || name.indexOf('\\') > 0) { + System.load(name); + } else { + System.loadLibrary(name); + } + } + } + + public static long findAddress(String symbol) { + try { + Method m = JavaInternals.getPrivateMethod(ClassLoader.class, "findNative", ClassLoader.class, String.class); + return (long) m.invoke(null, Linker.class.getClassLoader(), symbol); + } catch (ReflectiveOperationException e) { + throw new IllegalStateException(e); + } + } + + public static void linkClass(Class c) { + Library library = c.getAnnotation(Library.class); + if (library != null) { + loadLibrary(library.value()); + } + + for (Method m : c.getDeclaredMethods()) { + if (m.getAnnotation(Link.class) != null || m.getAnnotation(Code.class) != null) { + linkMethod(m); + } + } + } + + public static void linkMethod(Method m) { + checkMethodType(m); + + Code code = m.getAnnotation(Code.class); + if (code != null) { + installCode(m, code.value()); + return; + } + + Link link = m.getAnnotation(Link.class); + if (link != null) { + linkMethod(m, link.name(), link.naked()); + } else { + linkMethod(m, m.getName(), false); + } + } + + public static void linkMethod(Method m, String symbol, boolean naked) { + checkMethodType(m); + + Library library = m.getAnnotation(Library.class); + if (library != null) { + loadLibrary(library.value()); + } + + if (symbol.isEmpty()) { + symbol = m.getName(); + } + long address = findAddress(symbol); + if (address == 0) { + throw new IllegalArgumentException("Symbol not found: " + symbol); + } + + ByteBuffer buf = ByteBuffer.allocate(100).order(ByteOrder.nativeOrder()); + if (!naked) { + callingConvention.javaToNative(buf, m.getParameterTypes()); + } + callingConvention.emitCall(buf, address); + + installCode(m, buf.array(), buf.position()); + } + + private static void checkMethodType(Method m) { + int modifiers = m.getModifiers(); + if (!Modifier.isStatic(modifiers) || !Modifier.isNative(modifiers)) { + throw new IllegalArgumentException("Method must be static native: " + m); + } + } + + public static void installCode(Method m, byte[] code) { + installCode(m, code, code.length); + } + + public static void installCode(Method m, byte[] code, int length) { + ResolvedJavaMethod rm = jvmci.getMetaAccess().lookupJavaMethod(m); + + HotSpotCompiledNmethod nm = new HotSpotCompiledNmethod( + m.getName(), + code, + length, + new Site[0], + new Assumptions.Assumption[0], + new ResolvedJavaMethod[0], + new HotSpotCompiledCode.Comment[0], + new byte[0], + 1, + new DataPatch[0], + true, + 0, + null, + (HotSpotResolvedJavaMethod) rm, + JVMCICompiler.INVOCATION_ENTRY_BCI, + 1, + 0, + false + ); + + jvmci.getCodeCache().setDefaultCode(rm, nm); + } +}