8187496: Possible memory leak in java.apple.security.KeychainStore.addItemToKeychain
authorigerasim
Thu, 07 Dec 2017 11:21:47 -0800
changeset 49863 4c448e31754d
parent 49862 8ee949103fb8
child 49864 1dcd0716a178
8187496: Possible memory leak in java.apple.security.KeychainStore.addItemToKeychain Reviewed-by: weijun, mullan, ahgross
src/java.base/macosx/native/libosxsecurity/KeystoreImpl.m
--- a/src/java.base/macosx/native/libosxsecurity/KeystoreImpl.m	Tue Oct 31 11:35:15 2017 -0700
+++ b/src/java.base/macosx/native/libosxsecurity/KeystoreImpl.m	Thu Dec 07 11:21:47 2017 -0800
@@ -438,12 +438,11 @@
             if (passwordChars == NULL) {
                 goto errOut;
             }
-            passwordStrRef = CFStringCreateWithCharacters(kCFAllocatorDefault, passwordChars, passwordLen);
 
-            // clear the password and release
-            memset(passwordChars, 0, passwordLen);
-            (*env)->ReleaseCharArrayElements(env, passwordObj, passwordChars,
-                JNI_ABORT);
+            passwordStrRef = CFStringCreateWithCharactersNoCopy(NULL, passwordChars, passwordLen, kCFAllocatorNull);
+            if (passwordStrRef == NULL) {
+                goto errOut;
+            }
         }
     }
 
@@ -471,7 +470,12 @@
 errOut:
     if (exportedData) CFRelease(exportedData);
     if (passwordStrRef) CFRelease(passwordStrRef);
-
+    if (passwordChars) {
+        // clear the password and release
+        memset(passwordChars, 0, passwordLen);
+        (*env)->ReleaseCharArrayElements(env, passwordObj, passwordChars,
+            JNI_ABORT);
+    }
     return returnValue;
 }
 
@@ -538,12 +542,11 @@
             if (passwordChars == NULL) {
                 goto errOut;
             }
-            passwordStrRef = CFStringCreateWithCharacters(kCFAllocatorDefault, passwordChars, passwordLen);
 
-            // clear the password and release
-            memset(passwordChars, 0, passwordLen);
-            (*env)->ReleaseCharArrayElements(env, passwordObj, passwordChars,
-                JNI_ABORT);
+            passwordStrRef = CFStringCreateWithCharactersNoCopy(NULL, passwordChars, passwordLen, kCFAllocatorNull);
+            if (passwordStrRef == NULL) {
+                goto errOut;
+            }
         }
     }
 
@@ -581,7 +584,14 @@
         CFRelease(createdItems);
     }
 
-errOut: ;
+errOut:
+    if (passwordStrRef) CFRelease(passwordStrRef);
+    if (passwordChars) {
+        // clear the password and release
+        memset(passwordChars, 0, passwordLen);
+        (*env)->ReleaseCharArrayElements(env, passwordObj, passwordChars,
+            JNI_ABORT);
+    }
 
 JNF_COCOA_EXIT(env);