43 points · by warrenm · 3y ago · 112 comments
"Traditional" compilable languages, like C, C++, FORTRAN, etc all ought to be targetable to a portable runtime like the JVM (since it defines its own instruction set (Java byte code)).
Scala and other languages target the JVM as their runtime environment.
Why not older/traditionally-compiled languages?
I don't know if it's worth it to port existing code to the JVM that way. There are so many pitfalls in porting that it's often easier to rewrite it. The older code is, the more likely it has something specific to the compiler/platform/library, and you'll spend more effort debugging that than just using it as a reference for a clean-sheet implementation in a modern language.
I picked Lisp and Prolog because those are languages with a very different style. Compared to that C/C++/Fortran are all kinda the same language. Since then functional programming has taken on a lot more prominence, though logic-style programming still hasn't caught much attention. (The book actually came out of a project to use logic programming as a database query language, and I still feel like that's better than where we are now.)
It blows my mind that the book is still in print, and dribbles out a few copies a year. It does need a good rewrite, since so many of the things I talked about are now practical rather than theoretical. The JVM has some new features for supporting non-Java languages, and there are now standard libraries for manipulating bytecode. (I had to roll my own.)
Someone could make up a mapping but it would be a numerological exercise, a flight of fancy forever lacking utility.
And anyway there is a practical integration between C and Fortran world and JVM world. The JVM can link to compiled C and Fortran object code, and for those who like suffering, JVM structures can be reached from C source.
I’m sure there are some other ways as well, but a supported one is through the Graal project, which can run LLVM bitcode (and thus any of C, C++, Rust, etc) natively. Hell, it can interop with regular Java code, or that of other Truffle languages, and even optimize across language barriers!
What's the point, just to say you did it?
It's not impossible, it's just not worth the ROI time wise for most people with the desire to make a C/C++ standard compliant compiler to do so-- and even if they do, the amount of traction it'll gain will be minimal because developers can make an educated choice not to use it when native C/C++ compilers are available, or alternative JVM languages like Kotlin.
Which is why you have a bunch of attempts at this that stopped development in 2009/2015.
Really?
C is available on so many hardware sets ... it's practically universal (Arduino, x86, MIPS, 68k, PowerPC, ARM, SPARC, RISCV...)
I find it incredibly hard to believe that you couldn't target the JVM (which also runs on SPARC, ARM, RISCV, x86, POWER...) with C as the source language!
Even Sun/Oracle recognized the mismatch and that's why GraalVM is a thing (and why Graal isn't entirely meshable with classic Java runtimes even if I hope they have a merge-strategy for the long-term).
The big problem is that C assumes a low-level target language, which all these architectures provide but the JVM does not. A C runtime on the JVM would have to re-implement things like direct memory access on top of JVM arrays, which, while possible, would introduce performance penalties that would completely negate the purpose of writing C.
Ahem, sun.misc.Unsafe.{get,put}{Byte,Short,Int,Long,Float,Double,Address}
> What, for instance, do you turn a malloc() call for a number of bytes into?
Perhaps sun.misc.Unsafe.allocateMemory?
In practice this is totally pointless.
https://en.wikipedia.org/wiki/List_of_JVM_languages
GCC-Bridge, a C/Fortran compiler targeting the Java Virtual Machine (JVM) that makes it possible for Renjin to run R packages that include "native" C and Fortran code
https://www.renjin.org/blog/2016-01-31-introducing-gcc-bridg...
Earlier attempts at FORTRAN struggle because of performance issues but there were some successes:
JLAPACK – Compiling LAPACK FORTRAN to Java https://www.hindawi.com/journals/sp/1999/179617/
https://www.semanticscholar.org/paper/Automatic-translation-...
C and C++ work with a large pointer-addressable heap, the JVM works with objects.
You could emulate a heap in the JVM though. You wouldn't get the advantage of JVM's automatic garbage collection, but at least you'd get some form of portability (don't expect to run the JVM inside the JVM this way).
Don't forget that the JVM already has ways to communicate with native programs (JNI originally, but now a new FFI is in the works), so if you depended on any native code you could still use it.
You would use it for the same thing that you can do with GraalVM Enterprise today: use native libraries written in C/Fortran/… from your other JVM code in a sandboxed way, without any possibility that the entire VM can crash due to memory corruption bugs in the C/Fortran/… code.
That counts as bad performance in my book.
As a matter of fact, you said it yourself in a neighbouring thread that all C needs is a large array - I cannot imagine how can you get any lower than that: mapping almost 1:1 to the general memory model of a CPU executing instructions with some addressable memory.
C++ has classes and templates, Rust has... a lot of things, they are definitely higher up in terms of abstractions built into the language.
C can’t control cache behavior, has no SIMD control, and no threading support (non-standard extensions doesn’t count) It maps well to PDP-11, but that has barely any similarity to modern CPUs.
For what its worth, one might argue that C++ and Rust are lower level, as they can even control some of the above listed functions.
As for “closeness to generated assembly”, as I said, at O3 the generated code doesn’t resemble the source at all — it might not even execute anything your wrote, it may have calculated the result at compile time and will just return the result/look it up in a map at runtime.
Hmm, I disagree. C is a mid-level language, one level of abstraction up from assembly. C++ and Rust are high-level languages, one or two levels of abstraction higher than C.
I prefer the one of “what features does the language give you idiomatic control of”. In that vein, Rust is more low-level than by having simd support.
Firstly, for the last few years when you talk about this topic you have to distinguish between the "old world" JVMs which can only be given bytecode as input, and GraalVM, which is a superset of those JVMs and enables language implementations to use the JVM's features whilst bypassing the bytecode layer entirely.
Java byte code has some problems that make it unsuitable for C-like languages. Most obviously you can't do pointer arithmetic or arbitrary casts, which is a fundamental requirement for real C code. This doesn't mean it can't be done, these are all Turing complete machines after all, but it means there's no point because performance would be very poor due to all the workarounds. For C++ the gap gets wider because Java has its own ideas about how objects work that aren't the same as those in C++, e.g. multiple inheritance, so you can't implement C++ classes as Java classes.
These sorts of problems affect any language that is semantically too far away from Java, like scripting languages. JVM bytecode is fairly well designed, is reasonably general, and the invokedynamic bytecode was put in there to make scripting languages easier. But it's a high level bytecode so the semantic mismatch is still there.
For a long time this problem seemed inherent to the design space. Any VM bytecode language you can design will end up encoding some assumptions about language design into it, if it doesn't then you've just got assembly language and we already have those. In effect, trying to create a universal bytecode is like trying to create a universal programming language.
But the JVM guys didn't give up. Sun/Oracle Labs spent many years on research and the result is Truffle. Instead of asking people to encode their language into a universal ISA so the JVM can understand it, Truffle is an API. It comes as part of GraalVM. You write an interpreter for your language using this API and compile that to JVM bytecode instead (it doesn't have to be written in Java but it does have to be a language that can produce bytecode). This interpreter is then fused with the code of your target language at runtime and fed through a very advanced optimizing compiler (Graal) which generates machine code for your language. This code is then "installed" into the running JVM using another API called JVMCI, and then has access to all the normal JVM services like the garbage collectors, profiling, deoptimization, observability, standard libraries, OS abstractions, ability to call to/from bytecode world and so on.
With Truffle you don't think about the low level details of all that. You just write an interpreter. You do have the learn the API - your generated machine code will be relatively slow until you start using the API to annotate your interpreter and optimize it for common cases. But the API is pretty comprehensive and offers a lot of functionality, like language interop, debugging, tracing, hot swapping ...
The first languages implemented with Truffle were scripting languages. But the technique is general. It's not scripting or JVM specific and there's no specific reason the language your interpreter reads has to be textual. So they implemented an interpreter for LLVM bitcode. Now you can compile C/C++/FORTRAN/Rust using LLVM, and then execute that on the JVM. Performance is good, not quite as fast as natively compiled with GCC but in the general area. It's a fairly specialized thing to do and today is mostly used for running Python/Ruby extensions. However, because the whole thing is virtualized you can do some mind-bending tricks with it, for example, you can eliminate all the memory errors in the software run this way and then sandbox it without using kernel sandboxing. So it has some potentially big security benefits.
And that's how you can run C or any other language on the JVM without killing performance.
That's not entirely true though, because the Graal compiler has certain assumptions about your language (e.g. you need some form of "methods" and "calls", otherwise Graal won't compile anything), which means it is not exactly straight forward or efficient to run let's say x86 machine code on the GraalVM. It's also not easy to properly support an "mmap" call in an efficient way although it is required by virtually every compiled program that uses glibc, because none of the "scripting or JVM languages" need this and therefore there are no facilities in Truffle to support this.
That being said, a fully sandboxed x86_64 emulator for the GraalVM exists and IIRC it is roughly as fast as the JIT based qemu-x86_64 after warmup.
Sulong (the LLVM bitcode interpreter of GraalVM) is also not ideal, because it directly executes the LLVM IR although some C code assumes that it is compiled to machine code. This means some libraries use e.g. inline assembly, or try to do some stack walking, or use entire subroutines implemented in assembly, or rely on certain POSIX behavior, which isn't (fully) implemented in Sulong. A lot of programs work, but if something doesn't work, chances are it's caused by one of the few fundamental flaws of Sulong. Oracle is experimenting with a workaround by not running everything in LLVM IR in the future, but we'll have to wait and see how good this works in the end.
I agree it's not designed to JIT machine code. To sandbox that it may be better to use a flyweight CPU-level VM anyway.
Yes, C can do anything and if it does stuff like trying to disassemble itself, then that will clearly fail. But then you could argue it's not really written in C.
Everything relevant that can be done with Panama in this context can already be done in a Truffle language with sun.misc.Unsafe and e.g. Sulong used it for exactly this purpose. In fact the Unsafe allowed a lot more with a much simpler API because you really get a function for raw memory access to arbitrary addresses.
But what's the problem anyway? For any normal compiled program, the dynamic linker will mmap the code and data into memory during startup. And a standard memory allocator in the libc like what's used by malloc also uses mmap (and sbrk) internally. Some C programs also directly use mmap to map files into memory or to reserve large amounts of memory, potentially at fixed addresses and with custom protection bits. All of this requires a proper implementation of mmap in the VM if you want to run such programs, in a way that accesses to unmapped or protected memory can be caught without crashing the VM. Side note: Panama does not provide this. The problem here is that the emulated address space only contains a few mapped regions and a lot of unmapped space in between, so you have to come up with a good way how to implement this. You could implement the emulated memory purely in Java, but it is quite slow because you essentially recreate an MMU. For performance reasons you really have to use the hardware MMU in a smart way. It can be done in the GraalVM (and was done in the GraalVM based x86_64 interpreter [1]), but it's not obvious how to do it and it's not particularly efficient either, at least if you want to catch segfaults properly. To efficiently catch segfaults, changes to at least HotSpot would be necessary.
What's even worse here is that it's perfectly valid for a program to register a segfault handler, then cause a segfault and catch it. A few real world programs do exactly this, including the JVM itself. You might ignore such custom signal handling from the guest program, but you definitely have to avoid VM crashes caused by such signals. And again, Panama cannot do it.
> Yes, C can do anything and if it does stuff like trying to disassemble itself, then that will clearly fail. But then you could argue it's not really written in C.
Sure, C programs can do anything, but the problem is that on e.g. a Linux/x86_64 system many things are allowed, certain low level hacks are necessary for performance reasons, and therefore many real world Linux/x86_64 programs do weird things internally, even if it's hidden within some library where you'll never see it. If you want to run an "average" program, you'll have to handle many such cases in your VM. Otherwise you end up with a toy VM which can run a lot of toy programs but fails at larger "real world" programs.
You can do what Sulong does and say "I don't care, I'll just pass malloc/free/mmap/... calls directly to the OS", but then you run into various problems, like e.g. you'll be unable to properly sandbox memory = the guest program can easily crash the VM. You can also do what Sulong in GraalVM Enterprise does and say "we don't support certain features like mmap", but a lot of interesting real world programs won't run. Or you can do what the x86_64 interpreter does and properly (although with reduced performance) emulate all these features, but then you end up building a Java implementation of e.g. the Linux kernel.
In case you wonder, the x86_64 interpreter I mentioned started as a tech demo to show that you can in fact emulate x86_64 with a limited Linux userspace in a fully sandboxed and cross-platform way and with somewhat decent performance on the GraalVM. It even supported Truffle interop with standard Linux .so libraries in the past. Of course it also showed some limitations of the Graal compiler and Truffle, after all that was the entire point of the project. Don't expect Sulong-like peak performance, it's much slower than that. One of the more interesting findings was that machine code emulation with Graal is feasible and works even for larger real world programs like GCC or xpdf or CPython and peak performance can (or at least could at some point in the past) somewhat compete with qemu which uses a hand crafted JIT compiler. This was especially interesting since machine code is the worst imaginable "language" for Graal and Graal is absolutely not built for this.
I feel like all of this kind of exists but it's quite esoteric "non-standard stuff" and not necessarily something sane people want in production.
https://github.com/bedatadriven/renjin/tree/master/tools/gcc...
https://www.graalvm.org/latest/reference-manual/llvm/Compati...
https://www.renjin.org/blog/2016-01-31-introducing-gcc-bridg...
Most of the time if you're writing C, Cpp, FORTRAN, your primary goal is performance, not memory safety or portability. So executing on the JVM wouldn't buy you much.
There are a lot of "modern" or "up-and-coming" languages out there (Hare, Python, Ruby, Swift...)
And there are a slew of "old", "traditional", or "classic" languages out there, too :) (APL, FORTRAN, C/C++...)
You could write backend for most compilers, to target JVM (instead of pure machine codes), but result will be extremely slow.
Going in opposite way is much more fruitful - for example, compiling Java to native machine codes you will got about 10 times faster execution.
But (and correct me if I'm wrong, please), isn't Ruby a "scripting" language? Ie one not 'meant' to be compiled?
JRuby targets the JVM while TruffleRuby is based on the graalVM.
If my memory stands correct, none of these have a compilation step, they both are interpreted. However, TruffleRuby has a feature called Native Image which compiles the language!
Thank you for the additional information :)