SlideShare a Scribd company logo
1 of 51
Download to read offline
Panama: A case study
With OpenSSL and Apache Tomcat TM
Jean-Frederic Clere
Software engineer at Red Hat
Working on HTTPD and Tomcat (JBCS/JWS)
Apache Tomcat committer for years
ASF member
Contents Panama basics
OpenSSL and Tomcat
Tooling
Design
Challenges
Results
Panama
The Panama project
“foreign function and memory API”
Project developed by Oracle for inclusion in java.base
Replacement for JNI
Improve safety and reliability
Better management of native memory
Replacement for various Unsafe based hacks
Incubating and JEPs since Java 14
Java code
Native code
ResourceScope/MemorySession/Arena
Handles native access lifecycle
Allocations and deallocations
Explicit close or GC close
MemorySegment
The main API in Java 21 (previously also MemoryAddress and Addressable)
Native or heap memory, with associated segment size
Basically a pointer
Tied to an associated session
Does size and lifecycle checks -> safety
Memory layouts and native types
Allows modelling types and structures
Simple types are easy
Valhalla will provide support for additional types (Vectors)
Function descriptors and Method handles
FunctionDescriptor API allows describing the native calls to the JVM
Associate a native function to a matching method handle
Use the Linker API for that
Downcalls
Calls from Java to native
Use lookup to get the native symbol
Use the linker to get the method handle
Simply call the method handle with the right arguments
Downcall example
System.loadLibrary("ssl");
MemorySegment OpenSSL_versionSymbol = SymbolLookup.loaderLookup().find("OpenSSL_version").orElseThrow();
MethodHandle OpenSSL_version = Linker.nativeLinker().downcallHandle(OpenSSL_versionSymbol,
FunctionDescriptor.of(ValueLayout.ADDRESS, ValueLayout.JAVA_INT));
MemorySegment version = (MemorySegment) OpenSSL_version.invokeExact(0);
MemorySegment ptr = version.reinterpret(128);
String sversion = ptr.getUtf8String(0);
Demo
Upcalls
Calls from native to Java
Get a method handle from your Java method
The linker gives a memory segment containing a function pointer
Call the appropriate native downcall to set the function pointer
Upcall example part 1
Arena arena = Arena.ofConfined();
MemorySegment nativeString = arena.allocateUtf8String("Hello World! Panama style");
System.loadLibrary("hex");
SymbolLookup mylib = SymbolLookup.libraryLookup("libhex.so", arena);
Linker cLinker = Linker.nativeLinker();
MethodHandle doconvert = cLinker.downcallHandle(mylib.find("doconvert").orElseThrow(),
FunctionDescriptor.of(ValueLayout.JAVA_INT, AddressLayout.ADDRESS));
Upcall example part 2
FunctionDescriptor desc = FunctionDescriptor.of(ValueLayout.JAVA_INT, AddressLayout.ADDRESS);
MethodHandle set_add_cb = cLinker.downcallHandle(mylib.find("set_add_cb").orElseThrow(), desc);
FunctionDescriptor jfcconvertdesc = FunctionDescriptor.of(ValueLayout.JAVA_INT, AddressLayout.ADDRESS);
MethodHandle jfcconvert = MethodHandles.lookup().findStatic(Hex.class, "jfcconvert", MethodType.methodType(int.class, MemorySegment.class));
MemorySegment call = Linker.nativeLinker().upcallStub(jfcconvert, jfcconvertdesc, arena);
set_add_cb.invoke(call);
len = (int) doconvert.invoke(nativeString);
Upcall example part 3 (the java method that is called)
public static int jfcconvert(MemorySegment mem) {
MemorySegment ptr = mem.reinterpret(128);
String string = ptr.getUtf8String(0);
string = jfcconvert(string);
ptr.setUtf8String(0, string);
return 0;
}
Demo
OpenSSL Upcall example
FunctionDescriptor openSSLCallbackVerifyFunctionDescriptor = FunctionDescriptor.of(ValueLayout.JAVA_INT, ValueLayout.JAVA_INT,
ValueLayout.ADDRESS); /* typedef int (*SSL_verify_cb)(int preverify_ok, X509_STORE_CTX *x509_ctx); */
MethodHandle openSSLCallbackVerifyHandle = MethodHandles.lookup().findStatic(OpenSSLEngine.class, "openSSLCallbackVerify",
MethodType.methodType(int.class, int.class, MemorySegment.class));
MethodHandle SSL_CTX_set_verify = …; // The OpenSSL downcall to set the function pointer
var openSSLCallbackVerify = Linker.nativeLinker().upcallStub(openSSLCallbackVerifyHandle,
openSSLCallbackVerifyFunctionDescriptor, engineArena);
SSL_CTX_set_verify(state.sslCtx, /* int */ validationMode, openSSLCallbackVerify);
OpenSSL
All things TLS
Everything
Even more later
Extremely useful to Tomcat
Tomcat needs
TLS 1.3 with PHA (post handshake authentication)
More key formats, ciphers, protocols as they are appear
Better performance
High level API for QUIC
Also used through Tomcat-native
Legacy code (java connector, C dynamic library linked with openssl).
Modernized and cleaned up with 2.0
Some platforms need static linking of OpenSSL (= CVEs !)
Productization needed
Cloud annoyances
OpenSSL API style
Factories and destructors for everything
Accessors and setters for everything
No need to model structures in Panama
Many callbacks needed
Tooling
Jextract
Helps write boilerplate code, handle library updates
Upcalls
Downcalls
Structures
Helps track Panama API changes across Java versions
Using jextract
Now easier to build from https://github.com/openjdk/jextract (or download it)
Uses native library headers
Generates sources or classes
Skips functional macros
Big library means huge very verbose blob
Trimming down the blob
List native APIs actually used
Limit jextract to these APIs
Time consuming …
Using jextract
● With OpenSSL
● Config file
Design and coding
Java code we had
Working OpenSSL implementation for JSSE (not a full provider but close)
Rather well tested
Support for OpenSSL 3.x
Significant amount of Java code using a thinner native API (compared to APR connector)
Tomcat-native code
Needs translation to Java code using Panama
Then integrate into the Tomcat OpenSSL code
Lots of wrapper code, needless structures and state tracking
Problem: large amount of logic inside the JNI layer in some places (certs handling, init, OCSP)
Lifecycle and Memory management
Was already appropriate for Panama
Needs to remain GC based for safety
Process
Generate the full OpenSSL API with jextract
Write OpenSSL init code and test out Panama
Translate the rest of the tomcat-native code into the existing Java classes
Add state tracking for upcalls
Test, fix, improve, test, fix, improve, etc
Challenges
No #ifdef and precompiler
This is bad for us
Also no functional macros support
Have to target real API functions
Of course there are tons macros and real API are often hidden in OpenSSL
OpenSSL API compatibility
Initial target was 1.1
API changes in 3.0, resolved by macros (which don't work with Panama)
Manual downcall declarations needed, with runtime version check
Extensive API changes would need a fully separate implementation
For example, support of LibreSSL and others are not doable as part of the same module
Memory leaks are easy
OpenSSL structures need cleanup
Memory segments point to the session
Bound downcalls unfortunately pins the session
API changes
Java 17 is the first LTS release with the incubating Panama (JEP 412)
Some changes in Java 18 (JEP 419)
Same in Java 19, moving to preview status (--enable-preview is enough) (JEP 424)
Same in Java 20, still preview, heavy API changes
Java 21 LTS was the target for the stable API but still preview
Java 17
Needs scary command line arguments (users will panic)
API is less refined than current
Functionally equivalent for us
Panama seems surprisingly stable
Ok for in house projects that cannot wait for Java 21, not ok for real productization
Java 21…
Still Needs scary command line arguments (users will panic)
API is less refined than current
Functionally equivalent for us
Panama seems surprisingly stable
Ok for in house projects that cannot wait for Java 22, not ok for real productization
Instability
Instability when initially trying with Java 18
Mysterious behaviors, debugging was inconclusive
Had to report to the Panama team
Was caused by stack corruption with (lots of) upcalls
Thankfully fixed
Updating to a new Java
Monitor Panama API changes in openjdk/panama-foreign and evaluate impact
Code merge into next Java openjdk/jdk
Wait for jextract updates to target new API (needed for a large library like OpenSSL)
Migrate and test !
MemoryAddress removal in Java 20
Was simply a long, so now the hacks will be easy to spot again !
Must use MemorySegment for everything, which references its associated session
Good since it holds a reference to the session, so safer
But cleanup tasks on session close must hold on a long or a segment from another session
Refactoring ahead !
Results
It worked !
Surprisingly stable on Java 17
Fast enough on Java 17
Works out of the box if OpenSSL is a system library
With new Java versions, only "--enable-preview" needed (with startup warnings)
Needs to have multiple branches
Many API differences with each JEP
https://github.com/apache/tomcat/tree/main/modules/openssl-foreign : Tracks the Panama API (Java
"22" right now, hopefully final API in Java xx), support for OpenSSL 1.1 and 3.0
https://github.com/apache/tomcat/tree/main/modules/openssl-java21 : Frozen for Java 21, support for
OpenSSL 1.1 and 3.0, "stable"
https://github.com/apache/tomcat/tree/main/modules/openssl-java17 : Frozen for Java 17, support for
OpenSSL 1.1 and 3.0, "stable"
Performance
A bit over 10% slower than JNI across Java 17 and 18
Custom Java 19 builds were about 5% slower
Probably not a glitch since all other testing results was unchanged
OpenSSL Demo
● With Java "21"
Conclusion
Roadmap to stable
Good performance already with safer code
Still preview in Java 21 (09/2023)
Will then be integrated into Tomcat's source tree and ready to use
Work out of the box on Java 22?
tomcat-native will be maintained for a long time (after Java 21 so after Tomcat 11.0.x)
QUESTIONS
THANK YOU!
Everything at:
https://github.com/jfclere/apacheconna2023/tree/master/panama
https://github.com/apache/tomcat/tree/main/modules/openssl-foreign
Ask me:
jfclere@gmail.com

