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