Skip to content

Commit

Permalink
only free native WOLFSSL_X509 in WolfSSLCertificate if we own the poi…
Browse files Browse the repository at this point in the history
…nter/memory
  • Loading branch information
cconlon committed Dec 21, 2022
1 parent f0606c3 commit aa0893d
Showing 1 changed file with 25 additions and 2 deletions.
27 changes: 25 additions & 2 deletions src/java/com/wolfssl/WolfSSLCertificate.java
Original file line number Diff line number Diff line change
Expand Up @@ -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();

Expand Down Expand Up @@ -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;
}
Expand Down Expand Up @@ -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;
}
Expand All @@ -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;
}
Expand Down Expand Up @@ -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;
}
Expand All @@ -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;
}
Expand Down Expand Up @@ -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;
Expand Down

0 comments on commit aa0893d

Please sign in to comment.