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 // GlibC specific specifiers.
164 PrintfConvBeg = ObjCObjArg, PrintfConvEnd = PrintErrno,
166 // ** Scanf-specific **
168 ScanfConvBeg = ScanListArg, ScanfConvEnd = ScanListArg
171 ConversionSpecifier(bool isPrintf = true)
172 : IsPrintf(isPrintf), Position(0), EndScanList(0), kind(InvalidSpecifier) {}
174 ConversionSpecifier(bool isPrintf, const char *pos, Kind k)
175 : IsPrintf(isPrintf), Position(pos), EndScanList(0), kind(k) {}
177 const char *getStart() const {
181 StringRef getCharacters() const {
182 return StringRef(getStart(), getLength());
185 bool consumesDataArgument() const {
197 Kind getKind() const { return kind; }
198 void setKind(Kind k) { kind = k; }
199 unsigned getLength() const {
200 return EndScanList ? EndScanList - Position : 1;
203 bool isIntArg() const { return kind >= IntArgBeg && kind <= IntArgEnd; }
204 bool isUIntArg() const { return kind >= UIntArgBeg && kind <= UIntArgEnd; }
205 bool isAnyIntArg() const { return kind >= IntArgBeg && kind <= UIntArgEnd; }
206 const char *toString() const;
208 bool isPrintfKind() const { return IsPrintf; }
210 Optional<ConversionSpecifier> getStandardSpecifier() const;
214 const char *Position;
215 const char *EndScanList;
221 enum Kind { UnknownTy, InvalidTy, SpecificTy, ObjCPointerTy, CPointerTy,
222 AnyCharTy, CStrTy, WCStrTy, WIntTy };
229 ArgType(Kind k = UnknownTy, const char *n = 0) : K(k), Name(n), Ptr(false) {}
230 ArgType(QualType t, const char *n = 0)
231 : K(SpecificTy), T(t), Name(n), Ptr(false) {}
232 ArgType(CanQualType t) : K(SpecificTy), T(t), Name(0), Ptr(false) {}
234 static ArgType Invalid() { return ArgType(InvalidTy); }
235 bool isValid() const { return K != InvalidTy; }
237 /// Create an ArgType which corresponds to the type pointer to A.
238 static ArgType PtrTo(const ArgType& A) {
239 assert(A.K >= InvalidTy && "ArgType cannot be pointer to invalid/unknown");
245 bool matchesType(ASTContext &C, QualType argTy) const;
247 QualType getRepresentativeType(ASTContext &C) const;
249 std::string getRepresentativeTypeName(ASTContext &C) const;
252 class OptionalAmount {
254 enum HowSpecified { NotSpecified, Constant, Arg, Invalid };
256 OptionalAmount(HowSpecified howSpecified,
258 const char *amountStart,
259 unsigned amountLength,
260 bool usesPositionalArg)
261 : start(amountStart), length(amountLength), hs(howSpecified), amt(amount),
262 UsesPositionalArg(usesPositionalArg), UsesDotPrefix(0) {}
264 OptionalAmount(bool valid = true)
265 : start(0),length(0), hs(valid ? NotSpecified : Invalid), amt(0),
266 UsesPositionalArg(0), UsesDotPrefix(0) {}
268 bool isInvalid() const {
269 return hs == Invalid;
272 HowSpecified getHowSpecified() const { return hs; }
273 void setHowSpecified(HowSpecified h) { hs = h; }
275 bool hasDataArgument() const { return hs == Arg; }
277 unsigned getArgIndex() const {
278 assert(hasDataArgument());
282 unsigned getConstantAmount() const {
283 assert(hs == Constant);
287 const char *getStart() const {
288 // We include the . character if it is given.
289 return start - UsesDotPrefix;
292 unsigned getConstantLength() const {
293 assert(hs == Constant);
294 return length + UsesDotPrefix;
297 ArgType getArgType(ASTContext &Ctx) const;
299 void toString(raw_ostream &os) const;
301 bool usesPositionalArg() const { return (bool) UsesPositionalArg; }
302 unsigned getPositionalArgIndex() const {
303 assert(hasDataArgument());
307 bool usesDotPrefix() const { return UsesDotPrefix; }
308 void setUsesDotPrefix() { UsesDotPrefix = true; }
315 bool UsesPositionalArg : 1;
320 class FormatSpecifier {
323 OptionalAmount FieldWidth;
324 ConversionSpecifier CS;
325 /// Positional arguments, an IEEE extension:
326 /// IEEE Std 1003.1, 2004 Edition
327 /// http://www.opengroup.org/onlinepubs/009695399/functions/printf.html
328 bool UsesPositionalArg;
331 FormatSpecifier(bool isPrintf)
332 : CS(isPrintf), UsesPositionalArg(false), argIndex(0) {}
334 void setLengthModifier(LengthModifier lm) {
338 void setUsesPositionalArg() { UsesPositionalArg = true; }
340 void setArgIndex(unsigned i) {
344 unsigned getArgIndex() const {
348 unsigned getPositionalArgIndex() const {
352 const LengthModifier &getLengthModifier() const {
356 const OptionalAmount &getFieldWidth() const {
360 void setFieldWidth(const OptionalAmount &Amt) {
364 bool usesPositionalArg() const { return UsesPositionalArg; }
366 bool hasValidLengthModifier(const TargetInfo &Target) const;
368 bool hasStandardLengthModifier() const;
370 Optional<LengthModifier> getCorrectedLengthModifier() const;
372 bool hasStandardConversionSpecifier(const LangOptions &LangOpt) const;
374 bool hasStandardLengthConversionCombination() const;
376 /// For a TypedefType QT, if it is a named integer type such as size_t,
377 /// assign the appropriate value to LM and return true.
378 static bool namedTypeToLengthModifier(QualType QT, LengthModifier &LM);
381 } // end analyze_format_string namespace
383 //===----------------------------------------------------------------------===//
384 /// Pieces specific to fprintf format strings.
386 namespace analyze_printf {
388 class PrintfConversionSpecifier :
389 public analyze_format_string::ConversionSpecifier {
391 PrintfConversionSpecifier()
392 : ConversionSpecifier(true, 0, InvalidSpecifier) {}
394 PrintfConversionSpecifier(const char *pos, Kind k)
395 : ConversionSpecifier(true, pos, k) {}
397 bool isObjCArg() const { return kind >= ObjCBeg && kind <= ObjCEnd; }
398 bool isDoubleArg() const { return kind >= DoubleArgBeg &&
399 kind <= DoubleArgEnd; }
400 unsigned getLength() const {
401 // Conversion specifiers currently only are represented by
402 // single characters, but we be flexible.
406 static bool classof(const analyze_format_string::ConversionSpecifier *CS) {
407 return CS->isPrintfKind();
411 using analyze_format_string::ArgType;
412 using analyze_format_string::LengthModifier;
413 using analyze_format_string::OptionalAmount;
414 using analyze_format_string::OptionalFlag;
416 class PrintfSpecifier : public analyze_format_string::FormatSpecifier {
417 OptionalFlag HasThousandsGrouping; // ''', POSIX extension.
418 OptionalFlag IsLeftJustified; // '-'
419 OptionalFlag HasPlusPrefix; // '+'
420 OptionalFlag HasSpacePrefix; // ' '
421 OptionalFlag HasAlternativeForm; // '#'
422 OptionalFlag HasLeadingZeroes; // '0'
423 OptionalAmount Precision;
426 FormatSpecifier(/* isPrintf = */ true),
427 HasThousandsGrouping("'"), IsLeftJustified("-"), HasPlusPrefix("+"),
428 HasSpacePrefix(" "), HasAlternativeForm("#"), HasLeadingZeroes("0") {}
430 static PrintfSpecifier Parse(const char *beg, const char *end);
432 // Methods for incrementally constructing the PrintfSpecifier.
433 void setConversionSpecifier(const PrintfConversionSpecifier &cs) {
436 void setHasThousandsGrouping(const char *position) {
437 HasThousandsGrouping = true;
438 HasThousandsGrouping.setPosition(position);
440 void setIsLeftJustified(const char *position) {
441 IsLeftJustified = true;
442 IsLeftJustified.setPosition(position);
444 void setHasPlusPrefix(const char *position) {
445 HasPlusPrefix = true;
446 HasPlusPrefix.setPosition(position);
448 void setHasSpacePrefix(const char *position) {
449 HasSpacePrefix = true;
450 HasSpacePrefix.setPosition(position);
452 void setHasAlternativeForm(const char *position) {
453 HasAlternativeForm = true;
454 HasAlternativeForm.setPosition(position);
456 void setHasLeadingZeros(const char *position) {
457 HasLeadingZeroes = true;
458 HasLeadingZeroes.setPosition(position);
460 void setUsesPositionalArg() { UsesPositionalArg = true; }
462 // Methods for querying the format specifier.
464 const PrintfConversionSpecifier &getConversionSpecifier() const {
465 return cast<PrintfConversionSpecifier>(CS);
468 void setPrecision(const OptionalAmount &Amt) {
470 Precision.setUsesDotPrefix();
473 const OptionalAmount &getPrecision() const {
477 bool consumesDataArgument() const {
478 return getConversionSpecifier().consumesDataArgument();
481 /// \brief Returns the builtin type that a data argument
482 /// paired with this format specifier should have. This method
483 /// will return null if the format specifier does not have
484 /// a matching data argument or the matching argument matches
485 /// more than one type.
486 ArgType getArgType(ASTContext &Ctx, bool IsObjCLiteral) const;
488 const OptionalFlag &hasThousandsGrouping() const {
489 return HasThousandsGrouping;
491 const OptionalFlag &isLeftJustified() const { return IsLeftJustified; }
492 const OptionalFlag &hasPlusPrefix() const { return HasPlusPrefix; }
493 const OptionalFlag &hasAlternativeForm() const { return HasAlternativeForm; }
494 const OptionalFlag &hasLeadingZeros() const { return HasLeadingZeroes; }
495 const OptionalFlag &hasSpacePrefix() const { return HasSpacePrefix; }
496 bool usesPositionalArg() const { return UsesPositionalArg; }
498 /// Changes the specifier and length according to a QualType, retaining any
499 /// flags or options. Returns true on success, or false when a conversion
500 /// was not successful.
501 bool fixType(QualType QT, const LangOptions &LangOpt, ASTContext &Ctx,
504 void toString(raw_ostream &os) const;
506 // Validation methods - to check if any element results in undefined behavior
507 bool hasValidPlusPrefix() const;
508 bool hasValidAlternativeForm() const;
509 bool hasValidLeadingZeros() const;
510 bool hasValidSpacePrefix() const;
511 bool hasValidLeftJustified() const;
512 bool hasValidThousandsGroupingPrefix() const;
514 bool hasValidPrecision() const;
515 bool hasValidFieldWidth() const;
517 } // end analyze_printf namespace
519 //===----------------------------------------------------------------------===//
520 /// Pieces specific to fscanf format strings.
522 namespace analyze_scanf {
524 class ScanfConversionSpecifier :
525 public analyze_format_string::ConversionSpecifier {
527 ScanfConversionSpecifier()
528 : ConversionSpecifier(false, 0, InvalidSpecifier) {}
530 ScanfConversionSpecifier(const char *pos, Kind k)
531 : ConversionSpecifier(false, pos, k) {}
533 void setEndScanList(const char *pos) { EndScanList = pos; }
535 static bool classof(const analyze_format_string::ConversionSpecifier *CS) {
536 return !CS->isPrintfKind();
540 using analyze_format_string::ArgType;
541 using analyze_format_string::LengthModifier;
542 using analyze_format_string::OptionalAmount;
543 using analyze_format_string::OptionalFlag;
545 class ScanfSpecifier : public analyze_format_string::FormatSpecifier {
546 OptionalFlag SuppressAssignment; // '*'
549 FormatSpecifier(/* isPrintf = */ false),
550 SuppressAssignment("*") {}
552 void setSuppressAssignment(const char *position) {
553 SuppressAssignment = true;
554 SuppressAssignment.setPosition(position);
557 const OptionalFlag &getSuppressAssignment() const {
558 return SuppressAssignment;
561 void setConversionSpecifier(const ScanfConversionSpecifier &cs) {
565 const ScanfConversionSpecifier &getConversionSpecifier() const {
566 return cast<ScanfConversionSpecifier>(CS);
569 bool consumesDataArgument() const {
570 return CS.consumesDataArgument() && !SuppressAssignment;
573 ArgType getArgType(ASTContext &Ctx) const;
575 bool fixType(QualType QT, const LangOptions &LangOpt, ASTContext &Ctx);
577 void toString(raw_ostream &os) const;
579 static ScanfSpecifier Parse(const char *beg, const char *end);
582 } // end analyze_scanf namespace
584 //===----------------------------------------------------------------------===//
585 // Parsing and processing of format strings (both fprintf and fscanf).
587 namespace analyze_format_string {
589 enum PositionContext { FieldWidthPos = 0, PrecisionPos = 1 };
591 class FormatStringHandler {
593 FormatStringHandler() {}
594 virtual ~FormatStringHandler();
596 virtual void HandleNullChar(const char *nullCharacter) {}
598 virtual void HandlePosition(const char *startPos, unsigned posLen) {}
600 virtual void HandleInvalidPosition(const char *startPos, unsigned posLen,
601 PositionContext p) {}
603 virtual void HandleZeroPosition(const char *startPos, unsigned posLen) {}
605 virtual void HandleIncompleteSpecifier(const char *startSpecifier,
606 unsigned specifierLen) {}
608 // Printf-specific handlers.
610 virtual bool HandleInvalidPrintfConversionSpecifier(
611 const analyze_printf::PrintfSpecifier &FS,
612 const char *startSpecifier,
613 unsigned specifierLen) {
617 virtual bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
618 const char *startSpecifier,
619 unsigned specifierLen) {
623 // Scanf-specific handlers.
625 virtual bool HandleInvalidScanfConversionSpecifier(
626 const analyze_scanf::ScanfSpecifier &FS,
627 const char *startSpecifier,
628 unsigned specifierLen) {
632 virtual bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
633 const char *startSpecifier,
634 unsigned specifierLen) {
638 virtual void HandleIncompleteScanList(const char *start, const char *end) {}
641 bool ParsePrintfString(FormatStringHandler &H,
642 const char *beg, const char *end, const LangOptions &LO,
643 const TargetInfo &Target);
645 bool ParseScanfString(FormatStringHandler &H,
646 const char *beg, const char *end, const LangOptions &LO,
647 const TargetInfo &Target);
649 } // end analyze_format_string namespace
650 } // end clang namespace