More Related Content

Similar to Panama.pdf

Breaking The Clustering Limits @ AlphaCSP JavaEdge 2007
Breaking The Clustering Limits @ AlphaCSP JavaEdge 2007Breaking The Clustering Limits @ AlphaCSP JavaEdge 2007
Breaking The Clustering Limits @ AlphaCSP JavaEdge 2007Baruch Sadogursky
 
Java Core | Modern Java Concurrency | Martijn Verburg & Ben Evans
Java Core | Modern Java Concurrency | Martijn Verburg & Ben EvansJava Core | Modern Java Concurrency | Martijn Verburg & Ben Evans
Java Core | Modern Java Concurrency | Martijn Verburg & Ben EvansJAX London
 
An Introduction to Java Compiler and Runtime
An Introduction to Java Compiler and RuntimeAn Introduction to Java Compiler and Runtime
An Introduction to Java Compiler and RuntimeOmar Bashir
 
It pro dev_birbilis_20101127_en
It pro dev_birbilis_20101127_enIt pro dev_birbilis_20101127_en
It pro dev_birbilis_20101127_enGeorge Birbilis
 
Introduction of Java 8 with emphasis on Lambda Expressions and Streams
Introduction of Java 8 with emphasis on Lambda Expressions and StreamsIntroduction of Java 8 with emphasis on Lambda Expressions and Streams
Introduction of Java 8 with emphasis on Lambda Expressions and StreamsEmiel Paasschens
 
