Is it possible to suppress Xcode 4 static analyzer

2019-01-13 03:47发布

问题:

The Xcode 4 static analyzer reports in my code some false positives. Is there any way to suppress them?

回答1:

I found a solution: false positives (like the Apple singleton design pattern) can be avoided with:

#ifndef __clang_analyzer__

// Code not to be analyzed

#endif

Analyzer will not analyze the code between those preprocessor directives.



回答2:

Take a look at this page which shows how to use several #defines to annotate objective-c methods and parameters to help the static analyzer (clang) do the right thing

http://clang-analyzer.llvm.org/annotations.html

From that page:

The Clang frontend supports several source-level annotations in the form of GCC-style attributes and pragmas that can help make using the Clang Static Analyzer more useful. These annotations can both help suppress false positives as well as enhance the analyzer's ability to find bugs.



回答3:

See my answer here. You can add a compile flag to the files and static analyzer will ignore them. This is probably better for 3rd party code you aren't concerned about, and not for first party code you are writing.



回答4:

most of the time, using things like CF_RETURNS_RETAINED and following the 'create' rule works for me, but I ran into a case I could NOT suppress. Finally found a way to suppress the analyzer by looking at llvm source code:

https://llvm.org/svn/llvm-project/cfe/trunk/test/ARCMT/objcmt-arc-cf-annotations.m.result

"Test to see if we suppress an error when we store the pointer to a global."

static CGLayerRef sSuppressStaticAnalyzer;
static CGLayerRef sDmxImg[2][2][1000]; // a cache of quartz drawings.
CGLayerRef CachedDmxImg(...) // which lives for lifetime of app!
{
    ...

    CGLayerRef img = sDmxImg[isDefault][leadingZeroes][dmxVal];
    if ( !img )
    {
        NSRect imgRect = <some cool rectangle>;

        [NSGraphicsContext saveGraphicsState];
        CGContextRef ctx = (CGContextRef)[[NSGraphicsContext currentContext] graphicsPort];
        CGLayerRef cgLayerRef = CGLayerCreateWithContext(ctx, imgRect.size, NULL);
        CGContextRef layerCtx = CGLayerGetContext(cgLayerRef);
        [NSGraphicsContext setCurrentContext: [NSGraphicsContext graphicsContextWithGraphicsPort:layerCtx flipped:YES]];

        ... draw some gorgeous expensive Quartz stuff ...

        img = cgLayerRef;
        sDmxImg[isDefault][leadingZeroes][dmxVal] = cgLayerRef;
        sSuppressStaticAnalyzer = cgLayerRef; // suppress static analyzer warning!
        [NSGraphicsContext restoreGraphicsState];
   }
   return img;
}

For some reason, assigning to a static array didn't suppress the warning, but assigning to a plain old static 'sSuppressStaticAnalyzer' does. By the way the above method, using CGLayerRef is the fastest way I've found to redraw cached images (besides OpenGL).