================
@@ -0,0 +1,261 @@
+// RUN: %check_clang_tidy %s bugprone-unsafe-format-string %t -- -- -isystem 
%S/Inputs/unsafe-format-string
+
+#include <system-header-simulator.h>
+
+void test_sprintf() {
+  char buffer[100];
+  const char* input = "user input";
+
+  /* Positive: unsafe %s without field width */
+  sprintf(buffer, "%s", input);
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: format specifier '%s' without 
precision may cause buffer overflow; consider using '%.Ns' where N limits 
output length [bugprone-unsafe-format-string]
+
+  /* Positive: field width doesn't prevent overflow in sprintf */
+  sprintf(buffer, "%99s", input);
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: format specifier '%s' without 
precision may cause buffer overflow; consider using '%.Ns' where N limits 
output length [bugprone-unsafe-format-string]
+
+  /* Positive: dynamic field width doesn't prevent overflow */
+  sprintf(buffer, "%*s", 10, input);
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: format specifier '%s' without 
precision may cause buffer overflow; consider using '%.Ns' where N limits 
output length [bugprone-unsafe-format-string]
+
+  /*Negative: precision limits string length */
+  sprintf(buffer, "%.99s", input);
+  /* no-warning */
+
+  /*Negative: precision with field width */
+  sprintf(buffer, "%1.99s", input);
+  /* no-warning */
+
+  /*Negative: dynamic precision */
+  sprintf(buffer, "%.*s", 99, input);
+  /* no-warning */
+
+  /*Negative: field width with dynamic precision */
+  sprintf(buffer, "%1.*s", 99, input);
+  /* no-warning */
+
+  /*Negative: dynamic field width with fixed precision */
+  sprintf(buffer, "%*.99s", 10, input);
+  /* no-warning */
+
+  /*Negative: dynamic field width and precision */
+  sprintf(buffer, "%*.*s", 10, 99, input);
+  /* no-warning */
+
+  /*Negative: other format specifiers are safe */
+  sprintf(buffer, "%d %f", 42, 3.14);
+  /* no-warning */
+}
+
+void test_vsprintf() {
+  char buffer[100];
+  va_list args;
+
+  /* Positive: unsafe %s without field width */
+  vsprintf(buffer, "%s", args);
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: format specifier '%s' without 
precision may cause buffer overflow; consider using '%.Ns' where N limits 
output length [bugprone-unsafe-format-string]
+
+  /* Positive: field width doesn't prevent overflow in vsprintf */
+  vsprintf(buffer, "%99s", args);
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: format specifier '%s' without 
precision may cause buffer overflow; consider using '%.Ns' where N limits 
output length [bugprone-unsafe-format-string]
+
+  /* Positive: precision limits string length */
----------------
zwuis wrote:

Positive?

https://github.com/llvm/llvm-project/pull/168691
_______________________________________________
cfe-commits mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits

Reply via email to