Java 9 features
Java 9 featuresJava 9 features
Java 9 featuresshrinath97
 
Laurens Van Den Oever Xopus Presentation
Laurens Van Den Oever Xopus PresentationLaurens Van Den Oever Xopus Presentation
Laurens Van Den Oever Xopus PresentationAjax Experience 2009
 
Jalimo Slides Linuxtag2007 (English)
Jalimo Slides Linuxtag2007 (English)Jalimo Slides Linuxtag2007 (English)
Jalimo Slides Linuxtag2007 (English)smancke
 
CollabSphere 2021 - DEV114 - The Nuts and Bolts of CI/CD With a Large XPages ...
CollabSphere 2021 - DEV114 - The Nuts and Bolts of CI/CD With a Large XPages ...CollabSphere 2021 - DEV114 - The Nuts and Bolts of CI/CD With a Large XPages ...
CollabSphere 2021 - DEV114 - The Nuts and Bolts of CI/CD With a Large XPages ...Jesse Gallagher
 
An Introduction to Websphere sMash for PHP Programmers
An Introduction to Websphere sMash for PHP ProgrammersAn Introduction to Websphere sMash for PHP Programmers
An Introduction to Websphere sMash for PHP Programmersjphl
 
Java dev mar_2021_keynote
Java dev mar_2021_keynoteJava dev mar_2021_keynote
Java dev mar_2021_keynoteSuyash Joshi
 

