clang 22.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
15#include "FormatStringParsing.h"
17
26using namespace clang;
27
30
33 const char *&Beg, const char *E) {
34 const char *I = Beg;
35 const char *start = I - 1;
36 UpdateOnReturn <const char*> UpdateBeg(Beg, I);
37
38 // No more characters?
39 if (I == E) {
40 H.HandleIncompleteScanList(start, I);
41 return true;
42 }
43
44 // Special case: ']' is the first character.
45 if (*I == ']') {
46 if (++I == E) {
47 H.HandleIncompleteScanList(start, I - 1);
48 return true;
49 }
50 }
51
52 // Special case: "^]" are the first characters.
53 if (I + 1 != E && I[0] == '^' && I[1] == ']') {
54 I += 2;
55 if (I == E) {
56 H.HandleIncompleteScanList(start, I - 1);
57 return true;
58 }
59 }
60
61 // Look for a ']' character which denotes the end of the scan list.
62 while (*I != ']') {
63 if (++I == E) {
64 H.HandleIncompleteScanList(start, I - 1);
65 return true;
66 }
67 }
68
69 CS.setEndScanList(I);
70 return false;
71}
72
73// FIXME: Much of this is copy-paste from ParsePrintfSpecifier.
74// We can possibly refactor.
76 const char *&Beg,
77 const char *E,
78 unsigned &argIndex,
79 const LangOptions &LO,
80 const TargetInfo &Target) {
81 using namespace clang::analyze_format_string;
82 using namespace clang::analyze_scanf;
83 const char *I = Beg;
84 const char *Start = nullptr;
85 UpdateOnReturn <const char*> UpdateBeg(Beg, I);
86
87 // Look for a '%' character that indicates the start of a format specifier.
88 for ( ; I != E ; ++I) {
89 char c = *I;
90 if (c == '\0') {
91 // Detect spurious null characters, which are likely errors.
92 H.HandleNullChar(I);
93 return true;
94 }
95 if (c == '%') {
96 Start = I++; // Record the start of the format specifier.
97 break;
98 }
99 }
100
101 // No format specifier found?
102 if (!Start)
103 return false;
104
105 if (I == E) {
106 // No more characters left?
107 H.HandleIncompleteSpecifier(Start, E - Start);
108 return true;
109 }
110
112 if (ParseArgPosition(H, FS, Start, I, E))
113 return true;
114
115 if (I == E) {
116 // No more characters left?
117 H.HandleIncompleteSpecifier(Start, E - Start);
118 return true;
119 }
120
121 // Look for '*' flag if it is present.
122 if (*I == '*') {
123 FS.setSuppressAssignment(I);
124 if (++I == E) {
125 H.HandleIncompleteSpecifier(Start, E - Start);
126 return true;
127 }
128 }
129
130 // Look for the field width (if any). Unlike printf, this is either
131 // a fixed integer or isn't present.
135 FS.setFieldWidth(Amt);
136
137 if (I == E) {
138 // No more characters left?
139 H.HandleIncompleteSpecifier(Start, E - Start);
140 return true;
141 }
142 }
143
144 // Look for the length modifier.
145 if (ParseLengthModifier(FS, I, E, LO, /*IsScanf=*/true) && I == E) {
146 // No more characters left?
147 H.HandleIncompleteSpecifier(Start, E - Start);
148 return true;
149 }
150
151 // Detect spurious null characters, which are likely errors.
152 if (*I == '\0') {
153 H.HandleNullChar(I);
154 return true;
155 }
156
157 // Finally, look for the conversion specifier.
158 const char *conversionPosition = I++;
160 switch (*conversionPosition) {
161 default:
162 break;
163 case '%': k = ConversionSpecifier::PercentArg; break;
164 case 'b': k = ConversionSpecifier::bArg; break;
165 case 'A': k = ConversionSpecifier::AArg; break;
166 case 'E': k = ConversionSpecifier::EArg; break;
167 case 'F': k = ConversionSpecifier::FArg; break;
168 case 'G': k = ConversionSpecifier::GArg; break;
169 case 'X': k = ConversionSpecifier::XArg; break;
170 case 'a': k = ConversionSpecifier::aArg; break;
171 case 'd': k = ConversionSpecifier::dArg; break;
172 case 'e': k = ConversionSpecifier::eArg; break;
173 case 'f': k = ConversionSpecifier::fArg; break;
174 case 'g': k = ConversionSpecifier::gArg; break;
175 case 'i': k = ConversionSpecifier::iArg; break;
176 case 'n': k = ConversionSpecifier::nArg; break;
177 case 'c': k = ConversionSpecifier::cArg; break;
178 case 'C': k = ConversionSpecifier::CArg; break;
179 case 'S': k = ConversionSpecifier::SArg; break;
180 case '[': k = ConversionSpecifier::ScanListArg; break;
181 case 'u': k = ConversionSpecifier::uArg; break;
182 case 'x': k = ConversionSpecifier::xArg; break;
183 case 'o': k = ConversionSpecifier::oArg; break;
184 case 's': k = ConversionSpecifier::sArg; break;
185 case 'p': k = ConversionSpecifier::pArg; break;
186 // Apple extensions
187 // Apple-specific
188 case 'D':
189 if (Target.getTriple().isOSDarwin())
191 break;
192 case 'O':
193 if (Target.getTriple().isOSDarwin())
195 break;
196 case 'U':
197 if (Target.getTriple().isOSDarwin())
199 break;
200 }
201 ScanfConversionSpecifier CS(conversionPosition, k);
203 if (ParseScanList(H, CS, I, E))
204 return true;
205 }
206 FS.setConversionSpecifier(CS);
207 if (CS.consumesDataArgument() && !FS.getSuppressAssignment()
208 && !FS.usesPositionalArg())
209 FS.setArgIndex(argIndex++);
210
211 // FIXME: '%' and '*' doesn't make sense. Issue a warning.
212 // FIXME: 'ConsumedSoFar' and '*' doesn't make sense.
213
215 unsigned Len = I - Beg;
216 if (ParseUTF8InvalidSpecifier(Beg, E, Len)) {
217 CS.setEndScanList(Beg + Len);
218 FS.setConversionSpecifier(CS);
219 }
220 // Assume the conversion takes one argument.
221 return !H.HandleInvalidScanfConversionSpecifier(FS, Beg, Len);
222 }
223 return ScanfSpecifierResult(Start, FS);
224}
225
228
230 return ArgType::Invalid();
231
232 switch(CS.getKind()) {
233 // Signed int.
234 case ConversionSpecifier::dArg:
235 case ConversionSpecifier::DArg:
236 case ConversionSpecifier::iArg:
237 switch (LM.getKind()) {
239 return ArgType::PtrTo(Ctx.IntTy);
243 return ArgType::PtrTo(Ctx.ShortTy);
245 return ArgType::PtrTo(Ctx.LongTy);
248 return ArgType::PtrTo(Ctx.LongLongTy);
250 return ArgType::PtrTo(ArgType(Ctx.LongLongTy, "__int64"));
252 return ArgType::PtrTo(ArgType(Ctx.getIntMaxType(), "intmax_t"));
255 ArgType(Ctx.getSignedSizeType(), "signed size_t")));
258 ArgType(Ctx.getPointerDiffType(), "ptrdiff_t")));
260 // GNU extension.
261 return ArgType::PtrTo(Ctx.LongLongTy);
268 return ArgType::Invalid();
269 }
270 llvm_unreachable("Unsupported LengthModifier Type");
271
272 // Unsigned int.
273 case ConversionSpecifier::bArg:
274 case ConversionSpecifier::oArg:
275 case ConversionSpecifier::OArg:
276 case ConversionSpecifier::uArg:
277 case ConversionSpecifier::UArg:
278 case ConversionSpecifier::xArg:
279 case ConversionSpecifier::XArg:
280 switch (LM.getKind()) {
282 return ArgType::PtrTo(Ctx.UnsignedIntTy);
284 return ArgType::PtrTo(Ctx.UnsignedCharTy);
288 return ArgType::PtrTo(Ctx.UnsignedLongTy);
293 return ArgType::PtrTo(ArgType(Ctx.UnsignedLongLongTy, "unsigned __int64"));
295 return ArgType::PtrTo(ArgType(Ctx.getUIntMaxType(), "uintmax_t"));
297 return ArgType::PtrTo(
298 ArgType::makeSizeT(ArgType(Ctx.getSizeType(), "size_t")));
301 ArgType(Ctx.getUnsignedPointerDiffType(), "unsigned ptrdiff_t")));
303 // GNU extension.
311 return ArgType::Invalid();
312 }
313 llvm_unreachable("Unsupported LengthModifier Type");
314
315 // Float.
316 case ConversionSpecifier::aArg:
317 case ConversionSpecifier::AArg:
318 case ConversionSpecifier::eArg:
319 case ConversionSpecifier::EArg:
320 case ConversionSpecifier::fArg:
321 case ConversionSpecifier::FArg:
322 case ConversionSpecifier::gArg:
323 case ConversionSpecifier::GArg:
324 switch (LM.getKind()) {
326 return ArgType::PtrTo(Ctx.FloatTy);
328 return ArgType::PtrTo(Ctx.DoubleTy);
330 return ArgType::PtrTo(Ctx.LongDoubleTy);
331 default:
332 return ArgType::Invalid();
333 }
334
335 // Char, string and scanlist.
336 case ConversionSpecifier::cArg:
337 case ConversionSpecifier::sArg:
338 case ConversionSpecifier::ScanListArg:
339 switch (LM.getKind()) {
344 return ArgType::PtrTo(ArgType(Ctx.getWideCharType(), "wchar_t"));
349 if (Ctx.getTargetInfo().getTriple().isOSMSVCRT())
351 [[fallthrough]];
352 default:
353 return ArgType::Invalid();
354 }
355 case ConversionSpecifier::CArg:
356 case ConversionSpecifier::SArg:
357 // FIXME: Mac OS X specific?
358 switch (LM.getKind()) {
361 return ArgType::PtrTo(ArgType(Ctx.getWideCharType(), "wchar_t"));
364 return ArgType::PtrTo(ArgType(ArgType::WCStrTy, "wchar_t *"));
366 if (Ctx.getTargetInfo().getTriple().isOSMSVCRT())
368 [[fallthrough]];
369 default:
370 return ArgType::Invalid();
371 }
372
373 // Pointer.
374 case ConversionSpecifier::pArg:
376
377 // Write-back.
378 case ConversionSpecifier::nArg:
379 switch (LM.getKind()) {
381 return ArgType::PtrTo(Ctx.IntTy);
383 return ArgType::PtrTo(Ctx.SignedCharTy);
385 return ArgType::PtrTo(Ctx.ShortTy);
387 return ArgType::PtrTo(Ctx.LongTy);
390 return ArgType::PtrTo(Ctx.LongLongTy);
392 return ArgType::PtrTo(ArgType(Ctx.LongLongTy, "__int64"));
394 return ArgType::PtrTo(ArgType(Ctx.getIntMaxType(), "intmax_t"));
397 ArgType(Ctx.getSignedSizeType(), "signed size_t")));
400 ArgType(Ctx.getPointerDiffType(), "ptrdiff_t")));
402 return ArgType(); // FIXME: Is this a known extension?
409 return ArgType::Invalid();
410 }
411
412 default:
413 break;
414 }
415
416 return ArgType();
417}
418
420 const LangOptions &LangOpt,
421 ASTContext &Ctx) {
422
423 // %n is different from other conversion specifiers; don't try to fix it.
424 if (CS.getKind() == ConversionSpecifier::nArg)
425 return false;
426
427 if (!QT->isPointerType())
428 return false;
429
430 QualType PT = QT->getPointeeType();
431
432 // If it's an enum, get its underlying type.
433 if (const auto *ED = PT->getAsEnumDecl()) {
434 // Don't try to fix incomplete enums.
435 if (!ED->isComplete())
436 return false;
437 PT = ED->getIntegerType();
438 }
439
440 const BuiltinType *BT = PT->getAs<BuiltinType>();
441 if (!BT)
442 return false;
443
444 // Pointer to a character.
445 if (PT->isAnyCharacterType()) {
446 CS.setKind(ConversionSpecifier::sArg);
447 if (PT->isWideCharType())
449 else
451
452 // If we know the target array length, we can use it as a field width.
453 if (const ConstantArrayType *CAT = Ctx.getAsConstantArrayType(RawQT)) {
454 if (CAT->getSizeModifier() == ArraySizeModifier::Normal)
456 CAT->getZExtSize() - 1, "", 0, false);
457 }
458 return true;
459 }
460
461 // Figure out the length modifier.
462 switch (BT->getKind()) {
463 // no modifier
464 case BuiltinType::UInt:
465 case BuiltinType::Int:
466 case BuiltinType::Float:
468 break;
469
470 // hh
471 case BuiltinType::Char_U:
472 case BuiltinType::UChar:
473 case BuiltinType::Char_S:
474 case BuiltinType::SChar:
476 break;
477
478 // h
479 case BuiltinType::Short:
480 case BuiltinType::UShort:
482 break;
483
484 // l
485 case BuiltinType::Long:
486 case BuiltinType::ULong:
487 case BuiltinType::Double:
489 break;
490
491 // ll
492 case BuiltinType::LongLong:
493 case BuiltinType::ULongLong:
495 break;
496
497 // L
498 case BuiltinType::LongDouble:
500 break;
501
502 // Don't know.
503 default:
504 return false;
505 }
506
507 // Handle size_t, ptrdiff_t, etc. that have dedicated length modifiers in C99.
508 if (LangOpt.C99 || LangOpt.CPlusPlus11)
510
511 // If fixing the length modifier was enough, we are done.
512 if (hasValidLengthModifier(Ctx.getTargetInfo(), LangOpt)) {
513 const analyze_scanf::ArgType &AT = getArgType(Ctx);
514 if (AT.isValid() && AT.matchesType(Ctx, QT))
515 return true;
516 }
517
518 // Figure out the conversion specifier.
519 if (PT->isRealFloatingType())
520 CS.setKind(ConversionSpecifier::fArg);
521 else if (PT->isSignedIntegerType())
522 CS.setKind(ConversionSpecifier::dArg);
523 else if (PT->isUnsignedIntegerType())
524 CS.setKind(ConversionSpecifier::uArg);
525 else
526 llvm_unreachable("Unexpected type");
527
528 return true;
529}
530
531void ScanfSpecifier::toString(raw_ostream &os) const {
532 os << "%";
533
534 if (usesPositionalArg())
535 os << getPositionalArgIndex() << "$";
536 if (SuppressAssignment)
537 os << "*";
538
540 os << LM.toString();
541 os << CS.toString();
542}
543
545 const char *I,
546 const char *E,
547 const LangOptions &LO,
548 const TargetInfo &Target) {
549
550 unsigned argIndex = 0;
551
552 // Keep looking for a format specifier until we have exhausted the string.
553 while (I != E) {
554 const ScanfSpecifierResult &FSR = ParseScanfSpecifier(H, I, E, argIndex,
555 LO, Target);
556 // Did a fail-stop error of any kind occur when parsing the specifier?
557 // If so, don't do any more processing.
558 if (FSR.shouldStop())
559 return true;
560 // Did we exhaust the string or encounter an error that
561 // we can recover from?
562 if (!FSR.hasValue())
563 continue;
564 // We have a format specifier. Pass it to the callback.
565 if (!H.HandleScanfSpecifier(FSR.getValue(), FSR.getStart(),
566 I - FSR.getStart())) {
567 return true;
568 }
569 }
570 assert(I == E && "Format string not exhausted");
571 return false;
572}
Expr * E
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
__device__ __2f16 float c
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:188
const ConstantArrayType * getAsConstantArrayType(QualType T) const
Definition: ASTContext.h:3056
CanQualType LongTy
Definition: ASTContext.h:1231
QualType getUnsignedPointerDiffType() const
Return the unique unsigned counterpart of "ptrdiff_t" integer type.
CanQualType FloatTy
Definition: ASTContext.h:1234
CanQualType DoubleTy
Definition: ASTContext.h:1234
CanQualType getIntMaxType() const
Return the unique type for "intmax_t" (C99 7.18.1.5), defined in <stdint.h>.
CanQualType LongDoubleTy
Definition: ASTContext.h:1234
QualType getPointerDiffType() const
Return the unique type for "ptrdiff_t" (C99 7.17) defined in <stddef.h>.
CanQualType UnsignedLongTy
Definition: ASTContext.h:1232
CanQualType IntTy
Definition: ASTContext.h:1231
CanQualType SignedCharTy
Definition: ASTContext.h:1231
CanQualType UnsignedCharTy
Definition: ASTContext.h:1232
CanQualType UnsignedIntTy
Definition: ASTContext.h:1232
CanQualType UnsignedLongLongTy
Definition: ASTContext.h:1233
CanQualType UnsignedShortTy
Definition: ASTContext.h:1232
CanQualType ShortTy
Definition: ASTContext.h:1231
QualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:859
QualType getSignedSizeType() const
Return the unique signed counterpart of the integer type corresponding to size_t.
CanQualType LongLongTy
Definition: ASTContext.h:1231
QualType getWideCharType() const
Return the type of wide characters.
Definition: ASTContext.h:2060
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:3182
Kind getKind() const
Definition: TypeBase.h:3230
Represents the canonical version of C arrays with a specified constant size.
Definition: TypeBase.h:3776
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:434
A (possibly-)qualified type.
Definition: TypeBase.h:937
Exposes information about the current target.
Definition: TargetInfo.h:226
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
Definition: TargetInfo.h:1288
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char,...
Definition: Type.cpp:2209
bool isPointerType() const
Definition: TypeBase.h:8580
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition: Type.cpp:752
bool isAnyCharacterType() const
Determine whether this type is any of the built-in character types.
Definition: Type.cpp:2172
EnumDecl * getAsEnumDecl() const
Retrieves the EnumDecl this type refers to.
Definition: Type.h:53
bool isRealFloatingType() const
Floating point categories.
Definition: Type.cpp:2324
bool isWideCharType() const
Definition: Type.cpp:2145
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:2257
const T * getAs() const
Member-template getAs<specific type>'.
Definition: TypeBase.h:9159
static ArgType makePtrdiffT(const ArgType &A)
Create an ArgType which corresponds to the ptrdiff_t/unsigned ptrdiff_t type.
Definition: FormatString.h:334
static ArgType PtrTo(const ArgType &A)
Create an ArgType which corresponds to the type pointer to A.
Definition: FormatString.h:318
static ArgType makeSizeT(const ArgType &A)
Create an ArgType which corresponds to the size_t/ssize_t type.
Definition: FormatString.h:326
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...
bool hasValidLengthModifier(const TargetInfo &Target, const LangOptions &LO) const
virtual void HandleIncompleteScanList(const char *start, const char *end)
Definition: FormatString.h:778
virtual void HandleNullChar(const char *nullCharacter)
Definition: FormatString.h:723
virtual void HandleIncompleteSpecifier(const char *startSpecifier, unsigned specifierLen)
Definition: FormatString.h:732
virtual bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS, const char *startSpecifier, unsigned specifierLen)
Definition: FormatString.h:772
virtual bool HandleInvalidScanfConversionSpecifier(const analyze_scanf::ScanfSpecifier &FS, const char *startSpecifier, unsigned specifierLen)
Definition: FormatString.h:765
Represents the length modifier in a format string in scanf/printf.
Definition: FormatString.h:65
bool fixType(QualType QT, QualType RawQT, const LangOptions &LangOpt, ASTContext &Ctx)
void toString(raw_ostream &os) const
const ScanfConversionSpecifier & getConversionSpecifier() const
Definition: FormatString.h:691
ArgType getArgType(ASTContext &Ctx) const
Defines the clang::TargetInfo interface.
Common components of both fprintf and fscanf format strings.
Definition: FormatString.h:30
OptionalAmount ParseAmount(const char *&Beg, const char *E)
bool ParseScanfString(FormatStringHandler &H, const char *beg, const char *end, const LangOptions &LO, const TargetInfo &Target)
Pieces specific to fscanf format strings.
Definition: FormatString.h:651
The JSON file list parser is used to communicate input to InstallAPI.