================
@@ -0,0 +1,285 @@
+// RUN: %check_clang_tidy %s bugprone-unsafe-format-string %t -- -- -I
%S/../Inputs/Headers/std
+
+#include "system-header-simulator.h"
+
+void test_sprintf() {
+ char buffer[100];
+ const char* input = "user input";
+ const wchar_t* winput = L"wide user input";
+
+
+ /* 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]
+
+ /* 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]
+
+ /* 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]
+
+ /*precision limits string length */
+ sprintf(buffer, "%.99s", input);
+
+ /*precision with field width */
+ sprintf(buffer, "%1.99s", input);
+
+ /*dynamic precision */
+ sprintf(buffer, "%.*s", 99, input);
+
+ /*field width with dynamic precision */
+ sprintf(buffer, "%1.*s", 99, input);
+
+ /*dynamic field width with fixed precision */
+ sprintf(buffer, "%*.99s", 10, input);
+
+ /*dynamic field width and precision */
+ sprintf(buffer, "%*.*s", 10, 99, input);
+
+ /*limit is taken as 0*/
+ sprintf(buffer, "%.s", 99, input);
+
+ /*limit is taken as 0*/
+ sprintf(buffer, "%.1ls", winput);
+
+ /*other format specifiers are safe */
+ sprintf(buffer, "%d %f", 42, 3.14);
----------------
NagyDonat wrote:
```suggestion
/*other format specifiers are safe, literal 's' following them is ignored */
sprintf(buffer, "%ds %fs", 42, 3.14);
```
Let's reuse this test to check one more thing.
https://github.com/llvm/llvm-project/pull/168691
_______________________________________________
cfe-commits mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits