2013-11-08 3 views
10

Мы автоматизировали сборку нашего текущего проекта с помощью TeamCity/Command Line Tools. Чтобы наверстать как можно больше потенциальных проблем, мы установили, что проект использует статический анализатор для каждой сборки. Несколько классов третьих сторон были помечены анализатором, поэтому мы исключили сомнительные классы помечая их:Проблемы с статическим анализатором с инструментами командной строки

-w -Xanalyzer -analyzer-disable-checker 

Все работает, как ожидалось при компиляции в Xcode (протестировано с 4.6.3 и 5.0.1).

Но при компиляции на сервере TeamCity, мы получаем следующую ошибку для каждого исключенного файла третьей стороной:

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

ошибка исчезнет, ​​если мы удалим -Xanalyzer -analyzer-отключить корректор (но, конечно, в этом случае мы получаем предупреждения анализатора).

Такая же ошибка возникает, если мы скомпилируем с помощью AppCode, что заставляет меня думать, что это как-то связано с инструментами командной строки, как с AppCode, так и с сервером TeamCity, использующим их для компиляции сборок.

Сервер TeamCity использует инструменты командной строки Xcode 4, и я пробовал AppCode с Xcode 4 и 5.

При попытке с AppCode с помощью инструментов командной строки Xcode 5 в погрешность немного отличается (опять же, один для каждого исключенного класса):

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

Итак, вопрос: есть ли какие-либо идеи, как избавиться этой ошибки при подавлении предупреждений анализатора для определенных классов при использовании инструментов командной строки (если инструменты командной строки действительно виноваты здесь)?

+0

Можете ли вы сравнить команду, отправленную с помощью Team City, той, которую производит Xcode, когда она работает? Вы должны уметь видеть все опции, которые поставляется Xcode. – user1118321

+0

На самом деле, я пропустил тот факт, что Xcode фактически отображал ошибку для этих исключенных файлов: «Analyzer пропустил этот файл из-за ошибок синтаксического анализа» (было видно только во всех сообщениях). Так что, в конце концов, Xcode, похоже, не так хорошо справляется с этим. Я все еще не понимаю, почему (и является ли это ожидаемым поведением при использовании -Xanalyzer -analyzer-disable-checker) – gillesguillemin

ответ

15

Я просто столкнулся с этой проблемой и предположил, что это ошибка с Кланом. Я думаю, что нашел обходной путь.

Попробуйте заменить эту

-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 имеет иерархию «Static Analyzer Checkers», и вы можете отключить их по отдельности или по группе.

В качестве примера средство проверки DeadStore является «мертвым кодом».DeadStores», так что вы можете отключить его, как это:

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

В качестве альтернативы вы можете отключить все Deadcode связанные с шашками, указав только„Deadcode“, как это:

-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 шашек верхнего уровня: alpha, core, cplusplus, deadcode, debug, llvm, osx, security и unix PLUS "insecureAPI" на основе комментариев ниже кажется, что отключение защиты также не отключает security.insecureAPI.

Надеюсь, это эквивалентно отсутствию анализатора.

Для получения дополнительной информации смотрите Руководство разработчика Checker здесь: http://clang-analyzer.llvm.org/checker_dev_manual.html

+0

Это действительно решает мою проблему. Кажется немного запутанным, и я согласен, что это определенно похоже на ошибку Clang (и я подозреваю, что это было там некоторое время). Благодаря! – gillesguillemin

+0

Интересно (так сказать, на самом деле это облом): как сказано, он работает для всех ... но за одним исключением: у меня есть предупреждение статического анализатора об использовании random() вместо arc4random(), которое не отфильтрованы этим методом. – gillesguillemin

+0

Похоже, что отключить security.insecureAPI.rand совершенно неэффективно. – gillesguillemin

0

Добавление флаг компилятора «-Xanalyzer Deadcode» после «-w -Xanalyzer -analyzer отключения из-корректора» для соответствующего файла на этапе сборки, если похоже, устраняет проблему.

Смежные вопросы