Similar to Panama.pdf (20)

Java 7 & 8 - A&BP CC
Java 7 & 8 - A&BP CCJava 7 & 8 - A&BP CC
Java 7 & 8 - A&BP CC
 
Java Basic PART I
Java Basic PART IJava Basic PART I
Java Basic PART I
 
What's new in Java 11
What's new in Java 11What's new in Java 11
What's new in Java 11
 
Java basic
Java basicJava basic
Java basic
 
Java On Speed
Java On SpeedJava On Speed
Java On Speed
 
Breaking The Clustering Limits @ AlphaCSP JavaEdge 2007
Breaking The Clustering Limits @ AlphaCSP JavaEdge 2007Breaking The Clustering Limits @ AlphaCSP JavaEdge 2007
Breaking The Clustering Limits @ AlphaCSP JavaEdge 2007
 
Java Core | Modern Java Concurrency | Martijn Verburg & Ben Evans
Java Core | Modern Java Concurrency | Martijn Verburg & Ben EvansJava Core | Modern Java Concurrency | Martijn Verburg & Ben Evans
Java Core | Modern Java Concurrency | Martijn Verburg & Ben Evans
 
An Introduction to Java Compiler and Runtime
An Introduction to Java Compiler and RuntimeAn Introduction to Java Compiler and Runtime
An Introduction to Java Compiler and Runtime
 
It pro dev_birbilis_20101127_en
It pro dev_birbilis_20101127_enIt pro dev_birbilis_20101127_en
It pro dev_birbilis_20101127_en
 
Introduction of Java 8 with emphasis on Lambda Expressions and Streams
Introduction of Java 8 with emphasis on Lambda Expressions and StreamsIntroduction of Java 8 with emphasis on Lambda Expressions and Streams
Introduction of Java 8 with emphasis on Lambda Expressions and Streams
 
Java 9 features
Java 9 featuresJava 9 features
Java 9 features
 
Introduction to Apache Beam
Introduction to Apache BeamIntroduction to Apache Beam
Introduction to Apache Beam
 
Laurens Van Den Oever Xopus Presentation
Laurens Van Den Oever Xopus PresentationLaurens Van Den Oever Xopus Presentation
Laurens Van Den Oever Xopus Presentation
 
Jalimo Slides Linuxtag2007 (English)
Jalimo Slides Linuxtag2007 (English)Jalimo Slides Linuxtag2007 (English)
Jalimo Slides Linuxtag2007 (English)
 
CollabSphere 2021 - DEV114 - The Nuts and Bolts of CI/CD With a Large XPages ...
CollabSphere 2021 - DEV114 - The Nuts and Bolts of CI/CD With a Large XPages ...CollabSphere 2021 - DEV114 - The Nuts and Bolts of CI/CD With a Large XPages ...
CollabSphere 2021 - DEV114 - The Nuts and Bolts of CI/CD With a Large XPages ...
 
An Introduction to Websphere sMash for PHP Programmers
An Introduction to Websphere sMash for PHP ProgrammersAn Introduction to Websphere sMash for PHP Programmers
An Introduction to Websphere sMash for PHP Programmers
 
Java EE 6 & Spring: A Lover's Quarrel
Java EE 6 & Spring: A Lover's QuarrelJava EE 6 & Spring: A Lover's Quarrel
Java EE 6 & Spring: A Lover's Quarrel
 
Hackingtomcat
HackingtomcatHackingtomcat
Hackingtomcat
 
Hacking Tomcat
Hacking TomcatHacking Tomcat
Hacking Tomcat
 
Java dev mar_2021_keynote
Java dev mar_2021_keynoteJava dev mar_2021_keynote
Java dev mar_2021_keynote
 

More from Jean-Frederic Clere

03_clere-HTTP2 HTTP3 the State of the Art in Our Servers.pdf
03_clere-HTTP2 HTTP3 the State of the Art in Our Servers.pdf03_clere-HTTP2 HTTP3 the State of the Art in Our Servers.pdf
03_clere-HTTP2 HTTP3 the State of the Art in Our Servers.pdfJean-Frederic Clere
 
