【问题标题】:Static analyser issues with command line tools命令行工具的静态分析器问题
【发布时间】:2013-11-20 17:02:22
【问题描述】:

我们已使用 TeamCity/命令行工具自动构建当前项目。为了确保尽可能多地发现潜在问题,我们将项目设置为每次构建都使用静态分析器。 分析器标记了几个第 3 方类,因此我们通过以下标记排除了可疑类:

-w -Xanalyzer -analyzer-disable-checker

在 Xcode 中编译时一切正常(用 4.6.3 和 5.0.1 测试)。

但是当在 TeamCity 服务器上编译时,对于每个排除的第 3 方文件,我们都会收到以下错误:

__PIC__ level differs in PCH file vs. current fileerror: __PIC__ level differs in PCH file vs. current file2 errors generated.

如果我们删除 -Xanalyzer -analyzer-disable-checker 标签,错误就会消失(当然,在这种情况下,我们会收到分析器警告)。

如果我们使用 AppCode 编译会发生同样的错误,这让我认为这与命令行工具有关,AppCode 和 TeamCity 服务器都使用它们来编译构建。

TeamCity 服务器使用 Xcode 4 的命令行工具,我已经尝试使用 Xcode 4 和 5 的 AppCode。

当使用 Xcode 5 的命令行工具尝试使用 AppCode 时,错误会略有不同(同样,每个排除类都有一个错误):

error reading 'pic'
no analyzer checkers are associated with '-mrelocation-model'

所以,问题是:有没有人知道如何在使用命令行工具时抑制特定类的分析器警告的同时消除此错误(如果命令行工具确实有问题)?

【问题讨论】:

  • 您能否将通过 Team City 发送的命令与 Xcode 在运行时生成的命令进行比较?您应该能够看到 Xcode 提供的所有选项。
  • 实际上,我错过了 Xcode 实际上为那些排除的文件显示错误的事实:“由于解析错误,分析器跳过了这个文件”(虽然只在所有消息中可见)。所以最后 Xcode 在这里似乎也不能很好地应对。我仍然不知道为什么(以及使用 -Xanalyzer -analyzer-disable-checker 时是否是预期的行为)

标签: xcode macos teamcity clang


【解决方案1】:

我刚刚遇到了这个问题,并认为这是 Clang 的一个错误。我想我找到了解决方法。

尝试替换它

-w -Xanalyzer -analyzer-disable-checker

这条长得可笑的线(继续向右滚动以查看全部内容):

-w -Xanalyzer -analyzer-disable-checker -Xanalyzer alpha -Xanalyzer -analyzer-disable-checker -Xanalyzer core -Xanalyzer -analyzer-disable-checker -Xanalyzer cplusplus -Xanalyzer -analyzer-disable-checker -Xanalyzer deadcode -Xanalyzer -analyzer-disable-checker -Xanalyzer debug -Xanalyzer -analyzer-disable-checker -Xanalyzer llvm -Xanalyzer -analyzer-disable-checker -Xanalyzer osx -Xanalyzer -analyzer-disable-checker -Xanalyzer security -Xanalyzer -analyzer-disable-checker -Xanalyzer unix -Xanalyzer -analyzer-disable-checker -Xanalyzer insecureAPI

好的,这就是我的方法。看起来 Clang 具有“静态分析检查器”的层次结构,您可以单独或按组禁用它们。

例如,DeadStore 检查器是“deadcode.DeadStores”,因此您可以像这样禁用它:

-Xanalyzer -analyzer-disable-checker -Xanalyzer deadcode.DeadStores

或者,您可以通过仅指定“死码”来禁用所有死码相关的检查器,如下所示:

-Xanalyzer -analyzer-disable-checker -Xanalyzer deadcode

您可以使用以下命令获取所有检查器的列表:

clang -cc1 -analyzer-checker-help

目前输出如下:

OVERVIEW: Clang Static Analyzer Checkers List

USAGE: -analyzer-checker <CHECKER or PACKAGE,...>

