Fix windows_read_sorted_physical_devices buffer overrun
authorJordan Peck <jordan.me2@gmail.com>
Wed, 25 Sep 2024 16:25:54 +0000 (17:25 +0100)
committerCharles Giessen <charles@lunarg.com>
Thu, 26 Sep 2024 16:18:10 +0000 (11:18 -0500)
loader/loader_windows.c

index db493c56442021cdab901d57f2d5da09a0bac74f..df2fffc5a578a174797002995ea59a50ca75e804 100644 (file)
@@ -964,20 +964,6 @@ VkResult windows_read_sorted_physical_devices(struct loader_instance *inst, uint
             continue;
         }
 
-        if (icd_phys_devs_array_size <= i) {
-            uint32_t old_size = icd_phys_devs_array_size * sizeof(struct loader_icd_physical_devices);
-            *icd_phys_devs_array = loader_instance_heap_realloc(inst, *icd_phys_devs_array, old_size, 2 * old_size,
-                                                                VK_SYSTEM_ALLOCATION_SCOPE_COMMAND);
-            if (*icd_phys_devs_array == NULL) {
-                adapter->lpVtbl->Release(adapter);
-                res = VK_ERROR_OUT_OF_HOST_MEMORY;
-                goto out;
-            }
-            icd_phys_devs_array_size *= 2;
-        }
-        (*icd_phys_devs_array)[*icd_phys_devs_array_count].device_count = 0;
-        (*icd_phys_devs_array)[*icd_phys_devs_array_count].physical_devices = NULL;
-
         icd_term = inst->icd_terms;
         while (NULL != icd_term) {
             // This is the new behavior, which cannot be run unless the ICD provides EnumerateAdapterPhysicalDevices
@@ -986,6 +972,20 @@ VkResult windows_read_sorted_physical_devices(struct loader_instance *inst, uint
                 continue;
             }
 
+            if (icd_phys_devs_array_size <= *icd_phys_devs_array_count) {
+                uint32_t old_size = icd_phys_devs_array_size * sizeof(struct loader_icd_physical_devices);
+                *icd_phys_devs_array = loader_instance_heap_realloc(inst, *icd_phys_devs_array, old_size, 2 * old_size,
+                                                                    VK_SYSTEM_ALLOCATION_SCOPE_COMMAND);
+                if (*icd_phys_devs_array == NULL) {
+                    adapter->lpVtbl->Release(adapter);
+                    res = VK_ERROR_OUT_OF_HOST_MEMORY;
+                    goto out;
+                }
+                icd_phys_devs_array_size *= 2;
+            }
+            (*icd_phys_devs_array)[*icd_phys_devs_array_count].device_count = 0;
+            (*icd_phys_devs_array)[*icd_phys_devs_array_count].physical_devices = NULL;
+
             res = enumerate_adapter_physical_devices(inst, icd_term, description.AdapterLuid, icd_phys_devs_array_count,
                                                      *icd_phys_devs_array);
             if (res == VK_ERROR_OUT_OF_HOST_MEMORY) {