clang  8.0.0svn
PrintfFormatString.cpp
Go to the documentation of this file.
1 //== PrintfFormatString.cpp - Analysis of printf format strings --*- C++ -*-==//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // Handling of format string in printf and friends. The structure of format
11 // strings for fprintf() are described in C99 7.19.6.1.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "clang/AST/FormatString.h"
16 #include "clang/AST/OSLog.h"
17 #include "FormatStringParsing.h"
18 #include "clang/Basic/TargetInfo.h"
19 
26 
27 using namespace clang;
28 
31 
32 //===----------------------------------------------------------------------===//
33 // Methods for parsing format strings.
34 //===----------------------------------------------------------------------===//
35 
37 
39  const char *Start, const char *&Beg, const char *E,
40  unsigned *argIndex) {
41  if (argIndex) {
42  FS.setPrecision(ParseNonPositionAmount(Beg, E, *argIndex));
43  } else {
44  const OptionalAmount Amt = ParsePositionAmount(H, Start, Beg, E,
46  if (Amt.isInvalid())
47  return true;
48  FS.setPrecision(Amt);
49  }
50  return false;
51 }
52 
54  const char *FlagBeg, const char *E, bool Warn) {
55  StringRef Flag(FlagBeg, E - FlagBeg);
56  // Currently there is only one flag.
57  if (Flag == "tt") {
58  FS.setHasObjCTechnicalTerm(FlagBeg);
59  return false;
60  }
61  // Handle either the case of no flag or an invalid flag.
62  if (Warn) {
63  if (Flag == "")
64  H.HandleEmptyObjCModifierFlag(FlagBeg, E - FlagBeg);
65  else
66  H.HandleInvalidObjCModifierFlag(FlagBeg, E - FlagBeg);
67  }
68  return true;
69 }
70 
72  const char *&Beg,
73  const char *E,
74  unsigned &argIndex,
75  const LangOptions &LO,
76  const TargetInfo &Target,
77  bool Warn,
78  bool isFreeBSDKPrintf) {
79 
80  using namespace clang::analyze_format_string;
81  using namespace clang::analyze_printf;
82 
83  const char *I = Beg;
84  const char *Start = nullptr;
85  UpdateOnReturn <const char*> UpdateBeg(Beg, I);
86 
87  // Look for a '%' character that indicates the start of a format specifier.
88  for ( ; I != E ; ++I) {
89  char c = *I;
90  if (c == '\0') {
91  // Detect spurious null characters, which are likely errors.
92  H.HandleNullChar(I);
93  return true;
94  }
95  if (c == '%') {
96  Start = I++; // Record the start of the format specifier.
97  break;
98  }
99  }
100 
101  // No format specifier found?
102  if (!Start)
103  return false;
104 
105  if (I == E) {
106  // No more characters left?
107  if (Warn)
108  H.HandleIncompleteSpecifier(Start, E - Start);
109  return true;
110  }
111 
112  PrintfSpecifier FS;
113  if (ParseArgPosition(H, FS, Start, I, E))
114  return true;
115 
116  if (I == E) {
117  // No more characters left?
118  if (Warn)
119  H.HandleIncompleteSpecifier(Start, E - Start);
120  return true;
121  }
122 
123  if (*I == '{') {
124  ++I;
125  unsigned char PrivacyFlags = 0;
126  StringRef MatchedStr;
127 
128  do {
129  StringRef Str(I, E - I);
130  std::string Match = "^[[:space:]]*"
131  "(private|public|sensitive|mask\\.[^[:space:],}]*)"
132  "[[:space:]]*(,|})";
133  llvm::Regex R(Match);
135 
136  if (R.match(Str, &Matches)) {
137  MatchedStr = Matches[1];
138  I += Matches[0].size();
139 
140  // Set the privacy flag if the privacy annotation in the
141  // comma-delimited segment is at least as strict as the privacy
142  // annotations in previous comma-delimited segments.
143  if (MatchedStr.startswith("mask")) {
144  StringRef MaskType = MatchedStr.substr(sizeof("mask.") - 1);
145  unsigned Size = MaskType.size();
146  if (Warn && (Size == 0 || Size > 8))
147  H.handleInvalidMaskType(MaskType);
148  FS.setMaskType(MaskType);
149  } else if (MatchedStr.equals("sensitive"))
151  else if (PrivacyFlags !=
153  MatchedStr.equals("private"))
155  else if (PrivacyFlags == 0 && MatchedStr.equals("public"))
157  } else {
158  size_t CommaOrBracePos =
159  Str.find_if([](char c) { return c == ',' || c == '}'; });
160 
161  if (CommaOrBracePos == StringRef::npos) {
162  // Neither a comma nor the closing brace was found.
163  if (Warn)
164  H.HandleIncompleteSpecifier(Start, E - Start);
165  return true;
166  }
167 
168  I += CommaOrBracePos + 1;
169  }
170  // Continue until the closing brace is found.
171  } while (*(I - 1) == ',');
172 
173  // Set the privacy flag.
174  switch (PrivacyFlags) {
175  case 0:
176  break;
178  FS.setIsPrivate(MatchedStr.data());
179  break;
181  FS.setIsPublic(MatchedStr.data());
182  break;
184  FS.setIsSensitive(MatchedStr.data());
185  break;
186  default:
187  llvm_unreachable("Unexpected privacy flag value");
188  }
189  }
190 
191  // Look for flags (if any).
192  bool hasMore = true;
193  for ( ; I != E; ++I) {
194  switch (*I) {
195  default: hasMore = false; break;
196  case '\'':
197  // FIXME: POSIX specific. Always accept?
199  break;
200  case '-': FS.setIsLeftJustified(I); break;
201  case '+': FS.setHasPlusPrefix(I); break;
202  case ' ': FS.setHasSpacePrefix(I); break;
203  case '#': FS.setHasAlternativeForm(I); break;
204  case '0': FS.setHasLeadingZeros(I); break;
205  }
206  if (!hasMore)
207  break;
208  }
209 
210  if (I == E) {
211  // No more characters left?
212  if (Warn)
213  H.HandleIncompleteSpecifier(Start, E - Start);
214  return true;
215  }
216 
217  // Look for the field width (if any).
218  if (ParseFieldWidth(H, FS, Start, I, E,
219  FS.usesPositionalArg() ? nullptr : &argIndex))
220  return true;
221 
222  if (I == E) {
223  // No more characters left?
224  if (Warn)
225  H.HandleIncompleteSpecifier(Start, E - Start);
226  return true;
227  }
228 
229  // Look for the precision (if any).
230  if (*I == '.') {
231  ++I;
232  if (I == E) {
233  if (Warn)
234  H.HandleIncompleteSpecifier(Start, E - Start);
235  return true;
236  }
237 
238  if (ParsePrecision(H, FS, Start, I, E,
239  FS.usesPositionalArg() ? nullptr : &argIndex))
240  return true;
241 
242  if (I == E) {
243  // No more characters left?
244  if (Warn)
245  H.HandleIncompleteSpecifier(Start, E - Start);
246  return true;
247  }
248  }
249 
250  // Look for the length modifier.
251  if (ParseLengthModifier(FS, I, E, LO) && I == E) {
252  // No more characters left?
253  if (Warn)
254  H.HandleIncompleteSpecifier(Start, E - Start);
255  return true;
256  }
257 
258  // Look for the Objective-C modifier flags, if any.
259  // We parse these here, even if they don't apply to
260  // the conversion specifier, and then emit an error
261  // later if the conversion specifier isn't '@'. This
262  // enables better recovery, and we don't know if
263  // these flags are applicable until later.
264  const char *ObjCModifierFlagsStart = nullptr,
265  *ObjCModifierFlagsEnd = nullptr;
266  if (*I == '[') {
267  ObjCModifierFlagsStart = I;
268  ++I;
269  auto flagStart = I;
270  for (;; ++I) {
271  ObjCModifierFlagsEnd = I;
272  if (I == E) {
273  if (Warn)
274  H.HandleIncompleteSpecifier(Start, E - Start);
275  return true;
276  }
277  // Did we find the closing ']'?
278  if (*I == ']') {
279  if (ParseObjCFlags(H, FS, flagStart, I, Warn))
280  return true;
281  ++I;
282  break;
283  }
284  // There are no separators defined yet for multiple
285  // Objective-C modifier flags. When those are
286  // defined, this is the place to check.
287  }
288  }
289 
290  if (*I == '\0') {
291  // Detect spurious null characters, which are likely errors.
292  H.HandleNullChar(I);
293  return true;
294  }
295 
296  // Finally, look for the conversion specifier.
297  const char *conversionPosition = I++;
299  switch (*conversionPosition) {
300  default:
301  break;
302  // C99: 7.19.6.1 (section 8).
303  case '%': k = ConversionSpecifier::PercentArg; break;
304  case 'A': k = ConversionSpecifier::AArg; break;
305  case 'E': k = ConversionSpecifier::EArg; break;
306  case 'F': k = ConversionSpecifier::FArg; break;
307  case 'G': k = ConversionSpecifier::GArg; break;
308  case 'X': k = ConversionSpecifier::XArg; break;
309  case 'a': k = ConversionSpecifier::aArg; break;
310  case 'c': k = ConversionSpecifier::cArg; break;
311  case 'd': k = ConversionSpecifier::dArg; break;
312  case 'e': k = ConversionSpecifier::eArg; break;
313  case 'f': k = ConversionSpecifier::fArg; break;
314  case 'g': k = ConversionSpecifier::gArg; break;
315  case 'i': k = ConversionSpecifier::iArg; break;
316  case 'n': k = ConversionSpecifier::nArg; break;
317  case 'o': k = ConversionSpecifier::oArg; break;
318  case 'p': k = ConversionSpecifier::pArg; break;
319  case 's': k = ConversionSpecifier::sArg; break;
320  case 'u': k = ConversionSpecifier::uArg; break;
321  case 'x': k = ConversionSpecifier::xArg; break;
322  // POSIX specific.
323  case 'C': k = ConversionSpecifier::CArg; break;
324  case 'S': k = ConversionSpecifier::SArg; break;
325  // Apple extension for os_log
326  case 'P':
328  break;
329  // Objective-C.
330  case '@': k = ConversionSpecifier::ObjCObjArg; break;
331  // Glibc specific.
332  case 'm': k = ConversionSpecifier::PrintErrno; break;
333  // FreeBSD kernel specific.
334  case 'b':
335  if (isFreeBSDKPrintf)
336  k = ConversionSpecifier::FreeBSDbArg; // int followed by char *
337  break;
338  case 'r':
339  if (isFreeBSDKPrintf)
341  break;
342  case 'y':
343  if (isFreeBSDKPrintf)
345  break;
346  // Apple-specific.
347  case 'D':
348  if (isFreeBSDKPrintf)
349  k = ConversionSpecifier::FreeBSDDArg; // void * followed by char *
350  else if (Target.getTriple().isOSDarwin())
352  break;
353  case 'O':
354  if (Target.getTriple().isOSDarwin())
356  break;
357  case 'U':
358  if (Target.getTriple().isOSDarwin())
360  break;
361  // MS specific.
362  case 'Z':
363  if (Target.getTriple().isOSMSVCRT())
365  }
366 
367  // Check to see if we used the Objective-C modifier flags with
368  // a conversion specifier other than '@'.
371  ObjCModifierFlagsStart) {
372  H.HandleObjCFlagsWithNonObjCConversion(ObjCModifierFlagsStart,
373  ObjCModifierFlagsEnd + 1,
374  conversionPosition);
375  return true;
376  }
377 
378  PrintfConversionSpecifier CS(conversionPosition, k);
379  FS.setConversionSpecifier(CS);
380  if (CS.consumesDataArgument() && !FS.usesPositionalArg())
381  FS.setArgIndex(argIndex++);
382  // FreeBSD kernel specific.
385  argIndex++;
386 
388  unsigned Len = I - Start;
389  if (ParseUTF8InvalidSpecifier(Start, E, Len)) {
390  CS.setEndScanList(Start + Len);
391  FS.setConversionSpecifier(CS);
392  }
393  // Assume the conversion takes one argument.
394  return !H.HandleInvalidPrintfConversionSpecifier(FS, Start, Len);
395  }
396  return PrintfSpecifierResult(Start, FS);
397 }
398 
400  const char *I,
401  const char *E,
402  const LangOptions &LO,
403  const TargetInfo &Target,
404  bool isFreeBSDKPrintf) {
405 
406  unsigned argIndex = 0;
407 
408  // Keep looking for a format specifier until we have exhausted the string.
409  while (I != E) {
410  const PrintfSpecifierResult &FSR = ParsePrintfSpecifier(H, I, E, argIndex,
411  LO, Target, true,
412  isFreeBSDKPrintf);
413  // Did a fail-stop error of any kind occur when parsing the specifier?
414  // If so, don't do any more processing.
415  if (FSR.shouldStop())
416  return true;
417  // Did we exhaust the string or encounter an error that
418  // we can recover from?
419  if (!FSR.hasValue())
420  continue;
421  // We have a format specifier. Pass it to the callback.
422  if (!H.HandlePrintfSpecifier(FSR.getValue(), FSR.getStart(),
423  I - FSR.getStart()))
424  return true;
425  }
426  assert(I == E && "Format string not exhausted");
427  return false;
428 }
429 
431  const char *E,
432  const LangOptions &LO,
433  const TargetInfo &Target) {
434 
435  unsigned argIndex = 0;
436 
437  // Keep looking for a %s format specifier until we have exhausted the string.
439  while (I != E) {
440  const PrintfSpecifierResult &FSR = ParsePrintfSpecifier(H, I, E, argIndex,
441  LO, Target, false,
442  false);
443  // Did a fail-stop error of any kind occur when parsing the specifier?
444  // If so, don't do any more processing.
445  if (FSR.shouldStop())
446  return false;
447  // Did we exhaust the string or encounter an error that
448  // we can recover from?
449  if (!FSR.hasValue())
450  continue;
451  const analyze_printf::PrintfSpecifier &FS = FSR.getValue();
452  // Return true if this a %s format specifier.
453  if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::Kind::sArg)
454  return true;
455  }
456  return false;
457 }
458 
459 //===----------------------------------------------------------------------===//
460 // Methods on PrintfSpecifier.
461 //===----------------------------------------------------------------------===//
462 
463 ArgType PrintfSpecifier::getArgType(ASTContext &Ctx,
464  bool IsObjCLiteral) const {
465  const PrintfConversionSpecifier &CS = getConversionSpecifier();
466 
467  if (!CS.consumesDataArgument())
468  return ArgType::Invalid();
469 
471  switch (LM.getKind()) {
473  return Ctx.IntTy;
476  return ArgType(ArgType::WIntTy, "wint_t");
478  if (Ctx.getTargetInfo().getTriple().isOSMSVCRT())
479  return Ctx.IntTy;
480  LLVM_FALLTHROUGH;
481  default:
482  return ArgType::Invalid();
483  }
484 
485  if (CS.isIntArg())
486  switch (LM.getKind()) {
488  // GNU extension.
489  return Ctx.LongLongTy;
491  return Ctx.IntTy;
493  return ArgType(Ctx.IntTy, "__int32");
495  case LengthModifier::AsShort: return Ctx.ShortTy;
496  case LengthModifier::AsLong: return Ctx.LongTy;
499  return Ctx.LongLongTy;
501  return ArgType(Ctx.LongLongTy, "__int64");
503  return ArgType(Ctx.getIntMaxType(), "intmax_t");
505  return ArgType::makeSizeT(ArgType(Ctx.getSignedSizeType(), "ssize_t"));
507  return Ctx.getTargetInfo().getTriple().isArch64Bit()
508  ? ArgType(Ctx.LongLongTy, "__int64")
509  : ArgType(Ctx.IntTy, "__int32");
511  return ArgType::makePtrdiffT(
512  ArgType(Ctx.getPointerDiffType(), "ptrdiff_t"));
516  return ArgType::Invalid();
517  }
518 
519  if (CS.isUIntArg())
520  switch (LM.getKind()) {
522  // GNU extension.
523  return Ctx.UnsignedLongLongTy;
525  return Ctx.UnsignedIntTy;
527  return ArgType(Ctx.UnsignedIntTy, "unsigned __int32");
528  case LengthModifier::AsChar: return Ctx.UnsignedCharTy;
529  case LengthModifier::AsShort: return Ctx.UnsignedShortTy;
530  case LengthModifier::AsLong: return Ctx.UnsignedLongTy;
533  return Ctx.UnsignedLongLongTy;
535  return ArgType(Ctx.UnsignedLongLongTy, "unsigned __int64");
537  return ArgType(Ctx.getUIntMaxType(), "uintmax_t");
539  return ArgType::makeSizeT(ArgType(Ctx.getSizeType(), "size_t"));
541  return Ctx.getTargetInfo().getTriple().isArch64Bit()
542  ? ArgType(Ctx.UnsignedLongLongTy, "unsigned __int64")
543  : ArgType(Ctx.UnsignedIntTy, "unsigned __int32");
545  return ArgType::makePtrdiffT(
546  ArgType(Ctx.getUnsignedPointerDiffType(), "unsigned ptrdiff_t"));
550  return ArgType::Invalid();
551  }
552 
553  if (CS.isDoubleArg()) {
554  if (LM.getKind() == LengthModifier::AsLongDouble)
555  return Ctx.LongDoubleTy;
556  return Ctx.DoubleTy;
557  }
558 
559  if (CS.getKind() == ConversionSpecifier::nArg) {
560  switch (LM.getKind()) {
562  return ArgType::PtrTo(Ctx.IntTy);
564  return ArgType::PtrTo(Ctx.SignedCharTy);
566  return ArgType::PtrTo(Ctx.ShortTy);
568  return ArgType::PtrTo(Ctx.LongTy);
571  return ArgType::PtrTo(Ctx.LongLongTy);
573  return ArgType::PtrTo(ArgType(Ctx.getIntMaxType(), "intmax_t"));
575  return ArgType::PtrTo(ArgType(Ctx.getSignedSizeType(), "ssize_t"));
577  return ArgType::PtrTo(ArgType(Ctx.getPointerDiffType(), "ptrdiff_t"));
579  return ArgType(); // FIXME: Is this a known extension?
586  return ArgType::Invalid();
587  }
588  }
589 
590  switch (CS.getKind()) {
592  if (LM.getKind() == LengthModifier::AsWideChar) {
593  if (IsObjCLiteral)
595  "const unichar *");
596  return ArgType(ArgType::WCStrTy, "wchar_t *");
597  }
598  if (LM.getKind() == LengthModifier::AsWide)
599  return ArgType(ArgType::WCStrTy, "wchar_t *");
600  return ArgType::CStrTy;
602  if (IsObjCLiteral)
604  "const unichar *");
605  if (Ctx.getTargetInfo().getTriple().isOSMSVCRT() &&
606  LM.getKind() == LengthModifier::AsShort)
607  return ArgType::CStrTy;
608  return ArgType(ArgType::WCStrTy, "wchar_t *");
610  if (IsObjCLiteral)
611  return ArgType(Ctx.UnsignedShortTy, "unichar");
612  if (Ctx.getTargetInfo().getTriple().isOSMSVCRT() &&
613  LM.getKind() == LengthModifier::AsShort)
614  return Ctx.IntTy;
615  return ArgType(Ctx.WideCharTy, "wchar_t");
618  return ArgType::CPointerTy;
620  return ArgType::ObjCPointerTy;
621  default:
622  break;
623  }
624 
625  // FIXME: Handle other cases.
626  return ArgType();
627 }
628 
629 bool PrintfSpecifier::fixType(QualType QT, const LangOptions &LangOpt,
630  ASTContext &Ctx, bool IsObjCLiteral) {
631  // %n is different from other conversion specifiers; don't try to fix it.
632  if (CS.getKind() == ConversionSpecifier::nArg)
633  return false;
634 
635  // Handle Objective-C objects first. Note that while the '%@' specifier will
636  // not warn for structure pointer or void pointer arguments (because that's
637  // how CoreFoundation objects are implemented), we only show a fixit for '%@'
638  // if we know it's an object (block, id, class, or __attribute__((NSObject))).
639  if (QT->isObjCRetainableType()) {
640  if (!IsObjCLiteral)
641  return false;
642 
644 
645  // Disable irrelevant flags
646  HasThousandsGrouping = false;
647  HasPlusPrefix = false;
648  HasSpacePrefix = false;
649  HasAlternativeForm = false;
650  HasLeadingZeroes = false;
651  Precision.setHowSpecified(OptionalAmount::NotSpecified);
652  LM.setKind(LengthModifier::None);
653 
654  return true;
655  }
656 
657  // Handle strings next (char *, wchar_t *)
658  if (QT->isPointerType() && (QT->getPointeeType()->isAnyCharacterType())) {
659  CS.setKind(ConversionSpecifier::sArg);
660 
661  // Disable irrelevant flags
662  HasAlternativeForm = 0;
663  HasLeadingZeroes = 0;
664 
665  // Set the long length modifier for wide characters
666  if (QT->getPointeeType()->isWideCharType())
667  LM.setKind(LengthModifier::AsWideChar);
668  else
669  LM.setKind(LengthModifier::None);
670 
671  return true;
672  }
673 
674  // If it's an enum, get its underlying type.
675  if (const EnumType *ETy = QT->getAs<EnumType>())
676  QT = ETy->getDecl()->getIntegerType();
677 
678  // We can only work with builtin types.
679  const BuiltinType *BT = QT->getAs<BuiltinType>();
680  if (!BT)
681  return false;
682 
683  // Set length modifier
684  switch (BT->getKind()) {
685  case BuiltinType::Bool:
686  case BuiltinType::WChar_U:
687  case BuiltinType::WChar_S:
688  case BuiltinType::Char8: // FIXME: Treat like 'char'?
689  case BuiltinType::Char16:
690  case BuiltinType::Char32:
691  case BuiltinType::UInt128:
692  case BuiltinType::Int128:
693  case BuiltinType::Half:
694  case BuiltinType::Float16:
695  case BuiltinType::Float128:
696  case BuiltinType::ShortAccum:
697  case BuiltinType::Accum:
698  case BuiltinType::LongAccum:
699  case BuiltinType::UShortAccum:
700  case BuiltinType::UAccum:
701  case BuiltinType::ULongAccum:
702  case BuiltinType::ShortFract:
703  case BuiltinType::Fract:
704  case BuiltinType::LongFract:
705  case BuiltinType::UShortFract:
706  case BuiltinType::UFract:
707  case BuiltinType::ULongFract:
708  case BuiltinType::SatShortAccum:
709  case BuiltinType::SatAccum:
710  case BuiltinType::SatLongAccum:
711  case BuiltinType::SatUShortAccum:
712  case BuiltinType::SatUAccum:
713  case BuiltinType::SatULongAccum:
714  case BuiltinType::SatShortFract:
715  case BuiltinType::SatFract:
716  case BuiltinType::SatLongFract:
717  case BuiltinType::SatUShortFract:
718  case BuiltinType::SatUFract:
719  case BuiltinType::SatULongFract:
720  // Various types which are non-trivial to correct.
721  return false;
722 
723 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
724  case BuiltinType::Id:
725 #include "clang/Basic/OpenCLImageTypes.def"
726 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
727  case BuiltinType::Id:
728 #include "clang/Basic/OpenCLExtensionTypes.def"
729 #define SIGNED_TYPE(Id, SingletonId)
730 #define UNSIGNED_TYPE(Id, SingletonId)
731 #define FLOATING_TYPE(Id, SingletonId)
732 #define BUILTIN_TYPE(Id, SingletonId) \
733  case BuiltinType::Id:
734 #include "clang/AST/BuiltinTypes.def"
735  // Misc other stuff which doesn't make sense here.
736  return false;
737 
738  case BuiltinType::UInt:
739  case BuiltinType::Int:
740  case BuiltinType::Float:
741  case BuiltinType::Double:
742  LM.setKind(LengthModifier::None);
743  break;
744 
745  case BuiltinType::Char_U:
746  case BuiltinType::UChar:
747  case BuiltinType::Char_S:
748  case BuiltinType::SChar:
749  LM.setKind(LengthModifier::AsChar);
750  break;
751 
752  case BuiltinType::Short:
753  case BuiltinType::UShort:
754  LM.setKind(LengthModifier::AsShort);
755  break;
756 
757  case BuiltinType::Long:
758  case BuiltinType::ULong:
759  LM.setKind(LengthModifier::AsLong);
760  break;
761 
762  case BuiltinType::LongLong:
763  case BuiltinType::ULongLong:
764  LM.setKind(LengthModifier::AsLongLong);
765  break;
766 
767  case BuiltinType::LongDouble:
768  LM.setKind(LengthModifier::AsLongDouble);
769  break;
770  }
771 
772  // Handle size_t, ptrdiff_t, etc. that have dedicated length modifiers in C99.
773  if (isa<TypedefType>(QT) && (LangOpt.C99 || LangOpt.CPlusPlus11))
774  namedTypeToLengthModifier(QT, LM);
775 
776  // If fixing the length modifier was enough, we might be done.
777  if (hasValidLengthModifier(Ctx.getTargetInfo())) {
778  // If we're going to offer a fix anyway, make sure the sign matches.
779  switch (CS.getKind()) {
782  if (QT->isSignedIntegerType())
784  break;
788  if (QT->isUnsignedIntegerType() && !HasPlusPrefix)
790  break;
791  default:
792  // Other specifiers do not have signed/unsigned variants.
793  break;
794  }
795 
796  const analyze_printf::ArgType &ATR = getArgType(Ctx, IsObjCLiteral);
797  if (ATR.isValid() && ATR.matchesType(Ctx, QT))
798  return true;
799  }
800 
801  // Set conversion specifier and disable any flags which do not apply to it.
802  // Let typedefs to char fall through to int, as %c is silly for uint8_t.
803  if (!isa<TypedefType>(QT) && QT->isCharType()) {
804  CS.setKind(ConversionSpecifier::cArg);
805  LM.setKind(LengthModifier::None);
806  Precision.setHowSpecified(OptionalAmount::NotSpecified);
807  HasAlternativeForm = 0;
808  HasLeadingZeroes = 0;
809  HasPlusPrefix = 0;
810  }
811  // Test for Floating type first as LongDouble can pass isUnsignedIntegerType
812  else if (QT->isRealFloatingType()) {
813  CS.setKind(ConversionSpecifier::fArg);
814  }
815  else if (QT->isSignedIntegerType()) {
816  CS.setKind(ConversionSpecifier::dArg);
817  HasAlternativeForm = 0;
818  }
819  else if (QT->isUnsignedIntegerType()) {
820  CS.setKind(ConversionSpecifier::uArg);
821  HasAlternativeForm = 0;
822  HasPlusPrefix = 0;
823  } else {
824  llvm_unreachable("Unexpected type");
825  }
826 
827  return true;
828 }
829 
830 void PrintfSpecifier::toString(raw_ostream &os) const {
831  // Whilst some features have no defined order, we are using the order
832  // appearing in the C99 standard (ISO/IEC 9899:1999 (E) 7.19.6.1)
833  os << "%";
834 
835  // Positional args
836  if (usesPositionalArg()) {
837  os << getPositionalArgIndex() << "$";
838  }
839 
840  // Conversion flags
841  if (IsLeftJustified) os << "-";
842  if (HasPlusPrefix) os << "+";
843  if (HasSpacePrefix) os << " ";
844  if (HasAlternativeForm) os << "#";
845  if (HasLeadingZeroes) os << "0";
846 
847  // Minimum field width
848  FieldWidth.toString(os);
849  // Precision
850  Precision.toString(os);
851  // Length modifier
852  os << LM.toString();
853  // Conversion specifier
854  os << CS.toString();
855 }
856 
857 bool PrintfSpecifier::hasValidPlusPrefix() const {
858  if (!HasPlusPrefix)
859  return true;
860 
861  // The plus prefix only makes sense for signed conversions
862  switch (CS.getKind()) {
876  return true;
877 
878  default:
879  return false;
880  }
881 }
882 
883 bool PrintfSpecifier::hasValidAlternativeForm() const {
884  if (!HasAlternativeForm)
885  return true;
886 
887  // Alternate form flag only valid with the oxXaAeEfFgG conversions
888  switch (CS.getKind()) {
903  return true;
904 
905  default:
906  return false;
907  }
908 }
909 
910 bool PrintfSpecifier::hasValidLeadingZeros() const {
911  if (!HasLeadingZeroes)
912  return true;
913 
914  // Leading zeroes flag only valid with the diouxXaAeEfFgG conversions
915  switch (CS.getKind()) {
935  return true;
936 
937  default:
938  return false;
939  }
940 }
941 
942 bool PrintfSpecifier::hasValidSpacePrefix() const {
943  if (!HasSpacePrefix)
944  return true;
945 
946  // The space prefix only makes sense for signed conversions
947  switch (CS.getKind()) {
961  return true;
962 
963  default:
964  return false;
965  }
966 }
967 
968 bool PrintfSpecifier::hasValidLeftJustified() const {
969  if (!IsLeftJustified)
970  return true;
971 
972  // The left justified flag is valid for all conversions except n
973  switch (CS.getKind()) {
975  return false;
976 
977  default:
978  return true;
979  }
980 }
981 
982 bool PrintfSpecifier::hasValidThousandsGroupingPrefix() const {
983  if (!HasThousandsGrouping)
984  return true;
985 
986  switch (CS.getKind()) {
996  return true;
997  default:
998  return false;
999  }
1000 }
1001 
1002 bool PrintfSpecifier::hasValidPrecision() const {
1003  if (Precision.getHowSpecified() == OptionalAmount::NotSpecified)
1004  return true;
1005 
1006  // Precision is only valid with the diouxXaAeEfFgGsP conversions
1007  switch (CS.getKind()) {
1029  return true;
1030 
1031  default:
1032  return false;
1033  }
1034 }
1035 bool PrintfSpecifier::hasValidFieldWidth() const {
1036  if (FieldWidth.getHowSpecified() == OptionalAmount::NotSpecified)
1037  return true;
1038 
1039  // The field width is valid for all conversions except n
1040  switch (CS.getKind()) {
1042  return false;
1043 
1044  default:
1045  return true;
1046  }
1047 }
QualType withConst() const
Retrieves a version of this type with const applied.
CanQualType LongLongTy
Definition: ASTContext.h:1034
static ArgType makePtrdiffT(const ArgType &A)
Create an ArgType which corresponds to the ptrdiff_t/unsigned ptrdiff_t type.
Definition: FormatString.h:296
A (possibly-)qualified type.
Definition: Type.h:642
void setIsPublic(const char *position)
Definition: FormatString.h:517
QualType getPointerDiffType() const
Return the unique type for "ptrdiff_t" (C99 7.17) defined in <stddef.h>.
Kind getKind() const
Definition: Type.h:2424
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee...
Definition: Type.cpp:497
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
Definition: TargetInfo.h:949
bool isRealFloatingType() const
Floating point categories.
Definition: Type.cpp:1929
virtual void HandleInvalidObjCModifierFlag(const char *startFlag, unsigned flagLen)
Definition: FormatString.h:677
static bool ParseObjCFlags(FormatStringHandler &H, PrintfSpecifier &FS, const char *FlagBeg, const char *E, bool Warn)
static bool ParsePrecision(FormatStringHandler &H, PrintfSpecifier &FS, const char *Start, const char *&Beg, const char *E, unsigned *argIndex)
bool ParseArgPosition(FormatStringHandler &H, FormatSpecifier &CS, const char *Start, const char *&Beg, const char *E)
CanQualType LongTy
Definition: ASTContext.h:1034
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:699
void setHasLeadingZeros(const char *position)
Definition: FormatString.h:510
CanQualType WideCharTy
Definition: ASTContext.h:1029
bool isUnsignedIntegerType() const
Return true if this is an integer type that is unsigned, according to C99 6.2.5p6 [which returns true...
Definition: Type.cpp:1876
const T * getAs() const
Member-template getAs<specific type>&#39;.
Definition: Type.h:6716
virtual void HandleEmptyObjCModifierFlag(const char *startFlags, unsigned flagsLen)
Definition: FormatString.h:674
bool isWideCharType() const
Definition: Type.cpp:1788
void setPrecision(const OptionalAmount &Amt)
Definition: FormatString.h:529
static ArgType makeSizeT(const ArgType &A)
Create an ArgType which corresponds to the size_t/ssize_t type.
Definition: FormatString.h:288
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:154
Pieces specific to fprintf format strings.
Definition: FormatString.h:443
bool isCharType() const
Definition: Type.cpp:1779
void setHasSpacePrefix(const char *position)
Definition: FormatString.h:504
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:50
QualType getUnsignedPointerDiffType() const
Return the unique unsigned counterpart of "ptrdiff_t" integer type.
void setConversionSpecifier(const PrintfConversionSpecifier &cs)
Definition: FormatString.h:492
virtual bool HandleInvalidPrintfConversionSpecifier(const analyze_printf::PrintfSpecifier &FS, const char *startSpecifier, unsigned specifierLen)
Definition: FormatString.h:685
MatchKind matchesType(ASTContext &C, QualType argTy) const
Represents the length modifier in a format string in scanf/printf.
Definition: FormatString.h:65
CanQualType LongDoubleTy
Definition: ASTContext.h:1037
void setIsLeftJustified(const char *position)
Definition: FormatString.h:498
virtual void handleInvalidMaskType(StringRef MaskType)
Handle mask types whose sizes are not between one and eight bytes.
Definition: FormatString.h:699
CanQualType UnsignedCharTy
Definition: ASTContext.h:1035
static ArgType PtrTo(const ArgType &A)
Create an ArgType which corresponds to the type pointer to A.
Definition: FormatString.h:280
OptionalAmount ParseNonPositionAmount(const char *&Beg, const char *E, unsigned &argIndex)
Exposes information about the current target.
Definition: TargetInfo.h:54
bool isObjCRetainableType() const
Definition: Type.cpp:3896
CanQualType ShortTy
Definition: ASTContext.h:1034
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char, signed char, short, int, long..], or an enum decl which has a signed representation.
Definition: Type.cpp:1836
virtual void HandleNullChar(const char *nullCharacter)
Definition: FormatString.h:662
CanQualType SignedCharTy
Definition: ASTContext.h:1034
CanQualType getUIntMaxType() const
Return the unique type for "uintmax_t" (C99 7.18.1.5), defined in <stdint.h>.
bool ParseFormatStringHasSArg(const char *beg, const char *end, const LangOptions &LO, const TargetInfo &Target)
virtual void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart, const char *flagsEnd, const char *conversionPosition)
Definition: FormatString.h:680
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of enums...
Definition: Type.h:4382
void setIsPrivate(const char *position)
Definition: FormatString.h:516
CanQualType getSignedSizeType() const
Return the unique signed counterpart of the integer type corresponding to size_t. ...
void setHasThousandsGrouping(const char *position)
Definition: FormatString.h:495
bool isAnyCharacterType() const
Determine whether this type is any of the built-in character types.
Definition: Type.cpp:1815
bool ParseFieldWidth(FormatStringHandler &H, FormatSpecifier &CS, const char *Start, const char *&Beg, const char *E, unsigned *argIndex)
const PrintfConversionSpecifier & getConversionSpecifier() const
Definition: FormatString.h:525
virtual bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS, const char *startSpecifier, unsigned specifierLen)
Definition: FormatString.h:692
CanQualType UnsignedShortTy
Definition: ASTContext.h:1035
Dataflow Directional Tag Classes.
CanQualType UnsignedLongLongTy
Definition: ASTContext.h:1036
bool ParseUTF8InvalidSpecifier(const char *SpecifierBegin, const char *FmtStrEnd, unsigned &Len)
Returns true if the invalid specifier in SpecifierBegin is a UTF-8 string; check that it won&#39;t go fur...
Common components of both fprintf and fscanf format strings.
Definition: FormatString.h:30
std::string toString(const til::SExpr *E)
void setHasObjCTechnicalTerm(const char *position)
Definition: FormatString.h:513
CanQualType UnsignedLongTy
Definition: ASTContext.h:1035
bool ParseLengthModifier(FormatSpecifier &FS, const char *&Beg, const char *E, const LangOptions &LO, bool IsScanf=false)
Returns true if a LengthModifier was parsed and installed in the FormatSpecifier& argument...
void setHasPlusPrefix(const char *position)
Definition: FormatString.h:501
virtual void HandleIncompleteSpecifier(const char *startSpecifier, unsigned specifierLen)
Definition: FormatString.h:671
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
This class is used for builtin types like &#39;int&#39;.
Definition: Type.h:2397
Defines the clang::TargetInfo interface.
CanQualType IntTy
Definition: ASTContext.h:1034
bool ParsePrintfString(FormatStringHandler &H, const char *beg, const char *end, const LangOptions &LO, const TargetInfo &Target, bool isFreeBSDKPrintf)
bool isPointerType() const
Definition: Type.h:6282
void setHasAlternativeForm(const char *position)
Definition: FormatString.h:507
void setIsSensitive(const char *position)
Definition: FormatString.h:518
clang::analyze_format_string::SpecifierResult< PrintfSpecifier > PrintfSpecifierResult
CanQualType getIntMaxType() const
Return the unique type for "intmax_t" (C99 7.18.1.5), defined in <stdint.h>.
CanQualType DoubleTy
Definition: ASTContext.h:1037
static PrintfSpecifierResult ParsePrintfSpecifier(FormatStringHandler &H, const char *&Beg, const char *E, unsigned &argIndex, const LangOptions &LO, const TargetInfo &Target, bool Warn, bool isFreeBSDKPrintf)
CanQualType UnsignedIntTy
Definition: ASTContext.h:1035
OptionalAmount ParsePositionAmount(FormatStringHandler &H, const char *Start, const char *&Beg, const char *E, PositionContext p)
CanQualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.