CHECKERS:
  alpha.core.BoolAssignment       Warn about assigning non-{0,1} values to Boolean variables
  alpha.core.CastSize             Check when casting a malloc'ed type T, whether the size is a multiple of the size of T
  alpha.core.CastToStruct         Check for cast from non-struct pointer to struct pointer
  alpha.core.FixedAddr            Check for assignment of a fixed address to a pointer
  alpha.core.PointerArithm        Check for pointer arithmetic on locations other than array elements
  alpha.core.PointerSub           Check for pointer subtractions on two pointers pointing to different memory chunks
  alpha.core.SizeofPtr            Warn about unintended use of sizeof() on pointer expressions
  alpha.cplusplus.NewDeleteLeaks  Check for memory leaks. Traces memory managed by new/delete.
  alpha.cplusplus.VirtualCall     Check virtual function calls during construction or destruction
  alpha.deadcode.IdempotentOperations
                                  Warn about idempotent operations
  alpha.deadcode.UnreachableCode  Check unreachable code
  alpha.osx.cocoa.Dealloc         Warn about Objective-C classes that lack a correct implementation of -dealloc
  alpha.osx.cocoa.DirectIvarAssignment
                                  Check for direct assignments to instance variables
  alpha.osx.cocoa.DirectIvarAssignmentForAnnotatedFunctions
                                  Check for direct assignments to instance variables in the methods annotated with objc_no_direct_instance_variable_assignment
  alpha.osx.cocoa.InstanceVariableInvalidation
                                  Check that the invalidatable instance variables are invalidated in the methods annotated with objc_instance_variable_invalidator
  alpha.osx.cocoa.MissingInvalidationMethod
                                  Check that the invalidation methods are present in classes that contain invalidatable instance variables
  alpha.osx.cocoa.MissingSuperCall
                                  Warn about Objective-C methods that lack a necessary call to super
  alpha.security.ArrayBound       Warn about buffer overflows (older checker)
  alpha.security.ArrayBoundV2     Warn about buffer overflows (newer checker)
  alpha.security.MallocOverflow   Check for overflows in the arguments to malloc()
  alpha.security.ReturnPtrRange   Check for an out-of-bound pointer being returned to callers
  alpha.security.taint.TaintPropagation
                                  Generate taint information used by other checkers
  alpha.unix.Chroot               Check improper use of chroot
  alpha.unix.MallocWithAnnotations
                                  Check for memory leaks, double free, and use-after-free problems. Traces memory managed by malloc()/free(). Assumes that all user-defined functions which might free a pointer are annotated.
  alpha.unix.PthreadLock          Simple lock -> unlock checker
  alpha.unix.SimpleStream         Check for misuses of stream APIs
  alpha.unix.Stream               Check stream handling functions
  alpha.unix.cstring.BufferOverlap
                                  Checks for overlap in two buffer arguments
  alpha.unix.cstring.NotNullTerminated
                                  Check for arguments which are not null-terminating strings
  alpha.unix.cstring.OutOfBounds  Check for out-of-bounds access in string functions
  core.CallAndMessage             Check for logical errors for function calls and Objective-C message expressions (e.g., uninitialized arguments, null function pointers)
  core.DivideZero                 Check for division by zero
  core.DynamicTypePropagation     Generate dynamic type information
  core.NonNullParamChecker        Check for null pointers passed as arguments to a function whose arguments are references or marked with the 'nonnull' attribute
  core.NullDereference            Check for dereferences of null pointers
  core.StackAddressEscape         Check that addresses to stack memory do not escape the function
  core.UndefinedBinaryOperatorResult
                                  Check for undefined results of binary operators
  core.VLASize                    Check for declarations of VLA of undefined or zero size
  core.builtin.BuiltinFunctions   Evaluate compiler builtin functions (e.g., alloca())
  core.builtin.NoReturnFunctions  Evaluate "panic" functions that are known to not return to the caller
  core.uninitialized.ArraySubscript
                                  Check for uninitialized values used as array subscripts
  core.uninitialized.Assign       Check for assigning uninitialized values
  core.uninitialized.Branch       Check for uninitialized values used as branch conditions
  core.uninitialized.CapturedBlockVariable
                                  Check for blocks that capture uninitialized values
  core.uninitialized.UndefReturn  Check for uninitialized values being returned to the caller
  cplusplus.NewDelete             Check for double-free and use-after-free problems. Traces memory managed by new/delete.
  deadcode.DeadStores             Check for values stored to variables that are never read afterwards
  debug.ConfigDumper              Dump config table
  debug.DumpCFG                   Display Control-Flow Graphs
  debug.DumpCallGraph             Display Call Graph
  debug.DumpCalls                 Print calls as they are traversed by the engine
  debug.DumpDominators            Print the dominance tree for a given CFG
  debug.DumpLiveVars              Print results of live variable analysis
  debug.DumpTraversal             Print branch conditions as they are traversed by the engine
  debug.ExprInspection            Check the analyzer's understanding of expressions
  debug.Stats                     Emit warnings with analyzer statistics
  debug.TaintTest                 Mark tainted symbols as such.
  debug.ViewCFG                   View Control-Flow Graphs using GraphViz
  debug.ViewCallGraph             View Call Graph using GraphViz
  llvm.Conventions                Check code for LLVM codebase conventions
  osx.API                         Check for proper uses of various Apple APIs
  osx.SecKeychainAPI              Check for proper uses of Secure Keychain APIs
  osx.cocoa.AtSync                Check for nil pointers used as mutexes for @synchronized
  osx.cocoa.ClassRelease          Check for sending 'retain', 'release', or 'autorelease' directly to a Class
  osx.cocoa.IncompatibleMethodTypes
                                  Warn about Objective-C method signatures with type incompatibilities
  osx.cocoa.Loops                 Improved modeling of loops using Cocoa collection types
  osx.cocoa.NSAutoreleasePool     Warn for suboptimal uses of NSAutoreleasePool in Objective-C GC mode
  osx.cocoa.NSError               Check usage of NSError** parameters
  osx.cocoa.NilArg                Check for prohibited nil arguments to ObjC method calls
  osx.cocoa.NonNilReturnValue     Model the APIs that are guaranteed to return a non-nil value
  osx.cocoa.RetainCount           Check for leaks and improper reference count management
  osx.cocoa.SelfInit              Check that 'self' is properly initialized inside an initializer method
  osx.cocoa.UnusedIvars           Warn about private ivars that are never used
  osx.cocoa.VariadicMethodTypes   Check for passing non-Objective-C types to variadic collection initialization methods that expect only Objective-C types
  osx.coreFoundation.CFError      Check usage of CFErrorRef* parameters
  osx.coreFoundation.CFNumber     Check for proper uses of CFNumberCreate
  osx.coreFoundation.CFRetainRelease
                                  Check for null arguments to CFRetain/CFRelease/CFMakeCollectable
  osx.coreFoundation.containers.OutOfBounds
                                  Checks for index out-of-bounds when using 'CFArray' API
  osx.coreFoundation.containers.PointerSizedValues
                                  Warns if 'CFArray', 'CFDictionary', 'CFSet' are created with non-pointer-size values
  security.FloatLoopCounter       Warn on using a floating point value as a loop counter (CERT: FLP30-C, FLP30-CPP)
  security.insecureAPI.UncheckedReturn
                                  Warn on uses of functions whose return values must be always checked
  security.insecureAPI.getpw      Warn on uses of the 'getpw' function
  security.insecureAPI.gets       Warn on uses of the 'gets' function
  security.insecureAPI.mkstemp    Warn when 'mkstemp' is passed fewer than 6 X's in the format string
  security.insecureAPI.mktemp     Warn on uses of the 'mktemp' function
  security.insecureAPI.rand       Warn on uses of the 'rand', 'random', and related functions
  security.insecureAPI.strcpy     Warn on uses of the 'strcpy' and 'strcat' functions
  security.insecureAPI.vfork      Warn on uses of the 'vfork' function
  unix.API                        Check calls to various UNIX/Posix functions
  unix.Malloc                     Check for memory leaks, double free, and use-after-free problems. Traces memory managed by malloc()/free().
  unix.MallocSizeof               Check for dubious malloc arguments involving sizeof
  unix.MismatchedDeallocator      Check for mismatched deallocators.
  unix.cstring.BadSizeArg         Check the size argument passed into C string functions for common erroneous patterns
  unix.cstring.NullArg            Check for null pointers being passed as arguments to C string functions

