1 //= FormatString.h - Analysis of printf/fprintf format strings --*- 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 // This file defines APIs for analyzing the format strings of printf, fscanf,
13 // The structure of format strings for fprintf are described in C99 7.19.6.1.
15 // The structure of format strings for fscanf are described in C99 7.19.6.2.
17 //===----------------------------------------------------------------------===//
19 #ifndef LLVM_CLANG_FORMAT_H
20 #define LLVM_CLANG_FORMAT_H
22 #include "clang/AST/CanonicalType.h"
28 //===----------------------------------------------------------------------===//
29 /// Common components of both fprintf and fscanf format strings.
30 namespace analyze_format_string {
32 /// Class representing optional flags with location and representation
36 OptionalFlag(const char *Representation)
37 : representation(Representation), flag(false) {}
38 bool isSet() { return flag; }
39 void set() { flag = true; }
40 void clear() { flag = false; }
41 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 LLVM_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 {
72 AsQuad, // 'q' (BSD, deprecated, for 64-bit integer types)
76 AsInt32, // 'I32' (MSVCRT, like __int32)
77 AsInt3264, // 'I' (MSVCRT, like __int3264 from MIDL)
78 AsInt64, // 'I64' (MSVCRT, like __int64)
80 AsAllocate, // for '%as', GNU extension to C90 scanf
81 AsMAllocate, // for '%ms', GNU extension to scanf
82 AsWideChar = AsLong // for '%ls', only makes sense for printf
86 : Position(0), kind(None) {}
87 LengthModifier(const char *pos, Kind k)
88 : Position(pos), kind(k) {}
90 const char *getStart() const {
94 unsigned getLength() const {
109 Kind getKind() const { return kind; }
110 void setKind(Kind k) { kind = k; }
112 const char *toString() const;
115 const char *Position;
119 class ConversionSpecifier {
122 InvalidSpecifier = 0,
123 // C99 conversion specifiers.
126 DArg, // Apple extension
128 IntArgBeg = dArg, IntArgEnd = iArg,
131 OArg, // Apple extension
133 UArg, // Apple extension
136 UIntArgBeg = oArg, UIntArgEnd = XArg,
146 DoubleArgBeg = fArg, DoubleArgEnd = AArg,
155 // ** Printf-specific **
157 // Objective-C specific specifiers.
159 ObjCBeg = ObjCObjArg, ObjCEnd = ObjCObjArg,
161 // FreeBSD specific specifiers
166 // GlibC specific specifiers.
169 PrintfConvBeg = ObjCObjArg, PrintfConvEnd = PrintErrno,
171 // ** Scanf-specific **
173 ScanfConvBeg = ScanListArg, ScanfConvEnd = ScanListArg
176 ConversionSpecifier(bool isPrintf = true)
177 : IsPrintf(isPrintf), Position(0), EndScanList(0), kind(InvalidSpecifier) {}
179 ConversionSpecifier(bool isPrintf, const char *pos, Kind k)
180 : IsPrintf(isPrintf), Position(pos), EndScanList(0), kind(k) {}
182 const char *getStart() const {
186 StringRef getCharacters() const {
187 return StringRef(getStart(), getLength());
190 bool consumesDataArgument() const {
202 Kind getKind() const { return kind; }
203 void setKind(Kind k) { kind = k; }
204 unsigned getLength() const {
205 return EndScanList ? EndScanList - Position : 1;
208 bool isIntArg() const { return kind >= IntArgBeg && kind <= IntArgEnd; }
209 bool isUIntArg() const { return kind >= UIntArgBeg && kind <= UIntArgEnd; }
210 bool isAnyIntArg() const { return kind >= IntArgBeg && kind <= UIntArgEnd; }
211 const char *toString() const;
213 bool isPrintfKind() const { return IsPrintf; }
215 Optional<ConversionSpecifier> getStandardSpecifier() const;
219 const char *Position;
220 const char *EndScanList;
226 enum Kind { UnknownTy, InvalidTy, SpecificTy, ObjCPointerTy, CPointerTy,
227 AnyCharTy, CStrTy, WCStrTy, WIntTy };
234 ArgType(Kind k = UnknownTy, const char *n = 0) : K(k), Name(n), Ptr(false) {}
235 ArgType(QualType t, const char *n = 0)
236 : K(SpecificTy), T(t), Name(n), Ptr(false) {}
237 ArgType(CanQualType t) : K(SpecificTy), T(t), Name(0), Ptr(false) {}
239 static ArgType Invalid() { return ArgType(InvalidTy); }
240 bool isValid() const { return K != InvalidTy; }
242 /// Create an ArgType which corresponds to the type pointer to A.
243 static ArgType PtrTo(const ArgType& A) {
244 assert(A.K >= InvalidTy && "ArgType cannot be pointer to invalid/unknown");
250 bool matchesType(ASTContext &C, QualType argTy) const;
252 QualType getRepresentativeType(ASTContext &C) const;
254 std::string getRepresentativeTypeName(ASTContext &C) const;
257 class OptionalAmount {
259 enum HowSpecified { NotSpecified, Constant, Arg, Invalid };
261 OptionalAmount(HowSpecified howSpecified,
263 const char *amountStart,
264 unsigned amountLength,
265 bool usesPositionalArg)
266 : start(amountStart), length(amountLength), hs(howSpecified), amt(amount),
267 UsesPositionalArg(usesPositionalArg), UsesDotPrefix(0) {}
269 OptionalAmount(bool valid = true)
270 : start(0),length(0), hs(valid ? NotSpecified : Invalid), amt(0),
271 UsesPositionalArg(0), UsesDotPrefix(0) {}
273 bool isInvalid() const {
274 return hs == Invalid;
277 HowSpecified getHowSpecified() const { return hs; }
278 void setHowSpecified(HowSpecified h) { hs = h; }
280 bool hasDataArgument() const { return hs == Arg; }
282 unsigned getArgIndex() const {
283 assert(hasDataArgument());
287 unsigned getConstantAmount() const {
288 assert(hs == Constant);
292 const char *getStart() const {
293 // We include the . character if it is given.
294 return start - UsesDotPrefix;
297 unsigned getConstantLength() const {
298 assert(hs == Constant);
299 return length + UsesDotPrefix;
302 ArgType getArgType(ASTContext &Ctx) const;
304 void toString(raw_ostream &os) const;
306 bool usesPositionalArg() const { return (bool) UsesPositionalArg; }
307 unsigned getPositionalArgIndex() const {
308 assert(hasDataArgument());
312 bool usesDotPrefix() const { return UsesDotPrefix; }
313 void setUsesDotPrefix() { UsesDotPrefix = true; }
320 bool UsesPositionalArg : 1;
325 class FormatSpecifier {
328 OptionalAmount FieldWidth;
329 ConversionSpecifier CS;
330 /// Positional arguments, an IEEE extension:
331 /// IEEE Std 1003.1, 2004 Edition
332 /// http://www.opengroup.org/onlinepubs/009695399/functions/printf.html
333 bool UsesPositionalArg;
336 FormatSpecifier(bool isPrintf)
337 : CS(isPrintf), UsesPositionalArg(false), argIndex(0) {}
339 void setLengthModifier(LengthModifier lm) {
343 void setUsesPositionalArg() { UsesPositionalArg = true; }
345 void setArgIndex(unsigned i) {
349 unsigned getArgIndex() const {
353 unsigned getPositionalArgIndex() const {
357 const LengthModifier &getLengthModifier() const {
361 const OptionalAmount &getFieldWidth() const {
365 void setFieldWidth(const OptionalAmount &Amt) {
369 bool usesPositionalArg() const { return UsesPositionalArg; }
371 bool hasValidLengthModifier(const TargetInfo &Target) const;
373 bool hasStandardLengthModifier() const;
375 Optional<LengthModifier> getCorrectedLengthModifier() const;
377 bool hasStandardConversionSpecifier(const LangOptions &LangOpt) const;
379 bool hasStandardLengthConversionCombination() const;
381 /// For a TypedefType QT, if it is a named integer type such as size_t,
382 /// assign the appropriate value to LM and return true.
383 static bool namedTypeToLengthModifier(QualType QT, LengthModifier &LM);
386 } // end analyze_format_string namespace
388 //===----------------------------------------------------------------------===//
389 /// Pieces specific to fprintf format strings.
391 namespace analyze_printf {
393 class PrintfConversionSpecifier :
394 public analyze_format_string::ConversionSpecifier {
396 PrintfConversionSpecifier()
397 : ConversionSpecifier(true, 0, InvalidSpecifier) {}
399 PrintfConversionSpecifier(const char *pos, Kind k)
400 : ConversionSpecifier(true, pos, k) {}
402 bool isObjCArg() const { return kind >= ObjCBeg && kind <= ObjCEnd; }
403 bool isDoubleArg() const { return kind >= DoubleArgBeg &&
404 kind <= DoubleArgEnd; }
405 unsigned getLength() const {
406 // Conversion specifiers currently only are represented by
407 // single characters, but we be flexible.
411 static bool classof(const analyze_format_string::ConversionSpecifier *CS) {
412 return CS->isPrintfKind();
416 using analyze_format_string::ArgType;
417 using analyze_format_string::LengthModifier;
418 using analyze_format_string::OptionalAmount;
419 using analyze_format_string::OptionalFlag;
421 class PrintfSpecifier : public analyze_format_string::FormatSpecifier {
422 OptionalFlag HasThousandsGrouping; // ''', POSIX extension.
423 OptionalFlag IsLeftJustified; // '-'
424 OptionalFlag HasPlusPrefix; // '+'
425 OptionalFlag HasSpacePrefix; // ' '
426 OptionalFlag HasAlternativeForm; // '#'
427 OptionalFlag HasLeadingZeroes; // '0'
428 OptionalAmount Precision;
431 FormatSpecifier(/* isPrintf = */ true),
432 HasThousandsGrouping("'"), IsLeftJustified("-"), HasPlusPrefix("+"),
433 HasSpacePrefix(" "), HasAlternativeForm("#"), HasLeadingZeroes("0") {}
435 static PrintfSpecifier Parse(const char *beg, const char *end);
437 // Methods for incrementally constructing the PrintfSpecifier.
438 void setConversionSpecifier(const PrintfConversionSpecifier &cs) {
441 void setHasThousandsGrouping(const char *position) {
442 HasThousandsGrouping = true;
443 HasThousandsGrouping.setPosition(position);
445 void setIsLeftJustified(const char *position) {
446 IsLeftJustified = true;
447 IsLeftJustified.setPosition(position);
449 void setHasPlusPrefix(const char *position) {
450 HasPlusPrefix = true;
451 HasPlusPrefix.setPosition(position);
453 void setHasSpacePrefix(const char *position) {
454 HasSpacePrefix = true;
455 HasSpacePrefix.setPosition(position);
457 void setHasAlternativeForm(const char *position) {
458 HasAlternativeForm = true;
459 HasAlternativeForm.setPosition(position);
461 void setHasLeadingZeros(const char *position) {
462 HasLeadingZeroes = true;
463 HasLeadingZeroes.setPosition(position);
465 void setUsesPositionalArg() { UsesPositionalArg = true; }
467 // Methods for querying the format specifier.
469 const PrintfConversionSpecifier &getConversionSpecifier() const {
470 return cast<PrintfConversionSpecifier>(CS);
473 void setPrecision(const OptionalAmount &Amt) {
475 Precision.setUsesDotPrefix();
478 const OptionalAmount &getPrecision() const {
482 bool consumesDataArgument() const {
483 return getConversionSpecifier().consumesDataArgument();
486 /// \brief Returns the builtin type that a data argument
487 /// paired with this format specifier should have. This method
488 /// will return null if the format specifier does not have
489 /// a matching data argument or the matching argument matches
490 /// more than one type.
491 ArgType getArgType(ASTContext &Ctx, bool IsObjCLiteral) const;
493 const OptionalFlag &hasThousandsGrouping() const {
494 return HasThousandsGrouping;
496 const OptionalFlag &isLeftJustified() const { return IsLeftJustified; }
497 const OptionalFlag &hasPlusPrefix() const { return HasPlusPrefix; }
498 const OptionalFlag &hasAlternativeForm() const { return HasAlternativeForm; }
499 const OptionalFlag &hasLeadingZeros() const { return HasLeadingZeroes; }
500 const OptionalFlag &hasSpacePrefix() const { return HasSpacePrefix; }
501 bool usesPositionalArg() const { return UsesPositionalArg; }
503 /// Changes the specifier and length according to a QualType, retaining any
504 /// flags or options. Returns true on success, or false when a conversion
505 /// was not successful.
506 bool fixType(QualType QT, const LangOptions &LangOpt, ASTContext &Ctx,
509 void toString(raw_ostream &os) const;
511 // Validation methods - to check if any element results in undefined behavior
512 bool hasValidPlusPrefix() const;
513 bool hasValidAlternativeForm() const;
514 bool hasValidLeadingZeros() const;
515 bool hasValidSpacePrefix() const;
516 bool hasValidLeftJustified() const;
517 bool hasValidThousandsGroupingPrefix() const;
519 bool hasValidPrecision() const;
520 bool hasValidFieldWidth() const;
522 } // end analyze_printf namespace
524 //===----------------------------------------------------------------------===//
525 /// Pieces specific to fscanf format strings.
527 namespace analyze_scanf {
529 class ScanfConversionSpecifier :
530 public analyze_format_string::ConversionSpecifier {
532 ScanfConversionSpecifier()
533 : ConversionSpecifier(false, 0, InvalidSpecifier) {}
535 ScanfConversionSpecifier(const char *pos, Kind k)
536 : ConversionSpecifier(false, pos, k) {}
538 void setEndScanList(const char *pos) { EndScanList = pos; }
540 static bool classof(const analyze_format_string::ConversionSpecifier *CS) {
541 return !CS->isPrintfKind();
545 using analyze_format_string::ArgType;
546 using analyze_format_string::LengthModifier;
547 using analyze_format_string::OptionalAmount;
548 using analyze_format_string::OptionalFlag;
550 class ScanfSpecifier : public analyze_format_string::FormatSpecifier {
551 OptionalFlag SuppressAssignment; // '*'
554 FormatSpecifier(/* isPrintf = */ false),
555 SuppressAssignment("*") {}
557 void setSuppressAssignment(const char *position) {
558 SuppressAssignment = true;
559 SuppressAssignment.setPosition(position);
562 const OptionalFlag &getSuppressAssignment() const {
563 return SuppressAssignment;
566 void setConversionSpecifier(const ScanfConversionSpecifier &cs) {
570 const ScanfConversionSpecifier &getConversionSpecifier() const {
571 return cast<ScanfConversionSpecifier>(CS);
574 bool consumesDataArgument() const {
575 return CS.consumesDataArgument() && !SuppressAssignment;
578 ArgType getArgType(ASTContext &Ctx) const;
580 bool fixType(QualType QT, const LangOptions &LangOpt, ASTContext &Ctx);
582 void toString(raw_ostream &os) const;
584 static ScanfSpecifier Parse(const char *beg, const char *end);
587 } // end analyze_scanf namespace
589 //===----------------------------------------------------------------------===//
590 // Parsing and processing of format strings (both fprintf and fscanf).
592 namespace analyze_format_string {
594 enum PositionContext { FieldWidthPos = 0, PrecisionPos = 1 };
596 class FormatStringHandler {
598 FormatStringHandler() {}
599 virtual ~FormatStringHandler();
601 virtual void HandleNullChar(const char *nullCharacter) {}
603 virtual void HandlePosition(const char *startPos, unsigned posLen) {}
605 virtual void HandleInvalidPosition(const char *startPos, unsigned posLen,
606 PositionContext p) {}
608 virtual void HandleZeroPosition(const char *startPos, unsigned posLen) {}
610 virtual void HandleIncompleteSpecifier(const char *startSpecifier,
611 unsigned specifierLen) {}
613 // Printf-specific handlers.
615 virtual bool HandleInvalidPrintfConversionSpecifier(
616 const analyze_printf::PrintfSpecifier &FS,
617 const char *startSpecifier,
618 unsigned specifierLen) {
622 virtual bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
623 const char *startSpecifier,
624 unsigned specifierLen) {
628 // Scanf-specific handlers.
630 virtual bool HandleInvalidScanfConversionSpecifier(
631 const analyze_scanf::ScanfSpecifier &FS,
632 const char *startSpecifier,
633 unsigned specifierLen) {
637 virtual bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
638 const char *startSpecifier,
639 unsigned specifierLen) {
643 virtual void HandleIncompleteScanList(const char *start, const char *end) {}
646 bool ParsePrintfString(FormatStringHandler &H,
647 const char *beg, const char *end, const LangOptions &LO,
648 const TargetInfo &Target);
650 bool ParseScanfString(FormatStringHandler &H,
651 const char *beg, const char *end, const LangOptions &LO,
652 const TargetInfo &Target);
654 } // end analyze_format_string namespace
655 } // end clang namespace