1// FormatString.cpp - Common stuff for handling printf/scanf formats -*- 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// Shared details for processing format strings of printf and scanf
10// (and friends).
11//
12//===----------------------------------------------------------------------===//
13
14#include "FormatStringParsing.h"
15#include "clang/Basic/LangOptions.h"
16#include "clang/Basic/TargetInfo.h"
17#include "llvm/Support/ConvertUTF.h"
18#include <optional>
19
20using clang::analyze_format_string::ArgType;
21using clang::analyze_format_string::FormatStringHandler;
22using clang::analyze_format_string::FormatSpecifier;
23using clang::analyze_format_string::LengthModifier;
24using clang::analyze_format_string::OptionalAmount;
25using clang::analyze_format_string::ConversionSpecifier;
26using namespace clang;
27
28// Key function to FormatStringHandler.
29FormatStringHandler::~FormatStringHandler() {}
30
31//===----------------------------------------------------------------------===//
32// Functions for parsing format strings components in both printf and
33// scanf format strings.
34//===----------------------------------------------------------------------===//
35
36OptionalAmount
37clang::analyze_format_string::ParseAmount(const char *&Beg, const char *E) {
38 const char *I = Beg;
39 UpdateOnReturn <const char*> UpdateBeg(Beg, I);
40
41 unsigned accumulator = 0;
42 bool hasDigits = false;
43
44 for ( ; I != E; ++I) {
45 char c = *I;
46 if (c >= '0' && c <= '9') {
47 hasDigits = true;
48 accumulator = (accumulator * 10) + (c - '0');
49 continue;
50 }
51
52 if (hasDigits)
53 return OptionalAmount(OptionalAmount::Constant, accumulator, Beg, I - Beg,
54 false);
55
56 break;
57 }
58
59 return OptionalAmount();
60}
61
62OptionalAmount
63clang::analyze_format_string::ParseNonPositionAmount(const char *&Beg,
64 const char *E,
65 unsigned &argIndex) {
66 if (*Beg == '*') {
67 ++Beg;
68 return OptionalAmount(OptionalAmount::Arg, argIndex++, Beg, 0, false);
69 }
70
71 return ParseAmount(Beg, E);
72}
73
74OptionalAmount
75clang::analyze_format_string::ParsePositionAmount(FormatStringHandler &H,
76 const char *Start,
77 const char *&Beg,
78 const char *E,
79 PositionContext p) {
80 if (*Beg == '*') {
81 const char *I = Beg + 1;
82 const OptionalAmount &Amt = ParseAmount(Beg&: I, E);
83
84 if (Amt.getHowSpecified() == OptionalAmount::NotSpecified) {
85 H.HandleInvalidPosition(startPos: Beg, posLen: I - Beg, p);
86 return OptionalAmount(false);
87 }
88
89 if (I == E) {
90 // No more characters left?
91 H.HandleIncompleteSpecifier(startSpecifier: Start, specifierLen: E - Start);
92 return OptionalAmount(false);
93 }
94
95 assert(Amt.getHowSpecified() == OptionalAmount::Constant);
96
97 if (*I == '$') {
98 // Handle positional arguments
99
100 // Special case: '*0$', since this is an easy mistake.
101 if (Amt.getConstantAmount() == 0) {
102 H.HandleZeroPosition(startPos: Beg, posLen: I - Beg + 1);
103 return OptionalAmount(false);
104 }
105
106 const char *Tmp = Beg;
107 Beg = ++I;
108
109 return OptionalAmount(OptionalAmount::Arg, Amt.getConstantAmount() - 1,
110 Tmp, 0, true);
111 }
112
113 H.HandleInvalidPosition(startPos: Beg, posLen: I - Beg, p);
114 return OptionalAmount(false);
115 }
116
117 return ParseAmount(Beg, E);
118}
119
120
121bool
122clang::analyze_format_string::ParseFieldWidth(FormatStringHandler &H,
123 FormatSpecifier &CS,
124 const char *Start,
125 const char *&Beg, const char *E,
126 unsigned *argIndex) {
127 // FIXME: Support negative field widths.
128 if (argIndex) {
129 CS.setFieldWidth(ParseNonPositionAmount(Beg, E, argIndex&: *argIndex));
130 }
131 else {
132 const OptionalAmount Amt =
133 ParsePositionAmount(H, Start, Beg, E,
134 p: analyze_format_string::FieldWidthPos);
135
136 if (Amt.isInvalid())
137 return true;
138 CS.setFieldWidth(Amt);
139 }
140 return false;
141}
142
143bool
144clang::analyze_format_string::ParseArgPosition(FormatStringHandler &H,
145 FormatSpecifier &FS,
146 const char *Start,
147 const char *&Beg,
148 const char *E) {
149 const char *I = Beg;
150
151 const OptionalAmount &Amt = ParseAmount(Beg&: I, E);
152
153 if (I == E) {
154 // No more characters left?
155 H.HandleIncompleteSpecifier(startSpecifier: Start, specifierLen: E - Start);
156 return true;
157 }
158
159 if (Amt.getHowSpecified() == OptionalAmount::Constant && *(I++) == '$') {
160 // Warn that positional arguments are non-standard.
161 H.HandlePosition(startPos: Start, posLen: I - Start);
162
163 // Special case: '%0$', since this is an easy mistake.
164 if (Amt.getConstantAmount() == 0) {
165 H.HandleZeroPosition(startPos: Start, posLen: I - Start);
166 return true;
167 }
168
169 FS.setArgIndex(Amt.getConstantAmount() - 1);
170 FS.setUsesPositionalArg();
171 // Update the caller's pointer if we decided to consume
172 // these characters.
173 Beg = I;
174 return false;
175 }
176
177 return false;
178}
179
180bool
181clang::analyze_format_string::ParseVectorModifier(FormatStringHandler &H,
182 FormatSpecifier &FS,
183 const char *&I,
184 const char *E,
185 const LangOptions &LO) {
186 if (!LO.OpenCL)
187 return false;
188
189 const char *Start = I;
190 if (*I == 'v') {
191 ++I;
192
193 if (I == E) {
194 H.HandleIncompleteSpecifier(startSpecifier: Start, specifierLen: E - Start);
195 return true;
196 }
197
198 OptionalAmount NumElts = ParseAmount(Beg&: I, E);
199 if (NumElts.getHowSpecified() != OptionalAmount::Constant) {
200 H.HandleIncompleteSpecifier(startSpecifier: Start, specifierLen: E - Start);
201 return true;
202 }
203
204 FS.setVectorNumElts(NumElts);
205 }
206
207 return false;
208}
209
210bool
211clang::analyze_format_string::ParseLengthModifier(FormatSpecifier &FS,
212 const char *&I,
213 const char *E,
214 const LangOptions &LO,
215 bool IsScanf) {
216 LengthModifier::Kind lmKind = LengthModifier::None;
217 const char *lmPosition = I;
218 switch (*I) {
219 default:
220 return false;
221 case 'h':
222 ++I;
223 if (I != E && *I == 'h') {
224 ++I;
225 lmKind = LengthModifier::AsChar;
226 } else if (I != E && *I == 'l' && LO.OpenCL) {
227 ++I;
228 lmKind = LengthModifier::AsShortLong;
229 } else {
230 lmKind = LengthModifier::AsShort;
231 }
232 break;
233 case 'l':
234 ++I;
235 if (I != E && *I == 'l') {
236 ++I;
237 lmKind = LengthModifier::AsLongLong;
238 } else {
239 lmKind = LengthModifier::AsLong;
240 }
241 break;
242 case 'j': lmKind = LengthModifier::AsIntMax; ++I; break;
243 case 'z': lmKind = LengthModifier::AsSizeT; ++I; break;
244 case 't': lmKind = LengthModifier::AsPtrDiff; ++I; break;
245 case 'L': lmKind = LengthModifier::AsLongDouble; ++I; break;
246 case 'q': lmKind = LengthModifier::AsQuad; ++I; break;
247 case 'a':
248 if (IsScanf && !LO.C99 && !LO.CPlusPlus11) {
249 // For scanf in C90, look at the next character to see if this should
250 // be parsed as the GNU extension 'a' length modifier. If not, this
251 // will be parsed as a conversion specifier.
252 ++I;
253 if (I != E && (*I == 's' || *I == 'S' || *I == '[')) {
254 lmKind = LengthModifier::AsAllocate;
255 break;
256 }
257 --I;
258 }
259 return false;
260 case 'm':
261 if (IsScanf) {
262 lmKind = LengthModifier::AsMAllocate;
263 ++I;
264 break;
265 }
266 return false;
267 // printf: AsInt64, AsInt32, AsInt3264
268 // scanf: AsInt64
269 case 'I':
270 if (I + 1 != E && I + 2 != E) {
271 if (I[1] == '6' && I[2] == '4') {
272 I += 3;
273 lmKind = LengthModifier::AsInt64;
274 break;
275 }
276 if (IsScanf)
277 return false;
278
279 if (I[1] == '3' && I[2] == '2') {
280 I += 3;
281 lmKind = LengthModifier::AsInt32;
282 break;
283 }
284 }
285 ++I;
286 lmKind = LengthModifier::AsInt3264;
287 break;
288 case 'w':
289 lmKind = LengthModifier::AsWide; ++I; break;
290 }
291 LengthModifier lm(lmPosition, lmKind);
292 FS.setLengthModifier(lm);
293 return true;
294}
295
296bool clang::analyze_format_string::ParseUTF8InvalidSpecifier(
297 const char *SpecifierBegin, const char *FmtStrEnd, unsigned &Len) {
298 if (SpecifierBegin + 1 >= FmtStrEnd)
299 return false;
300
301 const llvm::UTF8 *SB =
302 reinterpret_cast<const llvm::UTF8 *>(SpecifierBegin + 1);
303 const llvm::UTF8 *SE = reinterpret_cast<const llvm::UTF8 *>(FmtStrEnd);
304 const char FirstByte = *SB;
305
306 // If the invalid specifier is a multibyte UTF-8 string, return the
307 // total length accordingly so that the conversion specifier can be
308 // properly updated to reflect a complete UTF-8 specifier.
309 unsigned NumBytes = llvm::getNumBytesForUTF8(firstByte: FirstByte);
310 if (NumBytes == 1)
311 return false;
312 if (SB + NumBytes > SE)
313 return false;
314
315 Len = NumBytes + 1;
316 return true;
317}
318
319//===----------------------------------------------------------------------===//
320// Methods on ArgType.
321//===----------------------------------------------------------------------===//
322
323static bool namedTypeToLengthModifierKind(ASTContext &Ctx, QualType QT,
324 LengthModifier::Kind &K) {
325 if (!Ctx.getLangOpts().C99 && !Ctx.getLangOpts().CPlusPlus)
326 return false;
327 for (/**/; const auto *TT = QT->getAs<TypedefType>(); QT = TT->desugar()) {
328 const auto *TD = TT->getDecl();
329 const auto *DC = TT->getDecl()->getDeclContext();
330 if (DC->isTranslationUnit() || DC->isStdNamespace()) {
331 StringRef Name = TD->getIdentifier()->getName();
332 if (Name == "size_t") {
333 K = LengthModifier::AsSizeT;
334 return true;
335 } else if (Name == "ssize_t" /*Not C99, but common in Unix.*/) {
336 K = LengthModifier::AsSizeT;
337 return true;
338 } else if (Name == "ptrdiff_t") {
339 K = LengthModifier::AsPtrDiff;
340 return true;
341 } else if (Name == "intmax_t") {
342 K = LengthModifier::AsIntMax;
343 return true;
344 } else if (Name == "uintmax_t") {
345 K = LengthModifier::AsIntMax;
346 return true;
347 }
348 }
349 }
350 if (const auto *PST = QT->getAs<PredefinedSugarType>()) {
351 using Kind = PredefinedSugarType::Kind;
352 switch (PST->getKind()) {
353 case Kind::SizeT:
354 case Kind::SignedSizeT:
355 K = LengthModifier::AsSizeT;
356 return true;
357 case Kind::PtrdiffT:
358 K = LengthModifier::AsPtrDiff;
359 return true;
360 }
361 llvm_unreachable("unexpected kind");
362 }
363 return false;
364}
365
366// Check whether T and E are compatible size_t/ptrdiff_t types. E must be
367// consistent with LE.
368// T is the type of the actual expression in the code to be checked, and E is
369// the expected type parsed from the format string.
370static clang::analyze_format_string::ArgType::MatchKind
371matchesSizeTPtrdiffT(ASTContext &C, QualType T, QualType E) {
372 using MatchKind = clang::analyze_format_string::ArgType::MatchKind;
373
374 if (!T->isIntegerType() || T->isBooleanType())
375 return MatchKind::NoMatch;
376
377 if (C.hasSameType(T1: T, T2: E))
378 return MatchKind::Match;
379
380 if (C.getCorrespondingSignedType(T: T.getCanonicalType()) !=
381 C.getCorrespondingSignedType(T: E.getCanonicalType()))
382 return MatchKind::NoMatch;
383
384 return MatchKind::NoMatchSignedness;
385}
386
387clang::analyze_format_string::ArgType::MatchKind
388ArgType::matchesType(ASTContext &C, QualType argTy) const {
389 // When using the format attribute in C++, you can receive a function or an
390 // array that will necessarily decay to a pointer when passed to the final
391 // format consumer. Apply decay before type comparison.
392 if (argTy->canDecayToPointerType())
393 argTy = C.getDecayedType(T: argTy);
394
395 if (Ptr) {
396 // It has to be a pointer.
397 const PointerType *PT = argTy->getAs<PointerType>();
398 if (!PT)
399 return NoMatch;
400
401 // We cannot write through a const qualified pointer.
402 if (PT->getPointeeType().isConstQualified())
403 return NoMatch;
404
405 argTy = PT->getPointeeType();
406 }
407
408 if (const auto *OBT = argTy->getAs<OverflowBehaviorType>())
409 argTy = OBT->getUnderlyingType();
410
411 switch (K) {
412 case InvalidTy:
413 llvm_unreachable("ArgType must be valid");
414
415 case UnknownTy:
416 return Match;
417
418 case AnyCharTy: {
419 if (const auto *ED = argTy->getAsEnumDecl()) {
420 // If the enum is incomplete we know nothing about the underlying type.
421 // Assume that it's 'int'. Do not use the underlying type for a scoped
422 // enumeration.
423 if (!ED->isComplete())
424 return NoMatch;
425 if (!ED->isScoped())
426 argTy = ED->getIntegerType();
427 }
428
429 if (const auto *BT = argTy->getAs<BuiltinType>()) {
430 // The types are perfectly matched?
431 switch (BT->getKind()) {
432 default:
433 break;
434 case BuiltinType::Char_S:
435 case BuiltinType::SChar:
436 case BuiltinType::UChar:
437 case BuiltinType::Char_U:
438 return Match;
439 case BuiltinType::Bool:
440 if (!Ptr)
441 return Match;
442 break;
443 }
444 // "Partially matched" because of promotions?
445 if (!Ptr) {
446 switch (BT->getKind()) {
447 default:
448 break;
449 case BuiltinType::Int:
450 case BuiltinType::UInt:
451 return MatchPromotion;
452 case BuiltinType::Short:
453 case BuiltinType::UShort:
454 case BuiltinType::WChar_S:
455 case BuiltinType::WChar_U:
456 return NoMatchPromotionTypeConfusion;
457 }
458 }
459 }
460 return NoMatch;
461 }
462
463 case SpecificTy: {
464 if (TK != TypeKind::DontCare) {
465 return matchesSizeTPtrdiffT(C, T: argTy, E: T);
466 }
467
468 if (const auto *ED = argTy->getAsEnumDecl()) {
469 // If the enum is incomplete we know nothing about the underlying type.
470 // Assume that it's 'int'. Do not use the underlying type for a scoped
471 // enumeration as that needs an exact match.
472 if (!ED->isComplete())
473 argTy = C.IntTy;
474 else if (!ED->isScoped())
475 argTy = ED->getIntegerType();
476 }
477
478 if (argTy->isSaturatedFixedPointType())
479 argTy = C.getCorrespondingUnsaturatedType(Ty: argTy);
480
481 argTy = C.getCanonicalType(T: argTy).getUnqualifiedType();
482
483 if (T == argTy)
484 return Match;
485 if (const auto *BT = argTy->getAs<BuiltinType>()) {
486 // Check if the only difference between them is signed vs unsigned
487 // if true, return match signedness.
488 switch (BT->getKind()) {
489 default:
490 break;
491 case BuiltinType::Bool:
492 if (Ptr && (T == C.UnsignedCharTy || T == C.SignedCharTy))
493 return NoMatch;
494 [[fallthrough]];
495 case BuiltinType::Char_S:
496 case BuiltinType::SChar:
497 if (T == C.UnsignedShortTy || T == C.ShortTy)
498 return NoMatchTypeConfusion;
499 if (T == C.UnsignedCharTy)
500 return NoMatchSignedness;
501 if (T == C.SignedCharTy)
502 return Match;
503 break;
504 case BuiltinType::Char_U:
505 case BuiltinType::UChar:
506 if (T == C.UnsignedShortTy || T == C.ShortTy)
507 return NoMatchTypeConfusion;
508 if (T == C.UnsignedCharTy)
509 return Match;
510 if (T == C.SignedCharTy)
511 return NoMatchSignedness;
512 break;
513 case BuiltinType::Short:
514 if (T == C.UnsignedShortTy)
515 return NoMatchSignedness;
516 break;
517 case BuiltinType::UShort:
518 if (T == C.ShortTy)
519 return NoMatchSignedness;
520 break;
521 case BuiltinType::Int:
522 if (T == C.UnsignedIntTy)
523 return NoMatchSignedness;
524 break;
525 case BuiltinType::UInt:
526 if (T == C.IntTy)
527 return NoMatchSignedness;
528 break;
529 case BuiltinType::Long:
530 if (T == C.UnsignedLongTy)
531 return NoMatchSignedness;
532 break;
533 case BuiltinType::ULong:
534 if (T == C.LongTy)
535 return NoMatchSignedness;
536 break;
537 case BuiltinType::LongLong:
538 if (T == C.UnsignedLongLongTy)
539 return NoMatchSignedness;
540 break;
541 case BuiltinType::ULongLong:
542 if (T == C.LongLongTy)
543 return NoMatchSignedness;
544 break;
545 }
546 // "Partially matched" because of promotions?
547 if (!Ptr) {
548 switch (BT->getKind()) {
549 default:
550 break;
551 case BuiltinType::Bool:
552 if (T == C.IntTy || T == C.UnsignedIntTy)
553 return MatchPromotion;
554 break;
555 case BuiltinType::Int:
556 case BuiltinType::UInt:
557 if (T == C.SignedCharTy || T == C.UnsignedCharTy ||
558 T == C.ShortTy || T == C.UnsignedShortTy || T == C.WCharTy ||
559 T == C.WideCharTy)
560 return MatchPromotion;
561 break;
562 case BuiltinType::Char_U:
563 if (T == C.UnsignedIntTy)
564 return MatchPromotion;
565 if (T == C.UnsignedShortTy)
566 return NoMatchPromotionTypeConfusion;
567 break;
568 case BuiltinType::Char_S:
569 if (T == C.IntTy)
570 return MatchPromotion;
571 if (T == C.ShortTy)
572 return NoMatchPromotionTypeConfusion;
573 break;
574 case BuiltinType::Half:
575 case BuiltinType::Float:
576 if (T == C.DoubleTy)
577 return MatchPromotion;
578 break;
579 case BuiltinType::Short:
580 case BuiltinType::UShort:
581 if (T == C.SignedCharTy || T == C.UnsignedCharTy)
582 return NoMatchPromotionTypeConfusion;
583 break;
584 case BuiltinType::WChar_U:
585 case BuiltinType::WChar_S:
586 if (T != C.WCharTy && T != C.WideCharTy)
587 return NoMatchPromotionTypeConfusion;
588 }
589 }
590 }
591 return NoMatch;
592 }
593
594 case CStrTy:
595 if (const auto *PT = argTy->getAs<PointerType>();
596 PT && PT->getPointeeType()->isCharType())
597 return Match;
598 return NoMatch;
599
600 case WCStrTy:
601 if (const auto *PT = argTy->getAs<PointerType>();
602 PT &&
603 C.hasSameUnqualifiedType(T1: PT->getPointeeType(), T2: C.getWideCharType()))
604 return Match;
605 return NoMatch;
606
607 case WIntTy: {
608 QualType WInt = C.getCanonicalType(T: C.getWIntType()).getUnqualifiedType();
609
610 if (C.getCanonicalType(T: argTy).getUnqualifiedType() == WInt)
611 return Match;
612
613 QualType PromoArg = C.isPromotableIntegerType(T: argTy)
614 ? C.getPromotedIntegerType(PromotableType: argTy)
615 : argTy;
616 PromoArg = C.getCanonicalType(T: PromoArg).getUnqualifiedType();
617
618 // If the promoted argument is the corresponding signed type of the
619 // wint_t type, then it should match.
620 if (PromoArg->hasSignedIntegerRepresentation() &&
621 C.getCorrespondingUnsignedType(T: PromoArg) == WInt)
622 return Match;
623
624 return WInt == PromoArg ? Match : NoMatch;
625 }
626
627 case CPointerTy:
628 if (const auto *PT = argTy->getAs<PointerType>()) {
629 QualType PointeeTy = PT->getPointeeType();
630 if (PointeeTy->isVoidType() || (!Ptr && PointeeTy->isCharType()))
631 return Match;
632 return NoMatchPedantic;
633 }
634
635 // nullptr_t* is not a double pointer, so reject when something like
636 // void** is expected.
637 // In C++, nullptr is promoted to void*. In C23, va_arg(ap, void*) is not
638 // undefined when the next argument is of type nullptr_t.
639 if (!Ptr && argTy->isNullPtrType())
640 return C.getLangOpts().CPlusPlus ? MatchPromotion : Match;
641
642 if (argTy->isObjCObjectPointerType() || argTy->isBlockPointerType())
643 return NoMatchPedantic;
644
645 return NoMatch;
646
647 case ObjCPointerTy: {
648 if (argTy->getAs<ObjCObjectPointerType>() ||
649 argTy->getAs<BlockPointerType>())
650 return Match;
651
652 // Handle implicit toll-free bridging.
653 if (const PointerType *PT = argTy->getAs<PointerType>()) {
654 // Things such as CFTypeRef are really just opaque pointers
655 // to C structs representing CF types that can often be bridged
656 // to Objective-C objects. Since the compiler doesn't know which
657 // structs can be toll-free bridged, we just accept them all.
658 QualType pointee = PT->getPointeeType();
659 if (pointee->isStructureType() || pointee->isVoidType())
660 return Match;
661 }
662 return NoMatch;
663 }
664 }
665
666 llvm_unreachable("Invalid ArgType Kind!");
667}
668
669static analyze_format_string::ArgType::MatchKind
670integerTypeMatch(ASTContext &C, QualType A, QualType B, bool CheckSign) {
671 using MK = analyze_format_string::ArgType::MatchKind;
672
673 uint64_t IntSize = C.getTypeSize(T: C.IntTy);
674 uint64_t ASize = C.getTypeSize(T: A);
675 uint64_t BSize = C.getTypeSize(T: B);
676 if (std::max(a: ASize, b: IntSize) != std::max(a: BSize, b: IntSize))
677 return MK::NoMatch;
678 if (CheckSign && A->isSignedIntegerType() != B->isSignedIntegerType())
679 return MK::NoMatchSignedness;
680 if (ASize != BSize)
681 return MK::MatchPromotion;
682 return MK::Match;
683}
684
685analyze_format_string::ArgType::MatchKind
686ArgType::matchesArgType(ASTContext &C, const ArgType &Other) const {
687 using AK = analyze_format_string::ArgType::Kind;
688
689 // Per matchesType.
690 if (K == AK::InvalidTy || Other.K == AK::InvalidTy)
691 return NoMatch;
692 if (K == AK::UnknownTy || Other.K == AK::UnknownTy)
693 return Match;
694
695 // Handle whether either (or both, or neither) sides has Ptr set,
696 // in addition to whether either (or both, or neither) sides is a SpecificTy
697 // that is a pointer.
698 ArgType Left = *this;
699 bool LeftWasPointer = false;
700 ArgType Right = Other;
701 bool RightWasPointer = false;
702 if (Left.Ptr) {
703 Left.Ptr = false;
704 LeftWasPointer = true;
705 } else if (Left.K == AK::SpecificTy && Left.T->isPointerType()) {
706 Left.T = Left.T->getPointeeType();
707 LeftWasPointer = true;
708 }
709 if (Right.Ptr) {
710 Right.Ptr = false;
711 RightWasPointer = true;
712 } else if (Right.K == AK::SpecificTy && Right.T->isPointerType()) {
713 Right.T = Right.T->getPointeeType();
714 RightWasPointer = true;
715 }
716
717 if (LeftWasPointer != RightWasPointer)
718 return NoMatch;
719
720 // Ensure that if at least one side is a SpecificTy, then Left is a
721 // SpecificTy.
722 if (Right.K == AK::SpecificTy)
723 std::swap(a&: Left, b&: Right);
724
725 if (Left.K == AK::SpecificTy) {
726 if (Right.K == AK::SpecificTy) {
727 if (Left.TK != TypeKind::DontCare) {
728 return matchesSizeTPtrdiffT(C, T: Right.T, E: Left.T);
729 } else if (Right.TK != TypeKind::DontCare) {
730 return matchesSizeTPtrdiffT(C, T: Left.T, E: Right.T);
731 }
732
733 auto Canon1 = C.getCanonicalType(T: Left.T);
734 auto Canon2 = C.getCanonicalType(T: Right.T);
735 if (Canon1 == Canon2)
736 return Match;
737
738 auto *BT1 = QualType(Canon1)->getAs<BuiltinType>();
739 auto *BT2 = QualType(Canon2)->getAs<BuiltinType>();
740 if (BT1 == nullptr || BT2 == nullptr)
741 return NoMatch;
742 if (BT1 == BT2)
743 return Match;
744
745 if (!LeftWasPointer && BT1->isInteger() && BT2->isInteger())
746 return integerTypeMatch(C, A: Canon1, B: Canon2, CheckSign: true);
747 return NoMatch;
748 } else if (Right.K == AK::AnyCharTy) {
749 if (!LeftWasPointer && Left.T->isIntegerType())
750 return integerTypeMatch(C, A: Left.T, B: C.CharTy, CheckSign: false);
751 return NoMatch;
752 } else if (Right.K == AK::WIntTy) {
753 if (!LeftWasPointer && Left.T->isIntegerType())
754 return integerTypeMatch(C, A: Left.T, B: C.WIntTy, CheckSign: true);
755 return NoMatch;
756 }
757 // It's hypothetically possible to create an AK::SpecificTy ArgType
758 // that matches another kind of ArgType, but in practice Clang doesn't
759 // do that, so ignore that case.
760 return NoMatch;
761 }
762
763 return Left.K == Right.K ? Match : NoMatch;
764}
765
766ArgType ArgType::makeVectorType(ASTContext &C, unsigned NumElts) const {
767 // Check for valid vector element types.
768 if (T.isNull())
769 return ArgType::Invalid();
770
771 QualType Vec = C.getExtVectorType(VectorType: T, NumElts);
772 return ArgType(Vec, Name);
773}
774
775QualType ArgType::getRepresentativeType(ASTContext &C) const {
776 QualType Res;
777 switch (K) {
778 case InvalidTy:
779 llvm_unreachable("No representative type for Invalid ArgType");
780 case UnknownTy:
781 llvm_unreachable("No representative type for Unknown ArgType");
782 case AnyCharTy:
783 Res = C.CharTy;
784 break;
785 case SpecificTy:
786 if (TK == TypeKind::PtrdiffT || TK == TypeKind::SizeT)
787 // Using Name as name, so no need to show the uglified name.
788 Res = T->getCanonicalTypeInternal();
789 else
790 Res = T;
791 break;
792 case CStrTy:
793 Res = C.getPointerType(T: C.CharTy);
794 break;
795 case WCStrTy:
796 Res = C.getPointerType(T: C.getWideCharType());
797 break;
798 case ObjCPointerTy:
799 Res = C.ObjCBuiltinIdTy;
800 break;
801 case CPointerTy:
802 Res = C.VoidPtrTy;
803 break;
804 case WIntTy: {
805 Res = C.getWIntType();
806 break;
807 }
808 }
809
810 if (Ptr)
811 Res = C.getPointerType(T: Res);
812 return Res;
813}
814
815std::string ArgType::getRepresentativeTypeName(ASTContext &C) const {
816 std::string S = getRepresentativeType(C).getAsString(Policy: C.getPrintingPolicy());
817 std::string Alias;
818 if (Name) {
819 // Use a specific name for this type, e.g. "size_t".
820 Alias = Name;
821 if (Ptr) {
822 // If ArgType is actually a pointer to T, append an asterisk.
823 Alias += (Alias[Alias.size()-1] == '*') ? "*" : " *";
824 }
825 // If Alias is the same as the underlying type, e.g. wchar_t, then drop it.
826 if (S == Alias)
827 Alias.clear();
828 }
829
830 if (!Alias.empty())
831 return std::string("'") + Alias + "' (aka '" + S + "')";
832 return std::string("'") + S + "'";
833}
834
835
836//===----------------------------------------------------------------------===//
837// Methods on OptionalAmount.
838//===----------------------------------------------------------------------===//
839
840ArgType
841analyze_format_string::OptionalAmount::getArgType(ASTContext &Ctx) const {
842 return Ctx.IntTy;
843}
844
845//===----------------------------------------------------------------------===//
846// Methods on LengthModifier.
847//===----------------------------------------------------------------------===//
848
849const char *
850analyze_format_string::LengthModifier::toString() const {
851 switch (kind) {
852 case AsChar:
853 return "hh";
854 case AsShort:
855 return "h";
856 case AsShortLong:
857 return "hl";
858 case AsLong: // or AsWideChar
859 return "l";
860 case AsLongLong:
861 return "ll";
862 case AsQuad:
863 return "q";
864 case AsIntMax:
865 return "j";
866 case AsSizeT:
867 return "z";
868 case AsPtrDiff:
869 return "t";
870 case AsInt32:
871 return "I32";
872 case AsInt3264:
873 return "I";
874 case AsInt64:
875 return "I64";
876 case AsLongDouble:
877 return "L";
878 case AsAllocate:
879 return "a";
880 case AsMAllocate:
881 return "m";
882 case AsWide:
883 return "w";
884 case None:
885 return "";
886 }
887 return nullptr;
888}
889
890//===----------------------------------------------------------------------===//
891// Methods on ConversionSpecifier.
892//===----------------------------------------------------------------------===//
893
894const char *ConversionSpecifier::toString() const {
895 switch (kind) {
896 case bArg: return "b";
897 case BArg: return "B";
898 case dArg: return "d";
899 case DArg: return "D";
900 case iArg: return "i";
901 case oArg: return "o";
902 case OArg: return "O";
903 case uArg: return "u";
904 case UArg: return "U";
905 case xArg: return "x";
906 case XArg: return "X";
907 case fArg: return "f";
908 case FArg: return "F";
909 case eArg: return "e";
910 case EArg: return "E";
911 case gArg: return "g";
912 case GArg: return "G";
913 case aArg: return "a";
914 case AArg: return "A";
915 case cArg: return "c";
916 case sArg: return "s";
917 case pArg: return "p";
918 case PArg:
919 return "P";
920 case nArg: return "n";
921 case PercentArg: return "%";
922 case ScanListArg: return "[";
923 case InvalidSpecifier: return nullptr;
924
925 // POSIX unicode extensions.
926 case CArg: return "C";
927 case SArg: return "S";
928
929 // Objective-C specific specifiers.
930 case ObjCObjArg: return "@";
931
932 // FreeBSD kernel specific specifiers.
933 case FreeBSDbArg: return "b";
934 case FreeBSDDArg: return "D";
935 case FreeBSDrArg: return "r";
936 case FreeBSDyArg: return "y";
937
938 // GlibC specific specifiers.
939 case PrintErrno: return "m";
940
941 // MS specific specifiers.
942 case ZArg: return "Z";
943
944 // ISO/IEC TR 18037 (fixed-point) specific specifiers.
945 case rArg:
946 return "r";
947 case RArg:
948 return "R";
949 case kArg:
950 return "k";
951 case KArg:
952 return "K";
953 }
954 return nullptr;
955}
956
957std::optional<ConversionSpecifier>
958ConversionSpecifier::getStandardSpecifier() const {
959 ConversionSpecifier::Kind NewKind;
960
961 switch (getKind()) {
962 default:
963 return std::nullopt;
964 case DArg:
965 NewKind = dArg;
966 break;
967 case UArg:
968 NewKind = uArg;
969 break;
970 case OArg:
971 NewKind = oArg;
972 break;
973 }
974
975 ConversionSpecifier FixedCS(*this);
976 FixedCS.setKind(NewKind);
977 return FixedCS;
978}
979
980//===----------------------------------------------------------------------===//
981// Methods on OptionalAmount.
982//===----------------------------------------------------------------------===//
983
984void OptionalAmount::toString(raw_ostream &os) const {
985 switch (hs) {
986 case Invalid:
987 case NotSpecified:
988 return;
989 case Arg:
990 if (UsesDotPrefix)
991 os << ".";
992 if (usesPositionalArg())
993 os << "*" << getPositionalArgIndex() << "$";
994 else
995 os << "*";
996 break;
997 case Constant:
998 if (UsesDotPrefix)
999 os << ".";
1000 os << amt;
1001 break;
1002 }
1003}
1004
1005bool FormatSpecifier::hasValidLengthModifier(const TargetInfo &Target,
1006 const LangOptions &LO) const {
1007 switch (LM.getKind()) {
1008 case LengthModifier::None:
1009 return true;
1010
1011 // Handle most integer flags
1012 case LengthModifier::AsShort:
1013 // Length modifier only applies to FP vectors.
1014 if (LO.OpenCL && CS.isDoubleArg())
1015 return !VectorNumElts.isInvalid();
1016
1017 if (CS.isFixedPointArg())
1018 return true;
1019
1020 if (Target.getTriple().isOSMSVCRT()) {
1021 switch (CS.getKind()) {
1022 case ConversionSpecifier::cArg:
1023 case ConversionSpecifier::CArg:
1024 case ConversionSpecifier::sArg:
1025 case ConversionSpecifier::SArg:
1026 case ConversionSpecifier::ZArg:
1027 return true;
1028 default:
1029 break;
1030 }
1031 }
1032 [[fallthrough]];
1033 case LengthModifier::AsChar:
1034 case LengthModifier::AsLongLong:
1035 case LengthModifier::AsQuad:
1036 case LengthModifier::AsIntMax:
1037 case LengthModifier::AsSizeT:
1038 case LengthModifier::AsPtrDiff:
1039 switch (CS.getKind()) {
1040 case ConversionSpecifier::bArg:
1041 case ConversionSpecifier::BArg:
1042 case ConversionSpecifier::dArg:
1043 case ConversionSpecifier::DArg:
1044 case ConversionSpecifier::iArg:
1045 case ConversionSpecifier::oArg:
1046 case ConversionSpecifier::OArg:
1047 case ConversionSpecifier::uArg:
1048 case ConversionSpecifier::UArg:
1049 case ConversionSpecifier::xArg:
1050 case ConversionSpecifier::XArg:
1051 case ConversionSpecifier::nArg:
1052 return true;
1053 case ConversionSpecifier::FreeBSDrArg:
1054 case ConversionSpecifier::FreeBSDyArg:
1055 return Target.getTriple().isOSFreeBSD() || Target.getTriple().isPS();
1056 default:
1057 return false;
1058 }
1059
1060 case LengthModifier::AsShortLong:
1061 return LO.OpenCL && !VectorNumElts.isInvalid();
1062
1063 // Handle 'l' flag
1064 case LengthModifier::AsLong: // or AsWideChar
1065 if (CS.isDoubleArg()) {
1066 // Invalid for OpenCL FP scalars.
1067 if (LO.OpenCL && VectorNumElts.isInvalid())
1068 return false;
1069 return true;
1070 }
1071
1072 if (CS.isFixedPointArg())
1073 return true;
1074
1075 switch (CS.getKind()) {
1076 case ConversionSpecifier::bArg:
1077 case ConversionSpecifier::BArg:
1078 case ConversionSpecifier::dArg:
1079 case ConversionSpecifier::DArg:
1080 case ConversionSpecifier::iArg:
1081 case ConversionSpecifier::oArg:
1082 case ConversionSpecifier::OArg:
1083 case ConversionSpecifier::uArg:
1084 case ConversionSpecifier::UArg:
1085 case ConversionSpecifier::xArg:
1086 case ConversionSpecifier::XArg:
1087 case ConversionSpecifier::nArg:
1088 case ConversionSpecifier::cArg:
1089 case ConversionSpecifier::sArg:
1090 case ConversionSpecifier::ScanListArg:
1091 case ConversionSpecifier::ZArg:
1092 return true;
1093 case ConversionSpecifier::FreeBSDrArg:
1094 case ConversionSpecifier::FreeBSDyArg:
1095 return Target.getTriple().isOSFreeBSD() || Target.getTriple().isPS();
1096 default:
1097 return false;
1098 }
1099
1100 case LengthModifier::AsLongDouble:
1101 switch (CS.getKind()) {
1102 case ConversionSpecifier::aArg:
1103 case ConversionSpecifier::AArg:
1104 case ConversionSpecifier::fArg:
1105 case ConversionSpecifier::FArg:
1106 case ConversionSpecifier::eArg:
1107 case ConversionSpecifier::EArg:
1108 case ConversionSpecifier::gArg:
1109 case ConversionSpecifier::GArg:
1110 return true;
1111 // GNU libc extension.
1112 case ConversionSpecifier::dArg:
1113 case ConversionSpecifier::iArg:
1114 case ConversionSpecifier::oArg:
1115 case ConversionSpecifier::uArg:
1116 case ConversionSpecifier::xArg:
1117 case ConversionSpecifier::XArg:
1118 return !Target.getTriple().isOSDarwin() &&
1119 !Target.getTriple().isOSWindows();
1120 default:
1121 return false;
1122 }
1123
1124 case LengthModifier::AsAllocate:
1125 switch (CS.getKind()) {
1126 case ConversionSpecifier::sArg:
1127 case ConversionSpecifier::SArg:
1128 case ConversionSpecifier::ScanListArg:
1129 return true;
1130 default:
1131 return false;
1132 }
1133
1134 case LengthModifier::AsMAllocate:
1135 switch (CS.getKind()) {
1136 case ConversionSpecifier::cArg:
1137 case ConversionSpecifier::CArg:
1138 case ConversionSpecifier::sArg:
1139 case ConversionSpecifier::SArg:
1140 case ConversionSpecifier::ScanListArg:
1141 return true;
1142 default:
1143 return false;
1144 }
1145 case LengthModifier::AsInt32:
1146 case LengthModifier::AsInt3264:
1147 case LengthModifier::AsInt64:
1148 switch (CS.getKind()) {
1149 case ConversionSpecifier::dArg:
1150 case ConversionSpecifier::iArg:
1151 case ConversionSpecifier::oArg:
1152 case ConversionSpecifier::uArg:
1153 case ConversionSpecifier::xArg:
1154 case ConversionSpecifier::XArg:
1155 return Target.getTriple().isOSMSVCRT();
1156 default:
1157 return false;
1158 }
1159 case LengthModifier::AsWide:
1160 switch (CS.getKind()) {
1161 case ConversionSpecifier::cArg:
1162 case ConversionSpecifier::CArg:
1163 case ConversionSpecifier::sArg:
1164 case ConversionSpecifier::SArg:
1165 case ConversionSpecifier::ZArg:
1166 return Target.getTriple().isOSMSVCRT();
1167 default:
1168 return false;
1169 }
1170 }
1171 llvm_unreachable("Invalid LengthModifier Kind!");
1172}
1173
1174bool FormatSpecifier::hasStandardLengthModifier() const {
1175 switch (LM.getKind()) {
1176 case LengthModifier::None:
1177 case LengthModifier::AsChar:
1178 case LengthModifier::AsShort:
1179 case LengthModifier::AsLong:
1180 case LengthModifier::AsLongLong:
1181 case LengthModifier::AsIntMax:
1182 case LengthModifier::AsSizeT:
1183 case LengthModifier::AsPtrDiff:
1184 case LengthModifier::AsLongDouble:
1185 return true;
1186 case LengthModifier::AsAllocate:
1187 case LengthModifier::AsMAllocate:
1188 case LengthModifier::AsQuad:
1189 case LengthModifier::AsInt32:
1190 case LengthModifier::AsInt3264:
1191 case LengthModifier::AsInt64:
1192 case LengthModifier::AsWide:
1193 case LengthModifier::AsShortLong: // ???
1194 return false;
1195 }
1196 llvm_unreachable("Invalid LengthModifier Kind!");
1197}
1198
1199bool FormatSpecifier::hasStandardConversionSpecifier(
1200 const LangOptions &LangOpt) const {
1201 switch (CS.getKind()) {
1202 case ConversionSpecifier::bArg:
1203 case ConversionSpecifier::BArg:
1204 case ConversionSpecifier::cArg:
1205 case ConversionSpecifier::dArg:
1206 case ConversionSpecifier::iArg:
1207 case ConversionSpecifier::oArg:
1208 case ConversionSpecifier::uArg:
1209 case ConversionSpecifier::xArg:
1210 case ConversionSpecifier::XArg:
1211 case ConversionSpecifier::fArg:
1212 case ConversionSpecifier::FArg:
1213 case ConversionSpecifier::eArg:
1214 case ConversionSpecifier::EArg:
1215 case ConversionSpecifier::gArg:
1216 case ConversionSpecifier::GArg:
1217 case ConversionSpecifier::aArg:
1218 case ConversionSpecifier::AArg:
1219 case ConversionSpecifier::sArg:
1220 case ConversionSpecifier::pArg:
1221 case ConversionSpecifier::nArg:
1222 case ConversionSpecifier::ObjCObjArg:
1223 case ConversionSpecifier::ScanListArg:
1224 case ConversionSpecifier::PercentArg:
1225 case ConversionSpecifier::PArg:
1226 return true;
1227 case ConversionSpecifier::CArg:
1228 case ConversionSpecifier::SArg:
1229 return LangOpt.ObjC;
1230 case ConversionSpecifier::InvalidSpecifier:
1231 case ConversionSpecifier::FreeBSDbArg:
1232 case ConversionSpecifier::FreeBSDDArg:
1233 case ConversionSpecifier::FreeBSDrArg:
1234 case ConversionSpecifier::FreeBSDyArg:
1235 case ConversionSpecifier::PrintErrno:
1236 case ConversionSpecifier::DArg:
1237 case ConversionSpecifier::OArg:
1238 case ConversionSpecifier::UArg:
1239 case ConversionSpecifier::ZArg:
1240 return false;
1241 case ConversionSpecifier::rArg:
1242 case ConversionSpecifier::RArg:
1243 case ConversionSpecifier::kArg:
1244 case ConversionSpecifier::KArg:
1245 return LangOpt.FixedPoint;
1246 }
1247 llvm_unreachable("Invalid ConversionSpecifier Kind!");
1248}
1249
1250bool FormatSpecifier::hasStandardLengthConversionCombination() const {
1251 if (LM.getKind() == LengthModifier::AsLongDouble) {
1252 switch(CS.getKind()) {
1253 case ConversionSpecifier::dArg:
1254 case ConversionSpecifier::iArg:
1255 case ConversionSpecifier::oArg:
1256 case ConversionSpecifier::uArg:
1257 case ConversionSpecifier::xArg:
1258 case ConversionSpecifier::XArg:
1259 return false;
1260 default:
1261 return true;
1262 }
1263 }
1264 return true;
1265}
1266
1267std::optional<LengthModifier>
1268FormatSpecifier::getCorrectedLengthModifier() const {
1269 if (CS.isAnyIntArg() || CS.getKind() == ConversionSpecifier::nArg) {
1270 if (LM.getKind() == LengthModifier::AsLongDouble ||
1271 LM.getKind() == LengthModifier::AsQuad) {
1272 LengthModifier FixedLM(LM);
1273 FixedLM.setKind(LengthModifier::AsLongLong);
1274 return FixedLM;
1275 }
1276 }
1277
1278 return std::nullopt;
1279}
1280
1281bool FormatSpecifier::namedTypeToLengthModifier(ASTContext &Ctx, QualType QT,
1282 LengthModifier &LM) {
1283 if (LengthModifier::Kind Out = LengthModifier::Kind::None;
1284 namedTypeToLengthModifierKind(Ctx, QT, K&: Out)) {
1285 LM.setKind(Out);
1286 return true;
1287 }
1288 return false;
1289}
1290