我在上面的答案中提供的长命令行禁用了所有 9 个顶级检查器: 基于以下 cmets 的 alpha、core、cplusplus、deadcode、debug、llvm、osx、security 和 unix PLUS“insecureAPI”,因为似乎禁用安全性并不会禁用 security.insecureAPI。

希望这相当于根本不运行分析器。

有关更多信息,请参阅此处的 Checker 开发人员手册:http://clang-analyzer.llvm.org/checker_dev_manual.html

【讨论】:

  • 它确实解决了我的问题。似乎有点令人费解,我同意这绝对看起来像一个 Clang 错误(我怀疑它已经存在了一段时间)。谢谢!
  • 有趣(可以这么说,这实际上是一个无赖):正如所说,它确实适用于所有人......但有一个例外:我有一个关于使用 random() 的静态分析器警告而不是通过此方法过滤掉的 arc4random()。
  • 看起来禁用 security.insecureAPI.rand 完全无效。
  • 很奇怪。也许这是静态分析器中的错误或上述层次结构输出中的错误。无论如何禁用“insecureAPI.rand”或只是“insecureAPI”似乎抓住了这个。作为参考,这里有一些在分析器中设置命名空间的代码:llvm.org/svn/llvm-project/cfe/trunk/lib/StaticAnalyzer/Checkers/…
  • 我的项目在升级到 Xcode 6,Beta 6 后突然出现这两个错误。解决方法对我不起作用。将sqlite3 编译为静态库时,该问题很容易重现。所以我把它打包并提交到 Apple 的 Bug Reporter,18115632。对于任何有兴趣的人,我也posted the bug and link to demo project on Open Radar