03_clere_Proxing to tomcat with httpd.pdf
03_clere_Proxing to tomcat with httpd.pdf03_clere_Proxing to tomcat with httpd.pdf
03_clere_Proxing to tomcat with httpd.pdfJean-Frederic Clere
 
01_clere_Having fun with a solar panel, camera and raspberry. How with a few ...
01_clere_Having fun with a solar panel, camera and raspberry. How with a few ...01_clere_Having fun with a solar panel, camera and raspberry. How with a few ...
01_clere_Having fun with a solar panel, camera and raspberry. How with a few ...Jean-Frederic Clere
 
Apache Httpd and TLS certificates validations
Apache Httpd and TLS certificates validationsApache Httpd and TLS certificates validations
Apache Httpd and TLS certificates validationsJean-Frederic Clere
 
HTTP/2, HTTP/3 and SSL/TLS State of the Art in Our Servers
HTTP/2, HTTP/3 and SSL/TLS State of the Art in Our ServersHTTP/2, HTTP/3 and SSL/TLS State of the Art in Our Servers
HTTP/2, HTTP/3 and SSL/TLS State of the Art in Our ServersJean-Frederic Clere
 
Apache httpd reverse proxy and Tomcat
Apache httpd reverse proxy and TomcatApache httpd reverse proxy and Tomcat
Apache httpd reverse proxy and TomcatJean-Frederic Clere
 
Apache httpd and TLS/SSL certificates validation
Apache httpd and TLS/SSL certificates validationApache httpd and TLS/SSL certificates validation
Apache httpd and TLS/SSL certificates validationJean-Frederic Clere
 
TomcatCon: from a cluster to the cloud
TomcatCon: from a cluster to the cloudTomcatCon: from a cluster to the cloud
TomcatCon: from a cluster to the cloudJean-Frederic Clere
 
Tomcat from a cluster to the cloud on RP3
Tomcat from a cluster to the cloud on RP3Tomcat from a cluster to the cloud on RP3
Tomcat from a cluster to the cloud on RP3Jean-Frederic Clere
 
Having fun with Raspberry(s) and Apache projects
Having fun with Raspberry(s) and Apache projectsHaving fun with Raspberry(s) and Apache projects
Having fun with Raspberry(s) and Apache projectsJean-Frederic Clere
 
Having fun with Raspberry and Apache projects
Having fun with Raspberry and Apache projectsHaving fun with Raspberry and Apache projects
Having fun with Raspberry and Apache projectsJean-Frederic Clere
 
HTTP/2 and SSL/TLS state of art in ASF servers
HTTP/2 and SSL/TLS state of art in ASF serversHTTP/2 and SSL/TLS state of art in ASF servers
HTTP/2 and SSL/TLS state of art in ASF serversJean-Frederic Clere
 

More from Jean-Frederic Clere (20)

03_clere-HTTP2 HTTP3 the State of the Art in Our Servers.pdf
03_clere-HTTP2 HTTP3 the State of the Art in Our Servers.pdf03_clere-HTTP2 HTTP3 the State of the Art in Our Servers.pdf
03_clere-HTTP2 HTTP3 the State of the Art in Our Servers.pdf
 
03_clere_Proxing to tomcat with httpd.pdf
03_clere_Proxing to tomcat with httpd.pdf03_clere_Proxing to tomcat with httpd.pdf
03_clere_Proxing to tomcat with httpd.pdf
 
01_clere_Having fun with a solar panel, camera and raspberry. How with a few ...
01_clere_Having fun with a solar panel, camera and raspberry. How with a few ...01_clere_Having fun with a solar panel, camera and raspberry. How with a few ...
01_clere_Having fun with a solar panel, camera and raspberry. How with a few ...
 
Apache Httpd and TLS certificates validations
Apache Httpd and TLS certificates validationsApache Httpd and TLS certificates validations
Apache Httpd and TLS certificates validations
 
Cloud RPI4 tomcat ARM64
Cloud RPI4 tomcat ARM64Cloud RPI4 tomcat ARM64
Cloud RPI4 tomcat ARM64
 
From a cluster to the Cloud
From a cluster to the CloudFrom a cluster to the Cloud
From a cluster to the Cloud
 
