diff --git a/src/java/com/wolfssl/WolfSSLCertificate.java b/src/java/com/wolfssl/WolfSSLCertificate.java index c1a3a3ad..47ba8dbe 100644 --- a/src/java/com/wolfssl/WolfSSLCertificate.java +++ b/src/java/com/wolfssl/WolfSSLCertificate.java @@ -50,6 +50,10 @@ public class WolfSSLCertificate { private boolean active = false; private long x509Ptr = 0; + /* Does this WolfSSLCertificate own the internal WOLFSSL_X509 pointer? + * If not, don't try to free native memory on free(). */ + private boolean weOwnX509Ptr = false; + /* lock around active state */ private static final Object stateLock = new Object(); @@ -101,6 +105,9 @@ public WolfSSLCertificate(byte[] der) throws WolfSSLException { throw new WolfSSLException("Failed to create WolfSSLCertificate"); } + /* x509Ptr has been allocated natively, mark as owned */ + this.weOwnX509Ptr = true; + synchronized (stateLock) { this.active = true; } @@ -136,6 +143,9 @@ public WolfSSLCertificate(byte[] in, int format) throws WolfSSLException { throw new WolfSSLException("Failed to create WolfSSLCertificate"); } + /* x509Ptr has been allocated natively, mark as owned */ + this.weOwnX509Ptr = true; + synchronized (stateLock) { this.active = true; } @@ -161,6 +171,9 @@ public WolfSSLCertificate(String fileName) throws WolfSSLException { throw new WolfSSLException("Failed to create WolfSSLCertificate"); } + /* x509Ptr has been allocated natively, mark as owned */ + this.weOwnX509Ptr = true; + synchronized (stateLock) { this.active = true; } @@ -197,6 +210,9 @@ public WolfSSLCertificate(String fileName, int format) throw new WolfSSLException("Failed to create WolfSSLCertificate"); } + /* x509Ptr has been allocated natively, mark as owned */ + this.weOwnX509Ptr = true; + synchronized (stateLock) { this.active = true; } @@ -216,6 +232,10 @@ public WolfSSLCertificate(long x509) throws WolfSSLException { } x509Ptr = x509; + /* x509Ptr has NOT been allocated natively, do not mark as owned. + * Original owner is responsible for freeing. */ + this.weOwnX509Ptr = false; + synchronized (stateLock) { this.active = true; } @@ -698,8 +718,11 @@ public synchronized void free() throws IllegalStateException { /* set this.altNames to null so GC can free */ this.altNames = null; - /* free native resources */ - X509_free(this.x509Ptr); + /* only free native resources if we own pointer */ + if (this.weOwnX509Ptr == true) { + /* free native resources */ + X509_free(this.x509Ptr); + } /* free Java resources */ this.active = false;