【解决方案2】:

在“-w -Xanalyzer -analyzer-disable-checker”之后为构建阶段的相应文件添加编译器标志“-Xanalyzer deadcode”,如果似乎可以解决问题。

【讨论】:

    【解决方案3】:

    顺便说一句。我最后定义了我的 PCH 文件,我遇到了可能的消息。 这是我的解决方法,非常简单。

    #define reuse pch library from non exec lib
    add_library(globalPch  my_pch.hpp my_pch.cpp)
    set_target_properties(globalPch PROPERTIES LINKER_LANGUAGE CXX)
    target_precompile_headers(globalPch PRIVATE my_pch.hpp)
    TARGET_LINK_LIBRARIES(globalPch ${Boost_LIBRARIES} )
    
    
    #define reuse pch library from  exec lib
    add_executable(globalPch_exec  my_pch.hpp my_pch_exec.cpp)
    set_target_properties(globalPch_exec PROPERTIES LINKER_LANGUAGE CXX)
    target_precompile_headers(globalPch_exec PRIVATE my_pch.hpp)
    TARGET_LINK_LIBRARIES(globalPch_exec ${Boost_LIBRARIES})
    

    my_pch_exec.cpp 是一个简单的主函数:

    #include "main.hpp"
    int main() {
        return 0;
    }
    

    如果您的库被定义为 add_executable,请使用 globalPch_exec。

    add_library(rps_entry rest_entry.cpp rest_entry.hpp)
    target_precompile_headers(rps_entry REUSE_FROM globalPch)
    

    如果您的库被定义为 add_library,请使用 globalPch。例如:

    add_library(rps_entry rest_entry.cpp rest_entry.hpp)
    target_precompile_headers(rps_entry REUSE_FROM globalPch)
    

    最后,它现在可以工作了。编译速度更快。

    【讨论】:

      猜你喜欢
      • 2021-01-07
      • 2014-04-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-21
      • 1970-01-01
      • 2011-12-01
      相关资源
      最近更新 更多