Fix cJSON_print using wrong allocation scope
authorCharles Giessen <charles@lunarg.com>
Sun, 14 May 2023 04:33:18 +0000 (22:33 -0600)
committerCharles Giessen <46324611+charles-lunarg@users.noreply.github.com>
Mon, 29 May 2023 23:45:08 +0000 (17:45 -0600)
Because cJSON_print uses cJSON_malloc, it meant that all calls to cJSON_print
used the command allocation scope. With the change to directly store the strings
returned by cJSON, this meant that various strings were being stored in the
instance that were not allocated with the instance scope. This fixes that.

This commit also adds a safeguard to ensure the cJSON object is cleaned up if
loader_get_json fails

loader/cJSON.c

index 741cc7d..3e7aafe 100644 (file)
@@ -44,6 +44,10 @@ void *cJSON_malloc(const VkAllocationCallbacks *pAllocator, size_t size) {
     return loader_alloc(pAllocator, size, VK_SYSTEM_ALLOCATION_SCOPE_COMMAND);
 }
 
+void *cJSON_malloc_instance_scope(const VkAllocationCallbacks *pAllocator, size_t size) {
+    return loader_alloc(pAllocator, size, VK_SYSTEM_ALLOCATION_SCOPE_INSTANCE);
+}
+
 void cJSON_Free(const VkAllocationCallbacks *pAllocator, void *pMemory) { loader_free(pAllocator, pMemory); }
 
 /*
@@ -353,7 +357,7 @@ char *print_string_ptr(const VkAllocationCallbacks *pAllocator, const char *str,
         if (p)
             out = ensure(pAllocator, p, out_buf_size);
         else
-            out = (char *)cJSON_malloc(pAllocator, out_buf_size);
+            out = (char *)cJSON_malloc_instance_scope(pAllocator, out_buf_size);
         if (!out) return 0;
         ptr2 = out;
         // *ptr2++ = '\"'; // Modified to not put quotes around the string
@@ -368,7 +372,7 @@ char *print_string_ptr(const VkAllocationCallbacks *pAllocator, const char *str,
         if (p)
             out = ensure(pAllocator, p, out_buf_size);
         else
-            out = (char *)cJSON_malloc(pAllocator, out_buf_size);
+            out = (char *)cJSON_malloc_instance_scope(pAllocator, out_buf_size);
         if (!out) return 0;
         strcpy(out, "\"\"");
         return out;
@@ -389,7 +393,7 @@ char *print_string_ptr(const VkAllocationCallbacks *pAllocator, const char *str,
     if (p)
         out = ensure(pAllocator, p, out_buf_size);
     else
-        out = (char *)cJSON_malloc(pAllocator, out_buf_size);
+        out = (char *)cJSON_malloc_instance_scope(pAllocator, out_buf_size);
     if (!out) return 0;
 
     ptr2 = out;
@@ -1293,6 +1297,10 @@ out:
     if (NULL != file) {
         fclose(file);
     }
+    if (res != VK_SUCCESS && *json != NULL) {
+        cJSON_Delete(*json);
+        *json = NULL;
+    }
 
     return res;
 }