1 // FormatString.cpp - Common stuff for handling printf/scanf formats -*- C++ -*-
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // Shared details for processing format strings of printf and scanf
13 //===----------------------------------------------------------------------===//
15 #include "FormatStringParsing.h"
16 #include "clang/Basic/LangOptions.h"
17 #include "clang/Basic/TargetInfo.h"
19 using clang::analyze_format_string::ArgType;
20 using clang::analyze_format_string::FormatStringHandler;
21 using clang::analyze_format_string::FormatSpecifier;
22 using clang::analyze_format_string::LengthModifier;
23 using clang::analyze_format_string::OptionalAmount;
24 using clang::analyze_format_string::PositionContext;
25 using clang::analyze_format_string::ConversionSpecifier;
26 using namespace clang;
28 // Key function to FormatStringHandler.
29 FormatStringHandler::~FormatStringHandler() {}
31 //===----------------------------------------------------------------------===//
32 // Functions for parsing format strings components in both printf and
33 // scanf format strings.
34 //===----------------------------------------------------------------------===//
37 clang::analyze_format_string::ParseAmount(const char *&Beg, const char *E) {
39 UpdateOnReturn <const char*> UpdateBeg(Beg, I);
41 unsigned accumulator = 0;
42 bool hasDigits = false;
44 for ( ; I != E; ++I) {
46 if (c >= '0' && c <= '9') {
48 accumulator = (accumulator * 10) + (c - '0');
53 return OptionalAmount(OptionalAmount::Constant, accumulator, Beg, I - Beg,
59 return OptionalAmount();
63 clang::analyze_format_string::ParseNonPositionAmount(const char *&Beg,
68 return OptionalAmount(OptionalAmount::Arg, argIndex++, Beg, 0, false);
71 return ParseAmount(Beg, E);
75 clang::analyze_format_string::ParsePositionAmount(FormatStringHandler &H,
81 const char *I = Beg + 1;
82 const OptionalAmount &Amt = ParseAmount(I, E);
84 if (Amt.getHowSpecified() == OptionalAmount::NotSpecified) {
85 H.HandleInvalidPosition(Beg, I - Beg, p);
86 return OptionalAmount(false);
90 // No more characters left?
91 H.HandleIncompleteSpecifier(Start, E - Start);
92 return OptionalAmount(false);
95 assert(Amt.getHowSpecified() == OptionalAmount::Constant);
98 // Handle positional arguments
100 // Special case: '*0$', since this is an easy mistake.
101 if (Amt.getConstantAmount() == 0) {
102 H.HandleZeroPosition(Beg, I - Beg + 1);
103 return OptionalAmount(false);
106 const char *Tmp = Beg;
109 return OptionalAmount(OptionalAmount::Arg, Amt.getConstantAmount() - 1,
113 H.HandleInvalidPosition(Beg, I - Beg, p);
114 return OptionalAmount(false);
117 return ParseAmount(Beg, E);
122 clang::analyze_format_string::ParseFieldWidth(FormatStringHandler &H,
125 const char *&Beg, const char *E,
126 unsigned *argIndex) {
127 // FIXME: Support negative field widths.
129 CS.setFieldWidth(ParseNonPositionAmount(Beg, E, *argIndex));
132 const OptionalAmount Amt =
133 ParsePositionAmount(H, Start, Beg, E,
134 analyze_format_string::FieldWidthPos);
138 CS.setFieldWidth(Amt);
144 clang::analyze_format_string::ParseArgPosition(FormatStringHandler &H,
151 const OptionalAmount &Amt = ParseAmount(I, E);
154 // No more characters left?
155 H.HandleIncompleteSpecifier(Start, E - Start);
159 if (Amt.getHowSpecified() == OptionalAmount::Constant && *(I++) == '$') {
160 // Warn that positional arguments are non-standard.
161 H.HandlePosition(Start, I - Start);
163 // Special case: '%0$', since this is an easy mistake.
164 if (Amt.getConstantAmount() == 0) {
165 H.HandleZeroPosition(Start, I - Start);
169 FS.setArgIndex(Amt.getConstantAmount() - 1);
170 FS.setUsesPositionalArg();
171 // Update the caller's pointer if we decided to consume
181 clang::analyze_format_string::ParseLengthModifier(FormatSpecifier &FS,
184 const LangOptions &LO,
186 LengthModifier::Kind lmKind = LengthModifier::None;
187 const char *lmPosition = I;
193 lmKind = (I != E && *I == 'h') ? (++I, LengthModifier::AsChar)
194 : LengthModifier::AsShort;
198 lmKind = (I != E && *I == 'l') ? (++I, LengthModifier::AsLongLong)
199 : LengthModifier::AsLong;
201 case 'j': lmKind = LengthModifier::AsIntMax; ++I; break;
202 case 'z': lmKind = LengthModifier::AsSizeT; ++I; break;
203 case 't': lmKind = LengthModifier::AsPtrDiff; ++I; break;
204 case 'L': lmKind = LengthModifier::AsLongDouble; ++I; break;
205 case 'q': lmKind = LengthModifier::AsQuad; ++I; break;
207 if (IsScanf && !LO.C99 && !LO.CPlusPlus11) {
208 // For scanf in C90, look at the next character to see if this should
209 // be parsed as the GNU extension 'a' length modifier. If not, this
210 // will be parsed as a conversion specifier.
212 if (I != E && (*I == 's' || *I == 'S' || *I == '[')) {
213 lmKind = LengthModifier::AsAllocate;
221 lmKind = LengthModifier::AsMAllocate;
226 // printf: AsInt64, AsInt32, AsInt3264
229 if (I + 1 != E && I + 2 != E) {
230 if (I[1] == '6' && I[2] == '4') {
232 lmKind = LengthModifier::AsInt64;
238 if (I[1] == '3' && I[2] == '2') {
240 lmKind = LengthModifier::AsInt32;
245 lmKind = LengthModifier::AsInt3264;
248 LengthModifier lm(lmPosition, lmKind);
249 FS.setLengthModifier(lm);
253 //===----------------------------------------------------------------------===//
254 // Methods on ArgType.
255 //===----------------------------------------------------------------------===//
257 bool ArgType::matchesType(ASTContext &C, QualType argTy) const {
259 // It has to be a pointer.
260 const PointerType *PT = argTy->getAs<PointerType>();
264 // We cannot write through a const qualified pointer.
265 if (PT->getPointeeType().isConstQualified())
268 argTy = PT->getPointeeType();
273 llvm_unreachable("ArgType must be valid");
279 if (const EnumType *ETy = argTy->getAs<EnumType>())
280 argTy = ETy->getDecl()->getIntegerType();
282 if (const BuiltinType *BT = argTy->getAs<BuiltinType>())
283 switch (BT->getKind()) {
286 case BuiltinType::Char_S:
287 case BuiltinType::SChar:
288 case BuiltinType::UChar:
289 case BuiltinType::Char_U:
296 if (const EnumType *ETy = argTy->getAs<EnumType>())
297 argTy = ETy->getDecl()->getIntegerType();
298 argTy = C.getCanonicalType(argTy).getUnqualifiedType();
302 // Check for "compatible types".
303 if (const BuiltinType *BT = argTy->getAs<BuiltinType>())
304 switch (BT->getKind()) {
307 case BuiltinType::Char_S:
308 case BuiltinType::SChar:
309 case BuiltinType::Char_U:
310 case BuiltinType::UChar:
311 return T == C.UnsignedCharTy || T == C.SignedCharTy;
312 case BuiltinType::Short:
313 return T == C.UnsignedShortTy;
314 case BuiltinType::UShort:
315 return T == C.ShortTy;
316 case BuiltinType::Int:
317 return T == C.UnsignedIntTy;
318 case BuiltinType::UInt:
320 case BuiltinType::Long:
321 return T == C.UnsignedLongTy;
322 case BuiltinType::ULong:
323 return T == C.LongTy;
324 case BuiltinType::LongLong:
325 return T == C.UnsignedLongLongTy;
326 case BuiltinType::ULongLong:
327 return T == C.LongLongTy;
333 const PointerType *PT = argTy->getAs<PointerType>();
336 QualType pointeeTy = PT->getPointeeType();
337 if (const BuiltinType *BT = pointeeTy->getAs<BuiltinType>())
338 switch (BT->getKind()) {
339 case BuiltinType::Void:
340 case BuiltinType::Char_U:
341 case BuiltinType::UChar:
342 case BuiltinType::Char_S:
343 case BuiltinType::SChar:
353 const PointerType *PT = argTy->getAs<PointerType>();
357 C.getCanonicalType(PT->getPointeeType()).getUnqualifiedType();
358 return pointeeTy == C.getWideCharType();
364 argTy->isPromotableIntegerType()
365 ? C.getPromotedIntegerType(argTy) : argTy;
367 QualType WInt = C.getCanonicalType(C.getWIntType()).getUnqualifiedType();
368 PromoArg = C.getCanonicalType(PromoArg).getUnqualifiedType();
370 // If the promoted argument is the corresponding signed type of the
371 // wint_t type, then it should match.
372 if (PromoArg->hasSignedIntegerRepresentation() &&
373 C.getCorrespondingUnsignedType(PromoArg) == WInt)
376 return WInt == PromoArg;
380 return argTy->isPointerType() || argTy->isObjCObjectPointerType() ||
381 argTy->isBlockPointerType() || argTy->isNullPtrType();
383 case ObjCPointerTy: {
384 if (argTy->getAs<ObjCObjectPointerType>() ||
385 argTy->getAs<BlockPointerType>())
388 // Handle implicit toll-free bridging.
389 if (const PointerType *PT = argTy->getAs<PointerType>()) {
390 // Things such as CFTypeRef are really just opaque pointers
391 // to C structs representing CF types that can often be bridged
392 // to Objective-C objects. Since the compiler doesn't know which
393 // structs can be toll-free bridged, we just accept them all.
394 QualType pointee = PT->getPointeeType();
395 if (pointee->getAsStructureType() || pointee->isVoidType())
402 llvm_unreachable("Invalid ArgType Kind!");
405 QualType ArgType::getRepresentativeType(ASTContext &C) const {
409 llvm_unreachable("No representative type for Invalid ArgType");
411 llvm_unreachable("No representative type for Unknown ArgType");
419 Res = C.getPointerType(C.CharTy);
422 Res = C.getPointerType(C.getWideCharType());
425 Res = C.ObjCBuiltinIdTy;
431 Res = C.getWIntType();
437 Res = C.getPointerType(Res);
441 std::string ArgType::getRepresentativeTypeName(ASTContext &C) const {
442 std::string S = getRepresentativeType(C).getAsString();
446 // Use a specific name for this type, e.g. "size_t".
449 // If ArgType is actually a pointer to T, append an asterisk.
450 Alias += (Alias[Alias.size()-1] == '*') ? "*" : " *";
452 // If Alias is the same as the underlying type, e.g. wchar_t, then drop it.
458 return std::string("'") + Alias + "' (aka '" + S + "')";
459 return std::string("'") + S + "'";
463 //===----------------------------------------------------------------------===//
464 // Methods on OptionalAmount.
465 //===----------------------------------------------------------------------===//
468 analyze_format_string::OptionalAmount::getArgType(ASTContext &Ctx) const {
472 //===----------------------------------------------------------------------===//
473 // Methods on LengthModifier.
474 //===----------------------------------------------------------------------===//
477 analyze_format_string::LengthModifier::toString() const {
483 case AsLong: // or AsWideChar
513 //===----------------------------------------------------------------------===//
514 // Methods on ConversionSpecifier.
515 //===----------------------------------------------------------------------===//
517 const char *ConversionSpecifier::toString() const {
519 case dArg: return "d";
520 case DArg: return "D";
521 case iArg: return "i";
522 case oArg: return "o";
523 case OArg: return "O";
524 case uArg: return "u";
525 case UArg: return "U";
526 case xArg: return "x";
527 case XArg: return "X";
528 case fArg: return "f";
529 case FArg: return "F";
530 case eArg: return "e";
531 case EArg: return "E";
532 case gArg: return "g";
533 case GArg: return "G";
534 case aArg: return "a";
535 case AArg: return "A";
536 case cArg: return "c";
537 case sArg: return "s";
538 case pArg: return "p";
539 case nArg: return "n";
540 case PercentArg: return "%";
541 case ScanListArg: return "[";
542 case InvalidSpecifier: return NULL;
544 // POSIX unicode extensions.
545 case CArg: return "C";
546 case SArg: return "S";
548 // Objective-C specific specifiers.
549 case ObjCObjArg: return "@";
551 // FreeBSD specific specifiers.
552 case FreeBSDbArg: return "b";
553 case FreeBSDDArg: return "D";
554 case FreeBSDrArg: return "r";
556 // GlibC specific specifiers.
557 case PrintErrno: return "m";
562 Optional<ConversionSpecifier>
563 ConversionSpecifier::getStandardSpecifier() const {
564 ConversionSpecifier::Kind NewKind;
580 ConversionSpecifier FixedCS(*this);
581 FixedCS.setKind(NewKind);
585 //===----------------------------------------------------------------------===//
586 // Methods on OptionalAmount.
587 //===----------------------------------------------------------------------===//
589 void OptionalAmount::toString(raw_ostream &os) const {
597 if (usesPositionalArg())
598 os << "*" << getPositionalArgIndex() << "$";
610 bool FormatSpecifier::hasValidLengthModifier(const TargetInfo &Target) const {
611 switch (LM.getKind()) {
612 case LengthModifier::None:
615 // Handle most integer flags
616 case LengthModifier::AsChar:
617 case LengthModifier::AsShort:
618 case LengthModifier::AsLongLong:
619 case LengthModifier::AsQuad:
620 case LengthModifier::AsIntMax:
621 case LengthModifier::AsSizeT:
622 case LengthModifier::AsPtrDiff:
623 switch (CS.getKind()) {
624 case ConversionSpecifier::dArg:
625 case ConversionSpecifier::DArg:
626 case ConversionSpecifier::iArg:
627 case ConversionSpecifier::oArg:
628 case ConversionSpecifier::OArg:
629 case ConversionSpecifier::uArg:
630 case ConversionSpecifier::UArg:
631 case ConversionSpecifier::xArg:
632 case ConversionSpecifier::XArg:
633 case ConversionSpecifier::nArg:
634 case ConversionSpecifier::FreeBSDrArg:
641 case LengthModifier::AsLong:
642 switch (CS.getKind()) {
643 case ConversionSpecifier::dArg:
644 case ConversionSpecifier::DArg:
645 case ConversionSpecifier::iArg:
646 case ConversionSpecifier::oArg:
647 case ConversionSpecifier::OArg:
648 case ConversionSpecifier::uArg:
649 case ConversionSpecifier::UArg:
650 case ConversionSpecifier::xArg:
651 case ConversionSpecifier::XArg:
652 case ConversionSpecifier::aArg:
653 case ConversionSpecifier::AArg:
654 case ConversionSpecifier::fArg:
655 case ConversionSpecifier::FArg:
656 case ConversionSpecifier::eArg:
657 case ConversionSpecifier::EArg:
658 case ConversionSpecifier::gArg:
659 case ConversionSpecifier::GArg:
660 case ConversionSpecifier::nArg:
661 case ConversionSpecifier::cArg:
662 case ConversionSpecifier::sArg:
663 case ConversionSpecifier::FreeBSDrArg:
664 case ConversionSpecifier::ScanListArg:
670 case LengthModifier::AsLongDouble:
671 switch (CS.getKind()) {
672 case ConversionSpecifier::aArg:
673 case ConversionSpecifier::AArg:
674 case ConversionSpecifier::fArg:
675 case ConversionSpecifier::FArg:
676 case ConversionSpecifier::eArg:
677 case ConversionSpecifier::EArg:
678 case ConversionSpecifier::gArg:
679 case ConversionSpecifier::GArg:
681 // GNU libc extension.
682 case ConversionSpecifier::dArg:
683 case ConversionSpecifier::iArg:
684 case ConversionSpecifier::oArg:
685 case ConversionSpecifier::uArg:
686 case ConversionSpecifier::xArg:
687 case ConversionSpecifier::XArg:
688 return !Target.getTriple().isOSDarwin() &&
689 !Target.getTriple().isOSWindows();
694 case LengthModifier::AsAllocate:
695 switch (CS.getKind()) {
696 case ConversionSpecifier::sArg:
697 case ConversionSpecifier::SArg:
698 case ConversionSpecifier::ScanListArg:
704 case LengthModifier::AsMAllocate:
705 switch (CS.getKind()) {
706 case ConversionSpecifier::cArg:
707 case ConversionSpecifier::CArg:
708 case ConversionSpecifier::sArg:
709 case ConversionSpecifier::SArg:
710 case ConversionSpecifier::ScanListArg:
715 case LengthModifier::AsInt32:
716 case LengthModifier::AsInt3264:
717 case LengthModifier::AsInt64:
718 switch (CS.getKind()) {
719 case ConversionSpecifier::dArg:
720 case ConversionSpecifier::iArg:
721 case ConversionSpecifier::oArg:
722 case ConversionSpecifier::uArg:
723 case ConversionSpecifier::xArg:
724 case ConversionSpecifier::XArg:
725 return Target.getTriple().isOSMSVCRT();
730 llvm_unreachable("Invalid LengthModifier Kind!");
733 bool FormatSpecifier::hasStandardLengthModifier() const {
734 switch (LM.getKind()) {
735 case LengthModifier::None:
736 case LengthModifier::AsChar:
737 case LengthModifier::AsShort:
738 case LengthModifier::AsLong:
739 case LengthModifier::AsLongLong:
740 case LengthModifier::AsIntMax:
741 case LengthModifier::AsSizeT:
742 case LengthModifier::AsPtrDiff:
743 case LengthModifier::AsLongDouble:
745 case LengthModifier::AsAllocate:
746 case LengthModifier::AsMAllocate:
747 case LengthModifier::AsQuad:
748 case LengthModifier::AsInt32:
749 case LengthModifier::AsInt3264:
750 case LengthModifier::AsInt64:
753 llvm_unreachable("Invalid LengthModifier Kind!");
756 bool FormatSpecifier::hasStandardConversionSpecifier(const LangOptions &LangOpt) const {
757 switch (CS.getKind()) {
758 case ConversionSpecifier::cArg:
759 case ConversionSpecifier::dArg:
760 case ConversionSpecifier::iArg:
761 case ConversionSpecifier::oArg:
762 case ConversionSpecifier::uArg:
763 case ConversionSpecifier::xArg:
764 case ConversionSpecifier::XArg:
765 case ConversionSpecifier::fArg:
766 case ConversionSpecifier::FArg:
767 case ConversionSpecifier::eArg:
768 case ConversionSpecifier::EArg:
769 case ConversionSpecifier::gArg:
770 case ConversionSpecifier::GArg:
771 case ConversionSpecifier::aArg:
772 case ConversionSpecifier::AArg:
773 case ConversionSpecifier::sArg:
774 case ConversionSpecifier::pArg:
775 case ConversionSpecifier::nArg:
776 case ConversionSpecifier::ObjCObjArg:
777 case ConversionSpecifier::ScanListArg:
778 case ConversionSpecifier::PercentArg:
780 case ConversionSpecifier::CArg:
781 case ConversionSpecifier::SArg:
782 return LangOpt.ObjC1 || LangOpt.ObjC2;
783 case ConversionSpecifier::InvalidSpecifier:
784 case ConversionSpecifier::FreeBSDbArg:
785 case ConversionSpecifier::FreeBSDDArg:
786 case ConversionSpecifier::FreeBSDrArg:
787 case ConversionSpecifier::PrintErrno:
788 case ConversionSpecifier::DArg:
789 case ConversionSpecifier::OArg:
790 case ConversionSpecifier::UArg:
793 llvm_unreachable("Invalid ConversionSpecifier Kind!");
796 bool FormatSpecifier::hasStandardLengthConversionCombination() const {
797 if (LM.getKind() == LengthModifier::AsLongDouble) {
798 switch(CS.getKind()) {
799 case ConversionSpecifier::dArg:
800 case ConversionSpecifier::iArg:
801 case ConversionSpecifier::oArg:
802 case ConversionSpecifier::uArg:
803 case ConversionSpecifier::xArg:
804 case ConversionSpecifier::XArg:
813 Optional<LengthModifier> FormatSpecifier::getCorrectedLengthModifier() const {
814 if (CS.isAnyIntArg() || CS.getKind() == ConversionSpecifier::nArg) {
815 if (LM.getKind() == LengthModifier::AsLongDouble ||
816 LM.getKind() == LengthModifier::AsQuad) {
817 LengthModifier FixedLM(LM);
818 FixedLM.setKind(LengthModifier::AsLongLong);
826 bool FormatSpecifier::namedTypeToLengthModifier(QualType QT,
827 LengthModifier &LM) {
828 assert(isa<TypedefType>(QT) && "Expected a TypedefType");
829 const TypedefNameDecl *Typedef = cast<TypedefType>(QT)->getDecl();
832 const IdentifierInfo *Identifier = Typedef->getIdentifier();
833 if (Identifier->getName() == "size_t") {
834 LM.setKind(LengthModifier::AsSizeT);
836 } else if (Identifier->getName() == "ssize_t") {
837 // Not C99, but common in Unix.
838 LM.setKind(LengthModifier::AsSizeT);
840 } else if (Identifier->getName() == "intmax_t") {
841 LM.setKind(LengthModifier::AsIntMax);
843 } else if (Identifier->getName() == "uintmax_t") {
844 LM.setKind(LengthModifier::AsIntMax);
846 } else if (Identifier->getName() == "ptrdiff_t") {
847 LM.setKind(LengthModifier::AsPtrDiff);
851 QualType T = Typedef->getUnderlyingType();
852 if (!isa<TypedefType>(T))
855 Typedef = cast<TypedefType>(T)->getDecl();