clang 23.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
32 const char *&Beg, const char *E) {
33 const char *I = Beg;
34 const char *start = I - 1;
35 UpdateOnReturn<const char *> UpdateBeg(Beg, I);
36
37 // No more characters?
38 if (I == E) {
39 H.HandleIncompleteScanList(start, I);
40 return true;
41 }
42
43 // Special case: ']' is the first character.
44 if (*I == ']') {
45 if (++I == E) {
46 H.HandleIncompleteScanList(start, I - 1);
47 return true;
48 }
49 }
50
51 // Special case: "^]" are the first characters.
52 if (I + 1 != E && I[0] == '^' && I[1] == ']') {
53 I += 2;
54 if (I == E) {
55 H.HandleIncompleteScanList(start, I - 1);
56 return true;
57 }
58 }
59
60 // Look for a ']' character which denotes the end of the scan list.
61 while (*I != ']') {
62 if (++I == E) {
63 H.HandleIncompleteScanList(start, I - 1);
64 return true;
65 }
66 }
67
68 CS.setEndScanList(I);
69 return false;
70}
71
72// FIXME: Much of this is copy-paste from ParsePrintfSpecifier.
73// We can possibly refactor.
75 const char *&Beg, const char *E,
76 unsigned &argIndex,
77 const LangOptions &LO,
78 const TargetInfo &Target) {
79 using namespace clang::analyze_format_string;
80 using namespace clang::analyze_scanf;
81 const char *I = Beg;
82 const char *Start = nullptr;
83 UpdateOnReturn<const char *> UpdateBeg(Beg, I);
84
85 // Look for a '%' character that indicates the start of a format specifier.
86 for (; I != E; ++I) {
87 char c = *I;
88 if (c == '\0') {
89 // Detect spurious null characters, which are likely errors.
90 H.HandleNullChar(I);
91 return true;
92 }
93 if (c == '%') {
94 Start = I++; // Record the start of the format specifier.
95 break;
96 }
97 }
98
99 // No format specifier found?
100 if (!Start)
101 return false;
102
103 if (I == E) {
104 // No more characters left?
105 H.HandleIncompleteSpecifier(Start, E - Start);
106 return true;
107 }
108
110 if (ParseArgPosition(H, FS, Start, I, E))
111 return true;
112
113 if (I == E) {
114 // No more characters left?
115 H.HandleIncompleteSpecifier(Start, E - Start);
116 return true;
117 }
118
119 // Look for '*' flag if it is present.
120 if (*I == '*') {
122 if (++I == E) {
123 H.HandleIncompleteSpecifier(Start, E - Start);
124 return true;
125 }
126 }
127
128 // Look for the field width (if any). Unlike printf, this is either
129 // a fixed integer or isn't present.
133 FS.setFieldWidth(Amt);
134
135 if (I == E) {
136 // No more characters left?
137 H.HandleIncompleteSpecifier(Start, E - Start);
138 return true;
139 }
140 }
141
142 // Look for the length modifier.
143 if (ParseLengthModifier(FS, I, E, LO, /*IsScanf=*/true) && I == E) {
144 // No more characters left?
145 H.HandleIncompleteSpecifier(Start, E - Start);
146 return true;
147 }
148
149 // Detect spurious null characters, which are likely errors.
150 if (*I == '\0') {
151 H.HandleNullChar(I);
152 return true;
153 }
154
155 // Finally, look for the conversion specifier.
156 const char *conversionPosition = I++;
158 switch (*conversionPosition) {
159 default:
160 break;
161 case '%':
163 break;
164 case 'b':
166 break;
167 case 'A':
169 break;
170 case 'E':
172 break;
173 case 'F':
175 break;
176 case 'G':
178 break;
179 case 'X':
181 break;
182 case 'a':
184 break;
185 case 'd':
187 break;
188 case 'e':
190 break;
191 case 'f':
193 break;
194 case 'g':
196 break;
197 case 'i':
199 break;
200 case 'n':
202 break;
203 case 'c':
205 break;
206 case 'C':
208 break;
209 case 'S':
211 break;
212 case '[':
214 break;
215 case 'u':
217 break;
218 case 'x':
220 break;
221 case 'o':
223 break;
224 case 's':
226 break;
227 case 'p':
229 break;
230 // Apple extensions
231 // Apple-specific
232 case 'D':
233 if (Target.getTriple().isOSDarwin())
235 break;
236 case 'O':
237 if (Target.getTriple().isOSDarwin())
239 break;
240 case 'U':
241 if (Target.getTriple().isOSDarwin())
243 break;
244 }
245 ScanfConversionSpecifier CS(conversionPosition, k);
247 if (ParseScanList(H, CS, I, E))
248 return true;
249 }
252 !FS.usesPositionalArg())
253 FS.setArgIndex(argIndex++);
254
255 // FIXME: '%' and '*' doesn't make sense. Issue a warning.
256 // FIXME: 'ConsumedSoFar' and '*' doesn't make sense.
257
259 unsigned Len = I - Beg;
260 if (ParseUTF8InvalidSpecifier(Beg, E, Len)) {
261 CS.setEndScanList(Beg + Len);
263 }
264 // Assume the conversion takes one argument.
265 return !H.HandleInvalidScanfConversionSpecifier(FS, Beg, Len);
266 }
267 return ScanfSpecifierResult(Start, FS);
268}
269
272
273 if (!CS.consumesDataArgument())
274 return ArgType::Invalid();
275
276 switch (CS.getKind()) {
277 // Signed int.
281 switch (LM.getKind()) {
283 return ArgType::PtrTo(Ctx.IntTy);
287 return ArgType::PtrTo(Ctx.ShortTy);
289 return ArgType::PtrTo(Ctx.LongTy);
292 return ArgType::PtrTo(Ctx.LongLongTy);
294 return ArgType::PtrTo(ArgType(Ctx.LongLongTy, "__int64"));
296 return ArgType::PtrTo(ArgType(Ctx.getIntMaxType(), "intmax_t"));
299 ArgType(Ctx.getSignedSizeType(), "signed size_t")));
302 ArgType(Ctx.getPointerDiffType(), "ptrdiff_t")));
305 return ArgType::PtrTo(ArgType::makeIntNType(Ctx, LM, /*Signed=*/true));
307 // GNU extension.
308 return ArgType::PtrTo(Ctx.LongLongTy);
318 return ArgType::Invalid();
319 }
320 llvm_unreachable("Unsupported LengthModifier Type");
321
322 // Unsigned int.
330 switch (LM.getKind()) {
332 return ArgType::PtrTo(Ctx.UnsignedIntTy);
334 return ArgType::PtrTo(Ctx.UnsignedCharTy);
338 return ArgType::PtrTo(Ctx.UnsignedLongTy);
343 return ArgType::PtrTo(
344 ArgType(Ctx.UnsignedLongLongTy, "unsigned __int64"));
346 return ArgType::PtrTo(ArgType(Ctx.getUIntMaxType(), "uintmax_t"));
348 return ArgType::PtrTo(
349 ArgType::makeSizeT(ArgType(Ctx.getSizeType(), "size_t")));
352 ArgType(Ctx.getUnsignedPointerDiffType(), "unsigned ptrdiff_t")));
355 return ArgType::PtrTo(ArgType::makeIntNType(Ctx, LM, /*Signed=*/false));
357 // GNU extension.
368 return ArgType::Invalid();
369 }
370 llvm_unreachable("Unsupported LengthModifier Type");
371
372 // Float.
381 switch (LM.getKind()) {
383 return ArgType::PtrTo(Ctx.FloatTy);
385 return ArgType::PtrTo(Ctx.DoubleTy);
387 return ArgType::PtrTo(Ctx.LongDoubleTy);
389 return ArgType::PtrTo(ArgType::Unsupported("_Decimal32"));
391 return ArgType::PtrTo(ArgType::Unsupported("_Decimal64"));
393 return ArgType::PtrTo(ArgType::Unsupported("_Decimal128"));
394 default:
395 return ArgType::Invalid();
396 }
397
398 // Char, string and scanlist.
402 switch (LM.getKind()) {
407 return ArgType::PtrTo(ArgType(Ctx.getWideCharType(), "wchar_t"));
412 if (Ctx.getTargetInfo().getTriple().isOSMSVCRT())
414 [[fallthrough]];
415 default:
416 return ArgType::Invalid();
417 }
420 // FIXME: Mac OS X specific?
421 switch (LM.getKind()) {
424 return ArgType::PtrTo(ArgType(Ctx.getWideCharType(), "wchar_t"));
427 return ArgType::PtrTo(ArgType(ArgType::WCStrTy, "wchar_t *"));
429 if (Ctx.getTargetInfo().getTriple().isOSMSVCRT())
431 [[fallthrough]];
432 default:
433 return ArgType::Invalid();
434 }
435
436 // Pointer.
439
440 // Write-back.
442 switch (LM.getKind()) {
444 return ArgType::PtrTo(Ctx.IntTy);
446 return ArgType::PtrTo(Ctx.SignedCharTy);
448 return ArgType::PtrTo(Ctx.ShortTy);
450 return ArgType::PtrTo(Ctx.LongTy);
453 return ArgType::PtrTo(Ctx.LongLongTy);
455 return ArgType::PtrTo(ArgType(Ctx.LongLongTy, "__int64"));
457 return ArgType::PtrTo(ArgType(Ctx.getIntMaxType(), "intmax_t"));
460 ArgType(Ctx.getSignedSizeType(), "signed size_t")));
463 ArgType(Ctx.getPointerDiffType(), "ptrdiff_t")));
466 return ArgType::PtrTo(ArgType::makeIntNType(Ctx, LM, /*Signed=*/true));
468 return ArgType(); // FIXME: Is this a known extension?
478 return ArgType::Invalid();
479 }
480
481 default:
482 break;
483 }
484
485 return ArgType();
486}
487
489 const LangOptions &LangOpt, ASTContext &Ctx) {
490
491 // %n is different from other conversion specifiers; don't try to fix it.
492 if (CS.getKind() == ConversionSpecifier::nArg)
493 return false;
494
495 if (!QT->isPointerType())
496 return false;
497
498 QualType PT = QT->getPointeeType();
499
500 // If it's an enum, get its underlying type.
501 if (const auto *ED = PT->getAsEnumDecl()) {
502 // Don't try to fix incomplete enums.
503 if (!ED->isComplete())
504 return false;
505 PT = ED->getIntegerType();
506 }
507
508 const BuiltinType *BT = PT->getAs<BuiltinType>();
509 if (!BT)
510 return false;
511
512 // Pointer to a character.
513 if (PT->isAnyCharacterType()) {
515 if (PT->isWideCharType())
517 else
518 LM.setKind(LengthModifier::None);
519
520 // If we know the target array length, we can use it as a field width.
521 if (const ConstantArrayType *CAT = Ctx.getAsConstantArrayType(RawQT)) {
522 if (CAT->getSizeModifier() == ArraySizeModifier::Normal)
524 CAT->getZExtSize() - 1, "", 0, false);
525 }
526 return true;
527 }
528
529 // Figure out the length modifier.
530 switch (BT->getKind()) {
531 // no modifier
532 case BuiltinType::UInt:
533 case BuiltinType::Int:
534 case BuiltinType::Float:
535 LM.setKind(LengthModifier::None);
536 break;
537
538 // hh
539 case BuiltinType::Char_U:
540 case BuiltinType::UChar:
541 case BuiltinType::Char_S:
542 case BuiltinType::SChar:
543 LM.setKind(LengthModifier::AsChar);
544 break;
545
546 // h
547 case BuiltinType::Short:
548 case BuiltinType::UShort:
550 break;
551
552 // l
553 case BuiltinType::Long:
554 case BuiltinType::ULong:
555 case BuiltinType::Double:
556 LM.setKind(LengthModifier::AsLong);
557 break;
558
559 // ll
560 case BuiltinType::LongLong:
561 case BuiltinType::ULongLong:
563 break;
564
565 // L
566 case BuiltinType::LongDouble:
568 break;
569
570 // Don't know.
571 default:
572 return false;
573 }
574
575 // Handle size_t, ptrdiff_t, etc. that have dedicated length modifiers in C99.
576 if (LangOpt.C99 || LangOpt.CPlusPlus11)
578
579 // If fixing the length modifier was enough, we are done.
580 if (hasValidLengthModifier(Ctx.getTargetInfo(), LangOpt)) {
581 const analyze_scanf::ArgType &AT = getArgType(Ctx);
582 if (AT.isValid() && AT.matchesType(Ctx, QT))
583 return true;
584 }
585
586 // Figure out the conversion specifier.
587 if (PT->isRealFloatingType())
589 else if (PT->isSignedIntegerType())
591 else if (PT->isUnsignedIntegerType())
593 else
594 llvm_unreachable("Unexpected type");
595
596 return true;
597}
598
599void ScanfSpecifier::toString(raw_ostream &os) const {
600 os << "%";
601
602 if (usesPositionalArg())
603 os << getPositionalArgIndex() << "$";
604 if (SuppressAssignment)
605 os << "*";
606
607 FieldWidth.toString(os);
608 os << LM.toString();
609 os << CS.toString();
610}
611
613 const char *I,
614 const char *E,
615 const LangOptions &LO,
616 const TargetInfo &Target) {
617
618 unsigned argIndex = 0;
619
620 // Keep looking for a format specifier until we have exhausted the string.
621 while (I != E) {
622 const ScanfSpecifierResult &FSR =
623 ParseScanfSpecifier(H, I, E, argIndex, LO, Target);
624 // Did a fail-stop error of any kind occur when parsing the specifier?
625 // If so, don't do any more processing.
626 if (FSR.shouldStop())
627 return true;
628 // Did we exhaust the string or encounter an error that
629 // we can recover from?
630 if (!FSR.hasValue())
631 continue;
632 // We have a format specifier. Pass it to the callback.
633 if (!H.HandleScanfSpecifier(FSR.getValue(), FSR.getStart(),
634 I - FSR.getStart())) {
635 return true;
636 }
637 }
638 assert(I == E && "Format string not exhausted");
639 return false;
640}
llvm::MachO::Target Target
Definition MachO.h:51
static bool ParseScanList(FormatStringHandler &H, ScanfConversionSpecifier &CS, const char *&Beg, const char *E)
static ScanfSpecifierResult ParseScanfSpecifier(FormatStringHandler &H, const char *&Beg, const char *E, unsigned &argIndex, const LangOptions &LO, const TargetInfo &Target)
clang::analyze_format_string::SpecifierResult< ScanfSpecifier > ScanfSpecifierResult
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:223
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:921
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:3228
Kind getKind() const
Definition TypeBase.h:3276
Represents the canonical version of C arrays with a specified constant size.
Definition TypeBase.h:3824
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:937
Exposes information about the current target.
Definition TargetInfo.h:227
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:2266
bool isPointerType() const
Definition TypeBase.h:8684
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:789
bool isAnyCharacterType() const
Determine whether this type is any of the built-in character types.
Definition Type.cpp:2229
EnumDecl * getAsEnumDecl() const
Retrieves the EnumDecl this type refers to.
Definition Type.h:53
bool isRealFloatingType() const
Floating point categories.
Definition Type.cpp:2405
bool isWideCharType() const
Definition Type.cpp:2202
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:2332
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9277
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 void HandleIncompleteScanList(const char *start, const char *end)
virtual void HandleNullChar(const char *nullCharacter)
virtual void HandleIncompleteSpecifier(const char *startSpecifier, unsigned specifierLen)
virtual bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS, const char *startSpecifier, unsigned specifierLen)
virtual bool HandleInvalidScanfConversionSpecifier(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.
bool fixType(QualType QT, QualType RawQT, const LangOptions &LangOpt, ASTContext &Ctx)
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.
Common components of both fprintf and fscanf format strings.
OptionalAmount ParseAmount(const char *&Beg, const char *E)
bool ParseLengthModifier(FormatSpecifier &FS, const char *&Beg, const char *E, const LangOptions &LO, bool IsScanf=false)
Returns true if a LengthModifier was parsed and installed in the FormatSpecifier& argument,...
bool ParseArgPosition(FormatStringHandler &H, FormatSpecifier &CS, const char *Start, const char *&Beg, const char *E)
bool ParseScanfString(FormatStringHandler &H, const char *beg, const char *end, const LangOptions &LO, const TargetInfo &Target)
bool ParseUTF8InvalidSpecifier(const char *SpecifierBegin, const char *FmtStrEnd, unsigned &Len)
Returns true if the invalid specifier in SpecifierBegin is a UTF-8 string; check that it won't go fur...
Pieces specific to fscanf format strings.
The JSON file list parser is used to communicate input to InstallAPI.