[edk2] [PATCH 08/17] BaseTools/C/Common: Refine using sprintf() with '%s' in format string

Hao Wu posted 17 patches 7 years ago
[edk2] [PATCH 08/17] BaseTools/C/Common: Refine using sprintf() with '%s' in format string
Posted by Hao Wu 7 years ago
The commit removes the usages of sprintf() function calls with '%s' in
the format string. And uses strncpy/strncat instead to ensure the
destination string buffers will not be accessed beyond their boundary.

Cc: Liming Gao <liming.gao@intel.com>
Cc: Yonghong Zhu <yonghong.zhu@intel.com>
Contributed-under: TianoCore Contribution Agreement 1.1
Signed-off-by: Hao Wu <hao.a.wu@intel.com>
---
 BaseTools/Source/C/Common/EfiUtilityMsgs.c | 21 ++++++++++++---------
 1 file changed, 12 insertions(+), 9 deletions(-)

diff --git a/BaseTools/Source/C/Common/EfiUtilityMsgs.c b/BaseTools/Source/C/Common/EfiUtilityMsgs.c
index 5496a439e2..44925c642b 100644
--- a/BaseTools/Source/C/Common/EfiUtilityMsgs.c
+++ b/BaseTools/Source/C/Common/EfiUtilityMsgs.c
@@ -462,10 +462,11 @@ Notes:
                        );
     }
     if (Cptr != NULL) {
-      sprintf (Line, ": %s", Cptr);
+      strcpy (Line, ": ");
+      strncat (Line, Cptr, MAX_LINE_LEN - strlen (Line) - 1);
       if (LineNumber != 0) {
         sprintf (Line2, "(%u)", (unsigned) LineNumber);
-        strcat (Line, Line2);
+        strncat (Line, Line2, MAX_LINE_LEN - strlen (Line) - 1);
       }
     }
   } else {
@@ -476,14 +477,16 @@ Notes:
       if (mUtilityName[0] != '\0') {
         fprintf (stdout, "%s...\n", mUtilityName);
       }
-      sprintf (Line, "%s", Cptr);
+      strncpy (Line, Cptr, MAX_LINE_LEN - 1);
+      Line[MAX_LINE_LEN - 1] = 0;
       if (LineNumber != 0) {
         sprintf (Line2, "(%u)", (unsigned) LineNumber);
-        strcat (Line, Line2);
+        strncat (Line, Line2, MAX_LINE_LEN - strlen (Line) - 1);
       }
     } else {
       if (mUtilityName[0] != '\0') {
-        sprintf (Line, "%s", mUtilityName);
+        strncpy (Line, mUtilityName, MAX_LINE_LEN - 1);
+        Line[MAX_LINE_LEN - 1] = 0;
       }
     }
 
@@ -501,12 +504,12 @@ Notes:
   // Have to print an error code or Visual Studio won't find the
   // message for you. It has to be decimal digits too.
   //
+  strncat (Line, ": ", MAX_LINE_LEN - strlen (Line) - 1);
+  strncat (Line, Type, MAX_LINE_LEN - strlen (Line) - 1);
   if (MessageCode != 0) {
-    sprintf (Line2, ": %s %04u", Type, (unsigned) MessageCode);
-  } else {
-    sprintf (Line2, ": %s", Type);
+    sprintf (Line2, " %04u", (unsigned) MessageCode);
+    strncat (Line, Line2, MAX_LINE_LEN - strlen (Line) - 1);
   }
-  strcat (Line, Line2);
   fprintf (stdout, "%s", Line);
   //
   // If offending text was provided, then print it
-- 
2.12.0.windows.1

_______________________________________________
edk2-devel mailing list
edk2-devel@lists.01.org
https://lists.01.org/mailman/listinfo/edk2-devel