简体   繁体   English

在 clang-tidy 中忽略系统标题

[英]Ignore system headers in clang-tidy

tldr;> How do I hide warnings from system headers in clang-tidy? tldr;> 如何在 clang-tidy 中隐藏来自系统标题的警告?

I have the following minimal example source file, which triggers a clang-tidy warning in the system headers:我有以下最小的示例源文件,它会在系统标头中触发 clang-tidy 警告:

#include <future>

int main() {
  std::promise<int> p;
  p.set_value(3);
}

Calling it with libstdc++ 7.0.1 using clang-tidy 4.0.0 on Ubuntu 17.04:在 Ubuntu 17.04 上使用 clang-tidy 4.0.0 使用 libstdc++ 7.0.1 调用它:

$ clang-tidy main.cpp -extra-arg=-std=c++14

yields产量

Running without flags.
1 warning generated.
/usr/lib/gcc/x86_64-linux-gnu/7.0.1/../../../../include/c++/7.0.1/mutex:693:5: warning: Address of stack memory associated with local variable '__callable' is still referred to by the global variable '__once_callable' upon returning to the caller.  This will be a dangling reference [clang-analyzer-core.StackAddressEscape]
    }
    ^
/home/user/main.cpp:5:3: note: Calling 'promise::set_value'
  p.set_value(3);
  ^
/usr/lib/gcc/x86_64-linux-gnu/7.0.1/../../../../include/c++/7.0.1/future:1094:9: note: Calling '_State_baseV2::_M_set_result'
      { _M_future->_M_set_result(_State::__setter(this, std::move(__r))); }
        ^
/usr/lib/gcc/x86_64-linux-gnu/7.0.1/../../../../include/c++/7.0.1/future:401:2: note: Calling 'call_once'
        call_once(_M_once, &_State_baseV2::_M_do_set, this,
        ^
/usr/lib/gcc/x86_64-linux-gnu/7.0.1/../../../../include/c++/7.0.1/mutex:691:11: note: Assuming '__e' is 0
      if (__e)
          ^
/usr/lib/gcc/x86_64-linux-gnu/7.0.1/../../../../include/c++/7.0.1/mutex:691:7: note: Taking false branch
      if (__e)
      ^
/usr/lib/gcc/x86_64-linux-gnu/7.0.1/../../../../include/c++/7.0.1/mutex:693:5: note: Address of stack memory associated with local variable '__callable' is still referred to by the global variable '__once_callable' upon returning to the caller.  This will be a dangling reference
    }

I want to hide warnings in system headers.我想隐藏系统标题中的警告。 I tried the following:我尝试了以下方法:

$ clang-tidy -extra-arg=-std=c++14 main.cpp -header-filter=$(realpath .) -system-headers=0

but the warning still shows.但警告仍然显示。

I ran into this issue as well, and spent some time trying to figure it out, but I could not see a way to disable this type of warning in clang-tidy.我也遇到了这个问题,并花了一些时间试图弄清楚,但我看不到在 clang-tidy 中禁用此类警告的方法。

From reading this discussion on the LLVM issue tracker regarding a similar issue , I get the impression that the problem is that from clang-tidy's perspective, the warning is actually located in main.cpp , because the call to set_value is from there.通过阅读关于 LLVM 问题跟踪器关于类似问题的讨论,我得到的印象是,从 clang-tidy 的角度来看,警告实际上位于main.cpp ,因为对set_value的调用来自那里。

My workaround has been to disable the static analysis checks in clang-tidy, and use the scan-build utility to run clang's static analysis, which seems to avoid these problems.我的解决方法是禁用 clang-tidy 中的静态分析检查,并使用scan-build 实用程序运行 clang 的静态分析,这似乎避免了这些问题。 For example, using your main.cpp :例如,使用您的main.cpp

$ scan-build-3.9 clang++ -std=c++14 main.cpp 
scan-build: Using '/usr/lib/llvm-3.9/bin/clang' for static analysis
In file included from main.cpp:1:
In file included from /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/future:39:
/usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/mutex:621:11: warning: Address of stack memory associated with local variable '__callable' is still referred to by the global variable '__once_callable' upon returning to the caller.  This will be a dangling reference
      if (__e)
          ^~~
1 warning generated.
scan-build: Removing directory '/tmp/scan-build-2017-12-02-112018-13035-1' because it contains no reports.
scan-build: No bugs found.

The analyzer finds the same error in a system header, but it's smart enough not to include it in the final report.分析器在系统标题中发现相同的错误,但它足够聪明,不会将其包含在最终报告中。 ("No bugs found") (“没有发现错误”)

You'll still need to run clang-tidy separately if you are interested in the style guide type warnings, like modernize-* or readability-* .如果您对样式指南类型警告(例如modernize-*readability-*感兴趣,您仍然需要单独运行 clang-tidy 。

I initially came to the conclusion that this was not possible, but I've got a hack that gets pretty close.我最初得出的结论是这是不可能的,但我有一个非常接近的黑客。

When I compile I use CMAKE_EXPORT_COMPILE_COMMANDS=ON which generates a compile_commands.json file showing what commands were passed to the compiler for each cpp file compiled.当我编译时,我使用 CMAKE_EXPORT_COMPILE_COMMANDS=ON 生成一个 compile_commands.json 文件,显示为每个编译的 cpp 文件传递​​给编译器的命令。 When I run clang-tidy I give it the -p option to point to the directory containing this file.当我运行clang-tidy我给它一个 -p 选项来指向包含这个文件的目录。

A typical entry in this file looks something like this:此文件中的典型条目如下所示:

