1 //===--- RestrictSystemLibcHeadersCheck.cpp - clang-tidy ------------------===//
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
7 //===----------------------------------------------------------------------===//
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"
16 // FixItHint - Hint to check documentation script to mark this check as
19 namespace clang::tidy::llvm_libc
{
23 class RestrictedIncludesPPCallbacks
24 : public portability::RestrictedIncludesPPCallbacks
{
26 explicit RestrictedIncludesPPCallbacks(
27 RestrictSystemLibcHeadersCheck
&Check
, const SourceManager
&SM
,
28 const SmallString
<128> CompilerIncudeDir
)
29 : portability::RestrictedIncludesPPCallbacks(Check
, SM
),
30 CompilerIncudeDir(CompilerIncudeDir
) {}
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
*Imported
,
37 SrcMgr::CharacteristicKind FileType
) override
;
40 const SmallString
<128> CompilerIncudeDir
;
45 void RestrictedIncludesPPCallbacks::InclusionDirective(
46 SourceLocation HashLoc
, const Token
&IncludeTok
, StringRef FileName
,
47 bool IsAngled
, CharSourceRange FilenameRange
, OptionalFileEntryRef File
,
48 StringRef SearchPath
, StringRef RelativePath
, const Module
*Imported
,
49 SrcMgr::CharacteristicKind FileType
) {
50 // Compiler provided headers are allowed (e.g stddef.h).
51 if (SrcMgr::isSystem(FileType
) && SearchPath
== CompilerIncudeDir
)
53 portability::RestrictedIncludesPPCallbacks::InclusionDirective(
54 HashLoc
, IncludeTok
, FileName
, IsAngled
, FilenameRange
, File
, SearchPath
,
55 RelativePath
, Imported
, FileType
);
58 void RestrictSystemLibcHeadersCheck::registerPPCallbacks(
59 const SourceManager
&SM
, Preprocessor
*PP
, Preprocessor
*ModuleExpanderPP
) {
60 SmallString
<128> CompilerIncudeDir
=
61 StringRef(PP
->getHeaderSearchInfo().getHeaderSearchOpts().ResourceDir
);
62 llvm::sys::path::append(CompilerIncudeDir
, "include");
63 PP
->addPPCallbacks(std::make_unique
<RestrictedIncludesPPCallbacks
>(
64 *this, SM
, CompilerIncudeDir
));
67 } // namespace clang::tidy::llvm_libc