HTTP/2, HTTP/3 and SSL/TLS State of the Art in Our Servers
HTTP/2, HTTP/3 and SSL/TLS State of the Art in Our ServersHTTP/2, HTTP/3 and SSL/TLS State of the Art in Our Servers
HTTP/2, HTTP/3 and SSL/TLS State of the Art in Our Servers
 
Apache httpd reverse proxy and Tomcat
Apache httpd reverse proxy and TomcatApache httpd reverse proxy and Tomcat
Apache httpd reverse proxy and Tomcat
 
Apache httpd and TLS/SSL certificates validation
Apache httpd and TLS/SSL certificates validationApache httpd and TLS/SSL certificates validation
Apache httpd and TLS/SSL certificates validation
 
Juggva cloud
Juggva cloudJuggva cloud
Juggva cloud
 
TomcatCon: from a cluster to the cloud
TomcatCon: from a cluster to the cloudTomcatCon: from a cluster to the cloud
TomcatCon: from a cluster to the cloud
 
Tomcat from a cluster to the cloud on RP3
Tomcat from a cluster to the cloud on RP3Tomcat from a cluster to the cloud on RP3
Tomcat from a cluster to the cloud on RP3
 
Having fun with Raspberry(s) and Apache projects
Having fun with Raspberry(s) and Apache projectsHaving fun with Raspberry(s) and Apache projects
Having fun with Raspberry(s) and Apache projects
 
Tomcat openssl
Tomcat opensslTomcat openssl
Tomcat openssl
 
Tomcat next
Tomcat nextTomcat next
Tomcat next
 
Having fun with Raspberry and Apache projects
Having fun with Raspberry and Apache projectsHaving fun with Raspberry and Apache projects
Having fun with Raspberry and Apache projects
 
HTTP/2 and SSL/TLS state of art in ASF servers
HTTP/2 and SSL/TLS state of art in ASF serversHTTP/2 and SSL/TLS state of art in ASF servers
HTTP/2 and SSL/TLS state of art in ASF servers
 
Tomcat next
Tomcat nextTomcat next
Tomcat next
 
Native 1.2.8
Native 1.2.8Native 1.2.8
Native 1.2.8
 
Tomcat openssl
Tomcat opensslTomcat openssl
Tomcat openssl
 

Recently uploaded

Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfPower Karaoke
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptkotipi9215
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
XpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software SolutionsXpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software SolutionsMehedi Hasan Shohan
 
buds n tech IT solutions
buds n  tech IT                solutionsbuds n  tech IT                solutions
buds n tech IT solutionsmonugehlot87
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...soniya singh
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataBradBedford3
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfjoe51371421
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...gurkirankumar98700
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideChristina Lin
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWave PLM
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxTier1 app
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfkalichargn70th171
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEOrtus Solutions, Corp
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)OPEN KNOWLEDGE GmbH
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio, Inc.
 

Recently uploaded (20)

Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdf
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.ppt
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
XpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software SolutionsXpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software Solutions
 
buds n tech IT solutions
buds n  tech IT                solutionsbuds n  tech IT                solutions
buds n tech IT solutions
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdf
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need It
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
 

