Chris Lattner | 59907c4 | 2007-08-10 20:18:51 +0000 | [diff] [blame] | 1 | //===--- SemaChecking.cpp - Extra Semantic Checking -----------------------===// |
| 2 | // |
| 3 | // The LLVM Compiler Infrastructure |
| 4 | // |
| 5 | // This file was developed by Ted Kremenek and is distributed under |
| 6 | // the University of Illinois Open Source License. See LICENSE.TXT for details. |
| 7 | // |
| 8 | //===----------------------------------------------------------------------===// |
| 9 | // |
| 10 | // This file implements extra semantic analysis beyond what is enforced |
| 11 | // by the C type system. |
| 12 | // |
| 13 | //===----------------------------------------------------------------------===// |
| 14 | |
| 15 | #include "Sema.h" |
| 16 | #include "clang/AST/ASTContext.h" |
| 17 | #include "clang/AST/Decl.h" |
| 18 | #include "clang/AST/Expr.h" |
Ted Kremenek | 2324512 | 2007-08-20 16:18:38 +0000 | [diff] [blame] | 19 | #include "clang/AST/ExprCXX.h" |
Chris Lattner | 59907c4 | 2007-08-10 20:18:51 +0000 | [diff] [blame] | 20 | #include "clang/Lex/Preprocessor.h" |
| 21 | #include "clang/Lex/LiteralSupport.h" |
| 22 | #include "clang/Basic/SourceManager.h" |
| 23 | #include "clang/Basic/Diagnostic.h" |
| 24 | #include "clang/Basic/LangOptions.h" |
| 25 | #include "clang/Basic/TargetInfo.h" |
| 26 | #include "llvm/ADT/SmallString.h" |
| 27 | #include "llvm/ADT/StringExtras.h" |
Ted Kremenek | 588e5eb | 2007-11-25 00:58:00 +0000 | [diff] [blame] | 28 | #include "SemaUtil.h" |
| 29 | |
Chris Lattner | 59907c4 | 2007-08-10 20:18:51 +0000 | [diff] [blame] | 30 | using namespace clang; |
| 31 | |
| 32 | /// CheckFunctionCall - Check a direct function call for various correctness |
| 33 | /// and safety properties not strictly enforced by the C type system. |
Anders Carlsson | 71993dd | 2007-08-17 05:31:46 +0000 | [diff] [blame] | 34 | bool |
Chris Lattner | 30ce344 | 2007-12-19 23:59:04 +0000 | [diff] [blame] | 35 | Sema::CheckFunctionCall(Expr *Fn, SourceLocation RParenLoc, |
Ted Kremenek | 71895b9 | 2007-08-14 17:39:48 +0000 | [diff] [blame] | 36 | FunctionDecl *FDecl, |
Chris Lattner | 59907c4 | 2007-08-10 20:18:51 +0000 | [diff] [blame] | 37 | Expr** Args, unsigned NumArgsInCall) { |
| 38 | |
| 39 | // Get the IdentifierInfo* for the called function. |
| 40 | IdentifierInfo *FnInfo = FDecl->getIdentifier(); |
| 41 | |
Chris Lattner | 30ce344 | 2007-12-19 23:59:04 +0000 | [diff] [blame] | 42 | switch (FnInfo->getBuiltinID()) { |
| 43 | case Builtin::BI__builtin___CFStringMakeConstantString: |
Anders Carlsson | 71993dd | 2007-08-17 05:31:46 +0000 | [diff] [blame] | 44 | assert(NumArgsInCall == 1 && |
Chris Lattner | 6f4b92c | 2007-08-30 17:08:17 +0000 | [diff] [blame] | 45 | "Wrong number of arguments to builtin CFStringMakeConstantString"); |
Anders Carlsson | 71993dd | 2007-08-17 05:31:46 +0000 | [diff] [blame] | 46 | return CheckBuiltinCFStringArgument(Args[0]); |
Chris Lattner | 30ce344 | 2007-12-19 23:59:04 +0000 | [diff] [blame] | 47 | case Builtin::BI__builtin_va_start: |
| 48 | return SemaBuiltinVAStart(Fn, Args, NumArgsInCall); |
Anders Carlsson | 71993dd | 2007-08-17 05:31:46 +0000 | [diff] [blame] | 49 | } |
| 50 | |
Chris Lattner | 59907c4 | 2007-08-10 20:18:51 +0000 | [diff] [blame] | 51 | // Search the KnownFunctionIDs for the identifier. |
| 52 | unsigned i = 0, e = id_num_known_functions; |
Ted Kremenek | 71895b9 | 2007-08-14 17:39:48 +0000 | [diff] [blame] | 53 | for (; i != e; ++i) { if (KnownFunctionIDs[i] == FnInfo) break; } |
Anders Carlsson | 9cdc4d3 | 2007-08-17 15:44:17 +0000 | [diff] [blame] | 54 | if (i == e) return false; |
Chris Lattner | 59907c4 | 2007-08-10 20:18:51 +0000 | [diff] [blame] | 55 | |
| 56 | // Printf checking. |
| 57 | if (i <= id_vprintf) { |
Ted Kremenek | 71895b9 | 2007-08-14 17:39:48 +0000 | [diff] [blame] | 58 | // Retrieve the index of the format string parameter and determine |
| 59 | // if the function is passed a va_arg argument. |
Chris Lattner | 59907c4 | 2007-08-10 20:18:51 +0000 | [diff] [blame] | 60 | unsigned format_idx = 0; |
Ted Kremenek | 71895b9 | 2007-08-14 17:39:48 +0000 | [diff] [blame] | 61 | bool HasVAListArg = false; |
| 62 | |
Chris Lattner | 59907c4 | 2007-08-10 20:18:51 +0000 | [diff] [blame] | 63 | switch (i) { |
Chris Lattner | 30ce344 | 2007-12-19 23:59:04 +0000 | [diff] [blame] | 64 | default: assert(false && "No format string argument index."); |
| 65 | case id_printf: format_idx = 0; break; |
| 66 | case id_fprintf: format_idx = 1; break; |
| 67 | case id_sprintf: format_idx = 1; break; |
| 68 | case id_snprintf: format_idx = 2; break; |
| 69 | case id_asprintf: format_idx = 1; break; |
| 70 | case id_vsnprintf: format_idx = 2; HasVAListArg = true; break; |
| 71 | case id_vasprintf: format_idx = 1; HasVAListArg = true; break; |
| 72 | case id_vfprintf: format_idx = 1; HasVAListArg = true; break; |
| 73 | case id_vsprintf: format_idx = 1; HasVAListArg = true; break; |
| 74 | case id_vprintf: format_idx = 0; HasVAListArg = true; break; |
Ted Kremenek | 71895b9 | 2007-08-14 17:39:48 +0000 | [diff] [blame] | 75 | } |
| 76 | |
Chris Lattner | 30ce344 | 2007-12-19 23:59:04 +0000 | [diff] [blame] | 77 | CheckPrintfArguments(Fn, RParenLoc, HasVAListArg, |
Ted Kremenek | 06de276 | 2007-08-17 16:46:58 +0000 | [diff] [blame] | 78 | FDecl, format_idx, Args, NumArgsInCall); |
Chris Lattner | 59907c4 | 2007-08-10 20:18:51 +0000 | [diff] [blame] | 79 | } |
Anders Carlsson | 71993dd | 2007-08-17 05:31:46 +0000 | [diff] [blame] | 80 | |
Anders Carlsson | 9cdc4d3 | 2007-08-17 15:44:17 +0000 | [diff] [blame] | 81 | return false; |
Anders Carlsson | 71993dd | 2007-08-17 05:31:46 +0000 | [diff] [blame] | 82 | } |
| 83 | |
| 84 | /// CheckBuiltinCFStringArgument - Checks that the argument to the builtin |
| 85 | /// CFString constructor is correct |
Chris Lattner | cc6f65d | 2007-08-25 05:30:33 +0000 | [diff] [blame] | 86 | bool Sema::CheckBuiltinCFStringArgument(Expr* Arg) { |
Chris Lattner | 459e848 | 2007-08-25 05:36:18 +0000 | [diff] [blame] | 87 | // FIXME: This should go in a helper. |
Chris Lattner | cc6f65d | 2007-08-25 05:30:33 +0000 | [diff] [blame] | 88 | while (1) { |
| 89 | if (ParenExpr *PE = dyn_cast<ParenExpr>(Arg)) |
| 90 | Arg = PE->getSubExpr(); |
| 91 | else if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) |
| 92 | Arg = ICE->getSubExpr(); |
| 93 | else |
| 94 | break; |
| 95 | } |
Anders Carlsson | 71993dd | 2007-08-17 05:31:46 +0000 | [diff] [blame] | 96 | |
| 97 | StringLiteral *Literal = dyn_cast<StringLiteral>(Arg); |
| 98 | |
| 99 | if (!Literal || Literal->isWide()) { |
| 100 | Diag(Arg->getLocStart(), |
| 101 | diag::err_cfstring_literal_not_string_constant, |
| 102 | Arg->getSourceRange()); |
Anders Carlsson | 9cdc4d3 | 2007-08-17 15:44:17 +0000 | [diff] [blame] | 103 | return true; |
Anders Carlsson | 71993dd | 2007-08-17 05:31:46 +0000 | [diff] [blame] | 104 | } |
| 105 | |
| 106 | const char *Data = Literal->getStrData(); |
| 107 | unsigned Length = Literal->getByteLength(); |
| 108 | |
| 109 | for (unsigned i = 0; i < Length; ++i) { |
| 110 | if (!isascii(Data[i])) { |
| 111 | Diag(PP.AdvanceToTokenCharacter(Arg->getLocStart(), i + 1), |
| 112 | diag::warn_cfstring_literal_contains_non_ascii_character, |
| 113 | Arg->getSourceRange()); |
| 114 | break; |
| 115 | } |
| 116 | |
| 117 | if (!Data[i]) { |
| 118 | Diag(PP.AdvanceToTokenCharacter(Arg->getLocStart(), i + 1), |
| 119 | diag::warn_cfstring_literal_contains_nul_character, |
| 120 | Arg->getSourceRange()); |
| 121 | break; |
| 122 | } |
| 123 | } |
| 124 | |
Anders Carlsson | 9cdc4d3 | 2007-08-17 15:44:17 +0000 | [diff] [blame] | 125 | return false; |
Chris Lattner | 59907c4 | 2007-08-10 20:18:51 +0000 | [diff] [blame] | 126 | } |
| 127 | |
Chris Lattner | c27c665 | 2007-12-20 00:05:45 +0000 | [diff] [blame^] | 128 | /// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity. |
| 129 | /// Emit an error and return true on failure, return false on success. |
Chris Lattner | 30ce344 | 2007-12-19 23:59:04 +0000 | [diff] [blame] | 130 | bool Sema::SemaBuiltinVAStart(Expr *Fn, Expr** Args, unsigned NumArgs) { |
| 131 | if (NumArgs > 2) { |
| 132 | Diag(Args[2]->getLocStart(), |
| 133 | diag::err_typecheck_call_too_many_args, Fn->getSourceRange(), |
| 134 | SourceRange(Args[2]->getLocStart(), Args[NumArgs-1]->getLocEnd())); |
| 135 | return true; |
| 136 | } |
| 137 | |
Chris Lattner | c27c665 | 2007-12-20 00:05:45 +0000 | [diff] [blame^] | 138 | // Determine whether the current function is variadic or not. |
| 139 | bool isVariadic; |
Chris Lattner | 30ce344 | 2007-12-19 23:59:04 +0000 | [diff] [blame] | 140 | if (CurFunctionDecl) |
Chris Lattner | c27c665 | 2007-12-20 00:05:45 +0000 | [diff] [blame^] | 141 | isVariadic = |
| 142 | cast<FunctionTypeProto>(CurFunctionDecl->getType())->isVariadic(); |
Chris Lattner | 30ce344 | 2007-12-19 23:59:04 +0000 | [diff] [blame] | 143 | else |
Chris Lattner | c27c665 | 2007-12-20 00:05:45 +0000 | [diff] [blame^] | 144 | isVariadic = CurMethodDecl->isVariadic(); |
Chris Lattner | 30ce344 | 2007-12-19 23:59:04 +0000 | [diff] [blame] | 145 | |
Chris Lattner | c27c665 | 2007-12-20 00:05:45 +0000 | [diff] [blame^] | 146 | if (!isVariadic) { |
Chris Lattner | 30ce344 | 2007-12-19 23:59:04 +0000 | [diff] [blame] | 147 | Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function); |
| 148 | return true; |
| 149 | } |
| 150 | |
| 151 | // Verify that the second argument to the builtin is the last argument of the |
| 152 | // current function or method. |
| 153 | bool SecondArgIsLastNamedArgument = false; |
| 154 | if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Args[1])) { |
| 155 | if (ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) { |
| 156 | // FIXME: This isn't correct for methods (results in bogus warning). |
| 157 | // Get the last formal in the current function. |
| 158 | ParmVarDecl *LastArg; |
| 159 | if (CurFunctionDecl) |
| 160 | LastArg = *(CurFunctionDecl->param_end()-1); |
| 161 | else |
| 162 | LastArg = *(CurMethodDecl->param_end()-1); |
| 163 | SecondArgIsLastNamedArgument = PV == LastArg; |
| 164 | } |
| 165 | } |
| 166 | |
| 167 | if (!SecondArgIsLastNamedArgument) |
| 168 | Diag(Args[1]->getLocStart(), |
| 169 | diag::warn_second_parameter_of_va_start_not_last_named_argument); |
| 170 | return false; |
| 171 | } |
| 172 | |
| 173 | |
Chris Lattner | 59907c4 | 2007-08-10 20:18:51 +0000 | [diff] [blame] | 174 | /// CheckPrintfArguments - Check calls to printf (and similar functions) for |
Ted Kremenek | 71895b9 | 2007-08-14 17:39:48 +0000 | [diff] [blame] | 175 | /// correct use of format strings. |
| 176 | /// |
| 177 | /// HasVAListArg - A predicate indicating whether the printf-like |
| 178 | /// function is passed an explicit va_arg argument (e.g., vprintf) |
| 179 | /// |
| 180 | /// format_idx - The index into Args for the format string. |
| 181 | /// |
| 182 | /// Improper format strings to functions in the printf family can be |
| 183 | /// the source of bizarre bugs and very serious security holes. A |
| 184 | /// good source of information is available in the following paper |
| 185 | /// (which includes additional references): |
Chris Lattner | 59907c4 | 2007-08-10 20:18:51 +0000 | [diff] [blame] | 186 | /// |
| 187 | /// FormatGuard: Automatic Protection From printf Format String |
| 188 | /// Vulnerabilities, Proceedings of the 10th USENIX Security Symposium, 2001. |
Ted Kremenek | 71895b9 | 2007-08-14 17:39:48 +0000 | [diff] [blame] | 189 | /// |
| 190 | /// Functionality implemented: |
| 191 | /// |
| 192 | /// We can statically check the following properties for string |
| 193 | /// literal format strings for non v.*printf functions (where the |
| 194 | /// arguments are passed directly): |
| 195 | // |
| 196 | /// (1) Are the number of format conversions equal to the number of |
| 197 | /// data arguments? |
| 198 | /// |
| 199 | /// (2) Does each format conversion correctly match the type of the |
| 200 | /// corresponding data argument? (TODO) |
| 201 | /// |
| 202 | /// Moreover, for all printf functions we can: |
| 203 | /// |
| 204 | /// (3) Check for a missing format string (when not caught by type checking). |
| 205 | /// |
| 206 | /// (4) Check for no-operation flags; e.g. using "#" with format |
| 207 | /// conversion 'c' (TODO) |
| 208 | /// |
| 209 | /// (5) Check the use of '%n', a major source of security holes. |
| 210 | /// |
| 211 | /// (6) Check for malformed format conversions that don't specify anything. |
| 212 | /// |
| 213 | /// (7) Check for empty format strings. e.g: printf(""); |
| 214 | /// |
| 215 | /// (8) Check that the format string is a wide literal. |
| 216 | /// |
| 217 | /// All of these checks can be done by parsing the format string. |
| 218 | /// |
| 219 | /// For now, we ONLY do (1), (3), (5), (6), (7), and (8). |
Chris Lattner | 59907c4 | 2007-08-10 20:18:51 +0000 | [diff] [blame] | 220 | void |
Chris Lattner | 30ce344 | 2007-12-19 23:59:04 +0000 | [diff] [blame] | 221 | Sema::CheckPrintfArguments(Expr *Fn, SourceLocation RParenLoc, |
Ted Kremenek | 71895b9 | 2007-08-14 17:39:48 +0000 | [diff] [blame] | 222 | bool HasVAListArg, FunctionDecl *FDecl, |
Ted Kremenek | 8207710 | 2007-08-10 21:21:05 +0000 | [diff] [blame] | 223 | unsigned format_idx, Expr** Args, |
| 224 | unsigned NumArgsInCall) { |
Ted Kremenek | 71895b9 | 2007-08-14 17:39:48 +0000 | [diff] [blame] | 225 | // CHECK: printf-like function is called with no format string. |
| 226 | if (format_idx >= NumArgsInCall) { |
| 227 | Diag(RParenLoc, diag::warn_printf_missing_format_string, |
| 228 | Fn->getSourceRange()); |
| 229 | return; |
| 230 | } |
| 231 | |
Chris Lattner | 459e848 | 2007-08-25 05:36:18 +0000 | [diff] [blame] | 232 | Expr *OrigFormatExpr = Args[format_idx]; |
| 233 | // FIXME: This should go in a helper. |
| 234 | while (1) { |
| 235 | if (ParenExpr *PE = dyn_cast<ParenExpr>(OrigFormatExpr)) |
| 236 | OrigFormatExpr = PE->getSubExpr(); |
| 237 | else if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(OrigFormatExpr)) |
| 238 | OrigFormatExpr = ICE->getSubExpr(); |
| 239 | else |
| 240 | break; |
| 241 | } |
| 242 | |
Chris Lattner | 59907c4 | 2007-08-10 20:18:51 +0000 | [diff] [blame] | 243 | // CHECK: format string is not a string literal. |
| 244 | // |
Ted Kremenek | 71895b9 | 2007-08-14 17:39:48 +0000 | [diff] [blame] | 245 | // Dynamically generated format strings are difficult to |
| 246 | // automatically vet at compile time. Requiring that format strings |
| 247 | // are string literals: (1) permits the checking of format strings by |
| 248 | // the compiler and thereby (2) can practically remove the source of |
| 249 | // many format string exploits. |
Chris Lattner | 459e848 | 2007-08-25 05:36:18 +0000 | [diff] [blame] | 250 | StringLiteral *FExpr = dyn_cast<StringLiteral>(OrigFormatExpr); |
Chris Lattner | 59907c4 | 2007-08-10 20:18:51 +0000 | [diff] [blame] | 251 | |
Ted Kremenek | 71895b9 | 2007-08-14 17:39:48 +0000 | [diff] [blame] | 252 | if (FExpr == NULL) { |
Ted Kremenek | 4a33646 | 2007-12-17 19:03:13 +0000 | [diff] [blame] | 253 | // For vprintf* functions (i.e., HasVAListArg==true), we add a |
| 254 | // special check to see if the format string is a function parameter |
| 255 | // of the function calling the printf function. If the function |
| 256 | // has an attribute indicating it is a printf-like function, then we |
| 257 | // should suppress warnings concerning non-literals being used in a call |
| 258 | // to a vprintf function. For example: |
| 259 | // |
| 260 | // void |
| 261 | // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...) { |
| 262 | // va_list ap; |
| 263 | // va_start(ap, fmt); |
| 264 | // vprintf(fmt, ap); // Do NOT emit a warning about "fmt". |
| 265 | // ... |
| 266 | // |
| 267 | // |
| 268 | // FIXME: We don't have full attribute support yet, so just check to see |
| 269 | // if the argument is a DeclRefExpr that references a parameter. We'll |
| 270 | // add proper support for checking the attribute later. |
| 271 | if (HasVAListArg) |
| 272 | if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(IgnoreParen(OrigFormatExpr))) |
| 273 | if (isa<ParmVarDecl>(DR->getDecl())) |
| 274 | return; |
| 275 | |
| 276 | Diag(Args[format_idx]->getLocStart(), diag::warn_printf_not_string_constant, |
| 277 | Fn->getSourceRange()); |
| 278 | |
Ted Kremenek | 71895b9 | 2007-08-14 17:39:48 +0000 | [diff] [blame] | 279 | return; |
| 280 | } |
| 281 | |
| 282 | // CHECK: is the format string a wide literal? |
| 283 | if (FExpr->isWide()) { |
| 284 | Diag(Args[format_idx]->getLocStart(), |
| 285 | diag::warn_printf_format_string_is_wide_literal, |
| 286 | Fn->getSourceRange()); |
| 287 | return; |
| 288 | } |
| 289 | |
| 290 | // Str - The format string. NOTE: this is NOT null-terminated! |
| 291 | const char * const Str = FExpr->getStrData(); |
| 292 | |
| 293 | // CHECK: empty format string? |
| 294 | const unsigned StrLen = FExpr->getByteLength(); |
| 295 | |
| 296 | if (StrLen == 0) { |
| 297 | Diag(Args[format_idx]->getLocStart(), |
| 298 | diag::warn_printf_empty_format_string, Fn->getSourceRange()); |
| 299 | return; |
| 300 | } |
| 301 | |
| 302 | // We process the format string using a binary state machine. The |
| 303 | // current state is stored in CurrentState. |
| 304 | enum { |
| 305 | state_OrdChr, |
| 306 | state_Conversion |
| 307 | } CurrentState = state_OrdChr; |
| 308 | |
| 309 | // numConversions - The number of conversions seen so far. This is |
| 310 | // incremented as we traverse the format string. |
| 311 | unsigned numConversions = 0; |
| 312 | |
| 313 | // numDataArgs - The number of data arguments after the format |
| 314 | // string. This can only be determined for non vprintf-like |
| 315 | // functions. For those functions, this value is 1 (the sole |
| 316 | // va_arg argument). |
| 317 | unsigned numDataArgs = NumArgsInCall-(format_idx+1); |
| 318 | |
| 319 | // Inspect the format string. |
| 320 | unsigned StrIdx = 0; |
| 321 | |
| 322 | // LastConversionIdx - Index within the format string where we last saw |
| 323 | // a '%' character that starts a new format conversion. |
| 324 | unsigned LastConversionIdx = 0; |
| 325 | |
| 326 | for ( ; StrIdx < StrLen ; ++StrIdx ) { |
| 327 | |
| 328 | // Is the number of detected conversion conversions greater than |
| 329 | // the number of matching data arguments? If so, stop. |
| 330 | if (!HasVAListArg && numConversions > numDataArgs) break; |
| 331 | |
| 332 | // Handle "\0" |
| 333 | if(Str[StrIdx] == '\0' ) { |
| 334 | // The string returned by getStrData() is not null-terminated, |
| 335 | // so the presence of a null character is likely an error. |
| 336 | |
| 337 | SourceLocation Loc = |
| 338 | PP.AdvanceToTokenCharacter(Args[format_idx]->getLocStart(),StrIdx+1); |
| 339 | |
| 340 | Diag(Loc, diag::warn_printf_format_string_contains_null_char, |
| 341 | Fn->getSourceRange()); |
| 342 | |
| 343 | return; |
| 344 | } |
| 345 | |
| 346 | // Ordinary characters (not processing a format conversion). |
| 347 | if (CurrentState == state_OrdChr) { |
| 348 | if (Str[StrIdx] == '%') { |
| 349 | CurrentState = state_Conversion; |
| 350 | LastConversionIdx = StrIdx; |
| 351 | } |
| 352 | continue; |
| 353 | } |
| 354 | |
| 355 | // Seen '%'. Now processing a format conversion. |
| 356 | switch (Str[StrIdx]) { |
Ted Kremenek | 580b664 | 2007-10-12 20:51:52 +0000 | [diff] [blame] | 357 | // Handle dynamic precision or width specifier. |
| 358 | case '*': { |
| 359 | ++numConversions; |
| 360 | |
| 361 | if (!HasVAListArg && numConversions > numDataArgs) { |
| 362 | |
| 363 | SourceLocation Loc = |
| 364 | PP.AdvanceToTokenCharacter(Args[format_idx]->getLocStart(), |
| 365 | StrIdx+1); |
| 366 | |
| 367 | if (Str[StrIdx-1] == '.') |
| 368 | Diag(Loc, diag::warn_printf_asterisk_precision_missing_arg, |
| 369 | Fn->getSourceRange()); |
| 370 | else |
| 371 | Diag(Loc, diag::warn_printf_asterisk_width_missing_arg, |
| 372 | Fn->getSourceRange()); |
| 373 | |
| 374 | // Don't do any more checking. We'll just emit spurious errors. |
| 375 | return; |
| 376 | } |
| 377 | |
| 378 | // Perform type checking on width/precision specifier. |
| 379 | Expr* E = Args[format_idx+numConversions]; |
| 380 | QualType T = E->getType().getCanonicalType(); |
| 381 | if (BuiltinType *BT = dyn_cast<BuiltinType>(T)) |
| 382 | if (BT->getKind() == BuiltinType::Int) |
| 383 | break; |
| 384 | |
| 385 | SourceLocation Loc = |
| 386 | PP.AdvanceToTokenCharacter(Args[format_idx]->getLocStart(), |
| 387 | StrIdx+1); |
| 388 | |
| 389 | if (Str[StrIdx-1] == '.') |
| 390 | Diag(Loc, diag::warn_printf_asterisk_precision_wrong_type, |
| 391 | T.getAsString(), E->getSourceRange()); |
| 392 | else |
| 393 | Diag(Loc, diag::warn_printf_asterisk_width_wrong_type, |
| 394 | T.getAsString(), E->getSourceRange()); |
| 395 | |
Ted Kremenek | bef679c | 2007-10-12 00:11:27 +0000 | [diff] [blame] | 396 | break; |
Ted Kremenek | 580b664 | 2007-10-12 20:51:52 +0000 | [diff] [blame] | 397 | } |
Ted Kremenek | bef679c | 2007-10-12 00:11:27 +0000 | [diff] [blame] | 398 | |
Ted Kremenek | 71895b9 | 2007-08-14 17:39:48 +0000 | [diff] [blame] | 399 | // Characters which can terminate a format conversion |
| 400 | // (e.g. "%d"). Characters that specify length modifiers or |
| 401 | // other flags are handled by the default case below. |
| 402 | // |
Ted Kremenek | bef679c | 2007-10-12 00:11:27 +0000 | [diff] [blame] | 403 | // FIXME: additional checks will go into the following cases. |
Ted Kremenek | 71895b9 | 2007-08-14 17:39:48 +0000 | [diff] [blame] | 404 | case 'i': |
| 405 | case 'd': |
| 406 | case 'o': |
| 407 | case 'u': |
| 408 | case 'x': |
| 409 | case 'X': |
| 410 | case 'D': |
| 411 | case 'O': |
| 412 | case 'U': |
| 413 | case 'e': |
| 414 | case 'E': |
| 415 | case 'f': |
| 416 | case 'F': |
| 417 | case 'g': |
| 418 | case 'G': |
| 419 | case 'a': |
| 420 | case 'A': |
| 421 | case 'c': |
| 422 | case 'C': |
| 423 | case 'S': |
| 424 | case 's': |
Chris Lattner | 5e9885d | 2007-08-26 17:39:38 +0000 | [diff] [blame] | 425 | case 'p': |
Ted Kremenek | 71895b9 | 2007-08-14 17:39:48 +0000 | [diff] [blame] | 426 | ++numConversions; |
| 427 | CurrentState = state_OrdChr; |
| 428 | break; |
| 429 | |
| 430 | // CHECK: Are we using "%n"? Issue a warning. |
| 431 | case 'n': { |
| 432 | ++numConversions; |
| 433 | CurrentState = state_OrdChr; |
| 434 | SourceLocation Loc = |
| 435 | PP.AdvanceToTokenCharacter(Args[format_idx]->getLocStart(), |
| 436 | LastConversionIdx+1); |
| 437 | |
| 438 | Diag(Loc, diag::warn_printf_write_back, Fn->getSourceRange()); |
| 439 | break; |
| 440 | } |
| 441 | |
| 442 | // Handle "%%" |
| 443 | case '%': |
| 444 | // Sanity check: Was the first "%" character the previous one? |
| 445 | // If not, we will assume that we have a malformed format |
| 446 | // conversion, and that the current "%" character is the start |
| 447 | // of a new conversion. |
| 448 | if (StrIdx - LastConversionIdx == 1) |
| 449 | CurrentState = state_OrdChr; |
| 450 | else { |
| 451 | // Issue a warning: invalid format conversion. |
| 452 | SourceLocation Loc = |
| 453 | PP.AdvanceToTokenCharacter(Args[format_idx]->getLocStart(), |
| 454 | LastConversionIdx+1); |
| 455 | |
| 456 | Diag(Loc, diag::warn_printf_invalid_conversion, |
Ted Kremenek | 580b664 | 2007-10-12 20:51:52 +0000 | [diff] [blame] | 457 | std::string(Str+LastConversionIdx, Str+StrIdx), |
Ted Kremenek | 71895b9 | 2007-08-14 17:39:48 +0000 | [diff] [blame] | 458 | Fn->getSourceRange()); |
| 459 | |
| 460 | // This conversion is broken. Advance to the next format |
| 461 | // conversion. |
| 462 | LastConversionIdx = StrIdx; |
| 463 | ++numConversions; |
| 464 | } |
| 465 | |
| 466 | break; |
| 467 | |
| 468 | default: |
| 469 | // This case catches all other characters: flags, widths, etc. |
| 470 | // We should eventually process those as well. |
| 471 | break; |
| 472 | } |
| 473 | } |
| 474 | |
| 475 | if (CurrentState == state_Conversion) { |
| 476 | // Issue a warning: invalid format conversion. |
| 477 | SourceLocation Loc = |
| 478 | PP.AdvanceToTokenCharacter(Args[format_idx]->getLocStart(), |
| 479 | LastConversionIdx+1); |
| 480 | |
| 481 | Diag(Loc, diag::warn_printf_invalid_conversion, |
Chris Lattner | a9e2ea1 | 2007-08-26 17:38:22 +0000 | [diff] [blame] | 482 | std::string(Str+LastConversionIdx, |
| 483 | Str+std::min(LastConversionIdx+2, StrLen)), |
Ted Kremenek | 71895b9 | 2007-08-14 17:39:48 +0000 | [diff] [blame] | 484 | Fn->getSourceRange()); |
| 485 | return; |
| 486 | } |
| 487 | |
| 488 | if (!HasVAListArg) { |
| 489 | // CHECK: Does the number of format conversions exceed the number |
| 490 | // of data arguments? |
| 491 | if (numConversions > numDataArgs) { |
| 492 | SourceLocation Loc = |
| 493 | PP.AdvanceToTokenCharacter(Args[format_idx]->getLocStart(), |
| 494 | LastConversionIdx); |
| 495 | |
| 496 | Diag(Loc, diag::warn_printf_insufficient_data_args, |
| 497 | Fn->getSourceRange()); |
| 498 | } |
| 499 | // CHECK: Does the number of data arguments exceed the number of |
| 500 | // format conversions in the format string? |
| 501 | else if (numConversions < numDataArgs) |
| 502 | Diag(Args[format_idx+numConversions+1]->getLocStart(), |
| 503 | diag::warn_printf_too_many_data_args, Fn->getSourceRange()); |
| 504 | } |
| 505 | } |
Ted Kremenek | 06de276 | 2007-08-17 16:46:58 +0000 | [diff] [blame] | 506 | |
| 507 | //===--- CHECK: Return Address of Stack Variable --------------------------===// |
| 508 | |
| 509 | static DeclRefExpr* EvalVal(Expr *E); |
| 510 | static DeclRefExpr* EvalAddr(Expr* E); |
| 511 | |
| 512 | /// CheckReturnStackAddr - Check if a return statement returns the address |
| 513 | /// of a stack variable. |
| 514 | void |
| 515 | Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType, |
| 516 | SourceLocation ReturnLoc) { |
| 517 | |
| 518 | // Perform checking for returned stack addresses. |
| 519 | if (lhsType->isPointerType()) { |
| 520 | if (DeclRefExpr *DR = EvalAddr(RetValExp)) |
| 521 | Diag(DR->getLocStart(), diag::warn_ret_stack_addr, |
| 522 | DR->getDecl()->getIdentifier()->getName(), |
| 523 | RetValExp->getSourceRange()); |
| 524 | } |
| 525 | // Perform checking for stack values returned by reference. |
| 526 | else if (lhsType->isReferenceType()) { |
Ted Kremenek | 96eabe0 | 2007-08-27 16:39:17 +0000 | [diff] [blame] | 527 | // Check for an implicit cast to a reference. |
| 528 | if (ImplicitCastExpr *I = dyn_cast<ImplicitCastExpr>(RetValExp)) |
| 529 | if (DeclRefExpr *DR = EvalVal(I->getSubExpr())) |
| 530 | Diag(DR->getLocStart(), diag::warn_ret_stack_ref, |
| 531 | DR->getDecl()->getIdentifier()->getName(), |
| 532 | RetValExp->getSourceRange()); |
Ted Kremenek | 06de276 | 2007-08-17 16:46:58 +0000 | [diff] [blame] | 533 | } |
| 534 | } |
| 535 | |
| 536 | /// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that |
| 537 | /// check if the expression in a return statement evaluates to an address |
| 538 | /// to a location on the stack. The recursion is used to traverse the |
| 539 | /// AST of the return expression, with recursion backtracking when we |
| 540 | /// encounter a subexpression that (1) clearly does not lead to the address |
| 541 | /// of a stack variable or (2) is something we cannot determine leads to |
| 542 | /// the address of a stack variable based on such local checking. |
| 543 | /// |
Ted Kremenek | e8c600f | 2007-08-28 17:02:55 +0000 | [diff] [blame] | 544 | /// EvalAddr processes expressions that are pointers that are used as |
| 545 | /// references (and not L-values). EvalVal handles all other values. |
Ted Kremenek | 06de276 | 2007-08-17 16:46:58 +0000 | [diff] [blame] | 546 | /// At the base case of the recursion is a check for a DeclRefExpr* in |
| 547 | /// the refers to a stack variable. |
| 548 | /// |
| 549 | /// This implementation handles: |
| 550 | /// |
| 551 | /// * pointer-to-pointer casts |
| 552 | /// * implicit conversions from array references to pointers |
| 553 | /// * taking the address of fields |
| 554 | /// * arbitrary interplay between "&" and "*" operators |
| 555 | /// * pointer arithmetic from an address of a stack variable |
| 556 | /// * taking the address of an array element where the array is on the stack |
| 557 | static DeclRefExpr* EvalAddr(Expr *E) { |
| 558 | |
| 559 | // We should only be called for evaluating pointer expressions. |
| 560 | assert (E->getType()->isPointerType() && "EvalAddr only works on pointers"); |
| 561 | |
| 562 | // Our "symbolic interpreter" is just a dispatch off the currently |
| 563 | // viewed AST node. We then recursively traverse the AST by calling |
| 564 | // EvalAddr and EvalVal appropriately. |
| 565 | switch (E->getStmtClass()) { |
| 566 | |
| 567 | case Stmt::ParenExprClass: |
| 568 | // Ignore parentheses. |
| 569 | return EvalAddr(cast<ParenExpr>(E)->getSubExpr()); |
| 570 | |
| 571 | case Stmt::UnaryOperatorClass: { |
| 572 | // The only unary operator that make sense to handle here |
| 573 | // is AddrOf. All others don't make sense as pointers. |
| 574 | UnaryOperator *U = cast<UnaryOperator>(E); |
| 575 | |
| 576 | if (U->getOpcode() == UnaryOperator::AddrOf) |
| 577 | return EvalVal(U->getSubExpr()); |
| 578 | else |
| 579 | return NULL; |
| 580 | } |
| 581 | |
| 582 | case Stmt::BinaryOperatorClass: { |
| 583 | // Handle pointer arithmetic. All other binary operators are not valid |
| 584 | // in this context. |
| 585 | BinaryOperator *B = cast<BinaryOperator>(E); |
| 586 | BinaryOperator::Opcode op = B->getOpcode(); |
| 587 | |
| 588 | if (op != BinaryOperator::Add && op != BinaryOperator::Sub) |
| 589 | return NULL; |
| 590 | |
| 591 | Expr *Base = B->getLHS(); |
| 592 | |
| 593 | // Determine which argument is the real pointer base. It could be |
| 594 | // the RHS argument instead of the LHS. |
| 595 | if (!Base->getType()->isPointerType()) Base = B->getRHS(); |
| 596 | |
| 597 | assert (Base->getType()->isPointerType()); |
| 598 | return EvalAddr(Base); |
| 599 | } |
| 600 | |
| 601 | // For conditional operators we need to see if either the LHS or RHS are |
| 602 | // valid DeclRefExpr*s. If one of them is valid, we return it. |
| 603 | case Stmt::ConditionalOperatorClass: { |
| 604 | ConditionalOperator *C = cast<ConditionalOperator>(E); |
| 605 | |
Anders Carlsson | 3907323 | 2007-11-30 19:04:31 +0000 | [diff] [blame] | 606 | // Handle the GNU extension for missing LHS. |
| 607 | if (Expr *lhsExpr = C->getLHS()) |
| 608 | if (DeclRefExpr* LHS = EvalAddr(lhsExpr)) |
| 609 | return LHS; |
| 610 | |
| 611 | return EvalAddr(C->getRHS()); |
Ted Kremenek | 06de276 | 2007-08-17 16:46:58 +0000 | [diff] [blame] | 612 | } |
| 613 | |
| 614 | // For implicit casts, we need to handle conversions from arrays to |
| 615 | // pointer values, and implicit pointer-to-pointer conversions. |
| 616 | case Stmt::ImplicitCastExprClass: { |
| 617 | ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E); |
| 618 | Expr* SubExpr = IE->getSubExpr(); |
| 619 | |
| 620 | if (SubExpr->getType()->isPointerType()) |
| 621 | return EvalAddr(SubExpr); |
| 622 | else |
| 623 | return EvalVal(SubExpr); |
| 624 | } |
| 625 | |
| 626 | // For casts, we handle pointer-to-pointer conversions (which |
| 627 | // is essentially a no-op from our mini-interpreter's standpoint). |
| 628 | // For other casts we abort. |
| 629 | case Stmt::CastExprClass: { |
| 630 | CastExpr *C = cast<CastExpr>(E); |
| 631 | Expr *SubExpr = C->getSubExpr(); |
| 632 | |
| 633 | if (SubExpr->getType()->isPointerType()) |
| 634 | return EvalAddr(SubExpr); |
| 635 | else |
| 636 | return NULL; |
| 637 | } |
| 638 | |
Ted Kremenek | 2324512 | 2007-08-20 16:18:38 +0000 | [diff] [blame] | 639 | // C++ casts. For dynamic casts, static casts, and const casts, we |
| 640 | // are always converting from a pointer-to-pointer, so we just blow |
| 641 | // through the cast. In the case the dynamic cast doesn't fail |
| 642 | // (and return NULL), we take the conservative route and report cases |
| 643 | // where we return the address of a stack variable. For Reinterpre |
| 644 | case Stmt::CXXCastExprClass: { |
| 645 | CXXCastExpr *C = cast<CXXCastExpr>(E); |
| 646 | |
| 647 | if (C->getOpcode() == CXXCastExpr::ReinterpretCast) { |
| 648 | Expr *S = C->getSubExpr(); |
| 649 | if (S->getType()->isPointerType()) |
| 650 | return EvalAddr(S); |
| 651 | else |
| 652 | return NULL; |
| 653 | } |
| 654 | else |
| 655 | return EvalAddr(C->getSubExpr()); |
| 656 | } |
Ted Kremenek | 06de276 | 2007-08-17 16:46:58 +0000 | [diff] [blame] | 657 | |
| 658 | // Everything else: we simply don't reason about them. |
| 659 | default: |
| 660 | return NULL; |
| 661 | } |
| 662 | } |
| 663 | |
| 664 | |
| 665 | /// EvalVal - This function is complements EvalAddr in the mutual recursion. |
| 666 | /// See the comments for EvalAddr for more details. |
| 667 | static DeclRefExpr* EvalVal(Expr *E) { |
| 668 | |
Ted Kremenek | e8c600f | 2007-08-28 17:02:55 +0000 | [diff] [blame] | 669 | // We should only be called for evaluating non-pointer expressions, or |
| 670 | // expressions with a pointer type that are not used as references but instead |
| 671 | // are l-values (e.g., DeclRefExpr with a pointer type). |
| 672 | |
Ted Kremenek | 06de276 | 2007-08-17 16:46:58 +0000 | [diff] [blame] | 673 | // Our "symbolic interpreter" is just a dispatch off the currently |
| 674 | // viewed AST node. We then recursively traverse the AST by calling |
| 675 | // EvalAddr and EvalVal appropriately. |
| 676 | switch (E->getStmtClass()) { |
| 677 | |
| 678 | case Stmt::DeclRefExprClass: { |
| 679 | // DeclRefExpr: the base case. When we hit a DeclRefExpr we are looking |
| 680 | // at code that refers to a variable's name. We check if it has local |
| 681 | // storage within the function, and if so, return the expression. |
| 682 | DeclRefExpr *DR = cast<DeclRefExpr>(E); |
| 683 | |
| 684 | if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) |
| 685 | if(V->hasLocalStorage()) return DR; |
| 686 | |
| 687 | return NULL; |
| 688 | } |
| 689 | |
| 690 | case Stmt::ParenExprClass: |
| 691 | // Ignore parentheses. |
| 692 | return EvalVal(cast<ParenExpr>(E)->getSubExpr()); |
| 693 | |
| 694 | case Stmt::UnaryOperatorClass: { |
| 695 | // The only unary operator that make sense to handle here |
| 696 | // is Deref. All others don't resolve to a "name." This includes |
| 697 | // handling all sorts of rvalues passed to a unary operator. |
| 698 | UnaryOperator *U = cast<UnaryOperator>(E); |
| 699 | |
| 700 | if (U->getOpcode() == UnaryOperator::Deref) |
| 701 | return EvalAddr(U->getSubExpr()); |
| 702 | |
| 703 | return NULL; |
| 704 | } |
| 705 | |
| 706 | case Stmt::ArraySubscriptExprClass: { |
| 707 | // Array subscripts are potential references to data on the stack. We |
| 708 | // retrieve the DeclRefExpr* for the array variable if it indeed |
| 709 | // has local storage. |
Ted Kremenek | 2324512 | 2007-08-20 16:18:38 +0000 | [diff] [blame] | 710 | return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase()); |
Ted Kremenek | 06de276 | 2007-08-17 16:46:58 +0000 | [diff] [blame] | 711 | } |
| 712 | |
| 713 | case Stmt::ConditionalOperatorClass: { |
| 714 | // For conditional operators we need to see if either the LHS or RHS are |
| 715 | // non-NULL DeclRefExpr's. If one is non-NULL, we return it. |
| 716 | ConditionalOperator *C = cast<ConditionalOperator>(E); |
| 717 | |
Anders Carlsson | 3907323 | 2007-11-30 19:04:31 +0000 | [diff] [blame] | 718 | // Handle the GNU extension for missing LHS. |
| 719 | if (Expr *lhsExpr = C->getLHS()) |
| 720 | if (DeclRefExpr *LHS = EvalVal(lhsExpr)) |
| 721 | return LHS; |
| 722 | |
| 723 | return EvalVal(C->getRHS()); |
Ted Kremenek | 06de276 | 2007-08-17 16:46:58 +0000 | [diff] [blame] | 724 | } |
| 725 | |
| 726 | // Accesses to members are potential references to data on the stack. |
| 727 | case Stmt::MemberExprClass: { |
| 728 | MemberExpr *M = cast<MemberExpr>(E); |
| 729 | |
| 730 | // Check for indirect access. We only want direct field accesses. |
| 731 | if (!M->isArrow()) |
| 732 | return EvalVal(M->getBase()); |
| 733 | else |
| 734 | return NULL; |
| 735 | } |
| 736 | |
| 737 | // Everything else: we simply don't reason about them. |
| 738 | default: |
| 739 | return NULL; |
| 740 | } |
| 741 | } |
Ted Kremenek | 588e5eb | 2007-11-25 00:58:00 +0000 | [diff] [blame] | 742 | |
| 743 | //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===// |
| 744 | |
| 745 | /// Check for comparisons of floating point operands using != and ==. |
| 746 | /// Issue a warning if these are no self-comparisons, as they are not likely |
| 747 | /// to do what the programmer intended. |
| 748 | void Sema::CheckFloatComparison(SourceLocation loc, Expr* lex, Expr *rex) { |
| 749 | bool EmitWarning = true; |
| 750 | |
| 751 | Expr* LeftExprSansParen = IgnoreParen(lex); |
| 752 | Expr* RightExprSansParen = IgnoreParen(rex); |
| 753 | |
| 754 | // Special case: check for x == x (which is OK). |
| 755 | // Do not emit warnings for such cases. |
| 756 | if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen)) |
| 757 | if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen)) |
| 758 | if (DRL->getDecl() == DRR->getDecl()) |
| 759 | EmitWarning = false; |
| 760 | |
Ted Kremenek | 1b500bb | 2007-11-29 00:59:04 +0000 | [diff] [blame] | 761 | |
| 762 | // Special case: check for comparisons against literals that can be exactly |
| 763 | // represented by APFloat. In such cases, do not emit a warning. This |
| 764 | // is a heuristic: often comparison against such literals are used to |
| 765 | // detect if a value in a variable has not changed. This clearly can |
| 766 | // lead to false negatives. |
| 767 | if (EmitWarning) { |
| 768 | if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) { |
| 769 | if (FLL->isExact()) |
| 770 | EmitWarning = false; |
| 771 | } |
| 772 | else |
| 773 | if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)){ |
| 774 | if (FLR->isExact()) |
| 775 | EmitWarning = false; |
| 776 | } |
| 777 | } |
| 778 | |
Ted Kremenek | 588e5eb | 2007-11-25 00:58:00 +0000 | [diff] [blame] | 779 | // Check for comparisons with builtin types. |
| 780 | if (EmitWarning) |
| 781 | if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen)) |
| 782 | if (isCallBuiltin(CL)) |
| 783 | EmitWarning = false; |
| 784 | |
| 785 | if (EmitWarning) |
| 786 | if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen)) |
| 787 | if (isCallBuiltin(CR)) |
| 788 | EmitWarning = false; |
| 789 | |
| 790 | // Emit the diagnostic. |
| 791 | if (EmitWarning) |
| 792 | Diag(loc, diag::warn_floatingpoint_eq, |
| 793 | lex->getSourceRange(),rex->getSourceRange()); |
| 794 | } |