yawanng updated this revision to Diff 100777.
yawanng added a comment.
Modify the detection algorithm. Add another two checks and corresponding tests
as well as the docs.
https://reviews.llvm.org/D33304
Files:
clang-tidy/CMakeLists.txt
clang-tidy/android/AndroidTidyModule.cpp
clang-tidy/android/CMakeLists.txt
clang-tidy/android/CreatUsageCheck.cpp
clang-tidy/android/CreatUsageCheck.h
clang-tidy/android/FileOpenFlagCheck.cpp
clang-tidy/android/FileOpenFlagCheck.h
clang-tidy/android/FopenModeCheck.cpp
clang-tidy/android/FopenModeCheck.h
clang-tidy/plugin/CMakeLists.txt
clang-tidy/tool/CMakeLists.txt
clang-tidy/tool/ClangTidyMain.cpp
clang-tidy/utils/CMakeLists.txt
clang-tidy/utils/ExprToStr.cpp
clang-tidy/utils/ExprToStr.h
docs/ReleaseNotes.rst
docs/clang-tidy/checks/android-creat-usage.rst
docs/clang-tidy/checks/android-file-open-flag.rst
docs/clang-tidy/checks/android-fopen-mode.rst
docs/clang-tidy/checks/list.rst
docs/clang-tidy/index.rst
test/clang-tidy/android-creat-usage.cpp
test/clang-tidy/android-file-open-flag.cpp
test/clang-tidy/android-fopen-mode.cpp
unittests/clang-tidy/CMakeLists.txt
Index: unittests/clang-tidy/CMakeLists.txt
===================================================================
--- unittests/clang-tidy/CMakeLists.txt
+++ unittests/clang-tidy/CMakeLists.txt
@@ -25,6 +25,7 @@
clangFrontend
clangLex
clangTidy
+ clangTidyAndroidModule
clangTidyGoogleModule
clangTidyLLVMModule
clangTidyMiscModule
Index: test/clang-tidy/android-fopen-mode.cpp
===================================================================
--- test/clang-tidy/android-fopen-mode.cpp
+++ test/clang-tidy/android-fopen-mode.cpp
@@ -0,0 +1,51 @@
+// RUN: %check_clang_tidy %s android-fopen-mode %t
+
+#define FILE_OPEN_RO "r"
+
+typedef int FILE;
+
+extern "C" FILE *fopen(const char *filename, const char *mode, ...);
+extern "C" FILE *open(const char *filename, const char *mode, ...);
+
+void f() {
+ fopen("filename", "r");
+ // CHECK-MESSAGES: :[[@LINE-1]]:21: warning: use fopen() mode 'e' to set O_CLOEXEC. [android-fopen-mode]
+ // CHECK-FIXES: "re"
+
+ fopen("filename", FILE_OPEN_RO);
+ // CHECK-MESSAGES: :[[@LINE-1]]:21: warning: use fopen() mode 'e' to set O_CLOEXEC. [android-fopen-mode]
+ // CHECK-FIXES: FILE_OPEN_RO "e"
+
+ fopen("filename", "er");
+ // CHECK-MESSAGES-NOT: warning:
+ fopen("filename", "re");
+ // CHECK-MESSAGES-NOT: warning:
+ fopen("filename", "e");
+ // CHECK-MESSAGES-NOT: warning:
+ open("filename", "e");
+ // CHECK-MESSAGES-NOT: warning:
+
+ char *str = "r";
+ fopen("filename", str);
+ // CHECK-MESSAGES-NOT: warning:
+ char arr[2] = "r";
+ fopen("filename", arr);
+ // CHECK-MESSAGES-NOT: warning:
+}
+
+namespace i {
+int *fopen(const char *filename, const char *mode, ...);
+void g() {
+ fopen("filename", "e");
+ // CHECK-MESSAGES-NOT: warning:
+}
+} // namespace i
+
+class C {
+public:
+ int *fopen(const char *filename, const char *mode, ...);
+ void h() {
+ fopen("filename", "e");
+ // CHECK-MESSAGES-NOT: warning:
+ }
+};
Index: test/clang-tidy/android-file-open-flag.cpp
===================================================================
--- test/clang-tidy/android-file-open-flag.cpp
+++ test/clang-tidy/android-file-open-flag.cpp
@@ -0,0 +1,104 @@
+// RUN: %check_clang_tidy %s android-file-open-flag %t
+
+#define O_RDWR 1
+#define O_EXCL 2
+#define __O_CLOEXEC 3
+#define O_CLOEXEC __O_CLOEXEC
+
+extern "C" int open(const char *fn, int flags, ...);
+extern "C" int open64(const char *fn, int flags, ...);
+extern "C" int openat(int dirfd, const char *pathname, int flags, ...);
+
+void a() {
+ open("filename", O_RDWR);
+ // CHECK-MESSAGES: :[[@LINE-1]]:20: warning: open should use O_CLOEXEC where possible. [android-file-open-flag]
+ // CHECK-FIXES: O_RDWR | O_CLOEXEC
+ open("filename", O_RDWR | O_EXCL);
+ // CHECK-MESSAGES: :[[@LINE-1]]:20: warning: open should use O_CLOEXEC where possible. [android-file-open-flag]
+ // CHECK-FIXES: O_RDWR | O_EXCL | O_CLOEXEC
+}
+
+void b() {
+ open64("filename", O_RDWR);
+ // CHECK-MESSAGES: :[[@LINE-1]]:22: warning: open64 should use O_CLOEXEC where possible. [android-file-open-flag]
+ // CHECK-FIXES: O_RDWR | O_CLOEXEC
+ open64("filename", O_RDWR | O_EXCL);
+ // CHECK-MESSAGES: :[[@LINE-1]]:22: warning: open64 should use O_CLOEXEC where possible. [android-file-open-flag]
+ // CHECK-FIXES: O_RDWR | O_EXCL | O_CLOEXEC
+}
+
+void c() {
+ openat(0, "filename", O_RDWR);
+ // CHECK-MESSAGES: :[[@LINE-1]]:25: warning: openat should use O_CLOEXEC where possible. [android-file-open-flag]
+ // CHECK-FIXES: O_RDWR | O_CLOEXEC
+ openat(0, "filename", O_RDWR | O_EXCL);
+ // CHECK-MESSAGES: :[[@LINE-1]]:25: warning: openat should use O_CLOEXEC where possible. [android-file-open-flag]
+ // CHECK-FIXES: O_RDWR | O_EXCL | O_CLOEXEC
+}
+
+void f() {
+ open("filename", 3);
+ // CHECK-MESSAGES: :[[@LINE-1]]:20: warning: open should use O_CLOEXEC where possible. [android-file-open-flag]
+ // CHECK-FIXES: 3 | O_CLOEXEC
+ open64("filename", 3);
+ // CHECK-MESSAGES: :[[@LINE-1]]:22: warning: open64 should use O_CLOEXEC where possible. [android-file-open-flag]
+ // CHECK-FIXES: 3 | O_CLOEXEC
+ openat(0, "filename", 3);
+ // CHECK-MESSAGES: :[[@LINE-1]]:25: warning: openat should use O_CLOEXEC where possible. [android-file-open-flag]
+ // CHECK-FIXES: 3 | O_CLOEXEC
+
+ int flag = 3;
+ open("filename", flag);
+ // CHECK-MESSAGES-NOT: warning:
+ open64("filename", flag);
+ // CHECK-MESSAGES-NOT: warning:
+ openat(0, "filename", flag);
+ // CHECK-MESSAGES-NOT: warning:
+}
+
+namespace i {
+int open(const char *pathname, int flags, ...);
+int open64(const char *pathname, int flags, ...);
+int openat(int dirfd, const char *pathname, int flags, ...);
+
+void d() {
+ open("filename", O_RDWR);
+ // CHECK-MESSAGES-NOT: warning:
+ open64("filename", O_RDWR);
+ // CHECK-MESSAGES-NOT: warning:
+ openat(0, "filename", O_RDWR);
+ // CHECK-MESSAGES-NOT: warning:
+}
+
+} // namespace i
+
+void e() {
+ open("filename", O_CLOEXEC);
+ // CHECK-MESSAGES-NOT: warning:
+ open("filename", O_RDWR | O_CLOEXEC);
+ // CHECK-MESSAGES-NOT: warning:
+ open64("filename", O_CLOEXEC);
+ // CHECK-MESSAGES-NOT: warning:
+ open64("filename", O_RDWR | O_CLOEXEC);
+ // CHECK-MESSAGES-NOT: warning:
+ openat(0, "filename", O_CLOEXEC);
+ // CHECK-MESSAGES-NOT: warning:
+ openat(0, "filename", O_RDWR | O_CLOEXEC);
+ // CHECK-MESSAGES-NOT: warning:
+}
+
+class G {
+public:
+ int open(const char *pathname, int flags, ...);
+ int open64(const char *pathname, int flags, ...);
+ int openat(int dirfd, const char *pathname, int flags, ...);
+
+ void h() {
+ open("filename", O_RDWR);
+ // CHECK-MESSAGES-NOT: warning:
+ open64("filename", O_RDWR);
+ // CHECK-MESSAGES-NOT: warning:
+ openat(0, "filename", O_RDWR);
+ // CHECK-MESSAGES-NOT: warning:
+ }
+};
Index: test/clang-tidy/android-creat-usage.cpp
===================================================================
--- test/clang-tidy/android-creat-usage.cpp
+++ test/clang-tidy/android-creat-usage.cpp
@@ -0,0 +1,31 @@
+// RUN: %check_clang_tidy %s android-creat-usage %t
+
+typedef int mode_t;
+
+extern "C" int creat(const char *path, mode_t, ...);
+extern "C" int create(const char *path, mode_t, ...);
+
+void f() {
+ creat("filename", 0);
+ // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: prefer open() to creat() because open() allows O_CLOEXEC. [android-creat-usage]
+ // CHECK-FIXES: open ("filename", O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0);
+ create("filename", 0);
+ // CHECK-MESSAGES-NOT: warning:
+}
+
+namespace i {
+int creat(const char *path, mode_t, ...);
+void g() {
+ creat("filename", 0);
+ // CHECK-MESSAGES-NOT: warning:
+}
+} // namespace i
+
+class C {
+public:
+ int creat(const char *path, mode_t, ...);
+ void h() {
+ creat("filename", 0);
+ // CHECK-MESSAGES-NOT: warning:
+ }
+};
Index: docs/clang-tidy/index.rst
===================================================================
--- docs/clang-tidy/index.rst
+++ docs/clang-tidy/index.rst
@@ -55,6 +55,7 @@
====================== =========================================================
Name prefix Description
====================== =========================================================
+``android-`` Checks related to Android.
``boost-`` Checks related to Boost library.
``cert-`` Checks related to CERT Secure Coding Guidelines.
``cppcoreguidelines-`` Checks related to C++ Core Guidelines.
Index: docs/clang-tidy/checks/list.rst
===================================================================
--- docs/clang-tidy/checks/list.rst
+++ docs/clang-tidy/checks/list.rst
@@ -4,6 +4,9 @@
=================
.. toctree::
+ android-creat-usage
+ android-file-open-flag
+ android-fopen-mode
boost-use-to-string
cert-dcl03-c (redirects to misc-static-assert) <cert-dcl03-c>
cert-dcl21-cpp
Index: docs/clang-tidy/checks/android-fopen-mode.rst
===================================================================
--- docs/clang-tidy/checks/android-fopen-mode.rst
+++ docs/clang-tidy/checks/android-fopen-mode.rst
@@ -0,0 +1,17 @@
+.. title:: clang-tidy - android-fopen-mode
+
+android-fopen-mode
+=========================
+``fopen()`` should include ``e`` in their mode string; so ``re`` would be
+valid.
+
+Examples:
+
+.. code-block:: c++
+
+ fopen("fn", "r");
+
+ // becomes
+
+ fopen("fn", "re");
+
Index: docs/clang-tidy/checks/android-file-open-flag.rst
===================================================================
--- docs/clang-tidy/checks/android-file-open-flag.rst
+++ docs/clang-tidy/checks/android-file-open-flag.rst
@@ -0,0 +1,24 @@
+.. title:: clang-tidy - android-file-open-flag
+
+android-file-open-flag
+==============================
+A common source of security bugs has been code that opens file without using
+the ``O_CLOEXEC`` flag. Without that flag, an opened sensitive file would
+remain open across a fork+exec to a lower-privileged SELinux domain, leaking
+that sensitive data Functions including ``open()``, ``openat()``, and
+``open64()`` must include ``O_CLOEXEC`` in their flags argument.
+
+
+Examples:
+
+.. code-block:: c++
+
+ open("filename", O_RDWR);
+ open64("filename", O_RDWR);
+ openat(0, "filename", O_RDWR);
+
+ // becomes
+
+ open("filename", O_RDWR | O_CLOEXEC);
+ open64("filename", O_RDWR | O_CLOEXEC);
+ openat(0, "filename", O_RDWR | O_CLOEXEC);
Index: docs/clang-tidy/checks/android-creat-usage.rst
===================================================================
--- docs/clang-tidy/checks/android-creat-usage.rst
+++ docs/clang-tidy/checks/android-creat-usage.rst
@@ -0,0 +1,5 @@
+.. title:: clang-tidy - android-creat-usage
+
+android-creat-usage
+===========================
+The usage of creat() is not recommended, it's better to use open().
Index: docs/ReleaseNotes.rst
===================================================================
--- docs/ReleaseNotes.rst
+++ docs/ReleaseNotes.rst
@@ -57,6 +57,22 @@
Improvements to clang-tidy
--------------------------
+- New `android-file-open-flag
+ <http://clang.llvm.org/extra/clang-tidy/checks/android-file-open-flag>`_ check
+
+ Checks if the required file flag ``O_CLOEXEC`` exists in ``open()``,
+ ``open64()`` and ``openat()``.
+
+- New `android-creat-call
+ <http://clang.llvm.org/extra/clang-tidy/checks/android-creat-call>`_ check
+
+ Checks if any usage of function ``creat()``.
+
+- New `android-fopen-mode
+ <http://clang.llvm.org/extra/clang-tidy/checks/android-fopen-mode>`_ check
+
+ Checks if the required mode ``e`` exists in the mode argument of ``fopen()``.
+
- New `cert-dcl21-cpp
<http://clang.llvm.org/extra/clang-tidy/checks/cert-dcl21-cpp.html>`_ check
@@ -71,7 +87,7 @@
<http://clang.llvm.org/extra/clang-tidy/checks/cppcoreguidelines-no-malloc.html>`_ check
Allow custom memory management functions to be considered as well.
-
+
- New `misc-forwarding-reference-overload
<http://clang.llvm.org/extra/clang-tidy/checks/misc-forwarding-reference-overload.html>`_ check
Index: clang-tidy/utils/ExprToStr.h
===================================================================
--- clang-tidy/utils/ExprToStr.h
+++ clang-tidy/utils/ExprToStr.h
@@ -0,0 +1,27 @@
+//===---------- ExprToStr.h - clang-tidy ----------------------------------===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_EXPRTOSTR_H
+#define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_EXPRTOSTR_H
+
+#include "../ClangTidy.h"
+#include "clang/Lex/Lexer.h"
+
+namespace clang {
+namespace tidy {
+namespace utils {
+
+// Get the source code of the corresponding expr.
+std::string ExprToStr(const Expr *EX, const SourceManager &SM,
+ const LangOptions &LangOpts);
+} // namespace utils
+} // namespace tidy
+} // namespace clang
+
+#endif // LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_EXPRTOSTR_H
Index: clang-tidy/utils/ExprToStr.cpp
===================================================================
--- clang-tidy/utils/ExprToStr.cpp
+++ clang-tidy/utils/ExprToStr.cpp
@@ -0,0 +1,26 @@
+//===---------- ExprToStr.cpp - clang-tidy --------------------------------===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+#include "ExprToStr.h"
+
+namespace clang {
+namespace tidy {
+namespace utils {
+
+std::string ExprToStr(const Expr *EX, const SourceManager &SM,
+ const LangOptions &LangOpts) {
+ clang::SourceLocation B(SM.getFileLoc(EX->getLocStart())),
+ E(SM.getFileLoc(EX->getLocEnd()));
+ SourceLocation TE(Lexer::getLocForEndOfToken(E, 0, SM, LangOpts));
+ return std::string(SM.getCharacterData(B),
+ SM.getCharacterData(TE) - SM.getCharacterData(B));
+}
+} // namespace utils
+} // namespace tidy
+} // namespace clang
Index: clang-tidy/utils/CMakeLists.txt
===================================================================
--- clang-tidy/utils/CMakeLists.txt
+++ clang-tidy/utils/CMakeLists.txt
@@ -4,6 +4,7 @@
ASTUtils.cpp
DeclRefExprUtils.cpp
ExprSequence.cpp
+ ExprToStr.cpp
FixItHintUtils.cpp
HeaderFileExtensionsUtils.cpp
HeaderGuard.cpp
Index: clang-tidy/tool/ClangTidyMain.cpp
===================================================================
--- clang-tidy/tool/ClangTidyMain.cpp
+++ clang-tidy/tool/ClangTidyMain.cpp
@@ -477,6 +477,11 @@
static int LLVM_ATTRIBUTE_UNUSED GoogleModuleAnchorDestination =
GoogleModuleAnchorSource;
+// This anchor is used to force the linker to link the AndroidModule.
+extern volatile int AndroidModuleAnchorSource;
+static int LLVM_ATTRIBUTE_UNUSED AndroidModuleAnchorDestination =
+ AndroidModuleAnchorSource;
+
// This anchor is used to force the linker to link the MiscModule.
extern volatile int MiscModuleAnchorSource;
static int LLVM_ATTRIBUTE_UNUSED MiscModuleAnchorDestination =
Index: clang-tidy/tool/CMakeLists.txt
===================================================================
--- clang-tidy/tool/CMakeLists.txt
+++ clang-tidy/tool/CMakeLists.txt
@@ -13,6 +13,7 @@
clangASTMatchers
clangBasic
clangTidy
+ clangTidyAndroidModule
clangTidyBoostModule
clangTidyCERTModule
clangTidyCppCoreGuidelinesModule
Index: clang-tidy/plugin/CMakeLists.txt
===================================================================
--- clang-tidy/plugin/CMakeLists.txt
+++ clang-tidy/plugin/CMakeLists.txt
@@ -8,6 +8,7 @@
clangFrontend
clangSema
clangTidy
+ clangTidyAndroidModule
clangTidyBoostModule
clangTidyCERTModule
clangTidyCppCoreGuidelinesModule
Index: clang-tidy/android/FopenModeCheck.h
===================================================================
--- clang-tidy/android/FopenModeCheck.h
+++ clang-tidy/android/FopenModeCheck.h
@@ -0,0 +1,42 @@
+//===--- FopenModeCheck.h - clang-tidy---------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source //
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_ANDROID_FOPEN_MODE_STRING_H
+#define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_ANDROID_FOPEN_MODE_STRING_H
+
+#include "../ClangTidy.h"
+
+namespace clang {
+namespace tidy {
+namespace android {
+
+/// fopen() is suggested to include "e" in their mode string; like "re" would be
+/// better than "r".
+///
+/// This check only works when corresponding argument is StringLiteral. No
+/// constant propagation.
+///
+/// http://clang.llvm.org/extra/clang-tidy/checks/android-fopen-mode.html
+
+class FopenModeCheck : public ClangTidyCheck {
+public:
+ FopenModeCheck(StringRef Name, ClangTidyContext *Context)
+ : ClangTidyCheck(Name, Context) {}
+ void registerMatchers(ast_matchers::MatchFinder *Finder) override;
+ void check(const ast_matchers::MatchFinder::MatchResult &Result) override;
+ bool checkMode(const Expr *ModeArg);
+ std::string BuildReplaceText(const Expr *Arg, const SourceManager &SM);
+ static const char MODE = 'e';
+};
+
+} // namespace android
+} // namespace tidy
+} // namespace clang
+
+#endif // LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_ANDROID_FOPEN_MODE_STRING_H
Index: clang-tidy/android/FopenModeCheck.cpp
===================================================================
--- clang-tidy/android/FopenModeCheck.cpp
+++ clang-tidy/android/FopenModeCheck.cpp
@@ -0,0 +1,85 @@
+//===--- FopenModeCheck.cpp - clang-tidy-----------------------------------===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+#include "FopenModeCheck.h"
+#include "../utils/ExprToStr.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/AST/Type.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/Lex/Lexer.h"
+
+using namespace clang::ast_matchers;
+
+namespace clang {
+namespace tidy {
+namespace android {
+
+void FopenModeCheck::registerMatchers(MatchFinder *Finder) {
+ auto CharPointerType = hasType(pointerType(pointee(isAnyCharacter())));
+
+ Finder->addMatcher(
+ callExpr(
+ callee(functionDecl(isExternC(), hasParameter(0, CharPointerType),
+ hasParameter(1, CharPointerType),
+ hasName("fopen"), returns(asString("FILE *")))
+ .bind("funcDecl")))
+ .bind("fopenFn"),
+ this);
+}
+
+void FopenModeCheck::check(const MatchFinder::MatchResult &Result) {
+ const auto *MatchedCall = Result.Nodes.getNodeAs<CallExpr>("fopenFn");
+ const auto *FD = Result.Nodes.getNodeAs<FunctionDecl>("funcDecl");
+ const Expr *ModeArg = MatchedCall->getArg(1);
+
+ if (checkMode(ModeArg->IgnoreParenCasts())) {
+ return;
+ }
+
+ const SourceManager &SM = *Result.SourceManager;
+ std::string ReplacementText = BuildReplaceText(ModeArg, SM);
+
+ SourceRange ModeRange(ModeArg->getLocStart(), ModeArg->getLocEnd());
+
+ diag(ModeRange.getBegin(), "use %0() mode 'e' to set O_CLOEXEC.")
+ << FD->getName()
+ << FixItHint::CreateReplacement(ModeRange, ReplacementText);
+}
+
+// Check if the required mode is in the argument.
+// Args:
+// ModeArg: The argument of the function.
+// Return:
+// True if the 'e' may be in the mode string. False if it's not in the string
+// literals.
+bool FopenModeCheck::checkMode(const Expr *ModeArg) {
+ if (isa<StringLiteral>(ModeArg)) {
+ StringRef ModeStr = cast<StringLiteral>(ModeArg)->getString();
+ if (ModeStr.find(MODE) == StringRef::npos) {
+ return false;
+ }
+ }
+ return true;
+}
+
+// Build the replace text. If it's string constant, add 'e' directly in the end
+// of the string. Else, add "e".
+std::string FopenModeCheck::BuildReplaceText(const Expr *Arg,
+ const SourceManager &SM) {
+ if (Arg->getLocStart().isMacroID()) {
+ return utils::ExprToStr(Arg, SM, getLangOpts()) + " \"" + MODE + "\"";
+ }
+
+ StringRef SR = cast<StringLiteral>(Arg->IgnoreParenCasts())->getString();
+ return "\"" + SR.str() + MODE + "\"";
+}
+
+} // namespace android
+} // namespace tidy
+} // namespace clang
Index: clang-tidy/android/FileOpenFlagCheck.h
===================================================================
--- clang-tidy/android/FileOpenFlagCheck.h
+++ clang-tidy/android/FileOpenFlagCheck.h
@@ -0,0 +1,48 @@
+//===--- FileOpenFlagCheck.h - clang-tidy----------------------------------===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_ANDROID_FILE_OPEN_FLAG_H
+#define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_ANDROID_FILE_OPEN_FLAG_H
+
+#include "../ClangTidy.h"
+#include <unordered_map>
+
+namespace clang {
+namespace tidy {
+namespace android {
+
+/// Finds code that opens file without using the O_CLOEXEC flag.
+///
+/// open(), openat(), and open64() had better to include O_CLOEXEC in their
+/// flags argument. Only consider simple cases that the corresponding argument
+/// is constant or binary operation OR among constants like 'O_CLOEXEC' or
+/// 'O_CLOEXEC | O_RDONLY'. No constant propagation is performed.
+///
+/// Only the symbolic 'O_CLOEXEC' macro definition is checked, not the concrete
+/// value.
+
+class FileOpenFlagCheck : public ClangTidyCheck {
+public:
+ FileOpenFlagCheck(StringRef Name, ClangTidyContext *Context)
+ : ClangTidyCheck(Name, Context) {}
+ void registerMatchers(ast_matchers::MatchFinder *Finder) override;
+ void check(const ast_matchers::MatchFinder::MatchResult &Result) override;
+ void doCheck(const ast_matchers::MatchFinder::MatchResult &Result,
+ const CallExpr *MatchedCall, const Expr *FlagArg,
+ const FunctionDecl *FD);
+ bool checkFlags(const Expr *Flags, const SourceManager &SM);
+
+ static constexpr const char *O_CLOEXEC = "O_CLOEXEC";
+};
+
+} // namespace android
+} // namespace tidy
+} // namespace clang
+
+#endif // LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_ANDROID_FILE_OPEN_FLAG_H
Index: clang-tidy/android/FileOpenFlagCheck.cpp
===================================================================
--- clang-tidy/android/FileOpenFlagCheck.cpp
+++ clang-tidy/android/FileOpenFlagCheck.cpp
@@ -0,0 +1,123 @@
+//===--- FileOpenFlagCheck.cpp - clang-tidy--------------------------------===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+#include "FileOpenFlagCheck.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/Lex/Lexer.h"
+
+using namespace clang::ast_matchers;
+
+namespace clang {
+namespace tidy {
+namespace android {
+
+void FileOpenFlagCheck::registerMatchers(MatchFinder *Finder) {
+ auto CharPointerType = hasType(pointerType(pointee(isAnyCharacter())));
+
+ Finder->addMatcher(
+ callExpr(callee(functionDecl(isExternC(), returns(isInteger()),
+ hasParameter(0, CharPointerType),
+ hasParameter(1, hasType(isInteger())),
+ hasAnyName("open", "open64"))
+ .bind("funcDecl")))
+ .bind("openFn"),
+ this);
+ Finder->addMatcher(
+ callExpr(callee(functionDecl(isExternC(), returns(isInteger()),
+ hasParameter(0, hasType(isInteger())),
+ hasParameter(1, CharPointerType),
+ hasParameter(2, hasType(isInteger())),
+ hasName("openat"))
+ .bind("funcDecl")))
+ .bind("openatFn"),
+ this);
+}
+
+void FileOpenFlagCheck::check(const MatchFinder::MatchResult &Result) {
+ const CallExpr *MatchedCall;
+ const Expr *FlagArg;
+ if ((MatchedCall = Result.Nodes.getNodeAs<CallExpr>("openFn")))
+ FlagArg = MatchedCall->getArg(1);
+ else if ((MatchedCall = Result.Nodes.getNodeAs<CallExpr>("openatFn")))
+ FlagArg = MatchedCall->getArg(2);
+ else
+ return;
+
+ const auto *FD = Result.Nodes.getNodeAs<FunctionDecl>("funcDecl");
+
+ // Check the required flag.
+ doCheck(Result, MatchedCall, FlagArg, FD);
+}
+
+void FileOpenFlagCheck::doCheck(const MatchFinder::MatchResult &Result,
+ const CallExpr *MatchedCall,
+ const Expr *FlagArg, const FunctionDecl *FD) {
+ SourceManager &SM = *Result.SourceManager;
+
+ if (!checkFlags(FlagArg->IgnoreParenCasts(), SM)) {
+ LangOptions LangOpts = getLangOpts();
+ SourceRange FlagsRange(FlagArg->getLocStart(), FlagArg->getLocEnd());
+ StringRef FlagsText = Lexer::getSourceText(
+ CharSourceRange::getTokenRange(FlagsRange), SM, LangOpts);
+ std::string ReplacementText =
+ (llvm::Twine(FlagsText) + " | " + O_CLOEXEC).str();
+ diag(FlagArg->getLocStart(), "%0 should use %1 where possible.")
+ << FD->getName() << O_CLOEXEC
+ << FixItHint::CreateReplacement(FlagsRange, ReplacementText);
+ }
+}
+
+// Check if flags contain required flag.
+// Args:
+// Flags: The argument in the code.
+// SM: The SourceManager.
+// Return:
+// True if the required flag is declared in the argument.
+bool FileOpenFlagCheck::checkFlags(const Expr *Flags, const SourceManager &SM) {
+ bool IsFlagIn;
+ // If the Flag is an integer constant, check it.
+ if (isa<IntegerLiteral>(Flags)) {
+ SourceLocation SL = Flags->getLocStart();
+
+ if (!SM.isMacroBodyExpansion(SL))
+ return false;
+
+ // Get the Marco name.
+ LangOptions LangOpts = getLangOpts();
+ auto Loc = SM.getFileLoc(SL);
+ std::pair<FileID, unsigned> ExpansionInfo = SM.getDecomposedLoc(Loc);
+ unsigned MacroTokenLength = Lexer::MeasureTokenLength(Loc, SM, LangOpts);
+ StringRef ExpansionBuffer = SM.getBufferData(ExpansionInfo.first);
+ auto MacroName =
+ ExpansionBuffer.substr(ExpansionInfo.second, MacroTokenLength);
+
+ IsFlagIn = (MacroName == O_CLOEXEC);
+
+ }
+ // If it's a binary OR operation.
+ else if ((isa<BinaryOperator>(Flags)) &&
+ (cast<BinaryOperator>(Flags)->getOpcode() ==
+ clang::BinaryOperatorKind::BO_Or)) {
+ IsFlagIn =
+ checkFlags(cast<BinaryOperator>(Flags)->getLHS()->IgnoreParenCasts(),
+ SM) ||
+ checkFlags(cast<BinaryOperator>(Flags)->getRHS()->IgnoreParenCasts(),
+ SM);
+ }
+ // Otherwise, we assume it has the flag to avoid false positive.
+ else
+ IsFlagIn = true;
+
+ return IsFlagIn;
+}
+
+} // namespace android
+} // namespace tidy
+} // namespace clang
Index: clang-tidy/android/CreatUsageCheck.h
===================================================================
--- clang-tidy/android/CreatUsageCheck.h
+++ clang-tidy/android/CreatUsageCheck.h
@@ -0,0 +1,39 @@
+//===--- CreatUsageCheck.h - clang-tidy--------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_ANDROID_CREAT_USAGE_H
+#define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_ANDROID_CREAT_USAGE_H
+
+#include "../ClangTidy.h"
+
+namespace clang {
+namespace tidy {
+namespace android {
+
+/// creat() is better to be replaced by open().
+/// Find the usage of creat() and redirect user to use open().
+
+/// http://clang.llvm.org/extra/clang-tidy/checks/android-creat-usage.html
+
+class CreatUsageCheck : public ClangTidyCheck {
+public:
+ CreatUsageCheck(StringRef Name, ClangTidyContext *Context)
+ : ClangTidyCheck(Name, Context) {}
+ void registerMatchers(ast_matchers::MatchFinder *Finder) override;
+ void check(const ast_matchers::MatchFinder::MatchResult &Result) override;
+ inline std::string BuildReplaceText(const Expr *FirstArg,
+ const Expr *SecondArg,
+ const SourceManager &SM);
+};
+
+} // namespace android
+} // namespace tidy
+} // namespace clang
+
+#endif // LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_ANDROID_CREAT_USAGE_H
Index: clang-tidy/android/CreatUsageCheck.cpp
===================================================================
--- clang-tidy/android/CreatUsageCheck.cpp
+++ clang-tidy/android/CreatUsageCheck.cpp
@@ -0,0 +1,58 @@
+//===--- CreatUsageCheck.cpp - clang-tidy----------------------------------===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+#include "CreatUsageCheck.h"
+#include "../utils/ExprToStr.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/Lex/Lexer.h"
+
+using namespace clang::ast_matchers;
+
+namespace clang {
+namespace tidy {
+namespace android {
+
+void CreatUsageCheck::registerMatchers(MatchFinder *Finder) {
+ auto CharPointerType = hasType(pointerType(pointee(isAnyCharacter())));
+ auto MODETType = hasType(namedDecl(hasName("mode_t")));
+
+ Finder->addMatcher(
+ callExpr(
+ callee(functionDecl(isExternC(), hasParameter(0, CharPointerType),
+ hasParameter(1, MODETType), returns(isInteger()),
+ hasName("creat"))
+ .bind("funcDecl")))
+ .bind("creatFn"),
+ this);
+}
+
+void CreatUsageCheck::check(const MatchFinder::MatchResult &Result) {
+ const auto *MatchedCall = Result.Nodes.getNodeAs<CallExpr>("creatFn");
+ const SourceManager &SM = *Result.SourceManager;
+
+ SourceRange Range(MatchedCall->getLocStart(), MatchedCall->getLocEnd());
+ const std::string &ReplacementText =
+ BuildReplaceText(MatchedCall->getArg(0), MatchedCall->getArg(1), SM);
+ diag(MatchedCall->getLocStart(),
+ "prefer open() to creat() because open() allows O_CLOEXEC.")
+ << FixItHint::CreateReplacement(Range, ReplacementText);
+}
+
+std::string CreatUsageCheck::BuildReplaceText(const Expr *FirstArg,
+ const Expr *SecondArg,
+ const SourceManager &SM) {
+ return "open (" + utils::ExprToStr(FirstArg, SM, getLangOpts()) +
+ ", O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, " +
+ utils::ExprToStr(SecondArg, SM, getLangOpts()) + ")";
+}
+
+} // namespace android
+} // namespace tidy
+} // namespace clang
Index: clang-tidy/android/CMakeLists.txt
===================================================================
--- clang-tidy/android/CMakeLists.txt
+++ clang-tidy/android/CMakeLists.txt
@@ -0,0 +1,17 @@
+set(LLVM_LINK_COMPONENTS support)
+
+add_clang_library(clangTidyAndroidModule
+ AndroidTidyModule.cpp
+ CreatUsageCheck.cpp
+ FileOpenFlagCheck.cpp
+ FopenModeCheck.cpp
+
+ LINK_LIBS
+ clangAST
+ clangASTMatchers
+ clangBasic
+ clangLex
+ clangTidy
+ clangTidyReadabilityModule
+ clangTidyUtils
+ )
Index: clang-tidy/android/AndroidTidyModule.cpp
===================================================================
--- clang-tidy/android/AndroidTidyModule.cpp
+++ clang-tidy/android/AndroidTidyModule.cpp
@@ -0,0 +1,45 @@
+//===--- AndroidTidyModule.cpp - clang-tidy--------------------------------===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+#include "../ClangTidy.h"
+#include "../ClangTidyModule.h"
+#include "../ClangTidyModuleRegistry.h"
+#include "CreatUsageCheck.h"
+#include "FileOpenFlagCheck.h"
+#include "FopenModeCheck.h"
+
+using namespace clang::ast_matchers;
+
+namespace clang {
+namespace tidy {
+namespace android {
+
+/// This module is for Android specific checks.
+
+class AndroidModule : public ClangTidyModule {
+public:
+ void addCheckFactories(ClangTidyCheckFactories &CheckFactories) override {
+ CheckFactories.registerCheck<FileOpenFlagCheck>("android-file-open-flag");
+ CheckFactories.registerCheck<CreatUsageCheck>("android-creat-usage");
+ CheckFactories.registerCheck<FopenModeCheck>("android-fopen-mode");
+ }
+};
+
+// Register the AndroidTidyModule using this statically initialized variable.
+static ClangTidyModuleRegistry::Add<AndroidModule>
+ X("android-module", "Adds Android platform checks.");
+
+} // namespace android
+
+// This anchor is used to force the linker to link in the generated object file
+// and thus register the AndroidModule.
+volatile int AndroidModuleAnchorSource = 0;
+
+} // namespace tidy
+} // namespace clang
Index: clang-tidy/CMakeLists.txt
===================================================================
--- clang-tidy/CMakeLists.txt
+++ clang-tidy/CMakeLists.txt
@@ -26,6 +26,7 @@
clangToolingCore
)
+add_subdirectory(android)
add_subdirectory(boost)
add_subdirectory(cert)
add_subdirectory(cppcoreguidelines)
_______________________________________________
cfe-commits mailing list
[email protected]
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits