]> git.proxmox.com Git - mirror_edk2.git/blobdiff - ShellPkg/Library/UefiShellDebug1CommandsLib/HexEdit/FileImage.c
ShellPkg/hexedit: Fix a read-after-free bug
[mirror_edk2.git] / ShellPkg / Library / UefiShellDebug1CommandsLib / HexEdit / FileImage.c
index ff3819c6c61aac604acc3230c73697dd9868a8c7..d9fd72cdd2eea475172cab7a46969b603dc6a7b8 100644 (file)
@@ -1,7 +1,7 @@
 /** @file\r
   Functions to deal with file buffer.\r
 \r
-  Copyright (c) 2005 - 2011, Intel Corporation. All rights reserved. <BR>\r
+  Copyright (c) 2005 - 2018, Intel Corporation. All rights reserved. <BR>\r
   This program and the accompanying materials\r
   are licensed and made available under the terms and conditions of the BSD License\r
   which accompanies this distribution.  The full text of the license may be found at\r
@@ -110,27 +110,22 @@ HFileImageSetFileName (
   IN CONST CHAR16 *Str\r
   )\r
 {\r
-  UINTN Size;\r
-  UINTN Index;\r
-\r
+  if (Str == HFileImage.FileName) {\r
+    //\r
+    // This function might be called using HFileImage.FileName as Str.\r
+    // Directly return without updating HFileImage.FileName.\r
+    //\r
+    return EFI_SUCCESS;\r
+  }\r
   //\r
   // free the old file name\r
   //\r
   SHELL_FREE_NON_NULL (HFileImage.FileName);\r
-\r
-  Size                = StrLen (Str);\r
-\r
-  HFileImage.FileName = AllocateZeroPool (2 * (Size + 1));\r
+  HFileImage.FileName = AllocateCopyPool (StrSize (Str), Str);\r
   if (HFileImage.FileName == NULL) {\r
     return EFI_OUT_OF_RESOURCES;\r
   }\r
 \r
-  for (Index = 0; Index < Size; Index++) {\r
-    HFileImage.FileName[Index] = Str[Index];\r
-  }\r
-\r
-  HFileImage.FileName[Size] = L'\0';\r
-\r
   return EFI_SUCCESS;\r
 }\r
 \r
@@ -169,8 +164,11 @@ HFileImageRead (
   // you should set the status string\r
   //\r
   Status = ReadFileIntoBuffer (FileName, (VOID**)&Buffer, &HFileImage.Size, &HFileImage.ReadOnly);\r
-  if (EFI_ERROR(Status) || Buffer == NULL) {\r
-    UnicodeBuffer = CatSPrint(NULL, L"Read error on file &s: %r", FileName, Status);\r
+  //\r
+  // NULL pointer is only also a failure for a non-zero file size.\r
+  //\r
+  if ((EFI_ERROR(Status)) || (Buffer == NULL && HFileImage.Size != 0)) {\r
+    UnicodeBuffer = CatSPrint(NULL, L"Read error on file %s: %r", FileName, Status);\r
     if (UnicodeBuffer == NULL) {\r
       SHELL_FREE_NON_NULL(Buffer);\r
       return EFI_OUT_OF_RESOURCES;\r