Merge pull request #21421 from geoffw0/wrongtypeformat

C++: Add some test cases for cpp/wrong-type-format-argument
This commit is contained in:
Geoffrey White
2026-03-19 14:25:33 +00:00
committed by GitHub
5 changed files with 43 additions and 0 deletions

View File

@@ -168,9 +168,11 @@ where
formatOtherArgType(ffc, n, expected, arg, actual) and
not actual.getUnspecifiedType().(IntegralType).getSize() = sizeof_IntType()
) and
// Exclude some cases where we're less confident the result is correct / clear / valuable
not arg.isAffectedByMacro() and
not arg.isFromUninstantiatedTemplate(_) and
not actual.stripType() instanceof ErroneousType and
not arg.getType().stripType().(RoutineType).getReturnType() instanceof ErroneousType and
not arg.(Call).mayBeFromImplicitlyDeclaredFunction() and
// Make sure that the format function definition is consistent
count(ffc.getTarget().getFormatParameterIndex()) = 1

View File

@@ -0,0 +1,4 @@
---
category: minorAnalysis
---
* Fixed an issue with the "Wrong type of arguments to formatting function" (`cpp/wrong-type-format-argument`) query causing false positive results in `build-mode: none` databases.

View File

@@ -1 +1,3 @@
| second.cpp:26:18:26:39 | ... - ... | This format specifier for type 'int' does not match the argument type 'long'. |
| second.cpp:29:18:29:39 | ... - ... | This format specifier for type 'unsigned int' does not match the argument type 'long'. |
| tests.c:7:18:7:18 | 1 | This format specifier for type 'char *' does not match the argument type 'int'. |

View File

@@ -0,0 +1,3 @@
// defines type size_t plausibly
typedef unsigned long size_t;

View File

@@ -0,0 +1,32 @@
// semmle-extractor-options: --expect_errors
int printf(const char * format, ...);
// defines type `myFunctionPointerType`, referencing `size_t`
typedef size_t (*myFunctionPointerType) ();
void test_size_t() {
size_t s = 0;
printf("%zd", s); // GOOD
printf("%zi", s); // GOOD
printf("%zu", s); // GOOD (we generally permit signedness changes)
printf("%zx", s); // GOOD (we generally permit signedness changes)
printf("%d", s); // BAD [NOT DETECTED]
printf("%ld", s); // DUBIOUS [NOT DETECTED]
printf("%lld", s); // DUBIOUS [NOT DETECTED]
printf("%u", s); // BAD [NOT DETECTED]
char buffer[1024];
printf("%zd", &buffer[1023] - buffer); // GOOD
printf("%zi", &buffer[1023] - buffer); // GOOD
printf("%zu", &buffer[1023] - buffer); // GOOD
printf("%zx", &buffer[1023] - buffer); // GOOD
printf("%d", &buffer[1023] - buffer); // BAD
printf("%ld", &buffer[1023] - buffer); // DUBIOUS [NOT DETECTED]
printf("%lld", &buffer[1023] - buffer); // DUBIOUS [NOT DETECTED]
printf("%u", &buffer[1023] - buffer); // BAD
// (for the `%ld` and `%lld` cases, the signedness and type sizes match, `%zd` would be most correct
// and robust but the developer may know enough to make this safe)
}