Fix NewLocalRef, NewGlobalRef to handle cleared weak globals.

We were not checking for null after decoding the reference, this
meant that we incorrectly created null weak global references instead
of returning null.

Issue: 63929
Bug: 13400455

(cherry-picked from e8c48db6bb507d7fa20c78481c58c23be0045f67)

Change-Id: I9159682e6edad8f415ef8144fc13b9aedd2cceb4
diff --git a/runtime/jni_internal.cc b/runtime/jni_internal.cc
index 6a0990e..412f96e 100644
--- a/runtime/jni_internal.cc
+++ b/runtime/jni_internal.cc
@@ -831,13 +831,14 @@
   }
 
   static jobject NewGlobalRef(JNIEnv* env, jobject obj) {
-    if (obj == NULL) {
-      return NULL;
-    }
     ScopedObjectAccess soa(env);
+    Object* decoded_obj = soa.Decode<Object*>(obj);
+    // Check for null after decoding the object to handle cleared weak globals.
+    if (decoded_obj == nullptr) {
+      return nullptr;
+    }
     JavaVMExt* vm = soa.Vm();
     IndirectReferenceTable& globals = vm->globals;
-    Object* decoded_obj = soa.Decode<Object*>(obj);
     WriterMutexLock mu(soa.Self(), vm->globals_lock);
     IndirectRef ref = globals.Add(IRT_FIRST_SEGMENT, decoded_obj);
     return reinterpret_cast<jobject>(ref);
@@ -871,11 +872,13 @@
   }
 
   static jobject NewLocalRef(JNIEnv* env, jobject obj) {
-    if (obj == NULL) {
-      return NULL;
-    }
     ScopedObjectAccess soa(env);
-    return soa.AddLocalReference<jobject>(soa.Decode<Object*>(obj));
+    mirror::Object* decoded_obj = soa.Decode<Object*>(obj);
+    // Check for null after decoding the object to handle cleared weak globals.
+    if (decoded_obj == nullptr) {
+      return nullptr;
+    }
+    return soa.AddLocalReference<jobject>(decoded_obj);
   }
 
   static void DeleteLocalRef(JNIEnv* env, jobject obj) {
diff --git a/runtime/thread.cc b/runtime/thread.cc
index 23cafe8..60a3bf8 100644
--- a/runtime/thread.cc
+++ b/runtime/thread.cc
@@ -1191,7 +1191,7 @@
     result = Runtime::Current()->GetJavaVM()->DecodeWeakGlobal(const_cast<Thread*>(this), ref);
     if (result == kClearedJniWeakGlobal) {
       // This is a special case where it's okay to return NULL.
-      return NULL;
+      return nullptr;
     }
   }