format-strings-scanf.c revision 6fcd932dfd6835f70cc00d6f7c6789793f6d7b66
1// RUN: %clang_cc1 -fsyntax-only -verify -Wformat-nonliteral %s
2
3typedef __typeof(sizeof(int)) size_t;
4typedef struct _FILE FILE;
5typedef __WCHAR_TYPE__ wchar_t;
6
7int fscanf(FILE * restrict, const char * restrict, ...) ;
8int scanf(const char * restrict, ...) ;
9int sscanf(const char * restrict, const char * restrict, ...) ;
10
11void test(const char *s, int *i) {
12  scanf(s, i); // expected-warning{{ormat string is not a string literal}}
13  scanf("%0d", i); // expected-warning{{zero field width in scanf format string is unused}}
14  scanf("%00d", i); // expected-warning{{zero field width in scanf format string is unused}}
15  scanf("%d%[asdfasdfd", i, s); // expected-warning{{no closing ']' for '%[' in scanf format string}}
16
17  unsigned short s_x;
18  scanf ("%" "hu" "\n", &s_x); // no-warning
19  scanf("%y", i); // expected-warning{{invalid conversion specifier 'y'}}
20  scanf("%%"); // no-warning
21  scanf("%%%1$d", i); // no-warning
22  scanf("%1$d%%", i); // no-warning
23  scanf("%d", i, i); // expected-warning{{data argument not used by format string}}
24  scanf("%*d", i); // // expected-warning{{data argument not used by format string}}
25  scanf("%*d", i); // // expected-warning{{data argument not used by format string}}
26  scanf("%*d%1$d", i); // no-warning
27}
28
29void bad_length_modifiers(char *s, void *p, wchar_t *ws, long double *ld) {
30  scanf("%hhs", "foo"); // expected-warning{{length modifier 'hh' results in undefined behavior or no effect with 's' conversion specifier}}
31  scanf("%1$zp", &p); // expected-warning{{length modifier 'z' results in undefined behavior or no effect with 'p' conversion specifier}}
32  scanf("%ls", ws); // no-warning
33  scanf("%#.2Lf", ld); // expected-warning{{invalid conversion specifier '#'}}
34}
35
36// Test that the scanf call site is where the warning is attached.  If the
37// format string is somewhere else, point to it in a note.
38void pr9751() {
39  int *i;
40  char str[100];
41  const char kFormat1[] = "%00d"; // expected-note{{format string is defined here}}}
42  scanf(kFormat1, i); // expected-warning{{zero field width in scanf format string is unused}}
43  scanf("%00d", i); // expected-warning{{zero field width in scanf format string is unused}}
44  const char kFormat2[] = "%["; // expected-note{{format string is defined here}}}
45  scanf(kFormat2, str); // expected-warning{{no closing ']' for '%[' in scanf format string}}
46  scanf("%[", str); // expected-warning{{no closing ']' for '%[' in scanf format string}}
47}
48