Panama.pdf

  • 1. Panama: A case study With OpenSSL and Apache Tomcat TM
  • 2. Jean-Frederic Clere Software engineer at Red Hat Working on HTTPD and Tomcat (JBCS/JWS) Apache Tomcat committer for years ASF member
  • 3. Contents Panama basics OpenSSL and Tomcat Tooling Design Challenges Results
  • 5. The Panama project “foreign function and memory API” Project developed by Oracle for inclusion in java.base Replacement for JNI Improve safety and reliability Better management of native memory Replacement for various Unsafe based hacks Incubating and JEPs since Java 14 Java code Native code
  • 6. ResourceScope/MemorySession/Arena Handles native access lifecycle Allocations and deallocations Explicit close or GC close
  • 7. MemorySegment The main API in Java 21 (previously also MemoryAddress and Addressable) Native or heap memory, with associated segment size Basically a pointer Tied to an associated session Does size and lifecycle checks -> safety
  • 8. Memory layouts and native types Allows modelling types and structures Simple types are easy Valhalla will provide support for additional types (Vectors)
  • 9. Function descriptors and Method handles FunctionDescriptor API allows describing the native calls to the JVM Associate a native function to a matching method handle Use the Linker API for that
  • 10. Downcalls Calls from Java to native Use lookup to get the native symbol Use the linker to get the method handle Simply call the method handle with the right arguments
  • 11. Downcall example System.loadLibrary("ssl"); MemorySegment OpenSSL_versionSymbol = SymbolLookup.loaderLookup().find("OpenSSL_version").orElseThrow(); MethodHandle OpenSSL_version = Linker.nativeLinker().downcallHandle(OpenSSL_versionSymbol, FunctionDescriptor.of(ValueLayout.ADDRESS, ValueLayout.JAVA_INT)); MemorySegment version = (MemorySegment) OpenSSL_version.invokeExact(0); MemorySegment ptr = version.reinterpret(128); String sversion = ptr.getUtf8String(0);
  • 12. Demo
  • 13. Upcalls Calls from native to Java Get a method handle from your Java method The linker gives a memory segment containing a function pointer Call the appropriate native downcall to set the function pointer
  • 14. Upcall example part 1 Arena arena = Arena.ofConfined(); MemorySegment nativeString = arena.allocateUtf8String("Hello World! Panama style"); System.loadLibrary("hex"); SymbolLookup mylib = SymbolLookup.libraryLookup("libhex.so", arena); Linker cLinker = Linker.nativeLinker(); MethodHandle doconvert = cLinker.downcallHandle(mylib.find("doconvert").orElseThrow(), FunctionDescriptor.of(ValueLayout.JAVA_INT, AddressLayout.ADDRESS));
  • 15. Upcall example part 2 FunctionDescriptor desc = FunctionDescriptor.of(ValueLayout.JAVA_INT, AddressLayout.ADDRESS); MethodHandle set_add_cb = cLinker.downcallHandle(mylib.find("set_add_cb").orElseThrow(), desc); FunctionDescriptor jfcconvertdesc = FunctionDescriptor.of(ValueLayout.JAVA_INT, AddressLayout.ADDRESS); MethodHandle jfcconvert = MethodHandles.lookup().findStatic(Hex.class, "jfcconvert", MethodType.methodType(int.class, MemorySegment.class)); MemorySegment call = Linker.nativeLinker().upcallStub(jfcconvert, jfcconvertdesc, arena); set_add_cb.invoke(call); len = (int) doconvert.invoke(nativeString);
  • 16. Upcall example part 3 (the java method that is called) public static int jfcconvert(MemorySegment mem) { MemorySegment ptr = mem.reinterpret(128); String string = ptr.getUtf8String(0); string = jfcconvert(string); ptr.setUtf8String(0, string); return 0; }
  • 17. Demo
  • 18. OpenSSL Upcall example FunctionDescriptor openSSLCallbackVerifyFunctionDescriptor = FunctionDescriptor.of(ValueLayout.JAVA_INT, ValueLayout.JAVA_INT, ValueLayout.ADDRESS); /* typedef int (*SSL_verify_cb)(int preverify_ok, X509_STORE_CTX *x509_ctx); */ MethodHandle openSSLCallbackVerifyHandle = MethodHandles.lookup().findStatic(OpenSSLEngine.class, "openSSLCallbackVerify", MethodType.methodType(int.class, int.class, MemorySegment.class)); MethodHandle SSL_CTX_set_verify = …; // The OpenSSL downcall to set the function pointer var openSSLCallbackVerify = Linker.nativeLinker().upcallStub(openSSLCallbackVerifyHandle, openSSLCallbackVerifyFunctionDescriptor, engineArena); SSL_CTX_set_verify(state.sslCtx, /* int */ validationMode, openSSLCallbackVerify);
  • 20. All things TLS Everything Even more later Extremely useful to Tomcat
  • 21. Tomcat needs TLS 1.3 with PHA (post handshake authentication) More key formats, ciphers, protocols as they are appear Better performance High level API for QUIC
  • 22. Also used through Tomcat-native Legacy code (java connector, C dynamic library linked with openssl). Modernized and cleaned up with 2.0 Some platforms need static linking of OpenSSL (= CVEs !) Productization needed Cloud annoyances
  • 23. OpenSSL API style Factories and destructors for everything Accessors and setters for everything No need to model structures in Panama Many callbacks needed
  • 25. Jextract Helps write boilerplate code, handle library updates Upcalls Downcalls Structures Helps track Panama API changes across Java versions
  • 26. Using jextract Now easier to build from https://github.com/openjdk/jextract (or download it) Uses native library headers Generates sources or classes Skips functional macros Big library means huge very verbose blob
  • 27. Trimming down the blob List native APIs actually used Limit jextract to these APIs Time consuming …
  • 28. Using jextract ● With OpenSSL ● Config file
  • 30. Java code we had Working OpenSSL implementation for JSSE (not a full provider but close) Rather well tested Support for OpenSSL 3.x Significant amount of Java code using a thinner native API (compared to APR connector)
  • 31. Tomcat-native code Needs translation to Java code using Panama Then integrate into the Tomcat OpenSSL code Lots of wrapper code, needless structures and state tracking Problem: large amount of logic inside the JNI layer in some places (certs handling, init, OCSP)
  • 32. Lifecycle and Memory management Was already appropriate for Panama Needs to remain GC based for safety
  • 33. Process Generate the full OpenSSL API with jextract Write OpenSSL init code and test out Panama Translate the rest of the tomcat-native code into the existing Java classes Add state tracking for upcalls Test, fix, improve, test, fix, improve, etc
  • 35. No #ifdef and precompiler This is bad for us Also no functional macros support Have to target real API functions Of course there are tons macros and real API are often hidden in OpenSSL
  • 36. OpenSSL API compatibility Initial target was 1.1 API changes in 3.0, resolved by macros (which don't work with Panama) Manual downcall declarations needed, with runtime version check Extensive API changes would need a fully separate implementation For example, support of LibreSSL and others are not doable as part of the same module
  • 37. Memory leaks are easy OpenSSL structures need cleanup Memory segments point to the session Bound downcalls unfortunately pins the session
  • 38. API changes Java 17 is the first LTS release with the incubating Panama (JEP 412) Some changes in Java 18 (JEP 419) Same in Java 19, moving to preview status (--enable-preview is enough) (JEP 424) Same in Java 20, still preview, heavy API changes Java 21 LTS was the target for the stable API but still preview
  • 39. Java 17 Needs scary command line arguments (users will panic) API is less refined than current Functionally equivalent for us Panama seems surprisingly stable Ok for in house projects that cannot wait for Java 21, not ok for real productization
  • 40. Java 21… Still Needs scary command line arguments (users will panic) API is less refined than current Functionally equivalent for us Panama seems surprisingly stable Ok for in house projects that cannot wait for Java 22, not ok for real productization
  • 41. Instability Instability when initially trying with Java 18 Mysterious behaviors, debugging was inconclusive Had to report to the Panama team Was caused by stack corruption with (lots of) upcalls Thankfully fixed
  • 42. Updating to a new Java Monitor Panama API changes in openjdk/panama-foreign and evaluate impact Code merge into next Java openjdk/jdk Wait for jextract updates to target new API (needed for a large library like OpenSSL) Migrate and test !
  • 43. MemoryAddress removal in Java 20 Was simply a long, so now the hacks will be easy to spot again ! Must use MemorySegment for everything, which references its associated session Good since it holds a reference to the session, so safer But cleanup tasks on session close must hold on a long or a segment from another session Refactoring ahead !
  • 45. It worked ! Surprisingly stable on Java 17 Fast enough on Java 17 Works out of the box if OpenSSL is a system library With new Java versions, only "--enable-preview" needed (with startup warnings)
  • 46. Needs to have multiple branches Many API differences with each JEP https://github.com/apache/tomcat/tree/main/modules/openssl-foreign : Tracks the Panama API (Java "22" right now, hopefully final API in Java xx), support for OpenSSL 1.1 and 3.0 https://github.com/apache/tomcat/tree/main/modules/openssl-java21 : Frozen for Java 21, support for OpenSSL 1.1 and 3.0, "stable" https://github.com/apache/tomcat/tree/main/modules/openssl-java17 : Frozen for Java 17, support for OpenSSL 1.1 and 3.0, "stable"
  • 47. Performance A bit over 10% slower than JNI across Java 17 and 18 Custom Java 19 builds were about 5% slower Probably not a glitch since all other testing results was unchanged
  • 50. Roadmap to stable Good performance already with safer code Still preview in Java 21 (09/2023) Will then be integrated into Tomcat's source tree and ready to use Work out of the box on Java 22? tomcat-native will be maintained for a long time (after Java 21 so after Tomcat 11.0.x)