use 2x buffer when sysctl fails with ENOMEM (#591)
authorTomas Weinfurt <tweinfurt@yahoo.com>
Fri, 6 Dec 2019 22:18:28 +0000 (14:18 -0800)
committerGitHub <noreply@github.com>
Fri, 6 Dec 2019 22:18:28 +0000 (14:18 -0800)
* use 2x buffer when sysctl fails with ENOMEM

* add comment to sysctl buffer logic

src/libraries/Native/Unix/System.Native/pal_interfaceaddresses.c

index 8fb4fd4..4db081d 100644 (file)
@@ -424,6 +424,22 @@ int32_t SystemNative_EnumerateGatewayAddressesForInterface(uint32_t interfaceInd
 
     while (sysctl(routeDumpName, 6, buffer, &byteCount, NULL, 0) != 0)
     {
+        if (errno != ENOMEM)
+        {
+            return -1;
+        }
+
+        // If buffer is not big enough double size to avoid calling sysctl again
+        // as byteCount only gets estimated size when passed buffer is NULL.
+        // This only happens if routing table grows between first and second call.
+        size_t tmpEstimatedSize;
+        if (!multiply_s(byteCount, (size_t)2, &tmpEstimatedSize))
+        {
+            errno = ENOMEM;
+            return -1;
+        }
+
+        byteCount = tmpEstimatedSize;
         buffer = realloc(buffer, byteCount);
         if (buffer == NULL)
         {