1//===--- RestrictSystemLibcHeadersCheck.cpp - clang-tidy ------------------===//
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#include "RestrictSystemLibcHeadersCheck.h"
10#include "clang/AST/ASTContext.h"
11#include "clang/ASTMatchers/ASTMatchFinder.h"
12#include "clang/Lex/HeaderSearch.h"
13#include "clang/Lex/HeaderSearchOptions.h"
14#include "clang/Lex/Preprocessor.h"
15
16// FixItHint - Hint to check documentation script to mark this check as
17// providing a FixIt.
18
19namespace clang::tidy::llvm_libc {
20
21namespace {
22
23class RestrictedIncludesPPCallbacks
24 : public portability::RestrictedIncludesPPCallbacks {
25public:
26 explicit RestrictedIncludesPPCallbacks(
27 RestrictSystemLibcHeadersCheck &Check, const SourceManager &SM,
28 const SmallString<128> CompilerIncudeDir)
29 : portability::RestrictedIncludesPPCallbacks(Check, SM),
30 CompilerIncudeDir(CompilerIncudeDir) {}
31
32 void InclusionDirective(SourceLocation HashLoc, const Token &IncludeTok,
33 StringRef FileName, bool IsAngled,
34 CharSourceRange FilenameRange,
35 OptionalFileEntryRef File, StringRef SearchPath,
36 StringRef RelativePath, const Module *SuggestedModule,
37 bool ModuleImported,
38 SrcMgr::CharacteristicKind FileType) override;
39
40private:
41 const SmallString<128> CompilerIncudeDir;
42};
43
44} // namespace
45
46void RestrictedIncludesPPCallbacks::InclusionDirective(
47 SourceLocation HashLoc, const Token &IncludeTok, StringRef FileName,
48 bool IsAngled, CharSourceRange FilenameRange, OptionalFileEntryRef File,
49 StringRef SearchPath, StringRef RelativePath, const Module *SuggestedModule,
50 bool ModuleImported, SrcMgr::CharacteristicKind FileType) {
51 // Compiler provided headers are allowed (e.g stddef.h).
52 if (SrcMgr::isSystem(CK: FileType) && SearchPath == CompilerIncudeDir)
53 return;
54 portability::RestrictedIncludesPPCallbacks::InclusionDirective(
55 HashLoc, IncludeTok, FileName, IsAngled, FilenameRange, File, SearchPath,
56 RelativePath, SuggestedModule, ModuleImported, FileType);
57}
58
59void RestrictSystemLibcHeadersCheck::registerPPCallbacks(
60 const SourceManager &SM, Preprocessor *PP, Preprocessor *ModuleExpanderPP) {
61 SmallString<128> CompilerIncudeDir =
62 StringRef(PP->getHeaderSearchInfo().getHeaderSearchOpts().ResourceDir);
63 llvm::sys::path::append(path&: CompilerIncudeDir, a: "include");
64 PP->addPPCallbacks(C: std::make_unique<RestrictedIncludesPPCallbacks>(
65 args&: *this, args: SM, args&: CompilerIncudeDir));
66}
67
68} // namespace clang::tidy::llvm_libc
69

source code of clang-tools-extra/clang-tidy/llvmlibc/RestrictSystemLibcHeadersCheck.cpp