1 //= FormatString.h - Analysis of printf/fprintf format strings --*- C++ -*-===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This file defines APIs for analyzing the format strings of printf, fscanf,
12 // The structure of format strings for fprintf are described in C99 7.19.6.1.
14 // The structure of format strings for fscanf are described in C99 7.19.6.2.
16 //===----------------------------------------------------------------------===//
18 #ifndef LLVM_CLANG_ANALYSIS_ANALYSES_FORMATSTRING_H
19 #define LLVM_CLANG_ANALYSIS_ANALYSES_FORMATSTRING_H
21 #include "clang/AST/CanonicalType.h"
27 //===----------------------------------------------------------------------===//
28 /// Common components of both fprintf and fscanf format strings.
29 namespace analyze_format_string {
31 /// Class representing optional flags with location and representation
35 OptionalFlag(const char *Representation)
36 : representation(Representation), flag(false) {}
37 bool isSet() const { return flag; }
38 void set() { flag = true; }
39 void clear() { flag = false; }
40 void setPosition(const char *position) {
43 this->position = position;
45 const char *getPosition() const {
49 const char *toString() const { return representation; }
51 // Overloaded operators for bool like qualities
52 explicit operator bool() const { return flag; }
53 OptionalFlag& operator=(const bool &rhs) {
55 return *this; // Return a reference to myself.
58 const char *representation;
63 /// Represents the length modifier in a format string in scanf/printf.
64 class LengthModifier {
70 AsShortLong, // 'hl' (OpenCL float/int vector element)
73 AsQuad, // 'q' (BSD, deprecated, for 64-bit integer types)
77 AsInt32, // 'I32' (MSVCRT, like __int32)
78 AsInt3264, // 'I' (MSVCRT, like __int3264 from MIDL)
79 AsInt64, // 'I64' (MSVCRT, like __int64)
81 AsAllocate, // for '%as', GNU extension to C90 scanf
82 AsMAllocate, // for '%ms', GNU extension to scanf
83 AsWide, // 'w' (MSVCRT, like l but only for c, C, s, S, or Z
84 AsWideChar = AsLong // for '%ls', only makes sense for printf
88 : Position(nullptr), kind(None) {}
89 LengthModifier(const char *pos, Kind k)
90 : Position(pos), kind(k) {}
92 const char *getStart() const {
96 unsigned getLength() const {
111 Kind getKind() const { return kind; }
112 void setKind(Kind k) { kind = k; }
114 const char *toString() const;
117 const char *Position;
121 class ConversionSpecifier {
124 InvalidSpecifier = 0,
125 // C99 conversion specifiers.
128 DArg, // Apple extension
134 OArg, // Apple extension
136 UArg, // Apple extension
160 // Apple extension: P specifies to os_log that the data being pointed to is
161 // to be copied by os_log. The precision indicates the number of bytes to
165 // ** Printf-specific **
167 ZArg, // MS extension
169 // Objective-C specific specifiers.
171 ObjCBeg = ObjCObjArg,
172 ObjCEnd = ObjCObjArg,
174 // FreeBSD kernel specific specifiers.
180 // GlibC specific specifiers.
183 PrintfConvBeg = ObjCObjArg,
184 PrintfConvEnd = PrintErrno,
186 // ** Scanf-specific **
188 ScanfConvBeg = ScanListArg,
189 ScanfConvEnd = ScanListArg
192 ConversionSpecifier(bool isPrintf = true)
193 : IsPrintf(isPrintf), Position(nullptr), EndScanList(nullptr),
194 kind(InvalidSpecifier) {}
196 ConversionSpecifier(bool isPrintf, const char *pos, Kind k)
197 : IsPrintf(isPrintf), Position(pos), EndScanList(nullptr), kind(k) {}
199 const char *getStart() const {
203 StringRef getCharacters() const {
204 return StringRef(getStart(), getLength());
207 bool consumesDataArgument() const {
214 case InvalidSpecifier:
221 Kind getKind() const { return kind; }
222 void setKind(Kind k) { kind = k; }
223 unsigned getLength() const {
224 return EndScanList ? EndScanList - Position : 1;
226 void setEndScanList(const char *pos) { EndScanList = pos; }
228 bool isIntArg() const { return (kind >= IntArgBeg && kind <= IntArgEnd) ||
229 kind == FreeBSDrArg || kind == FreeBSDyArg; }
230 bool isUIntArg() const { return kind >= UIntArgBeg && kind <= UIntArgEnd; }
231 bool isAnyIntArg() const { return kind >= IntArgBeg && kind <= UIntArgEnd; }
232 bool isDoubleArg() const {
233 return kind >= DoubleArgBeg && kind <= DoubleArgEnd;
236 const char *toString() const;
238 bool isPrintfKind() const { return IsPrintf; }
240 Optional<ConversionSpecifier> getStandardSpecifier() const;
244 const char *Position;
245 const char *EndScanList;
251 enum Kind { UnknownTy, InvalidTy, SpecificTy, ObjCPointerTy, CPointerTy,
252 AnyCharTy, CStrTy, WCStrTy, WIntTy };
254 enum MatchKind { NoMatch = 0, Match = 1, NoMatchPedantic };
259 const char *Name = nullptr;
262 /// The TypeKind identifies certain well-known types like size_t and
264 enum class TypeKind { DontCare, SizeT, PtrdiffT };
265 TypeKind TK = TypeKind::DontCare;
268 ArgType(Kind K = UnknownTy, const char *N = nullptr) : K(K), Name(N) {}
269 ArgType(QualType T, const char *N = nullptr) : K(SpecificTy), T(T), Name(N) {}
270 ArgType(CanQualType T) : K(SpecificTy), T(T) {}
272 static ArgType Invalid() { return ArgType(InvalidTy); }
273 bool isValid() const { return K != InvalidTy; }
275 bool isSizeT() const { return TK == TypeKind::SizeT; }
277 bool isPtrdiffT() const { return TK == TypeKind::PtrdiffT; }
279 /// Create an ArgType which corresponds to the type pointer to A.
280 static ArgType PtrTo(const ArgType& A) {
281 assert(A.K >= InvalidTy && "ArgType cannot be pointer to invalid/unknown");
287 /// Create an ArgType which corresponds to the size_t/ssize_t type.
288 static ArgType makeSizeT(const ArgType &A) {
290 Res.TK = TypeKind::SizeT;
294 /// Create an ArgType which corresponds to the ptrdiff_t/unsigned ptrdiff_t
296 static ArgType makePtrdiffT(const ArgType &A) {
298 Res.TK = TypeKind::PtrdiffT;
302 MatchKind matchesType(ASTContext &C, QualType argTy) const;
304 QualType getRepresentativeType(ASTContext &C) const;
306 ArgType makeVectorType(ASTContext &C, unsigned NumElts) const;
308 std::string getRepresentativeTypeName(ASTContext &C) const;
311 class OptionalAmount {
313 enum HowSpecified { NotSpecified, Constant, Arg, Invalid };
315 OptionalAmount(HowSpecified howSpecified,
317 const char *amountStart,
318 unsigned amountLength,
319 bool usesPositionalArg)
320 : start(amountStart), length(amountLength), hs(howSpecified), amt(amount),
321 UsesPositionalArg(usesPositionalArg), UsesDotPrefix(0) {}
323 OptionalAmount(bool valid = true)
324 : start(nullptr),length(0), hs(valid ? NotSpecified : Invalid), amt(0),
325 UsesPositionalArg(0), UsesDotPrefix(0) {}
327 explicit OptionalAmount(unsigned Amount)
328 : start(nullptr), length(0), hs(Constant), amt(Amount),
329 UsesPositionalArg(false), UsesDotPrefix(false) {}
331 bool isInvalid() const {
332 return hs == Invalid;
335 HowSpecified getHowSpecified() const { return hs; }
336 void setHowSpecified(HowSpecified h) { hs = h; }
338 bool hasDataArgument() const { return hs == Arg; }
340 unsigned getArgIndex() const {
341 assert(hasDataArgument());
345 unsigned getConstantAmount() const {
346 assert(hs == Constant);
350 const char *getStart() const {
351 // We include the . character if it is given.
352 return start - UsesDotPrefix;
355 unsigned getConstantLength() const {
356 assert(hs == Constant);
357 return length + UsesDotPrefix;
360 ArgType getArgType(ASTContext &Ctx) const;
362 void toString(raw_ostream &os) const;
364 bool usesPositionalArg() const { return (bool) UsesPositionalArg; }
365 unsigned getPositionalArgIndex() const {
366 assert(hasDataArgument());
370 bool usesDotPrefix() const { return UsesDotPrefix; }
371 void setUsesDotPrefix() { UsesDotPrefix = true; }
378 bool UsesPositionalArg : 1;
383 class FormatSpecifier {
386 OptionalAmount FieldWidth;
387 ConversionSpecifier CS;
388 OptionalAmount VectorNumElts;
390 /// Positional arguments, an IEEE extension:
391 /// IEEE Std 1003.1, 2004 Edition
392 /// http://www.opengroup.org/onlinepubs/009695399/functions/printf.html
393 bool UsesPositionalArg;
396 FormatSpecifier(bool isPrintf)
397 : CS(isPrintf), VectorNumElts(false),
398 UsesPositionalArg(false), argIndex(0) {}
400 void setLengthModifier(LengthModifier lm) {
404 void setUsesPositionalArg() { UsesPositionalArg = true; }
406 void setArgIndex(unsigned i) {
410 unsigned getArgIndex() const {
414 unsigned getPositionalArgIndex() const {
418 const LengthModifier &getLengthModifier() const {
422 const OptionalAmount &getFieldWidth() const {
426 void setVectorNumElts(const OptionalAmount &Amt) {
430 const OptionalAmount &getVectorNumElts() const {
431 return VectorNumElts;
434 void setFieldWidth(const OptionalAmount &Amt) {
438 bool usesPositionalArg() const { return UsesPositionalArg; }
440 bool hasValidLengthModifier(const TargetInfo &Target,
441 const LangOptions &LO) const;
443 bool hasStandardLengthModifier() const;
445 Optional<LengthModifier> getCorrectedLengthModifier() const;
447 bool hasStandardConversionSpecifier(const LangOptions &LangOpt) const;
449 bool hasStandardLengthConversionCombination() const;
451 /// For a TypedefType QT, if it is a named integer type such as size_t,
452 /// assign the appropriate value to LM and return true.
453 static bool namedTypeToLengthModifier(QualType QT, LengthModifier &LM);
456 } // end analyze_format_string namespace
458 //===----------------------------------------------------------------------===//
459 /// Pieces specific to fprintf format strings.
461 namespace analyze_printf {
463 class PrintfConversionSpecifier :
464 public analyze_format_string::ConversionSpecifier {
466 PrintfConversionSpecifier()
467 : ConversionSpecifier(true, nullptr, InvalidSpecifier) {}
469 PrintfConversionSpecifier(const char *pos, Kind k)
470 : ConversionSpecifier(true, pos, k) {}
472 bool isObjCArg() const { return kind >= ObjCBeg && kind <= ObjCEnd; }
473 bool isDoubleArg() const { return kind >= DoubleArgBeg &&
474 kind <= DoubleArgEnd; }
476 static bool classof(const analyze_format_string::ConversionSpecifier *CS) {
477 return CS->isPrintfKind();
481 using analyze_format_string::ArgType;
482 using analyze_format_string::LengthModifier;
483 using analyze_format_string::OptionalAmount;
484 using analyze_format_string::OptionalFlag;
486 class PrintfSpecifier : public analyze_format_string::FormatSpecifier {
487 OptionalFlag HasThousandsGrouping; // ''', POSIX extension.
488 OptionalFlag IsLeftJustified; // '-'
489 OptionalFlag HasPlusPrefix; // '+'
490 OptionalFlag HasSpacePrefix; // ' '
491 OptionalFlag HasAlternativeForm; // '#'
492 OptionalFlag HasLeadingZeroes; // '0'
493 OptionalFlag HasObjCTechnicalTerm; // '[tt]'
494 OptionalFlag IsPrivate; // '{private}'
495 OptionalFlag IsPublic; // '{public}'
496 OptionalFlag IsSensitive; // '{sensitive}'
497 OptionalAmount Precision;
500 ArgType getScalarArgType(ASTContext &Ctx, bool IsObjCLiteral) const;
504 : FormatSpecifier(/* isPrintf = */ true), HasThousandsGrouping("'"),
505 IsLeftJustified("-"), HasPlusPrefix("+"), HasSpacePrefix(" "),
506 HasAlternativeForm("#"), HasLeadingZeroes("0"),
507 HasObjCTechnicalTerm("tt"), IsPrivate("private"), IsPublic("public"),
508 IsSensitive("sensitive") {}
510 static PrintfSpecifier Parse(const char *beg, const char *end);
512 // Methods for incrementally constructing the PrintfSpecifier.
513 void setConversionSpecifier(const PrintfConversionSpecifier &cs) {
516 void setHasThousandsGrouping(const char *position) {
517 HasThousandsGrouping.setPosition(position);
519 void setIsLeftJustified(const char *position) {
520 IsLeftJustified.setPosition(position);
522 void setHasPlusPrefix(const char *position) {
523 HasPlusPrefix.setPosition(position);
525 void setHasSpacePrefix(const char *position) {
526 HasSpacePrefix.setPosition(position);
528 void setHasAlternativeForm(const char *position) {
529 HasAlternativeForm.setPosition(position);
531 void setHasLeadingZeros(const char *position) {
532 HasLeadingZeroes.setPosition(position);
534 void setHasObjCTechnicalTerm(const char *position) {
535 HasObjCTechnicalTerm.setPosition(position);
537 void setIsPrivate(const char *position) { IsPrivate.setPosition(position); }
538 void setIsPublic(const char *position) { IsPublic.setPosition(position); }
539 void setIsSensitive(const char *position) {
540 IsSensitive.setPosition(position);
542 void setUsesPositionalArg() { UsesPositionalArg = true; }
544 // Methods for querying the format specifier.
546 const PrintfConversionSpecifier &getConversionSpecifier() const {
547 return cast<PrintfConversionSpecifier>(CS);
550 void setPrecision(const OptionalAmount &Amt) {
552 Precision.setUsesDotPrefix();
555 const OptionalAmount &getPrecision() const {
559 bool consumesDataArgument() const {
560 return getConversionSpecifier().consumesDataArgument();
563 /// Returns the builtin type that a data argument
564 /// paired with this format specifier should have. This method
565 /// will return null if the format specifier does not have
566 /// a matching data argument or the matching argument matches
567 /// more than one type.
568 ArgType getArgType(ASTContext &Ctx, bool IsObjCLiteral) const;
570 const OptionalFlag &hasThousandsGrouping() const {
571 return HasThousandsGrouping;
573 const OptionalFlag &isLeftJustified() const { return IsLeftJustified; }
574 const OptionalFlag &hasPlusPrefix() const { return HasPlusPrefix; }
575 const OptionalFlag &hasAlternativeForm() const { return HasAlternativeForm; }
576 const OptionalFlag &hasLeadingZeros() const { return HasLeadingZeroes; }
577 const OptionalFlag &hasSpacePrefix() const { return HasSpacePrefix; }
578 const OptionalFlag &hasObjCTechnicalTerm() const { return HasObjCTechnicalTerm; }
579 const OptionalFlag &isPrivate() const { return IsPrivate; }
580 const OptionalFlag &isPublic() const { return IsPublic; }
581 const OptionalFlag &isSensitive() const { return IsSensitive; }
582 bool usesPositionalArg() const { return UsesPositionalArg; }
584 StringRef getMaskType() const { return MaskType; }
585 void setMaskType(StringRef S) { MaskType = S; }
587 /// Changes the specifier and length according to a QualType, retaining any
588 /// flags or options. Returns true on success, or false when a conversion
589 /// was not successful.
590 bool fixType(QualType QT, const LangOptions &LangOpt, ASTContext &Ctx,
593 void toString(raw_ostream &os) const;
595 // Validation methods - to check if any element results in undefined behavior
596 bool hasValidPlusPrefix() const;
597 bool hasValidAlternativeForm() const;
598 bool hasValidLeadingZeros() const;
599 bool hasValidSpacePrefix() const;
600 bool hasValidLeftJustified() const;
601 bool hasValidThousandsGroupingPrefix() const;
603 bool hasValidPrecision() const;
604 bool hasValidFieldWidth() const;
606 } // end analyze_printf namespace
608 //===----------------------------------------------------------------------===//
609 /// Pieces specific to fscanf format strings.
611 namespace analyze_scanf {
613 class ScanfConversionSpecifier :
614 public analyze_format_string::ConversionSpecifier {
616 ScanfConversionSpecifier()
617 : ConversionSpecifier(false, nullptr, InvalidSpecifier) {}
619 ScanfConversionSpecifier(const char *pos, Kind k)
620 : ConversionSpecifier(false, pos, k) {}
622 static bool classof(const analyze_format_string::ConversionSpecifier *CS) {
623 return !CS->isPrintfKind();
627 using analyze_format_string::ArgType;
628 using analyze_format_string::LengthModifier;
629 using analyze_format_string::OptionalAmount;
630 using analyze_format_string::OptionalFlag;
632 class ScanfSpecifier : public analyze_format_string::FormatSpecifier {
633 OptionalFlag SuppressAssignment; // '*'
636 FormatSpecifier(/* isPrintf = */ false),
637 SuppressAssignment("*") {}
639 void setSuppressAssignment(const char *position) {
640 SuppressAssignment.setPosition(position);
643 const OptionalFlag &getSuppressAssignment() const {
644 return SuppressAssignment;
647 void setConversionSpecifier(const ScanfConversionSpecifier &cs) {
651 const ScanfConversionSpecifier &getConversionSpecifier() const {
652 return cast<ScanfConversionSpecifier>(CS);
655 bool consumesDataArgument() const {
656 return CS.consumesDataArgument() && !SuppressAssignment;
659 ArgType getArgType(ASTContext &Ctx) const;
661 bool fixType(QualType QT, QualType RawQT, const LangOptions &LangOpt,
664 void toString(raw_ostream &os) const;
666 static ScanfSpecifier Parse(const char *beg, const char *end);
669 } // end analyze_scanf namespace
671 //===----------------------------------------------------------------------===//
672 // Parsing and processing of format strings (both fprintf and fscanf).
674 namespace analyze_format_string {
676 enum PositionContext { FieldWidthPos = 0, PrecisionPos = 1 };
678 class FormatStringHandler {
680 FormatStringHandler() {}
681 virtual ~FormatStringHandler();
683 virtual void HandleNullChar(const char *nullCharacter) {}
685 virtual void HandlePosition(const char *startPos, unsigned posLen) {}
687 virtual void HandleInvalidPosition(const char *startPos, unsigned posLen,
688 PositionContext p) {}
690 virtual void HandleZeroPosition(const char *startPos, unsigned posLen) {}
692 virtual void HandleIncompleteSpecifier(const char *startSpecifier,
693 unsigned specifierLen) {}
695 virtual void HandleEmptyObjCModifierFlag(const char *startFlags,
696 unsigned flagsLen) {}
698 virtual void HandleInvalidObjCModifierFlag(const char *startFlag,
701 virtual void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
702 const char *flagsEnd,
703 const char *conversionPosition) {}
704 // Printf-specific handlers.
706 virtual bool HandleInvalidPrintfConversionSpecifier(
707 const analyze_printf::PrintfSpecifier &FS,
708 const char *startSpecifier,
709 unsigned specifierLen) {
713 virtual bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
714 const char *startSpecifier,
715 unsigned specifierLen) {
719 /// Handle mask types whose sizes are not between one and eight bytes.
720 virtual void handleInvalidMaskType(StringRef MaskType) {}
722 // Scanf-specific handlers.
724 virtual bool HandleInvalidScanfConversionSpecifier(
725 const analyze_scanf::ScanfSpecifier &FS,
726 const char *startSpecifier,
727 unsigned specifierLen) {
731 virtual bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
732 const char *startSpecifier,
733 unsigned specifierLen) {
737 virtual void HandleIncompleteScanList(const char *start, const char *end) {}
740 bool ParsePrintfString(FormatStringHandler &H,
741 const char *beg, const char *end, const LangOptions &LO,
742 const TargetInfo &Target, bool isFreeBSDKPrintf);
744 bool ParseFormatStringHasSArg(const char *beg, const char *end,
745 const LangOptions &LO, const TargetInfo &Target);
747 bool ParseScanfString(FormatStringHandler &H,
748 const char *beg, const char *end, const LangOptions &LO,
749 const TargetInfo &Target);
751 } // end analyze_format_string namespace
752 } // end clang namespace