{
  "directory": "/project/build/package1",
  "command": "/usr/bin/clang++-9 -I/opt/thirdparty/include -isystem /usr/include . . . /project/src/package1/src/foo.cpp",
  "file": "/project/src/package1/src/foo.cpp"
},

If I re-write this file so that -I/opt/thirdparty/include becomes -isystem /opt/thirdparty/include the previously problematic headers in /opt/third-party/include are ignored because clang-tidy will see them as system headers.如果我重新编写此文件,以便-I/opt/thirdparty/include -isystem /opt/thirdparty/include -I/opt/thirdparty/include变为-isystem /opt/thirdparty/include /opt/third-party/include 中先前有问题的标头将被忽略,因为 clang-tidy 会将它们视为系统标题。

I use sed to rewrite the file我使用sed重写文件

# Trick clang-tidy into thinking anything in /opt/thirdparty/include is a system header
sed -i 's|-I/opt/thirdparty/include|-isystem /opt/thirdparty/include|g' build/compile_commands.json
# Run clang-tidy using the run-clang-tidy python wrapper
run-clang-tidy.py -p build -header-filter .* $(find src -iname "*.cpp")

My solution to this problem is to execute clang-tidy from a script and then filter all issues based on the file location because issues from user-code are located in eg C:\\Repos\\myLib , whereas issues from system-headers are located in C:\\Program Files (x86) or similar.我对这个问题的解决方案是从脚本中执行clang-tidy ,然后根据文件位置过滤所有问题,因为来自用户代码的问题位于例如C:\\Repos\\myLib ,而来自系统头文件的问题位于C:\\Program Files (x86)或类似的。

The script is a powershell script, maybe you can do something similar with bash :该脚本是一个powershell脚本,也许你可以用bash做类似的事情:

# clang-filter-user-code.ps1
Param(
    [parameter(Mandatory=$true)]
    [string]$CLANG_TIDY,
    [parameter(Mandatory=$true)]
    [string[]]$SOURCE_FILES,
    [parameter(Mandatory=$true)]
    [string]$SOURCE_DIR,
    [parameter(Mandatory=$true)]
    [string]$TARGET_DIR
)

$TMP = $TARGET_DIR + "/tmp-clang-output.txt"
$PATTERN = "(?s)(" + $SOURCE_DIR.Replace("/", "\\") + ".*)"

# Reading the content as Raw text, where everything is stored within one line, is only possible with specifying a path to a file.
# Therefore we store the clang-tidy output in a temporary file, that is deleted afterwards.
&($CLANG_TIDY) $SOURCE_FILES > $TMP
Get-Content -Raw -Path $TMP | Select-String -Pattern $PATTERN -AllMatches | Select-Object -ExpandProperty Matches | % {$_.Groups[1].Value }
Remove-Item $TMP

You have to pass the path to clang-tidy, your source files, the path of your source directory and the path to your target directory to the script.您必须将 clang-tidy 的路径、源文件、源目录的路径和目标目录的路径传递给脚本。

Using CMAKE , you can integrate this into your build:使用CMAKE ,您可以将其集成到您的构建中:

# clang-dev-tools.cmake
function(PREPARE_SOURCE_FILE_LIST SOURCE_FILES OUTPUT)
    # Put each entry between single quotes
    foreach(SOURCE_FILE ${SOURCE_FILES})
        list(APPEND SOURCE_FILES_LIST '${SOURCE_FILE}')
    endforeach()

    # Join all entries using comma as delimiter - based on https://stackoverflow.com/questions/7172670/best-shortest-way-to-join-a-list-in-cmake
    string(REGEX REPLACE "([^\\]|^);" "\\1," TMP_STR "${SOURCE_FILES_LIST}")
    string(REGEX REPLACE "[\\](.)" "\\1" TMP_STR "${TMP_STR}") #fixes escaping
    set(${OUTPUT} "${TMP_STR}" PARENT_SCOPE)
endfunction()

# Detect all source files
file(GLOB_RECURSE
        SOURCE_FILES
        ${CMAKE_SOURCE_DIR}/Src/Libs/*/Src/*.cpp
        ${CMAKE_SOURCE_DIR}/Src/Libs/*/Src/*.h)

find_program(CLANG_TIDY NAMES clang-tidy clang-tidy-6.0)
if (CLANG_TIDY)
    PREPARE_SOURCE_FILE_LIST("${SOURCE_FILES}" SOURCE_FILES_LIST)
    set(SCRIPT_ARGUMENTS "-CLANG_TIDY" '${CLANG_TIDY}' "-SOURCE_FILES" ("${SOURCE_FILES_LIST}") "-SOURCE_DIR" '${CMAKE_SOURCE_DIR}' "-TARGET_DIR" '${CMAKE_BINARY_DIR}')
    
    # Because clang-tidy also detects warnings/errors in non-user code, we need to filter its output via this script.
    add_custom_command(
        OUTPUT clang-output
        COMMAND PowerShell (${CMAKE_CURRENT_SOURCE_DIR}/cmake/clang-filter-user-code.ps1 ${SCRIPT_ARGUMENTS})
        WORKING_DIRECTORY ${CMAKE_BINARY_DIR}
    )
    add_custom_target(
        FilterClang ALL 
        DEPENDS clang-output
    )
endif ()

I'm not so familiar with both CMAKE and powershell , so please bear with me if I did not find the most elegant solution.我对CMAKEpowershellCMAKE熟悉,所以如果我没有找到最优雅的解决方案,请耐心CMAKE

There is also an open PR to an even better solution on LLVM , but since it is already open for almost 4 years now, we don't know if and when it's going to come.在 LLVM 上还有一个更好的解决方案公开 PR ,但由于它已经开放了将近 4 年,我们不知道它是否以及何时会出现。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM