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 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)
77 AsAllocate, // for '%as', GNU extension to C90 scanf
78 AsMAllocate, // for '%ms', GNU extension to scanf
79 AsWideChar = AsLong // for '%ls', only makes sense for printf
83 : Position(0), kind(None) {}
84 LengthModifier(const char *pos, Kind k)
85 : Position(pos), kind(k) {}
87 const char *getStart() const {
91 unsigned getLength() const {
103 Kind getKind() const { return kind; }
104 void setKind(Kind k) { kind = k; }
106 const char *toString() const;
109 const char *Position;
113 class ConversionSpecifier {
116 InvalidSpecifier = 0,
117 // C99 conversion specifiers.
120 DArg, // Apple extension
122 IntArgBeg = dArg, IntArgEnd = iArg,
125 OArg, // Apple extension
127 UArg, // Apple extension
130 UIntArgBeg = oArg, UIntArgEnd = XArg,
140 DoubleArgBeg = fArg, DoubleArgEnd = AArg,
149 // ** Printf-specific **
151 // Objective-C specific specifiers.
153 ObjCBeg = ObjCObjArg, ObjCEnd = ObjCObjArg,
155 // GlibC specific specifiers.
158 PrintfConvBeg = ObjCObjArg, PrintfConvEnd = PrintErrno,
160 // ** Scanf-specific **
162 ScanfConvBeg = ScanListArg, ScanfConvEnd = ScanListArg
165 ConversionSpecifier(bool isPrintf = true)
166 : IsPrintf(isPrintf), Position(0), EndScanList(0), kind(InvalidSpecifier) {}
168 ConversionSpecifier(bool isPrintf, const char *pos, Kind k)
169 : IsPrintf(isPrintf), Position(pos), EndScanList(0), kind(k) {}
171 const char *getStart() const {
175 StringRef getCharacters() const {
176 return StringRef(getStart(), getLength());
179 bool consumesDataArgument() const {
191 Kind getKind() const { return kind; }
192 void setKind(Kind k) { kind = k; }
193 unsigned getLength() const {
194 return EndScanList ? EndScanList - Position : 1;
197 bool isIntArg() const { return kind >= IntArgBeg && kind <= IntArgEnd; }
198 bool isUIntArg() const { return kind >= UIntArgBeg && kind <= UIntArgEnd; }
199 bool isAnyIntArg() const { return kind >= IntArgBeg && kind <= UIntArgEnd; }
200 const char *toString() const;
202 bool isPrintfKind() const { return IsPrintf; }
204 llvm::Optional<ConversionSpecifier> getStandardSpecifier() const;
208 const char *Position;
209 const char *EndScanList;
215 enum Kind { UnknownTy, InvalidTy, SpecificTy, ObjCPointerTy, CPointerTy,
216 AnyCharTy, CStrTy, WCStrTy, WIntTy };
223 ArgType(Kind k = UnknownTy, const char *n = 0) : K(k), Name(n), Ptr(false) {}
224 ArgType(QualType t, const char *n = 0)
225 : K(SpecificTy), T(t), Name(n), Ptr(false) {}
226 ArgType(CanQualType t) : K(SpecificTy), T(t), Name(0), Ptr(false) {}
228 static ArgType Invalid() { return ArgType(InvalidTy); }
229 bool isValid() const { return K != InvalidTy; }
231 /// Create an ArgType which corresponds to the type pointer to A.
232 static ArgType PtrTo(const ArgType& A) {
233 assert(A.K >= InvalidTy && "ArgType cannot be pointer to invalid/unknown");
239 bool matchesType(ASTContext &C, QualType argTy) const;
241 QualType getRepresentativeType(ASTContext &C) const;
243 std::string getRepresentativeTypeName(ASTContext &C) const;
246 class OptionalAmount {
248 enum HowSpecified { NotSpecified, Constant, Arg, Invalid };
250 OptionalAmount(HowSpecified howSpecified,
252 const char *amountStart,
253 unsigned amountLength,
254 bool usesPositionalArg)
255 : start(amountStart), length(amountLength), hs(howSpecified), amt(amount),
256 UsesPositionalArg(usesPositionalArg), UsesDotPrefix(0) {}
258 OptionalAmount(bool valid = true)
259 : start(0),length(0), hs(valid ? NotSpecified : Invalid), amt(0),
260 UsesPositionalArg(0), UsesDotPrefix(0) {}
262 bool isInvalid() const {
263 return hs == Invalid;
266 HowSpecified getHowSpecified() const { return hs; }
267 void setHowSpecified(HowSpecified h) { hs = h; }
269 bool hasDataArgument() const { return hs == Arg; }
271 unsigned getArgIndex() const {
272 assert(hasDataArgument());
276 unsigned getConstantAmount() const {
277 assert(hs == Constant);
281 const char *getStart() const {
282 // We include the . character if it is given.
283 return start - UsesDotPrefix;
286 unsigned getConstantLength() const {
287 assert(hs == Constant);
288 return length + UsesDotPrefix;
291 ArgType getArgType(ASTContext &Ctx) const;
293 void toString(raw_ostream &os) const;
295 bool usesPositionalArg() const { return (bool) UsesPositionalArg; }
296 unsigned getPositionalArgIndex() const {
297 assert(hasDataArgument());
301 bool usesDotPrefix() const { return UsesDotPrefix; }
302 void setUsesDotPrefix() { UsesDotPrefix = true; }
309 bool UsesPositionalArg : 1;
314 class FormatSpecifier {
317 OptionalAmount FieldWidth;
318 ConversionSpecifier CS;
319 /// Positional arguments, an IEEE extension:
320 /// IEEE Std 1003.1, 2004 Edition
321 /// http://www.opengroup.org/onlinepubs/009695399/functions/printf.html
322 bool UsesPositionalArg;
325 FormatSpecifier(bool isPrintf)
326 : CS(isPrintf), UsesPositionalArg(false), argIndex(0) {}
328 void setLengthModifier(LengthModifier lm) {
332 void setUsesPositionalArg() { UsesPositionalArg = true; }
334 void setArgIndex(unsigned i) {
338 unsigned getArgIndex() const {
342 unsigned getPositionalArgIndex() const {
346 const LengthModifier &getLengthModifier() const {
350 const OptionalAmount &getFieldWidth() const {
354 void setFieldWidth(const OptionalAmount &Amt) {
358 bool usesPositionalArg() const { return UsesPositionalArg; }
360 bool hasValidLengthModifier(const TargetInfo &Target) const;
362 bool hasStandardLengthModifier() const;
364 llvm::Optional<LengthModifier> getCorrectedLengthModifier() const;
366 bool hasStandardConversionSpecifier(const LangOptions &LangOpt) const;
368 bool hasStandardLengthConversionCombination() const;
370 /// For a TypedefType QT, if it is a named integer type such as size_t,
371 /// assign the appropriate value to LM and return true.
372 static bool namedTypeToLengthModifier(QualType QT, LengthModifier &LM);
375 } // end analyze_format_string namespace
377 //===----------------------------------------------------------------------===//
378 /// Pieces specific to fprintf format strings.
380 namespace analyze_printf {
382 class PrintfConversionSpecifier :
383 public analyze_format_string::ConversionSpecifier {
385 PrintfConversionSpecifier()
386 : ConversionSpecifier(true, 0, InvalidSpecifier) {}
388 PrintfConversionSpecifier(const char *pos, Kind k)
389 : ConversionSpecifier(true, pos, k) {}
391 bool isObjCArg() const { return kind >= ObjCBeg && kind <= ObjCEnd; }
392 bool isDoubleArg() const { return kind >= DoubleArgBeg &&
393 kind <= DoubleArgEnd; }
394 unsigned getLength() const {
395 // Conversion specifiers currently only are represented by
396 // single characters, but we be flexible.
400 static bool classof(const analyze_format_string::ConversionSpecifier *CS) {
401 return CS->isPrintfKind();
405 using analyze_format_string::ArgType;
406 using analyze_format_string::LengthModifier;
407 using analyze_format_string::OptionalAmount;
408 using analyze_format_string::OptionalFlag;
410 class PrintfSpecifier : public analyze_format_string::FormatSpecifier {
411 OptionalFlag HasThousandsGrouping; // ''', POSIX extension.
412 OptionalFlag IsLeftJustified; // '-'
413 OptionalFlag HasPlusPrefix; // '+'
414 OptionalFlag HasSpacePrefix; // ' '
415 OptionalFlag HasAlternativeForm; // '#'
416 OptionalFlag HasLeadingZeroes; // '0'
417 OptionalAmount Precision;
420 FormatSpecifier(/* isPrintf = */ true),
421 HasThousandsGrouping("'"), IsLeftJustified("-"), HasPlusPrefix("+"),
422 HasSpacePrefix(" "), HasAlternativeForm("#"), HasLeadingZeroes("0") {}
424 static PrintfSpecifier Parse(const char *beg, const char *end);
426 // Methods for incrementally constructing the PrintfSpecifier.
427 void setConversionSpecifier(const PrintfConversionSpecifier &cs) {
430 void setHasThousandsGrouping(const char *position) {
431 HasThousandsGrouping = true;
432 HasThousandsGrouping.setPosition(position);
434 void setIsLeftJustified(const char *position) {
435 IsLeftJustified = true;
436 IsLeftJustified.setPosition(position);
438 void setHasPlusPrefix(const char *position) {
439 HasPlusPrefix = true;
440 HasPlusPrefix.setPosition(position);
442 void setHasSpacePrefix(const char *position) {
443 HasSpacePrefix = true;
444 HasSpacePrefix.setPosition(position);
446 void setHasAlternativeForm(const char *position) {
447 HasAlternativeForm = true;
448 HasAlternativeForm.setPosition(position);
450 void setHasLeadingZeros(const char *position) {
451 HasLeadingZeroes = true;
452 HasLeadingZeroes.setPosition(position);
454 void setUsesPositionalArg() { UsesPositionalArg = true; }
456 // Methods for querying the format specifier.
458 const PrintfConversionSpecifier &getConversionSpecifier() const {
459 return cast<PrintfConversionSpecifier>(CS);
462 void setPrecision(const OptionalAmount &Amt) {
464 Precision.setUsesDotPrefix();
467 const OptionalAmount &getPrecision() const {
471 bool consumesDataArgument() const {
472 return getConversionSpecifier().consumesDataArgument();
475 /// \brief Returns the builtin type that a data argument
476 /// paired with this format specifier should have. This method
477 /// will return null if the format specifier does not have
478 /// a matching data argument or the matching argument matches
479 /// more than one type.
480 ArgType getArgType(ASTContext &Ctx, bool IsObjCLiteral) const;
482 const OptionalFlag &hasThousandsGrouping() const {
483 return HasThousandsGrouping;
485 const OptionalFlag &isLeftJustified() const { return IsLeftJustified; }
486 const OptionalFlag &hasPlusPrefix() const { return HasPlusPrefix; }
487 const OptionalFlag &hasAlternativeForm() const { return HasAlternativeForm; }
488 const OptionalFlag &hasLeadingZeros() const { return HasLeadingZeroes; }
489 const OptionalFlag &hasSpacePrefix() const { return HasSpacePrefix; }
490 bool usesPositionalArg() const { return UsesPositionalArg; }
492 /// Changes the specifier and length according to a QualType, retaining any
493 /// flags or options. Returns true on success, or false when a conversion
494 /// was not successful.
495 bool fixType(QualType QT, const LangOptions &LangOpt, ASTContext &Ctx,
498 void toString(raw_ostream &os) const;
500 // Validation methods - to check if any element results in undefined behavior
501 bool hasValidPlusPrefix() const;
502 bool hasValidAlternativeForm() const;
503 bool hasValidLeadingZeros() const;
504 bool hasValidSpacePrefix() const;
505 bool hasValidLeftJustified() const;
506 bool hasValidThousandsGroupingPrefix() const;
508 bool hasValidPrecision() const;
509 bool hasValidFieldWidth() const;
511 } // end analyze_printf namespace
513 //===----------------------------------------------------------------------===//
514 /// Pieces specific to fscanf format strings.
516 namespace analyze_scanf {
518 class ScanfConversionSpecifier :
519 public analyze_format_string::ConversionSpecifier {
521 ScanfConversionSpecifier()
522 : ConversionSpecifier(false, 0, InvalidSpecifier) {}
524 ScanfConversionSpecifier(const char *pos, Kind k)
525 : ConversionSpecifier(false, pos, k) {}
527 void setEndScanList(const char *pos) { EndScanList = pos; }
529 static bool classof(const analyze_format_string::ConversionSpecifier *CS) {
530 return !CS->isPrintfKind();
534 using analyze_format_string::ArgType;
535 using analyze_format_string::LengthModifier;
536 using analyze_format_string::OptionalAmount;
537 using analyze_format_string::OptionalFlag;
539 class ScanfSpecifier : public analyze_format_string::FormatSpecifier {
540 OptionalFlag SuppressAssignment; // '*'
543 FormatSpecifier(/* isPrintf = */ false),
544 SuppressAssignment("*") {}
546 void setSuppressAssignment(const char *position) {
547 SuppressAssignment = true;
548 SuppressAssignment.setPosition(position);
551 const OptionalFlag &getSuppressAssignment() const {
552 return SuppressAssignment;
555 void setConversionSpecifier(const ScanfConversionSpecifier &cs) {
559 const ScanfConversionSpecifier &getConversionSpecifier() const {
560 return cast<ScanfConversionSpecifier>(CS);
563 bool consumesDataArgument() const {
564 return CS.consumesDataArgument() && !SuppressAssignment;
567 ArgType getArgType(ASTContext &Ctx) const;
569 bool fixType(QualType QT, const LangOptions &LangOpt, ASTContext &Ctx);
571 void toString(raw_ostream &os) const;
573 static ScanfSpecifier Parse(const char *beg, const char *end);
576 } // end analyze_scanf namespace
578 //===----------------------------------------------------------------------===//
579 // Parsing and processing of format strings (both fprintf and fscanf).
581 namespace analyze_format_string {
583 enum PositionContext { FieldWidthPos = 0, PrecisionPos = 1 };
585 class FormatStringHandler {
587 FormatStringHandler() {}
588 virtual ~FormatStringHandler();
590 virtual void HandleNullChar(const char *nullCharacter) {}
592 virtual void HandlePosition(const char *startPos, unsigned posLen) {}
594 virtual void HandleInvalidPosition(const char *startPos, unsigned posLen,
595 PositionContext p) {}
597 virtual void HandleZeroPosition(const char *startPos, unsigned posLen) {}
599 virtual void HandleIncompleteSpecifier(const char *startSpecifier,
600 unsigned specifierLen) {}
602 // Printf-specific handlers.
604 virtual bool HandleInvalidPrintfConversionSpecifier(
605 const analyze_printf::PrintfSpecifier &FS,
606 const char *startSpecifier,
607 unsigned specifierLen) {
611 virtual bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
612 const char *startSpecifier,
613 unsigned specifierLen) {
617 // Scanf-specific handlers.
619 virtual bool HandleInvalidScanfConversionSpecifier(
620 const analyze_scanf::ScanfSpecifier &FS,
621 const char *startSpecifier,
622 unsigned specifierLen) {
626 virtual bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
627 const char *startSpecifier,
628 unsigned specifierLen) {
632 virtual void HandleIncompleteScanList(const char *start, const char *end) {}
635 bool ParsePrintfString(FormatStringHandler &H,
636 const char *beg, const char *end, const LangOptions &LO,
637 const TargetInfo &Target);
639 bool ParseScanfString(FormatStringHandler &H,
640 const char *beg, const char *end, const LangOptions &LO,
641 const TargetInfo &Target);
643 } // end analyze_format_string namespace
644 } // end clang namespace