pef: sanity check before malloc

Message ID Y1yxxfpJz+Jx4KTh@squeak.grove.modra.org
State Repeat Merge
Headers
Series pef: sanity check before malloc |

Checks

Context Check Description
snail/binutils-gdb-check warning Git am fail log

Commit Message

Alan Modra Oct. 29, 2022, 4:53 a.m. UTC
  And do the sanity check in a way that can't overflow.

	* pef.c (bfd_pef_parse_function_stubs): Sanity check header
	imported_library_count and total_imported_symbol_count before
	allocating memory.
  

Patch

diff --git a/bfd/pef.c b/bfd/pef.c
index d9936f750c1..334d802eb75 100644
--- a/bfd/pef.c
+++ b/bfd/pef.c
@@ -751,6 +751,13 @@  bfd_pef_parse_function_stubs (bfd *abfd,
   if (ret < 0)
     goto error;
 
+  if ((loaderlen - 56) / 24 < header.imported_library_count)
+    goto error;
+
+  if ((loaderlen - 56 - header.imported_library_count * 24) / 4
+      < header.total_imported_symbol_count)
+    goto error;
+
   libraries = bfd_malloc
     (header.imported_library_count * sizeof (bfd_pef_imported_library));
   imports = bfd_malloc
@@ -758,8 +765,6 @@  bfd_pef_parse_function_stubs (bfd *abfd,
   if (libraries == NULL || imports == NULL)
     goto error;
 
-  if (loaderlen < (56 + (header.imported_library_count * 24)))
-    goto error;
   for (i = 0; i < header.imported_library_count; i++)
     {
       ret = bfd_pef_parse_imported_library
@@ -768,9 +773,6 @@  bfd_pef_parse_function_stubs (bfd *abfd,
 	goto error;
     }
 
-  if (loaderlen < (56 + (header.imported_library_count * 24)
-		   + (header.total_imported_symbol_count * 4)))
-    goto error;
   for (i = 0; i < header.total_imported_symbol_count; i++)
     {
       ret = (bfd_pef_parse_imported_symbol