clang 24.0.0git
ScanfFormatString.cpp
Go to the documentation of this file.
1//= ScanfFormatString.cpp - Analysis of printf format strings --*- C++ -*-===//
2//
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
6//
7//===----------------------------------------------------------------------===//
8//
9// Handling of format string in scanf and friends. The structure of format
10// strings for fscanf() are described in C99 7.19.6.2.
11//
12//===----------------------------------------------------------------------===//
13
14#include "FormatStringParsing.h"
17
26using namespace clang;
27
30
31namespace {
32
33class ScanfFormatStringParser : analyze_format_string::FormatStringParser {
34public:
35 ScanfFormatStringParser(FormatStringHandler &H, const LangOptions &LO,
36 const TargetInfo &Target)
37 : FormatStringParser(H, LO, Target, /*IsScanf=*/true) {}
38
39 ScanfSpecifierResult parseSpecifier(const char *&Beg, const char *E,
40 unsigned &argIndex) const;
41
42private:
43 bool parseScanList(ScanfConversionSpecifier &CS, const char *&Beg,
44 const char *E) const;
45};
46
47} // namespace
48
49bool ScanfFormatStringParser::parseScanList(ScanfConversionSpecifier &CS,
50 const char *&Beg,
51 const char *E) const {
52 const char *I = Beg;
53 const char *start = I - 1;
54 UpdateOnReturn<const char *> UpdateBeg(Beg, I);
55
56 // No more characters?
57 if (I == E) {
58 H.HandleIncompleteScanList(start, I);
59 return true;
60 }
61
62 // Special case: ']' is the first character.
63 if (*I == ']') {
64 if (++I == E) {
65 H.HandleIncompleteScanList(start, I - 1);
66 return true;
67 }
68 }
69
70 // Special case: "^]" are the first characters.
71 if (I + 1 != E && I[0] == '^' && I[1] == ']') {
72 I += 2;
73 if (I == E) {
74 H.HandleIncompleteScanList(start, I - 1);
75 return true;
76 }
77 }
78
79 // Look for a ']' character which denotes the end of the scan list.
80 while (*I != ']') {
81 if (++I == E) {
82 H.HandleIncompleteScanList(start, I - 1);
83 return true;
84 }
85 }
86
87 CS.setEndScanList(I);
88 return false;
89}
90
91// FIXME: Much of this is copy-paste from PrintfFormatStringParser.
92// We can possibly refactor.
94ScanfFormatStringParser::parseSpecifier(const char *&Beg, const char *E,
95 unsigned &argIndex) const {
96 using namespace clang::analyze_format_string;
97 using namespace clang::analyze_scanf;
98 const char *I = Beg;
99 const char *Start = nullptr;
100 UpdateOnReturn<const char *> UpdateBeg(Beg, I);
101
102 // Look for a '%' character that indicates the start of a format specifier.
103 for (; I != E; ++I) {
104 char c = *I;
105 if (c == '\0') {
106 // Detect spurious null characters, which are likely errors.
107 H.HandleNullChar(I);
108 return true;
109 }
110 if (c == '%') {
111 Start = I++; // Record the start of the format specifier.
112 break;
113 }
114 }
115
116 // No format specifier found?
117 if (!Start)
118 return false;
119
120 if (I == E) {
121 // No more characters left?
122 H.HandleIncompleteSpecifier(Start, E - Start);
123 return true;
124 }
125
126 ScanfSpecifier FS;
127 if (parseArgPosition(FS, Start, I, E))
128 return true;
129
130 if (I == E) {
131 // No more characters left?
132 H.HandleIncompleteSpecifier(Start, E - Start);
133 return true;
134 }
135
136 // Look for '*' flag if it is present.
137 if (*I == '*') {
139 if (++I == E) {
140 H.HandleIncompleteSpecifier(Start, E - Start);
141 return true;
142 }
143 }
144
145 // Look for the field width (if any). Unlike printf, this is either
146 // a fixed integer or isn't present.
147 const OptionalAmount &Amt = parseAmount(I, E);
150 FS.setFieldWidth(Amt);
151
152 if (I == E) {
153 // No more characters left?
154 H.HandleIncompleteSpecifier(Start, E - Start);
155 return true;
156 }
157 }
158
159 // Look for the length modifier.
160 if (parseLengthModifier(FS, I, E) && I == E) {
161 // No more characters left?
162 H.HandleIncompleteSpecifier(Start, E - Start);
163 return true;
164 }
165
166 // Detect spurious null characters, which are likely errors.
167 if (*I == '\0') {
168 H.HandleNullChar(I);
169 return true;
170 }
171
172 // Finally, look for the conversion specifier.
173 const char *conversionPosition = I++;
175 switch (*conversionPosition) {
176 default:
177 break;
178 case '%':
180 break;
181 case 'b':
183 break;
184 case 'A':
186 break;
187 case 'E':
189 break;
190 case 'F':
192 break;
193 case 'G':
195 break;
196 case 'X':
198 break;
199 case 'a':
201 break;
202 case 'd':
204 break;
205 case 'e':
207 break;
208 case 'f':
210 break;
211 case 'g':
213 break;
214 case 'i':
216 break;
217 case 'n':
219 break;
220 case 'c':
222 break;
223 case 'C':
225 break;
226 case 'S':
228 break;
229 case '[':
231 break;
232 case 'u':
234 break;
235 case 'x':
237 break;
238 case 'o':
240 break;
241 case 's':
243 break;
244 case 'p':
246 break;
247 // Apple extensions
248 // Apple-specific
249 case 'D':
250 if (Target.getTriple().isOSDarwin())
252 break;
253 case 'O':
254 if (Target.getTriple().isOSDarwin())
256 break;
257 case 'U':
258 if (Target.getTriple().isOSDarwin())
260 break;
261 }
262 ScanfConversionSpecifier CS(conversionPosition, k);
264 if (parseScanList(CS, I, E))
265 return true;
266 }
269 !FS.usesPositionalArg())
270 FS.setArgIndex(argIndex++);
271
272 // FIXME: '%' and '*' doesn't make sense. Issue a warning.
273 // FIXME: 'ConsumedSoFar' and '*' doesn't make sense.
274
276 unsigned Len = I - Beg;
277 if (parseUTF8InvalidSpecifier(Beg, E, Len)) {
278 CS.setEndScanList(Beg + Len);
280 }
281 // Assume the conversion takes one argument.
282 return !H.HandleInvalidScanfConversionSpecifier(FS, Beg, Len);
283 }
284 return ScanfSpecifierResult(Start, FS);
285}
286
289
290 if (!CS.consumesDataArgument())
291 return ArgType::Invalid();
292
293 switch (CS.getKind()) {
294 // Signed int.
298 switch (LM.getKind()) {
300 return ArgType::PtrTo(Ctx.IntTy);
304 return ArgType::PtrTo(Ctx.ShortTy);
306 return ArgType::PtrTo(Ctx.LongTy);
309 return ArgType::PtrTo(Ctx.LongLongTy);
311 return ArgType::PtrTo(ArgType(Ctx.LongLongTy, "__int64"));
313 return ArgType::PtrTo(ArgType(Ctx.getIntMaxType(), "intmax_t"));
316 ArgType(Ctx.getSignedSizeType(), "signed size_t")));
319 ArgType(Ctx.getPointerDiffType(), "ptrdiff_t")));
322 return ArgType::PtrTo(ArgType::makeIntNType(Ctx, LM, /*Signed=*/true));
324 // GNU extension.
325 return ArgType::PtrTo(Ctx.LongLongTy);
335 return ArgType::Invalid();
336 }
337 llvm_unreachable("Unsupported LengthModifier Type");
338
339 // Unsigned int.
347 switch (LM.getKind()) {
349 return ArgType::PtrTo(Ctx.UnsignedIntTy);
351 return ArgType::PtrTo(Ctx.UnsignedCharTy);
355 return ArgType::PtrTo(Ctx.UnsignedLongTy);
360 return ArgType::PtrTo(
361 ArgType(Ctx.UnsignedLongLongTy, "unsigned __int64"));
363 return ArgType::PtrTo(ArgType(Ctx.getUIntMaxType(), "uintmax_t"));
365 return ArgType::PtrTo(
366 ArgType::makeSizeT(ArgType(Ctx.getSizeType(), "size_t")));
369 ArgType(Ctx.getUnsignedPointerDiffType(), "unsigned ptrdiff_t")));
372 return ArgType::PtrTo(ArgType::makeIntNType(Ctx, LM, /*Signed=*/false));
374 // GNU extension.
385 return ArgType::Invalid();
386 }
387 llvm_unreachable("Unsupported LengthModifier Type");
388
389 // Float.
398 switch (LM.getKind()) {
400 return ArgType::PtrTo(Ctx.FloatTy);
402 return ArgType::PtrTo(Ctx.DoubleTy);
404 return ArgType::PtrTo(Ctx.LongDoubleTy);
406 return ArgType::PtrTo(ArgType::Unsupported("_Decimal32"));
408 return ArgType::PtrTo(ArgType::Unsupported("_Decimal64"));
410 return ArgType::PtrTo(ArgType::Unsupported("_Decimal128"));
411 default:
412 return ArgType::Invalid();
413 }
414
415 // Char, string and scanlist.
419 switch (LM.getKind()) {
424 return ArgType::PtrTo(ArgType(Ctx.getWideCharType(), "wchar_t"));
429 if (Ctx.getTargetInfo().getTriple().isOSMSVCRT())
431 [[fallthrough]];
432 default:
433 return ArgType::Invalid();
434 }
437 // FIXME: Mac OS X specific?
438 switch (LM.getKind()) {
441 return ArgType::PtrTo(ArgType(Ctx.getWideCharType(), "wchar_t"));
444 return ArgType::PtrTo(ArgType(ArgType::WCStrTy, "wchar_t *"));
446 if (Ctx.getTargetInfo().getTriple().isOSMSVCRT())
448 [[fallthrough]];
449 default:
450 return ArgType::Invalid();
451 }
452
453 // Pointer.
456
457 // Write-back.
459 switch (LM.getKind()) {
461 return ArgType::PtrTo(Ctx.IntTy);
463 return ArgType::PtrTo(Ctx.SignedCharTy);
465 return ArgType::PtrTo(Ctx.ShortTy);
467 return ArgType::PtrTo(Ctx.LongTy);
470 return ArgType::PtrTo(Ctx.LongLongTy);
472 return ArgType::PtrTo(ArgType(Ctx.LongLongTy, "__int64"));
474 return ArgType::PtrTo(ArgType(Ctx.getIntMaxType(), "intmax_t"));
477 ArgType(Ctx.getSignedSizeType(), "signed size_t")));
480 ArgType(Ctx.getPointerDiffType(), "ptrdiff_t")));
483 return ArgType::PtrTo(ArgType::makeIntNType(Ctx, LM, /*Signed=*/true));
485 return ArgType(); // FIXME: Is this a known extension?
495 return ArgType::Invalid();
496 }
497
498 default:
499 break;
500 }
501
502 return ArgType();
503}
504
506 const LangOptions &LangOpt, ASTContext &Ctx) {
507
508 // %n is different from other conversion specifiers; don't try to fix it.
509 if (CS.getKind() == ConversionSpecifier::nArg)
510 return false;
511
512 if (!QT->isPointerType())
513 return false;
514
515 QualType PT = QT->getPointeeType();
516
517 // If it's an enum, get its underlying type.
518 if (const auto *ED = PT->getAsEnumDecl()) {
519 // Don't try to fix incomplete enums.
520 if (!ED->isComplete())
521 return false;
522 PT = ED->getIntegerType();
523 }
524
525 const BuiltinType *BT = PT->getAs<BuiltinType>();
526 if (!BT)
527 return false;
528
529 // Pointer to a character.
530 if (PT->isAnyCharacterType()) {
532 if (PT->isWideCharType())
534 else
535 LM.setKind(LengthModifier::None);
536
537 // If we know the target array length, we can use it as a field width.
538 if (const ConstantArrayType *CAT = Ctx.getAsConstantArrayType(RawQT)) {
539 if (CAT->getSizeModifier() == ArraySizeModifier::Normal)
541 CAT->getZExtSize() - 1, "", 0, false);
542 }
543 return true;
544 }
545
546 // Figure out the length modifier.
547 switch (BT->getKind()) {
548 // no modifier
549 case BuiltinType::UInt:
550 case BuiltinType::Int:
551 case BuiltinType::Float:
552 LM.setKind(LengthModifier::None);
553 break;
554
555 // hh
556 case BuiltinType::Char_U:
557 case BuiltinType::UChar:
558 case BuiltinType::Char_S:
559 case BuiltinType::SChar:
560 LM.setKind(LengthModifier::AsChar);
561 break;
562
563 // h
564 case BuiltinType::Short:
565 case BuiltinType::UShort:
567 break;
568
569 // l
570 case BuiltinType::Long:
571 case BuiltinType::ULong:
572 case BuiltinType::Double:
573 LM.setKind(LengthModifier::AsLong);
574 break;
575
576 // ll
577 case BuiltinType::LongLong:
578 case BuiltinType::ULongLong:
580 break;
581
582 // L
583 case BuiltinType::LongDouble:
585 break;
586
587 // Don't know.
588 default:
589 return false;
590 }
591
592 // Handle size_t, ptrdiff_t, etc. that have dedicated length modifiers in C99.
593 if (LangOpt.C99 || LangOpt.CPlusPlus11)
595
596 // If fixing the length modifier was enough, we are done.
597 if (hasValidLengthModifier(Ctx.getTargetInfo(), LangOpt)) {
598 const analyze_scanf::ArgType &AT = getArgType(Ctx);
599 if (AT.isValid() && AT.matchesType(Ctx, QT))
600 return true;
601 }
602
603 // Figure out the conversion specifier.
604 if (PT->isRealFloatingType())
606 else if (PT->isSignedIntegerType())
608 else if (PT->isUnsignedIntegerType())
610 else
611 llvm_unreachable("Unexpected type");
612
613 return true;
614}
615
616void ScanfSpecifier::toString(raw_ostream &os) const {
617 os << "%";
618
619 if (usesPositionalArg())
620 os << getPositionalArgIndex() << "$";
621 if (SuppressAssignment)
622 os << "*";
623
624 FieldWidth.toString(os);
625 os << LM.toString();
626 os << CS.toString();
627}
628
630 const char *I,
631 const char *E,
632 const LangOptions &LO,
633 const TargetInfo &Target) {
634
635 unsigned argIndex = 0;
636
637 // Keep looking for a format specifier until we have exhausted the string.
638 ScanfFormatStringParser P(H, LO, Target);
639 while (I != E) {
640 const ScanfSpecifierResult &FSR = P.parseSpecifier(I, E, argIndex);
641 // Did a fail-stop error of any kind occur when parsing the specifier?
642 // If so, don't do any more processing.
643 if (FSR.shouldStop())
644 return true;
645 // Did we exhaust the string or encounter an error that
646 // we can recover from?
647 if (!FSR.hasValue())
648 continue;
649 // We have a format specifier. Pass it to the callback.
650 if (!H.HandleScanfSpecifier(FSR.getValue(), FSR.getStart(),
651 I - FSR.getStart())) {
652 return true;
653 }
654 }
655 assert(I == E && "Format string not exhausted");
656 return false;
657}
llvm::MachO::Target Target
Definition MachO.h:51
clang::analyze_format_string::SpecifierResult< ScanfSpecifier > ScanfSpecifierResult
bool fixType(QualType QT, QualType RawQT, const LangOptions &LangOpt, ASTContext &Ctx)
void toString(raw_ostream &os) const
ArgType getArgType(ASTContext &Ctx) const
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:245
const ConstantArrayType * getAsConstantArrayType(QualType T) const
CanQualType LongTy
QualType getUnsignedPointerDiffType() const
Return the unique unsigned counterpart of "ptrdiff_t" integer type.
CanQualType FloatTy
CanQualType DoubleTy
CanQualType getIntMaxType() const
Return the unique type for "intmax_t" (C99 7.18.1.5), defined in <stdint.h>.
CanQualType LongDoubleTy
QualType getPointerDiffType() const
Return the unique type for "ptrdiff_t" (C99 7.17) defined in <stddef.h>.
CanQualType UnsignedLongTy
CanQualType IntTy
CanQualType SignedCharTy
CanQualType UnsignedCharTy
CanQualType UnsignedIntTy
CanQualType UnsignedLongLongTy
CanQualType UnsignedShortTy
CanQualType ShortTy
QualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
const TargetInfo & getTargetInfo() const
Definition ASTContext.h:975
QualType getSignedSizeType() const
Return the unique signed counterpart of the integer type corresponding to size_t.
CanQualType LongLongTy
QualType getWideCharType() const
Return the type of wide characters.
CanQualType getUIntMaxType() const
Return the unique type for "uintmax_t" (C99 7.18.1.5), defined in <stdint.h>.
This class is used for builtin types like 'int'.
Definition TypeBase.h:3246
Kind getKind() const
Definition TypeBase.h:3300
Represents the canonical version of C arrays with a specified constant size.
Definition TypeBase.h:3859
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
A (possibly-)qualified type.
Definition TypeBase.h:938
Exposes information about the current target.
Definition TargetInfo.h:228
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char,...
Definition Type.cpp:2410
bool isPointerType() const
Definition TypeBase.h:8917
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:885
bool isAnyCharacterType() const
Determine whether this type is any of the built-in character types.
Definition Type.cpp:2373
EnumDecl * getAsEnumDecl() const
Retrieves the EnumDecl this type refers to.
Definition Type.h:53
bool isRealFloatingType() const
Floating point categories.
Definition Type.cpp:2551
bool isWideCharType() const
Definition Type.cpp:2346
bool isUnsignedIntegerType() const
Return true if this is an integer type that is unsigned, according to C99 6.2.5p6 [which returns true...
Definition Type.cpp:2478
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9537
MatchKind matchesType(ASTContext &C, QualType argTy) const
static bool namedTypeToLengthModifier(ASTContext &Ctx, QualType QT, LengthModifier &LM)
For a TypedefType QT, if it is a named integer type such as size_t, assign the appropriate value to L...
void setFieldWidth(const OptionalAmount &Amt)
bool hasValidLengthModifier(const TargetInfo &Target, const LangOptions &LO) const
virtual bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS, const char *startSpecifier, unsigned specifierLen)
Represents the length modifier in a format string in scanf/printf.
static ArgType makePtrdiffT(const ArgType &A)
Create an ArgType which corresponds to the ptrdiff_t/unsigned ptrdiff_t type.
static ArgType PtrTo(const ArgType &A)
Create an ArgType which corresponds to the type pointer to A.
static ArgType Unsupported(const char *N)
static ArgType makeIntNType(ASTContext &Ctx, const LengthModifier &LengthMod, bool Signed)
static ArgType makeSizeT(const ArgType &A)
Create an ArgType which corresponds to the size_t/ssize_t type.
const OptionalFlag & getSuppressAssignment() const
void setConversionSpecifier(const ScanfConversionSpecifier &cs)
const ScanfConversionSpecifier & getConversionSpecifier() const
void setSuppressAssignment(const char *position)
ArgType getArgType(ASTContext &Ctx) const
Defines the clang::TargetInfo interface.
bool ParseScanfString(FormatStringHandler &H, const char *beg, const char *end, const LangOptions &LO, const TargetInfo &Target)
Top level wrappers for InstallAPI frontend operations.