FormatString.cpp revision 5deddafd3ef51e94b4ac4d80e38271d3768b1af6
1// FormatString.cpp - Common stuff for handling printf/scanf formats -*- 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// Shared details for processing format strings of printf and scanf
11// (and friends).
12//
13//===----------------------------------------------------------------------===//
14
15#include "FormatStringParsing.h"
16#include "clang/Basic/LangOptions.h"
17
18using clang::analyze_format_string::ArgTypeResult;
19using clang::analyze_format_string::FormatStringHandler;
20using clang::analyze_format_string::FormatSpecifier;
21using clang::analyze_format_string::LengthModifier;
22using clang::analyze_format_string::OptionalAmount;
23using clang::analyze_format_string::PositionContext;
24using clang::analyze_format_string::ConversionSpecifier;
25using namespace clang;
26
27// Key function to FormatStringHandler.
28FormatStringHandler::~FormatStringHandler() {}
29
30//===----------------------------------------------------------------------===//
31// Functions for parsing format strings components in both printf and
32// scanf format strings.
33//===----------------------------------------------------------------------===//
34
35OptionalAmount
36clang::analyze_format_string::ParseAmount(const char *&Beg, const char *E) {
37  const char *I = Beg;
38  UpdateOnReturn <const char*> UpdateBeg(Beg, I);
39
40  unsigned accumulator = 0;
41  bool hasDigits = false;
42
43  for ( ; I != E; ++I) {
44    char c = *I;
45    if (c >= '0' && c <= '9') {
46      hasDigits = true;
47      accumulator = (accumulator * 10) + (c - '0');
48      continue;
49    }
50
51    if (hasDigits)
52      return OptionalAmount(OptionalAmount::Constant, accumulator, Beg, I - Beg,
53          false);
54
55    break;
56  }
57
58  return OptionalAmount();
59}
60
61OptionalAmount
62clang::analyze_format_string::ParseNonPositionAmount(const char *&Beg,
63                                                     const char *E,
64                                                     unsigned &argIndex) {
65  if (*Beg == '*') {
66    ++Beg;
67    return OptionalAmount(OptionalAmount::Arg, argIndex++, Beg, 0, false);
68  }
69
70  return ParseAmount(Beg, E);
71}
72
73OptionalAmount
74clang::analyze_format_string::ParsePositionAmount(FormatStringHandler &H,
75                                                  const char *Start,
76                                                  const char *&Beg,
77                                                  const char *E,
78                                                  PositionContext p) {
79  if (*Beg == '*') {
80    const char *I = Beg + 1;
81    const OptionalAmount &Amt = ParseAmount(I, E);
82
83    if (Amt.getHowSpecified() == OptionalAmount::NotSpecified) {
84      H.HandleInvalidPosition(Beg, I - Beg, p);
85      return OptionalAmount(false);
86    }
87
88    if (I == E) {
89      // No more characters left?
90      H.HandleIncompleteSpecifier(Start, E - Start);
91      return OptionalAmount(false);
92    }
93
94    assert(Amt.getHowSpecified() == OptionalAmount::Constant);
95
96    if (*I == '$') {
97      // Handle positional arguments
98
99      // Special case: '*0$', since this is an easy mistake.
100      if (Amt.getConstantAmount() == 0) {
101        H.HandleZeroPosition(Beg, I - Beg + 1);
102        return OptionalAmount(false);
103      }
104
105      const char *Tmp = Beg;
106      Beg = ++I;
107
108      return OptionalAmount(OptionalAmount::Arg, Amt.getConstantAmount() - 1,
109                            Tmp, 0, true);
110    }
111
112    H.HandleInvalidPosition(Beg, I - Beg, p);
113    return OptionalAmount(false);
114  }
115
116  return ParseAmount(Beg, E);
117}
118
119
120bool
121clang::analyze_format_string::ParseFieldWidth(FormatStringHandler &H,
122                                              FormatSpecifier &CS,
123                                              const char *Start,
124                                              const char *&Beg, const char *E,
125                                              unsigned *argIndex) {
126  // FIXME: Support negative field widths.
127  if (argIndex) {
128    CS.setFieldWidth(ParseNonPositionAmount(Beg, E, *argIndex));
129  }
130  else {
131    const OptionalAmount Amt =
132      ParsePositionAmount(H, Start, Beg, E,
133                          analyze_format_string::FieldWidthPos);
134
135    if (Amt.isInvalid())
136      return true;
137    CS.setFieldWidth(Amt);
138  }
139  return false;
140}
141
142bool
143clang::analyze_format_string::ParseArgPosition(FormatStringHandler &H,
144                                               FormatSpecifier &FS,
145                                               const char *Start,
146                                               const char *&Beg,
147                                               const char *E) {
148  const char *I = Beg;
149
150  const OptionalAmount &Amt = ParseAmount(I, E);
151
152  if (I == E) {
153    // No more characters left?
154    H.HandleIncompleteSpecifier(Start, E - Start);
155    return true;
156  }
157
158  if (Amt.getHowSpecified() == OptionalAmount::Constant && *(I++) == '$') {
159    // Warn that positional arguments are non-standard.
160    H.HandlePosition(Start, I - Start);
161
162    // Special case: '%0$', since this is an easy mistake.
163    if (Amt.getConstantAmount() == 0) {
164      H.HandleZeroPosition(Start, I - Start);
165      return true;
166    }
167
168    FS.setArgIndex(Amt.getConstantAmount() - 1);
169    FS.setUsesPositionalArg();
170    // Update the caller's pointer if we decided to consume
171    // these characters.
172    Beg = I;
173    return false;
174  }
175
176  return false;
177}
178
179bool
180clang::analyze_format_string::ParseLengthModifier(FormatSpecifier &FS,
181                                                  const char *&I,
182                                                  const char *E,
183                                                  const LangOptions &LO,
184                                                  bool IsScanf) {
185  LengthModifier::Kind lmKind = LengthModifier::None;
186  const char *lmPosition = I;
187  switch (*I) {
188    default:
189      return false;
190    case 'h':
191      ++I;
192      lmKind = (I != E && *I == 'h') ? (++I, LengthModifier::AsChar)
193                                     : LengthModifier::AsShort;
194      break;
195    case 'l':
196      ++I;
197      lmKind = (I != E && *I == 'l') ? (++I, LengthModifier::AsLongLong)
198                                     : LengthModifier::AsLong;
199      break;
200    case 'j': lmKind = LengthModifier::AsIntMax;     ++I; break;
201    case 'z': lmKind = LengthModifier::AsSizeT;      ++I; break;
202    case 't': lmKind = LengthModifier::AsPtrDiff;    ++I; break;
203    case 'L': lmKind = LengthModifier::AsLongDouble; ++I; break;
204    case 'q': lmKind = LengthModifier::AsQuad;       ++I; break;
205    case 'a':
206      if (IsScanf && !LO.C99 && !LO.CPlusPlus0x) {
207        // For scanf in C90, look at the next character to see if this should
208        // be parsed as the GNU extension 'a' length modifier. If not, this
209        // will be parsed as a conversion specifier.
210        ++I;
211        if (I != E && (*I == 's' || *I == 'S' || *I == '[')) {
212          lmKind = LengthModifier::AsAllocate;
213          break;
214        }
215        --I;
216      }
217      return false;
218    case 'm':
219      if (IsScanf) {
220        lmKind = LengthModifier::AsMAllocate;
221        ++I;
222        break;
223      }
224      return false;
225  }
226  LengthModifier lm(lmPosition, lmKind);
227  FS.setLengthModifier(lm);
228  return true;
229}
230
231//===----------------------------------------------------------------------===//
232// Methods on ArgTypeResult.
233//===----------------------------------------------------------------------===//
234
235bool ArgTypeResult::matchesType(ASTContext &C, QualType argTy) const {
236  switch (K) {
237    case InvalidTy:
238      llvm_unreachable("ArgTypeResult must be valid");
239
240    case UnknownTy:
241      return true;
242
243    case AnyCharTy: {
244      if (const EnumType *ETy = argTy->getAs<EnumType>())
245        argTy = ETy->getDecl()->getIntegerType();
246
247      if (const BuiltinType *BT = argTy->getAs<BuiltinType>())
248        switch (BT->getKind()) {
249          default:
250            break;
251          case BuiltinType::Char_S:
252          case BuiltinType::SChar:
253          case BuiltinType::UChar:
254          case BuiltinType::Char_U:
255            return true;
256        }
257      return false;
258    }
259
260    case SpecificTy: {
261      if (const EnumType *ETy = argTy->getAs<EnumType>())
262        argTy = ETy->getDecl()->getIntegerType();
263      argTy = C.getCanonicalType(argTy).getUnqualifiedType();
264
265      if (const PointerType *PTy = argTy->getAs<PointerType>()) {
266        // Strip volatile qualifier from pointee type.
267        QualType Pointee = PTy->getPointeeType();
268        Pointee.removeLocalVolatile();
269        argTy = C.getPointerType(Pointee);
270      }
271
272      if (T == argTy)
273        return true;
274      // Check for "compatible types".
275      if (const BuiltinType *BT = argTy->getAs<BuiltinType>())
276        switch (BT->getKind()) {
277          default:
278            break;
279          case BuiltinType::Char_S:
280          case BuiltinType::SChar:
281          case BuiltinType::Char_U:
282          case BuiltinType::UChar:
283            return T == C.UnsignedCharTy || T == C.SignedCharTy;
284          case BuiltinType::Short:
285            return T == C.UnsignedShortTy;
286          case BuiltinType::UShort:
287            return T == C.ShortTy;
288          case BuiltinType::Int:
289            return T == C.UnsignedIntTy;
290          case BuiltinType::UInt:
291            return T == C.IntTy;
292          case BuiltinType::Long:
293            return T == C.UnsignedLongTy;
294          case BuiltinType::ULong:
295            return T == C.LongTy;
296          case BuiltinType::LongLong:
297            return T == C.UnsignedLongLongTy;
298          case BuiltinType::ULongLong:
299            return T == C.LongLongTy;
300        }
301      return false;
302    }
303
304    case CStrTy: {
305      const PointerType *PT = argTy->getAs<PointerType>();
306      if (!PT)
307        return false;
308      QualType pointeeTy = PT->getPointeeType();
309      if (const BuiltinType *BT = pointeeTy->getAs<BuiltinType>())
310        switch (BT->getKind()) {
311          case BuiltinType::Void:
312          case BuiltinType::Char_U:
313          case BuiltinType::UChar:
314          case BuiltinType::Char_S:
315          case BuiltinType::SChar:
316            return true;
317          default:
318            break;
319        }
320
321      return false;
322    }
323
324    case WCStrTy: {
325      const PointerType *PT = argTy->getAs<PointerType>();
326      if (!PT)
327        return false;
328      QualType pointeeTy =
329        C.getCanonicalType(PT->getPointeeType()).getUnqualifiedType();
330      return pointeeTy == C.getWCharType();
331    }
332
333    case WIntTy: {
334
335      QualType PromoArg =
336        argTy->isPromotableIntegerType()
337          ? C.getPromotedIntegerType(argTy) : argTy;
338
339      QualType WInt = C.getCanonicalType(C.getWIntType()).getUnqualifiedType();
340      PromoArg = C.getCanonicalType(PromoArg).getUnqualifiedType();
341
342      // If the promoted argument is the corresponding signed type of the
343      // wint_t type, then it should match.
344      if (PromoArg->hasSignedIntegerRepresentation() &&
345          C.getCorrespondingUnsignedType(PromoArg) == WInt)
346        return true;
347
348      return WInt == PromoArg;
349    }
350
351    case CPointerTy:
352      return argTy->isPointerType() || argTy->isObjCObjectPointerType() ||
353             argTy->isBlockPointerType() || argTy->isNullPtrType();
354
355    case ObjCPointerTy: {
356      if (argTy->getAs<ObjCObjectPointerType>() ||
357          argTy->getAs<BlockPointerType>())
358        return true;
359
360      // Handle implicit toll-free bridging.
361      if (const PointerType *PT = argTy->getAs<PointerType>()) {
362        // Things such as CFTypeRef are really just opaque pointers
363        // to C structs representing CF types that can often be bridged
364        // to Objective-C objects.  Since the compiler doesn't know which
365        // structs can be toll-free bridged, we just accept them all.
366        QualType pointee = PT->getPointeeType();
367        if (pointee->getAsStructureType() || pointee->isVoidType())
368          return true;
369      }
370      return false;
371    }
372  }
373
374  llvm_unreachable("Invalid ArgTypeResult Kind!");
375}
376
377QualType ArgTypeResult::getRepresentativeType(ASTContext &C) const {
378  switch (K) {
379    case InvalidTy:
380      llvm_unreachable("No representative type for Invalid ArgTypeResult");
381    case UnknownTy:
382      return QualType();
383    case AnyCharTy:
384      return C.CharTy;
385    case SpecificTy:
386      return T;
387    case CStrTy:
388      return C.getPointerType(C.CharTy);
389    case WCStrTy:
390      return C.getPointerType(C.getWCharType());
391    case ObjCPointerTy:
392      return C.ObjCBuiltinIdTy;
393    case CPointerTy:
394      return C.VoidPtrTy;
395    case WIntTy: {
396      return C.getWIntType();
397    }
398  }
399
400  llvm_unreachable("Invalid ArgTypeResult Kind!");
401}
402
403std::string ArgTypeResult::getRepresentativeTypeName(ASTContext &C) const {
404  std::string S = getRepresentativeType(C).getAsString();
405  if (Name && S != Name)
406    return std::string("'") + Name + "' (aka '" + S + "')";
407  return std::string("'") + S + "'";
408}
409
410
411//===----------------------------------------------------------------------===//
412// Methods on OptionalAmount.
413//===----------------------------------------------------------------------===//
414
415ArgTypeResult
416analyze_format_string::OptionalAmount::getArgType(ASTContext &Ctx) const {
417  return Ctx.IntTy;
418}
419
420//===----------------------------------------------------------------------===//
421// Methods on LengthModifier.
422//===----------------------------------------------------------------------===//
423
424const char *
425analyze_format_string::LengthModifier::toString() const {
426  switch (kind) {
427  case AsChar:
428    return "hh";
429  case AsShort:
430    return "h";
431  case AsLong: // or AsWideChar
432    return "l";
433  case AsLongLong:
434    return "ll";
435  case AsQuad:
436    return "q";
437  case AsIntMax:
438    return "j";
439  case AsSizeT:
440    return "z";
441  case AsPtrDiff:
442    return "t";
443  case AsLongDouble:
444    return "L";
445  case AsAllocate:
446    return "a";
447  case AsMAllocate:
448    return "m";
449  case None:
450    return "";
451  }
452  return NULL;
453}
454
455//===----------------------------------------------------------------------===//
456// Methods on ConversionSpecifier.
457//===----------------------------------------------------------------------===//
458
459const char *ConversionSpecifier::toString() const {
460  switch (kind) {
461  case dArg: return "d";
462  case iArg: return "i";
463  case oArg: return "o";
464  case uArg: return "u";
465  case xArg: return "x";
466  case XArg: return "X";
467  case fArg: return "f";
468  case FArg: return "F";
469  case eArg: return "e";
470  case EArg: return "E";
471  case gArg: return "g";
472  case GArg: return "G";
473  case aArg: return "a";
474  case AArg: return "A";
475  case cArg: return "c";
476  case sArg: return "s";
477  case pArg: return "p";
478  case nArg: return "n";
479  case PercentArg:  return "%";
480  case ScanListArg: return "[";
481  case InvalidSpecifier: return NULL;
482
483  // MacOS X unicode extensions.
484  case CArg: return "C";
485  case SArg: return "S";
486
487  // Objective-C specific specifiers.
488  case ObjCObjArg: return "@";
489
490  // GlibC specific specifiers.
491  case PrintErrno: return "m";
492  }
493  return NULL;
494}
495
496//===----------------------------------------------------------------------===//
497// Methods on OptionalAmount.
498//===----------------------------------------------------------------------===//
499
500void OptionalAmount::toString(raw_ostream &os) const {
501  switch (hs) {
502  case Invalid:
503  case NotSpecified:
504    return;
505  case Arg:
506    if (UsesDotPrefix)
507        os << ".";
508    if (usesPositionalArg())
509      os << "*" << getPositionalArgIndex() << "$";
510    else
511      os << "*";
512    break;
513  case Constant:
514    if (UsesDotPrefix)
515        os << ".";
516    os << amt;
517    break;
518  }
519}
520
521bool FormatSpecifier::hasValidLengthModifier() const {
522  switch (LM.getKind()) {
523    case LengthModifier::None:
524      return true;
525
526    // Handle most integer flags
527    case LengthModifier::AsChar:
528    case LengthModifier::AsShort:
529    case LengthModifier::AsLongLong:
530    case LengthModifier::AsQuad:
531    case LengthModifier::AsIntMax:
532    case LengthModifier::AsSizeT:
533    case LengthModifier::AsPtrDiff:
534      switch (CS.getKind()) {
535        case ConversionSpecifier::dArg:
536        case ConversionSpecifier::iArg:
537        case ConversionSpecifier::oArg:
538        case ConversionSpecifier::uArg:
539        case ConversionSpecifier::xArg:
540        case ConversionSpecifier::XArg:
541        case ConversionSpecifier::nArg:
542          return true;
543        default:
544          return false;
545      }
546
547    // Handle 'l' flag
548    case LengthModifier::AsLong:
549      switch (CS.getKind()) {
550        case ConversionSpecifier::dArg:
551        case ConversionSpecifier::iArg:
552        case ConversionSpecifier::oArg:
553        case ConversionSpecifier::uArg:
554        case ConversionSpecifier::xArg:
555        case ConversionSpecifier::XArg:
556        case ConversionSpecifier::aArg:
557        case ConversionSpecifier::AArg:
558        case ConversionSpecifier::fArg:
559        case ConversionSpecifier::FArg:
560        case ConversionSpecifier::eArg:
561        case ConversionSpecifier::EArg:
562        case ConversionSpecifier::gArg:
563        case ConversionSpecifier::GArg:
564        case ConversionSpecifier::nArg:
565        case ConversionSpecifier::cArg:
566        case ConversionSpecifier::sArg:
567        case ConversionSpecifier::ScanListArg:
568          return true;
569        default:
570          return false;
571      }
572
573    case LengthModifier::AsLongDouble:
574      switch (CS.getKind()) {
575        case ConversionSpecifier::aArg:
576        case ConversionSpecifier::AArg:
577        case ConversionSpecifier::fArg:
578        case ConversionSpecifier::FArg:
579        case ConversionSpecifier::eArg:
580        case ConversionSpecifier::EArg:
581        case ConversionSpecifier::gArg:
582        case ConversionSpecifier::GArg:
583          return true;
584        // GNU extension.
585        case ConversionSpecifier::dArg:
586        case ConversionSpecifier::iArg:
587        case ConversionSpecifier::oArg:
588        case ConversionSpecifier::uArg:
589        case ConversionSpecifier::xArg:
590        case ConversionSpecifier::XArg:
591          return true;
592        default:
593          return false;
594      }
595
596    case LengthModifier::AsAllocate:
597      switch (CS.getKind()) {
598        case ConversionSpecifier::sArg:
599        case ConversionSpecifier::SArg:
600        case ConversionSpecifier::ScanListArg:
601          return true;
602        default:
603          return false;
604      }
605
606    case LengthModifier::AsMAllocate:
607      switch (CS.getKind()) {
608        case ConversionSpecifier::cArg:
609        case ConversionSpecifier::CArg:
610        case ConversionSpecifier::sArg:
611        case ConversionSpecifier::SArg:
612        case ConversionSpecifier::ScanListArg:
613          return true;
614        default:
615          return false;
616      }
617  }
618  llvm_unreachable("Invalid LengthModifier Kind!");
619}
620
621bool FormatSpecifier::hasStandardLengthModifier() const {
622  switch (LM.getKind()) {
623    case LengthModifier::None:
624    case LengthModifier::AsChar:
625    case LengthModifier::AsShort:
626    case LengthModifier::AsLong:
627    case LengthModifier::AsLongLong:
628    case LengthModifier::AsIntMax:
629    case LengthModifier::AsSizeT:
630    case LengthModifier::AsPtrDiff:
631    case LengthModifier::AsLongDouble:
632      return true;
633    case LengthModifier::AsAllocate:
634    case LengthModifier::AsMAllocate:
635    case LengthModifier::AsQuad:
636      return false;
637  }
638  llvm_unreachable("Invalid LengthModifier Kind!");
639}
640
641bool FormatSpecifier::hasStandardConversionSpecifier(const LangOptions &LangOpt) const {
642  switch (CS.getKind()) {
643    case ConversionSpecifier::cArg:
644    case ConversionSpecifier::dArg:
645    case ConversionSpecifier::iArg:
646    case ConversionSpecifier::oArg:
647    case ConversionSpecifier::uArg:
648    case ConversionSpecifier::xArg:
649    case ConversionSpecifier::XArg:
650    case ConversionSpecifier::fArg:
651    case ConversionSpecifier::FArg:
652    case ConversionSpecifier::eArg:
653    case ConversionSpecifier::EArg:
654    case ConversionSpecifier::gArg:
655    case ConversionSpecifier::GArg:
656    case ConversionSpecifier::aArg:
657    case ConversionSpecifier::AArg:
658    case ConversionSpecifier::sArg:
659    case ConversionSpecifier::pArg:
660    case ConversionSpecifier::nArg:
661    case ConversionSpecifier::ObjCObjArg:
662    case ConversionSpecifier::ScanListArg:
663    case ConversionSpecifier::PercentArg:
664      return true;
665    case ConversionSpecifier::CArg:
666    case ConversionSpecifier::SArg:
667      return LangOpt.ObjC1 || LangOpt.ObjC2;
668    case ConversionSpecifier::InvalidSpecifier:
669    case ConversionSpecifier::PrintErrno:
670      return false;
671  }
672  llvm_unreachable("Invalid ConversionSpecifier Kind!");
673}
674
675bool FormatSpecifier::hasStandardLengthConversionCombination() const {
676  if (LM.getKind() == LengthModifier::AsLongDouble) {
677    switch(CS.getKind()) {
678        case ConversionSpecifier::dArg:
679        case ConversionSpecifier::iArg:
680        case ConversionSpecifier::oArg:
681        case ConversionSpecifier::uArg:
682        case ConversionSpecifier::xArg:
683        case ConversionSpecifier::XArg:
684          return false;
685        default:
686          return true;
687    }
688  }
689  return true;
690}
691
692bool FormatSpecifier::namedTypeToLengthModifier(QualType QT,
693                                                LengthModifier &LM) {
694  assert(isa<TypedefType>(QT) && "Expected a TypedefType");
695  const TypedefNameDecl *Typedef = cast<TypedefType>(QT)->getDecl();
696
697  for (;;) {
698    const IdentifierInfo *Identifier = Typedef->getIdentifier();
699    if (Identifier->getName() == "size_t") {
700      LM.setKind(LengthModifier::AsSizeT);
701      return true;
702    } else if (Identifier->getName() == "ssize_t") {
703      // Not C99, but common in Unix.
704      LM.setKind(LengthModifier::AsSizeT);
705      return true;
706    } else if (Identifier->getName() == "intmax_t") {
707      LM.setKind(LengthModifier::AsIntMax);
708      return true;
709    } else if (Identifier->getName() == "uintmax_t") {
710      LM.setKind(LengthModifier::AsIntMax);
711      return true;
712    } else if (Identifier->getName() == "ptrdiff_t") {
713      LM.setKind(LengthModifier::AsPtrDiff);
714      return true;
715    }
716
717    QualType T = Typedef->getUnderlyingType();
718    if (!isa<TypedefType>(T))
719      break;
720
721    Typedef = cast<TypedefType>(T)->getDecl();
722  }
723  return false;
724}
725