1.Available Checkers

The analyzer performs checks that are categorized into families or “checkers”.

The default set of checkers covers a variety of checks targeted at finding security and API usage bugs,dead code, and other logic errors. See theDefault Checkers checkers list below.

In addition to these, the analyzer contains a number ofExperimental Checkers (akaalpha checkers).These checkers are under development and are switched off by default. They may crash or emit a higher number of false positives.

Thedebug package contains checkers for analyzer developers for debugging purposes.

1.1.Default Checkers

1.1.1.core

Models core language features and contains general-purpose checkers such as division by zero,null pointer dereference, usage of uninitialized values, etc.These checkers must be always switched on as other checker rely on them.

1.1.1.1.core.BitwiseShift (C, C++)

Finds undefined behavior caused by the bitwise left- and right-shift operatoroperating on integer types.

By default, this checker only reports situations when the right operand iseither negative or larger than the bit width of the type of the left operand;these are logically unsound.

Moreover, if the pedantic mode is activated by-analyzer-configcore.BitwiseShift:Pedantic=true, then this checker alsoreports situations where the _left_ operand of a shift operator is negative oroverflow occurs during the right shift of a signed value. (Most compilershandle these predictably, but the C standard and the C++ standards before C++20say that they’re undefined behavior. In the C++20 standard these constructs arewell-defined, so activating pedantic mode in C++20 has no effect.)

Examples

static_assert(sizeof(int)==4,"assuming 32-bit int")voidbasic_examples(inta,intb){if(b<0){b=a<<b;// warn: right operand is negative in left shift}elseif(b>=32){b=a>>b;// warn: right shift overflows the capacity of 'int'}}intpedantic_examples(inta,intb){if(a<0){returna>>b;// warn: left operand is negative in right shift}a=1000u<<31;// OK, overflow of unsigned value is well-defined, a == 0if(b>10){a=b<<31;// this is undefined before C++20, but the checker doesn't// warn because it doesn't know the exact value of b}return1000<<31;// warn: this overflows the capacity of 'int'}

Solution

Ensure the shift operands are in proper range before shifting.

1.1.1.2.core.CallAndMessage (C, C++, ObjC)

Check for logical errors for function calls and Objective-C message expressions (e.g., uninitialized arguments, null function pointers).

//Cvoidtest(){void(*foo)(void);foo=0;foo();// warn: function pointer is null}// C++classC{public:voidf();};voidtest(){C*pc;pc->f();// warn: object pointer is uninitialized}// C++classC{public:voidf();};voidtest(){C*pc=0;pc->f();// warn: object pointer is null}// Objective-C@interfaceMyClass :NSObject@property(readwrite,assign)idx;-(longdouble)longDoubleM;@endvoidtest(){MyClass*obj1;longdoubleld1=[obj1longDoubleM];// warn: receiver is uninitialized}// Objective-C@interfaceMyClass :NSObject@property(readwrite,assign)idx;-(longdouble)longDoubleM;@endvoidtest(){MyClass*obj1;idi=obj1.x;// warn: uninitialized object pointer}// Objective-C@interfaceSubscriptable :NSObject-(id)objectAtIndexedSubscript:(unsignedint)index;@end@interfaceMyClass :Subscriptable@property(readwrite,assign)idx;-(longdouble)longDoubleM;@endvoidtest(){MyClass*obj1;idi=obj1[0];// warn: uninitialized object pointer}

1.1.1.3.core.DivideZero (C, C++, ObjC)

Check for division by zero.

voidtest(intz){if(z==0)intx=1/z;// warn}voidtest(){intx=1;inty=x%0;// warn}

1.1.1.4.core.FixedAddressDereference (C, C++, ObjC)

Check for dereferences of fixed addresses.

A pointer contains a fixed address if it was set to a hard-coded value or itbecomes otherwise obvious that at that point it can have only a single fixednumerical value.

voidtest1(){int*p=(int*)0x020;intx=p[0];// warn}voidtest2(int*p){if(p==(int*)-1)*p=0;// warn}voidtest3(){int(*p_function)(char,char);p_function=(int(*)(char,char))0x04080;intx=(*p_function)('x','y');// NO warning yet at functon pointer calls}

If the analyzer optionsuppress-dereferences-from-any-address-space is setto true (the default value), then this checker never reports dereference ofpointers with a specified address space. If the option is set to false, thenreports from the specific x86 address spaces 256, 257 and 258 are stillsuppressed, but fixed address dereferences from other address spaces arereported.

1.1.1.5.core.NonNullParamChecker (C, C++, ObjC)

Check for null pointers passed as arguments to a function whose arguments are references or marked with the ‘nonnull’ attribute.

intf(int*p)__attribute__((nonnull));voidtest(int*p){if(!p)f(p);// warn}

1.1.1.6.core.NullDereference (C, C++, ObjC)

Check for dereferences of null pointers.

// Cvoidtest(int*p){if(p)return;intx=p[0];// warn}// Cvoidtest(int*p){if(!p)*p=0;// warn}// C++classC{public:intx;};voidtest(){C*pc=0;intk=pc->x;// warn}// Objective-C@interfaceMyClass{@publicintx;}@endvoidtest(){MyClass*obj=0;obj->x=1;// warn}

Null pointer dereferences of pointers with address spaces are not always definedas error. Specifically on x86/x86-64 target if the pointer address space is256 (x86 GS Segment), 257 (x86 FS Segment), or 258 (x86 SS Segment), a nulldereference is not defined as error. SeeX86/X86-64 Language Extensionsfor reference.

If the analyzer optionsuppress-dereferences-from-any-address-space is setto true (the default value), then this checker never reports dereference ofpointers with a specified address space. If the option is set to false, thenreports from the specific x86 address spaces 256, 257 and 258 are stillsuppressed, but null dereferences from other address spaces are reported.

1.1.1.7.core.NullPointerArithm (C, C++)

Check for undefined arithmetic operations with null pointers.

The checker can detect the following cases:

  • p+x andx+p wherep is a null pointer andx is a nonzerointeger value.

  • p-x wherep is a null pointer andx is a nonzero integervalue.

  • p1-p2 where one ofp1 andp2 is null and the other anon-null pointer.

Result of these operations is undefined according to the standard.In the above listed cases, the checker will warn even if the expressiondescribed to be “nonzero” or “non-null” has unknown value, because it is likelythat it can have non-zero value during the program execution.

voidtest1(int*p,intoffset){if(p)return;int*p1=p+offset;// warn: 'p' is null, 'offset' is unknown but likely non-zero}voidtest2(int*p,intoffset){if(p){}// this indicates that it is possible for 'p' to be nullif(offset==0)return;int*p1=p-offset;// warn: 'p' is null, 'offset' is known to be non-zero}voidtest3(char*p1,char*p2){if(p1)return;inta=p1-p2;// warn: 'p1' is null, 'p2' can be likely non-null}

1.1.1.8.core.StackAddressEscape (C)

Check that addresses to stack memory do not escape the function.

charconst*p;voidtest(){charconststr[]="string";p=str;// warn}void*test(){return__builtin_alloca(12);// warn}voidtest(){staticint*x;inty;x=&y;// warn}

1.1.1.9.core.UndefinedBinaryOperatorResult (C)

Check for undefined results of binary operators.

voidtest(){intx;inty=x+1;// warn: left operand is garbage}

1.1.1.10.core.VLASize (C)

Check for declarations of Variable Length Arrays (VLA) of undefined, zero or negativesize.

voidtest(){intx;intvla1[x];// warn: garbage as size}voidtest(){intx=0;intvla2[x];// warn: zero size}

The checker also gives warning if theTaintPropagation checker is switched onand an unbound, attacker controlled (tainted) value is used to definethe size of the VLA.

voidtaintedVLA(void){intx;scanf("%d",&x);intvla[x];// Declared variable-length array (VLA) has tainted (attacker controlled) size, that can be 0 or negative}voidtaintedVerfieidVLA(void){intx;scanf("%d",&x);if(x<1)return;intvla[x];// no-warning. The analyzer can prove that x must be positive.}

1.1.1.11.core.uninitialized.ArraySubscript (C)

Check for uninitialized values used as array subscripts.

voidtest(){inti,a[10];intx=a[i];// warn: array subscript is undefined}

1.1.1.12.core.uninitialized.Assign (C)

Check for assigning uninitialized values.

voidtest(){intx;x|=1;// warn: left expression is uninitialized}

1.1.1.13.core.uninitialized.Branch (C)

Check for uninitialized values used as branch conditions.

voidtest(){intx;if(x)// warnreturn;}

1.1.1.14.core.uninitialized.CapturedBlockVariable (C)

Check for blocks that capture uninitialized values.

voidtest(){intx;^{inty=x;}();// warn}

1.1.1.15.core.uninitialized.UndefReturn (C)

Check for uninitialized values being returned to the caller.

inttest(){intx;returnx;// warn}

1.1.1.16.core.uninitialized.NewArraySize (C++)

Check if the element count in new[] is garbage or undefined.

voidtest(){intn;int*arr=newint[n];// warn: Element count in new[] is a garbage valuedelete[]arr;}

1.1.2.cplusplus

C++ Checkers.

1.1.2.1.cplusplus.ArrayDelete (C++)

Reports destructions of arrays of polymorphic objects that are destructed astheir base class. If the dynamic type of the array is different from its statictype, callingdelete[] is undefined.

This checker corresponds to the SEI CERT ruleEXP51-CPP: Do not delete an array through a pointer of the incorrect type.

classBase{public:virtual~Base(){}};classDerived:publicBase{};Base*create(){Base*x=newDerived[10];// note: Casting from 'Derived' to 'Base' herereturnx;}voidfoo(){Base*x=create();delete[]x;// warn: Deleting an array of 'Derived' objects as their base class 'Base' is undefined}

Limitations

The checker does not emit note tags when casting to and from reference types,even though the pointer values are tracked across references.

voidfoo(){Derived*d=newDerived[10];Derived&dref=*d;Base&bref=static_cast<Base&>(dref);// no noteBase*b=&bref;delete[]b;// warn: Deleting an array of 'Derived' objects as their base class 'Base' is undefined}

1.1.2.2.cplusplus.InnerPointer (C++)

Check for inner pointers of C++ containers used after re/deallocation.

Many container methods in the C++ standard library are known to invalidate“references” (including actual references, iterators and raw pointers) toelements of the container. Using such references after they are invalidatedcauses undefined behavior, which is a common source of memory errors in C++ thatthis checker is capable of finding.

The checker is currently limited tostd::string objects and doesn’trecognize some of the more sophisticated approaches to passing unowned pointersaround, such asstd::string_view.

voidderef_after_assignment(){std::strings="llvm";constchar*c=s.data();// note: pointer to inner buffer of 'std::string' obtained heres="clang";// note: inner buffer of 'std::string' reallocated by call to 'operator='consume(c);// warn: inner pointer of container used after re/deallocation}constchar*return_temp(intx){returnstd::to_string(x).c_str();// warn: inner pointer of container used after re/deallocation// note: pointer to inner buffer of 'std::string' obtained here// note: inner buffer of 'std::string' deallocated by call to destructor}

1.1.2.3.cplusplus.Move (C++)

Find use-after-move bugs in C++. This includes method calls on moved-fromobjects, assignment of a moved-from object, and repeated move of a moved-fromobject.

structA{voidfoo(){}};voidf1(){Aa;Ab=std::move(a);// note: 'a' became 'moved-from' herea.foo();// warn: method call on a 'moved-from' object 'a'}voidf2(){Aa;Ab=std::move(a);Ac(std::move(a));// warn: move of an already moved-from object}voidf3(){Aa;Ab=std::move(a);b=a;// warn: copy of moved-from object}

The checker optionWarnOn controls on what objects the use-after-move ischecked:

  • The most strict value isKnownsOnly, in this mode only objects arechecked whose type is known to be move-unsafe. These include most STL objects(but excluding move-safe ones) and smart pointers.

  • With option valueKnownsAndLocals local variables (of any type) areadditionally checked. The idea behind this is that local variables areusually not tempting to be re-used so an use after move is more likely a bugthan with member variables.

  • With option valueAll any use-after move condition is checked on allkinds of variables, excluding global variables and known move-safe cases.

Default value isKnownsAndLocals.

Calls of methods namedempty() orisEmpty() are allowed on moved-fromobjects because these methods are considered as move-safe. Functions calledreset(),destroy(),clear(),assign,resize,shrink aretreated as state-reset functions and are allowed on moved-from objects, thesemake the object valid again. This applies to any type of object (not only STLones).

1.1.2.4.cplusplus.NewDelete (C++)

Check for double-free and use-after-free problems. Traces memory managed by new/delete.

Custom allocation/deallocation functions can be defined usingownership attributes.

voidf(int*p);voidtestUseMiddleArgAfterDelete(int*p){deletep;f(p);// warn: use after free}classSomeClass{public:voidf();};voidtest(){SomeClass*c=newSomeClass;deletec;c->f();// warn: use after free}voidtest(){int*p=(int*)__builtin_alloca(sizeof(int));deletep;// warn: deleting memory allocated by alloca}voidtest(){int*p=newint;deletep;deletep;// warn: attempt to free released}voidtest(){inti;delete&i;// warn: delete address of local}voidtest(){int*p=newint[1];delete[](++p);// warn: argument to 'delete[]' is offset by 4 bytes// from the start of memory allocated by 'new[]'}

1.1.2.5.cplusplus.NewDeleteLeaks (C++)

Check for memory leaks. Traces memory managed by new/delete.

Custom allocation/deallocation functions can be defined usingownership attributes.

voidtest(){int*p=newint;}// warn

1.1.2.6.cplusplus.PlacementNew (C++)

Check if default placement new is provided with pointers to sufficient storage capacity.

#include<new>voidf(){shorts;long*lp=::new(&s)long;// warn}

1.1.2.7.cplusplus.SelfAssignment (C++)

Checks C++ copy and move assignment operators for self assignment.

1.1.2.8.cplusplus.StringChecker (C++)

Checks std::string operations.

Checks if the cstring pointer from which thestd::string object isconstructed isNULL or not.If the checker cannot reason about the nullness of the pointer it will assumethat it was non-null to satisfy the precondition of the constructor.

This checker is capable of checking theSEI CERT C++ coding rule STR51-CPP.Do not attempt to create a std::string from a null pointer.

#include<string>voidf(constchar*p){if(!p){std::stringmsg(p);// warn: The parameter must not be null}}

1.1.2.9.cplusplus.PureVirtualCall (C++)

Whenvirtual methods are called during construction and destructionthe polymorphism is restricted to the class that’s being constructed ordestructed because the more derived contexts are either not yet initialized oralready destructed.

This checker reports situations where this restricted polymorphism causes acall to a pure virtual method, which is undefined behavior. (See also therelated checkeroptin.cplusplus.VirtualCall (C++) which reports situationswhere the restricted polymorphism affects a call and the called method is notpure virtual – but may be still surprising for the programmer.)

structA{virtualintgetKind()=0;A(){// warn: This calls the pure virtual method A::getKind().log<<"Constructing "<<getKind();}virtual~A(){releaseResources();}voidreleaseResources(){// warn: This can call the pure virtual method A::getKind() when this is// called from the destructor.callSomeFunction(getKind());}};

1.1.3.deadcode

Dead Code Checkers.

1.1.3.1.deadcode.DeadStores (C)

Check for values stored to variables that are never read afterwards.

voidtest(){intx;x=1;// warn}

TheWarnForDeadNestedAssignments option enables the checker to emitwarnings for nested dead assignments. You can disable with the-analyzer-configdeadcode.DeadStores:WarnForDeadNestedAssignments=false.Defaults to true.

Would warn for this e.g.:if ((y = make_int())) {}

1.1.4.nullability

Checkers (mostly Objective C) that warn for null pointer passing and dereferencing errors.

1.1.4.1.nullability.NullPassedToNonnull (ObjC)

Warns when a null pointer is passed to a pointer which has a _Nonnull type.

if(name!=nil)return;// Warning: nil passed to a callee that requires a non-null 1st parameterNSString*greeting=[@"Hello "stringByAppendingString:name];

1.1.4.2.nullability.NullReturnedFromNonnull (C, C++, ObjC)

Warns when a null pointer is returned from a function that has _Nonnull return type.

-(nonnullid)firstChild{idresult=nil;if([_childrencount]>0)result=_children[0];// Warning: nil returned from a method that is expected// to return a non-null valuereturnresult;}

Warns when a null pointer is returned from a function annotated with__attribute__((returns_nonnull))

intglobal;__attribute__((returns_nonnull))void*getPtr(void*p);void*getPtr(void*p){if(p){// forgot to negate the conditionreturn&global;}// Warning: nullptr returned from a function that is expected// to return a non-null valuereturnp;}

1.1.4.3.nullability.NullableDereferenced (ObjC)

Warns when a nullable pointer is dereferenced.

structLinkedList{intdata;structLinkedList*next;};structLinkedList*_NullablegetNext(structLinkedList*l);voidupdateNextData(structLinkedList*list,intnewData){structLinkedList*next=getNext(list);// Warning: Nullable pointer is dereferencednext->data=7;}

1.1.4.4.nullability.NullablePassedToNonnull (ObjC)

Warns when a nullable pointer is passed to a pointer which has a _Nonnull type.

typedefstructDummy{intval;}Dummy;Dummy*_NullablereturnsNullable();voidtakesNonnull(Dummy*_Nonnull);voidtest(){Dummy*p=returnsNullable();takesNonnull(p);// warn}

1.1.4.5.nullability.NullableReturnedFromNonnull (ObjC)

Warns when a nullable pointer is returned from a function that has _Nonnull return type.

1.1.5.optin

Checkers for portability, performance, optional security and coding style specific rules.

1.1.5.1.optin.core.EnumCastOutOfRange (C, C++)

Check for integer to enumeration casts that would produce a value with nocorresponding enumerator. This is not necessarily undefined behavior, but canlead to nasty surprises, so projects may decide to use a coding standard thatdisallows these “unusual” conversions.

Note that no warnings are produced when the enum type (e.g.std::byte) has noenumerators at all.

enumWidgetKind{A=1,B,C,X=99};voidfoo(){WidgetKindc=static_cast<WidgetKind>(3);// OKWidgetKindx=static_cast<WidgetKind>(99);// OKWidgetKindd=static_cast<WidgetKind>(4);// warn}

Limitations

This checker does not accept the coding pattern where an enum type is used tostore combinations of flag values.Such enums should be annotated with the__attribute__((flag_enum)) or by the[[clang::flag_enum]] attribute to signal this intent. Refer to thedocumentationof this Clang attribute.

enumAnimalFlags{HasClaws=1,CanFly=2,EatsFish=4,Endangered=8};AnimalFlagsoperator|(AnimalFlagsa,AnimalFlagsb){returnstatic_cast<AnimalFlags>(static_cast<int>(a)|static_cast<int>(b));}autoflags=HasClaws|CanFly;

Projects that use this pattern should not enable this optin checker.

1.1.5.2.optin.cplusplus.UninitializedObject (C++)

This checker reports uninitialized fields in objects created after a constructorcall. It doesn’t only find direct uninitialized fields, but rather makes a deepinspection of the object, analyzing all of its fields’ subfields.The checker regards inherited fields as direct fields, so one will receivewarnings for uninitialized inherited data members as well.

// With Pedantic and CheckPointeeInitialization set to truestructA{structB{intx;// note: uninitialized field 'this->b.x'// note: uninitialized field 'this->bptr->x'inty;// note: uninitialized field 'this->b.y'// note: uninitialized field 'this->bptr->y'};int*iptr;// note: uninitialized pointer 'this->iptr'Bb;B*bptr;char*cptr;// note: uninitialized pointee 'this->cptr'A(B*bptr,char*cptr):bptr(bptr),cptr(cptr){}};voidf(){A::Bb;charc;Aa(&b,&c);// warning: 6 uninitialized fields//          after the constructor call}// With Pedantic set to false and// CheckPointeeInitialization set to true// (every field is uninitialized)structA{structB{intx;inty;};int*iptr;Bb;B*bptr;char*cptr;A(B*bptr,char*cptr):bptr(bptr),cptr(cptr){}};voidf(){A::Bb;charc;Aa(&b,&c);// no warning}// With Pedantic set to true and// CheckPointeeInitialization set to false// (pointees are regarded as initialized)structA{structB{intx;// note: uninitialized field 'this->b.x'inty;// note: uninitialized field 'this->b.y'};int*iptr;// note: uninitialized pointer 'this->iptr'Bb;B*bptr;char*cptr;A(B*bptr,char*cptr):bptr(bptr),cptr(cptr){}};voidf(){A::Bb;charc;Aa(&b,&c);// warning: 3 uninitialized fields//          after the constructor call}

Options

This checker has several options which can be set from command line (e.g.-analyzer-configoptin.cplusplus.UninitializedObject:Pedantic=true):

  • Pedantic (boolean). If to false, the checker won’t emit warnings forobjects that don’t have at least one initialized field. Defaults to false.

  • NotesAsWarnings (boolean). If set to true, the checker will emit awarning for each uninitialized field, as opposed to emitting one warning perconstructor call, and listing the uninitialized fields that belongs to it innotes.Defaults to false.

  • CheckPointeeInitialization (boolean). If set to false, the checker willnot analyze the pointee of pointer/reference fields, and will only checkwhether the object itself is initialized.Defaults to false.

  • IgnoreRecordsWithField (string). If supplied, the checker will not analyzestructures that have a field with a name or type name that matches the givenpattern.Defaults to “”.

1.1.5.3.optin.cplusplus.VirtualCall (C++)

Whenvirtual methods are called during construction and destructionthe polymorphism is restricted to the class that’s being constructed ordestructed because the more derived contexts are either not yet initialized oralready destructed.

Although this behavior is well-defined, it can surprise the programmer andcause unintended behavior, so this checker reports calls that appear to bevirtual calls but can be affected by this restricted polymorphism.

Note that situations where this restricted polymorphism causes a call to a purevirtual method (which is definitely invalid, triggers undefined behavior) arereported by another checker:cplusplus.PureVirtualCall (C++) andthischecker does not report them.

structA{virtualintgetKind();A(){// warn: This calls A::getKind() even if we are constructing an instance// of a different class that is derived from A.log<<"Constructing "<<getKind();}virtual~A(){releaseResources();}voidreleaseResources(){// warn: This can be called within ~A() and calls A::getKind() even if// we are destructing a class that is derived from A.callSomeFunction(getKind());}};

1.1.5.4.optin.mpi.MPI-Checker (C)

Checks MPI code.

voidtest(){doublebuf=0;MPI_RequestsendReq1;MPI_Ireduce(MPI_IN_PLACE,&buf,1,MPI_DOUBLE,MPI_SUM,0,MPI_COMM_WORLD,&sendReq1);}// warn: request 'sendReq1' has no matching wait.voidtest(){doublebuf=0;MPI_RequestsendReq;MPI_Isend(&buf,1,MPI_DOUBLE,0,0,MPI_COMM_WORLD,&sendReq);MPI_Irecv(&buf,1,MPI_DOUBLE,0,0,MPI_COMM_WORLD,&sendReq);// warnMPI_Isend(&buf,1,MPI_DOUBLE,0,0,MPI_COMM_WORLD,&sendReq);// warnMPI_Wait(&sendReq,MPI_STATUS_IGNORE);}voidmissingNonBlocking(){intrank=0;MPI_Comm_rank(MPI_COMM_WORLD,&rank);MPI_RequestsendReq1[10][10][10];MPI_Wait(&sendReq1[1][7][9],MPI_STATUS_IGNORE);// warn}

1.1.5.5.optin.osx.cocoa.localizability.EmptyLocalizationContextChecker (ObjC)

Check that NSLocalizedString macros include a comment for context.

-(void)test{NSString*string=NSLocalizedString(@"LocalizedString",nil);// warnNSString*string2=NSLocalizedString(@"LocalizedString",@" ");// warnNSString*string3=NSLocalizedStringWithDefaultValue(@"LocalizedString",nil,[[NSBundlealloc]init],nil,@"");// warn}

1.1.5.6.optin.osx.cocoa.localizability.NonLocalizedStringChecker (ObjC)

Warns about uses of non-localized NSStrings passed to UI methods expecting localized NSStrings.

NSString*alarmText=NSLocalizedString(@"Enabled",@"Indicates alarm is turned on");if(!isEnabled){alarmText=@"Disabled";}UILabel*alarmStateLabel=[[UILabelalloc]init];// Warning: User-facing text should use localized string macro[alarmStateLabelsetText:alarmText];

1.1.5.7.optin.performance.GCDAntipattern

Check for performance anti-patterns when using Grand Central Dispatch.

1.1.5.8.optin.performance.Padding (C, C++, ObjC)

Check for excessively padded structs.

This checker detects structs with excessive padding, which can lead to wastedmemory thus decreased performance by reducing the effectiveness of theprocessor cache. Padding bytes are added by compilers to align data accessesas some processors require data to be aligned to certain boundaries. On others,unaligned data access are possible, but impose significantly larger latencies.

To avoid padding bytes, the fields of a struct should be ordered by decreasingby alignment. Usually, its easier to think of thesizeof of the fields, andordering the fields bysizeof would usually also lead to the same optimallayout.

In rare cases, one can use the#pragmapack(1) directive to enforce a packedlayout too, but it can significantly increase the access times, so reordering thefields is usually a better solution.

// warn: Excessive padding in 'struct NonOptimal' (35 padding bytes, where 3 is optimal)structNonOptimal{charc1;// 7 bytes of paddingstd::int64_tbig1;// 8 bytescharc2;// 7 bytes of paddingstd::int64_tbig2;// 8 bytescharc3;// 7 bytes of paddingstd::int64_tbig3;// 8 bytescharc4;// 7 bytes of paddingstd::int64_tbig4;// 8 bytescharc5;// 7 bytes of padding};static_assert(sizeof(NonOptimal)==4*8+5+5*7);// no-warning: The fields are nicely aligned to have the minimal amount of padding bytes.structOptimal{std::int64_tbig1;// 8 bytesstd::int64_tbig2;// 8 bytesstd::int64_tbig3;// 8 bytesstd::int64_tbig4;// 8 bytescharc1;charc2;charc3;charc4;charc5;// 3 bytes of padding};static_assert(sizeof(Optimal)==4*8+5+3);// no-warning: Bit packing representation is also accepted by this checker, but// it can significantly increase access times, so prefer reordering the fields.#pragma pack(1)structBitPacked{charc1;std::int64_tbig1;// 8 bytescharc2;std::int64_tbig2;// 8 bytescharc3;std::int64_tbig3;// 8 bytescharc4;std::int64_tbig4;// 8 bytescharc5;};static_assert(sizeof(BitPacked)==4*8+5);

TheAllowedPad option can be used to specify a threshold for the numberpadding bytes raising the warning. If the number of padding bytes of the structand the optimal number of padding bytes differ by more than the threshold value,a warning will be raised.

By default, theAllowedPad threshold is 24 bytes.

To override this threshold to e.g. 4 bytes, use the-analyzer-configoptin.performance.Padding:AllowedPad=4 option.

1.1.5.9.optin.portability.UnixAPI

Reports situations where 0 is passed as the “size” argument of variousallocation functions (calloc,malloc,realloc,reallocf,alloca,__builtin_alloca,__builtin_alloca_with_align,valloc).

Note that similar functionality is also supported byunix.Malloc (C) whichreports code thatuses memory allocated with size zero.

(The name of this checker is motivated by the fact that it was originallyintroduced with the vague goal that it “Finds implementation-defined behaviorin UNIX/Posix functions.”)

1.1.6.optin.taint

Checkers implementingtaint analysis.

1.1.6.1.optin.taint.GenericTaint (C, C++)

Taint analysis identifies potential security vulnerabilities where theattacker can inject malicious data to the program to execute an attack(privilege escalation, command injection, SQL injection etc.).

The malicious data is injected at the taint source (e.g.getenv() call)which is then propagated through function calls and being used as arguments ofsensitive operations, also called as taint sinks (e.g.system() call).

One can defend against this type of vulnerability by always checking andsanitizing the potentially malicious, untrusted user input.

The goal of the checker is to discover and show to the user these potentialtaint source-sink pairs and the propagation call chain.

The most notable examples of taint sources are:

  • data from network

  • files or standard input

  • environment variables

  • data from databases

Let us examine a practical example of a Command Injection attack.

// Command Injection Vulnerability Exampleintmain(intargc,char**argv){charcmd[2048]="/bin/cat ";charfilename[1024];printf("Filename:");scanf(" %1023[^\n]",filename);// The attacker can inject a shell escape herestrcat(cmd,filename);system(cmd);// Warning: Untrusted data is passed to a system call}

The program prints the content of any user specified file.Unfortunately the attacker can execute arbitrary commandswith shell escapes. For example with the following input thels command is alsoexecuted after the contents of/etc/shadow is printed.Input: /etc/shadow ; ls /

The analysis implemented in this checker points out this problem.

One can protect against such attack by for example checking if the providedinput refers to a valid file and removing any invalid user input.

// No vulnerability anymore, but we still get the warningvoidsanitizeFileName(char*filename){if(access(filename,F_OK)){// Verifying user inputprintf("File does not exist\n");filename[0]='\0';}}intmain(intargc,char**argv){charcmd[2048]="/bin/cat ";charfilename[1024];printf("Filename:");scanf(" %1023[^\n]",filename);// The attacker can inject a shell escape heresanitizeFileName(filename);// filename is safe after this pointif(!filename[0])return-1;strcat(cmd,filename);system(cmd);// Superfluous Warning: Untrusted data is passed to a system call}

Unfortunately, the checker cannot discover automatically that the programmerhave performed data sanitation, so it still emits the warning.

One can get rid of this superfluous warning by telling by specifying thesanitation functions in the taint configuration file (seeTaint Analysis Configuration).

Filters:-Name:sanitizeFileNameArgs:[0]

The clang invocation to pass the configuration file location:

clang--analyze-Xclang-analyzer-config-Xclangoptin.taint.TaintPropagation:Config=`pwd`/taint_config.yml...

If you are validating your inputs instead of sanitizing them, or don’t want tomention each sanitizing function in our configuration,you can use a more generic approach.

Introduce a generic no-opcsa_mark_sanitized(..) function totell the Clang Static Analyzerthat the variable is safe to be used on that analysis path.

// Marking sanitized variables safe.// No vulnerability anymore, no warning.// User csa_mark_sanitize function is for the analyzer only#ifdef __clang_analyzer__voidcsa_mark_sanitized(constvoid*);#endifintmain(intargc,char**argv){charcmd[2048]="/bin/cat ";charfilename[1024];printf("Filename:");scanf(" %1023[^\n]",filename);if(access(filename,F_OK)){// Verifying user inputprintf("File does not exist\n");return-1;}#ifdef __clang_analyzer__csa_mark_sanitized(filename);// Indicating to CSA that filename variable is safe to be used after this point#endifstrcat(cmd,filename);system(cmd);// No warning}

Similarly to the previous example, you need todefine aFilter function in aYAML configuration fileand add thecsa_mark_sanitized function.

Filters:-Name:csa_mark_sanitizedArgs:[0]

Then callingcsa_mark_sanitized(X) will tell the analyzer thatX is safe tobe used after this point, because its contents are verified. It is theresponsibility of the programmer to ensure that this verification was indeedcorrect. Please note thatcsa_mark_sanitized function is only declared andused during Clang Static Analysis and skipped in (production) builds.

Further examples of injection vulnerabilities this checker can find.

voidtest(){charx=getchar();// 'x' marked as taintedsystem(&x);// warn: untrusted data is passed to a system call}// note: compiler internally checks if the second param to// sprintf is a string literal or not.// Use -Wno-format-security to suppress compiler warning.voidtest(){chars[10],buf[10];fscanf(stdin,"%s",s);// 's' marked as taintedsprintf(buf,s);// warn: untrusted data used as a format string}

There are built-in sources, propagations and sinks even if no external taintconfiguration is provided.

Default sources:

_IO_getc,fdopen,fopen,freopen,get_current_dir_name,getch,getchar,getchar_unlocked,getwd,getcwd,getgroups,gethostname,getlogin,getlogin_r,getnameinfo,gets,gets_s,getseuserbyname,readlink,readlinkat,scanf,scanf_s,socket,wgetch

Default propagations rules:

atoi,atol,atoll,basename,dirname,fgetc,fgetln,fgets,fnmatch,fread,fscanf,fscanf_s,index,inflate,isalnum,isalpha,isascii,isblank,iscntrl,isdigit,isgraph,islower,isprint,ispunct,isspace,isupper,isxdigit,memchr,memrchr,sscanf,getc,getc_unlocked,getdelim,getline,getw,memcmp,memcpy,memmem,memmove,mbtowc,pread,qsort,qsort_r,rawmemchr,read,recv,recvfrom,rindex,strcasestr,strchr,strchrnul,strcasecmp,strcmp,strcspn,strncasecmp,strncmp,strndup,strndupa,strpbrk,strrchr,strsep,strspn,strstr,strtol,strtoll,strtoul,strtoull,tolower,toupper,ttyname,ttyname_r,wctomb,wcwidth

Default sinks:

printf,setproctitle,system,popen,execl,execle,execlp,execv,execvp,execvP,execve,dlopen

Please note that there are no built-in filter functions.

One can configure their own taint sources, sinks, and propagation rules byproviding a configuration file via checker optionoptin.taint.TaintPropagation:Config. The configuration file is inYAML format. Thetaint-related options defined in the config file extend but do not override thebuilt-in sources, rules, sinks. The format of the external taint configurationfile is not stable, and could change without any notice even in a non-backwardcompatible way.

For a more detailed description of configuration options, please see theTaint Analysis Configuration. For an example seeExample configuration file.

Configuration

  • Config Specifies the name of the YAML configuration file. The user candefine their own taint sources and sinks.

Related Guidelines

Limitations

  • The taintedness property is not propagated through function calls which areunknown (or too complex) to the analyzer, unless there is a specificpropagation rule built-in to the checker or given in the YAML configurationfile. This causes potential true positive findings to be lost.

1.1.6.2.optin.taint.TaintedAlloc (C, C++)

This checker warns for cases when thesize parameter of themalloc ,calloc,realloc,alloca or the size parameter of thearray new C++ operator is tainted (potentially attacker controlled).If an attacker can inject a large value as the size parameter, memory exhaustiondenial of service attack can be carried out.

The analyzer emits warning only if it cannot prove that the size parameter iswithin reasonable bounds (<=SIZE_MAX/4). This functionality partiallycovers the SEI Cert coding standard ruleINT04-C.

You can silence this warning either by bound checking thesize parameter, orby explicitly marking thesize parameter as sanitized. See theoptin.taint.GenericTaint (C, C++) checker for an example.

Custom allocation/deallocation functions can be defined usingownership attributes.

voidvulnerable(void){size_tsize=0;scanf("%zu",&size);int*p=malloc(size);// warn: malloc is called with a tainted (potentially attacker controlled) valuefree(p);}voidnot_vulnerable(void){size_tsize=0;scanf("%zu",&size);if(1024<size)return;int*p=malloc(size);// No warning expected as the the user input is boundfree(p);}voidvulnerable_cpp(void){size_tsize=0;scanf("%zu",&size);int*ptr=newint[size];// warn: Memory allocation function is called with a tainted (potentially attacker controlled) valuedelete[]ptr;}

1.1.6.3.optin.taint.TaintedDiv (C, C++, ObjC)

This checker warns when the denominator in a divisionoperation is a tainted (potentially attacker controlled) value.If the attacker can set the denominator to 0, a runtime error canbe triggered. The checker warns when the denominator is a taintedvalue and the analyzer cannot prove that it is not 0. This warningis more pessimistic than thecore.DivideZero (C, C++, ObjC) checkerwhich warns only when it can prove that the denominator is 0.

intvulnerable(intn){size_tsize=0;scanf("%zu",&size);returnn/size;// warn: Division by a tainted value, possibly zero}intnot_vulnerable(intn){size_tsize=0;scanf("%zu",&size);if(!size)return0;returnn/size;// no warning}

1.1.7.security

Security related checkers.

1.1.7.1.security.ArrayBound (C, C++)

Report out of bounds access to memory that is before the start or after the endof the accessed region (array, heap-allocated region, string literal etc.).This usually means incorrect indexing, but the checker also detects access viathe operators* and->.

voidtest_underflow(intx){intbuf[100][100];if(x<0)buf[0][x]=1;// warn}voidtest_overflow(){intbuf[100];int*p=buf+100;*p=1;// warn}

If checkers likeunix.Malloc (C) orcplusplus.NewDelete (C++) are enabledto model the behavior ofmalloc(),operatornew and similarallocators), then this checker can also reports out of bounds access todynamically allocated memory:

int*test_dynamic(){int*mem=newint[100];mem[-1]=42;// warnreturnmem;}

In uncertain situations (when the checker can neither prove nor disprove thatoverflow occurs), the checker assumes that the the index (more precisely, thememory offeset) is within bounds.

However, ifoptin.taint.GenericTaint (C, C++) is enabled and the index/offset istainted (i.e. it is influenced by an untrusted source), then this checkerreports the potential out of bounds access:

voidtest_with_tainted_index(){chars[]="abc";intx=getchar();charc=s[x];// warn: potential out of bounds access with tainted index}

Note

This checker is an improved and renamed version of the checker that waspreviously known asalpha.security.ArrayBoundV2. The old checkeralpha.security.ArrayBound was removed when the (previously“experimental”) V2 variant became stable enough for regular use.

1.1.7.2.security.cert.env.InvalidPtr

Corresponds to SEI CERT RulesENV31-C andENV34-C.

  • ENV31-C:Rule is about the possible problem withmain function’s third argument, environment pointer,“envp”. When environment array is modified using some modification functionsuch asputenv,setenv or others, It may happen that memory is reallocated,however “envp” is not updated to reflect the changes and points to old memoryregion.

  • ENV34-C:Some functions return a pointer to a statically allocated buffer.Consequently, subsequent call of these functions will invalidate previouspointer. These functions include:getenv,localeconv,asctime,setlocale,strerror

intmain(intargc,constchar*argv[],constchar*envp[]){if(setenv("MY_NEW_VAR","new_value",1)!=0){// setenv call may invalidate 'envp'/* Handle error */}if(envp!=NULL){for(size_ti=0;envp[i]!=NULL;++i){puts(envp[i]);// envp may no longer point to the current environment// this program has unanticipated behavior, since envp// does not reflect changes made by setenv function.}}return0;}voidprevious_call_invalidation(){char*p,*pp;p=getenv("VAR");setenv("SOMEVAR","VALUE",/*overwrite = */1);// call to 'setenv' may invalidate p*p;// dereferencing invalid pointer}

TheInvalidatingGetEnv option is available for treatinggetenv calls asinvalidating. When enabled, the checker issues a warning ifgetenv is calledmultiple times and their results are used without first creating a copy.This level of strictness might be considered overly pedantic for the commonlyusedgetenv implementations.

To enable this option, use:-analyzer-configsecurity.cert.env.InvalidPtr:InvalidatingGetEnv=true.

By default, this option is set tofalse.

When this option is enabled, warnings will be generated for scenarios like thefollowing:

char*p=getenv("VAR");char*pp=getenv("VAR2");// assumes this call can invalidate `env`strlen(p);// warns about accessing invalid ptr

1.1.7.3.security.FloatLoopCounter (C)

Warn on using a floating point value as a loop counter (CERT: FLP30-C, FLP30-CPP).

voidtest(){for(floatx=0.1f;x<=1.0f;x+=0.1f){}// warn}

1.1.7.4.security.insecureAPI.UncheckedReturn (C)

Warn on uses of functions whose return values must be always checked.

voidtest(){setuid(1);// warn}

1.1.7.5.security.insecureAPI.bcmp (C)

Warn on uses of the ‘bcmp’ function.

voidtest(){bcmp(ptr0,ptr1,n);// warn}

1.1.7.6.security.insecureAPI.bcopy (C)

Warn on uses of the ‘bcopy’ function.

voidtest(){bcopy(src,dst,n);// warn}

1.1.7.7.security.insecureAPI.bzero (C)

Warn on uses of the ‘bzero’ function.

voidtest(){bzero(ptr,n);// warn}

1.1.7.8.security.insecureAPI.getpw (C)

Warn on uses of the ‘getpw’ function.

voidtest(){charbuff[1024];getpw(2,buff);// warn}

1.1.7.9.security.insecureAPI.gets (C)

Warn on uses of the ‘gets’ function.

voidtest(){charbuff[1024];gets(buff);// warn}

1.1.7.10.security.insecureAPI.mkstemp (C)

Warn when ‘mkstemp’ is passed fewer than 6 X’s in the format string.

voidtest(){mkstemp("XX");// warn}

1.1.7.11.security.insecureAPI.mktemp (C)

Warn on uses of themktemp function.

voidtest(){char*x=mktemp("/tmp/zxcv");// warn: insecure, use mkstemp}

1.1.7.12.security.insecureAPI.rand (C)

Warn on uses of inferior random number generating functions (only if arc4random function is available):drand48,erand48,jrand48,lcong48,lrand48,mrand48,nrand48,random,rand_r.

voidtest(){random();// warn}

1.1.7.13.security.insecureAPI.strcpy (C)

Warn on uses of thestrcpy andstrcat functions.

voidtest(){charx[4];char*y="abcd";strcpy(x,y);// warn}

1.1.7.14.security.insecureAPI.vfork (C)

Warn on uses of the ‘vfork’ function.

voidtest(){vfork();// warn}

1.1.7.15.security.insecureAPI.DeprecatedOrUnsafeBufferHandling (C)

Warn on occurrences of unsafe or deprecated buffer handling functions, which now have a secure variant:sprintf,fprintf,vsprintf,scanf,wscanf,fscanf,fwscanf,vscanf,vwscanf,vfscanf,vfwscanf,sscanf,swscanf,vsscanf,vswscanf,swprintf,snprintf,vswprintf,vsnprintf,memcpy,memmove,strncpy,strncat,memset

voidtest(){charbuf[5];strncpy(buf,"a",1);// warn}

1.1.7.16.security.MmapWriteExec (C)

Warn onmmap() calls with both writable and executable access.

voidtest(intn){void*c=mmap(NULL,32,PROT_READ|PROT_WRITE|PROT_EXEC,MAP_PRIVATE|MAP_ANON,-1,0);// warn: Both PROT_WRITE and PROT_EXEC flags are set. This can lead to//       exploitable memory regions, which could be overwritten with malicious//       code}

1.1.7.17.security.PointerSub (C)

Check for pointer subtractions on two pointers pointing to different memorychunks. According to the C standard §6.5.6 only subtraction of pointers thatpoint into (or one past the end) the same array object is valid (for thispurpose non-array variables are like arrays of size 1). This checker onlysearches for different memory objects at subtraction, but does not check if thearray index is correct. Furthermore, only cases are reported wherestack-allocated objects are involved (no warnings on pointers to memoryallocated bymalloc).

voidtest(){inta,b,c[10],d[10];intx=&c[3]-&c[1];x=&d[4]-&c[1];// warn: 'c' and 'd' are different arraysx=(&a+1)-&a;x=&b-&a;// warn: 'a' and 'b' are different variables}structS{intx[10];inty[10];};voidtest1(){structSa[10];structSb;intd=&a[4]-&a[6];d=&a[0].x[3]-&a[0].x[1];d=a[0].y-a[0].x;// warn: 'S.b' and 'S.a' are different objectsd=(char*)&b.y-(char*)&b.x;// warn: different members of the same objectd=(char*)&b.y-(char*)&b;// warn: object of type S is not the same array as a member of it}

There may be existing applications that use code like above for calculatingoffsets of members in a structure, using pointer subtractions. This is stillundefined behavior according to the standard and code like this can be replacedwith theoffsetof macro.

1.1.7.18.security.PutenvStackArray (C)

Finds calls to theputenv function which pass a pointer to a stack-allocated(automatic) array as the argument. Functionputenv does not copy the passedstring, only a pointer to the data is stored and this data can be read even byother threads. Content of a stack-allocated array is likely to be overwrittenafter exiting from the function.

The problem can be solved by using a static array variable or dynamicallyallocated memory. Even better is to avoid usingputenv (it has otherproblems related to memory leaks) and usesetenv instead.

The check corresponds to CERT rulePOS34-C. Do not call putenv() with a pointer to an automatic variable as the argument.

intf(){charenv[]="NAME=value";returnputenv(env);// putenv function should not be called with stack-allocated string}

There is one case where the checker can report a false positive. This is whenthe stack-allocated array is used atputenv in a function or code branch thatdoes not return (process is terminated on all execution paths).

Another special case is if theputenv is called from functionmain. Herethe stack is deallocated at the end of the program and it should be no problemto use the stack-allocated string (a multi-threaded program may require moreattention). The checker does not warn for cases when stack space ofmain isused at theputenv call.

1.1.7.19.security.SetgidSetuidOrder (C)

When dropping user-level and group-level privileges in a program by usingsetuid andsetgid calls, it is important to reset the group-levelprivileges (withsetgid) first. Functionsetgid will likely fail ifthe superuser privileges are already dropped.

The checker checks for sequences ofsetuid(getuid()) andsetgid(getgid()) calls (in this order). If such a sequence is found andthere is no other privilege-changing function call (seteuid,setreuid,setresuid and the GID versions of these) in between, a warning isgenerated. The checker finds only exactlysetuid(getuid()) calls (and theGID versions), not for example if the result ofgetuid() is stored in avariable.

voidtest1(){// ...// end of section with elevated privileges// reset privileges (user and group) to normal userif(setuid(getuid())!=0){handle_error();return;}if(setgid(getgid())!=0){// warning: A 'setgid(getgid())' call following a 'setuid(getuid())' call is likely to failhandle_error();return;}// user-ID and group-ID are reset to normal user now// ...}

In the code above the problem is thatsetuid(getuid()) removes superuserprivileges beforesetgid(getgid()) is called. To fix the problem thesetgid(getgid()) should be called first. Further attention is needed toavoid code likesetgid(getuid()) (this checker does not detect bugs likethis) and always check the return value of these calls.

This check corresponds to SEI CERT RulePOS36-C.

1.1.7.20.security.VAList (C, C++)

Reports use of uninitialized (or already released)va_list objects andsituations where ava_start call is not followed byva_end.

inttest_use_after_release(intx,...){va_listva;va_start(va,x);va_end(va);returnva_arg(va,int);// warn: va is uninitialized}voidtest_leak(intx,...){va_listva;va_start(va,x);}// warn: va is leaked

1.1.8.unix

POSIX/Unix checkers.

1.1.8.1.unix.API (C)

Check calls to various UNIX/Posix functions:open,pthread_once,calloc,malloc,realloc,alloca.

// Currently the check is performed for apple targets only.voidtest(constchar*path){intfd=open(path,O_CREAT);// warn: call to 'open' requires a third argument when the// 'O_CREAT' flag is set}voidf();voidtest(){pthread_once_tpred={0x30B1BCBA,{0}};pthread_once(&pred,f);// warn: call to 'pthread_once' uses the local variable}voidtest(){void*p=malloc(0);// warn: allocation size of 0 bytes}voidtest(){void*p=calloc(0,42);// warn: allocation size of 0 bytes}voidtest(){void*p=malloc(1);p=realloc(p,0);// warn: allocation size of 0 bytes}voidtest(){void*p=alloca(0);// warn: allocation size of 0 bytes}voidtest(){void*p=valloc(0);// warn: allocation size of 0 bytes}

1.1.8.2.unix.BlockInCriticalSection (C, C++)

Check for calls to blocking functions inside a critical section.Blocking functions detected by this checker:sleep,getc,fgets,read,recv.Critical section handling functions modeled by this checker:lock,unlock,pthread_mutex_lock,pthread_mutex_trylock,pthread_mutex_unlock,mtx_lock,mtx_timedlock,mtx_trylock,mtx_unlock,lock_guard,unique_lock.

voidpthread_lock_example(pthread_mutex_t*m){pthread_mutex_lock(m);// note: entering critical section heresleep(10);// warn: Call to blocking function 'sleep' inside of critical sectionpthread_mutex_unlock(m);}
voidoverlapping_critical_sections(mtx_t*m1,std::mutex&m2){std::lock_guardlg{m2};// note: entering critical section heremtx_lock(m1);// note: entering critical section heresleep(10);// warn: Call to blocking function 'sleep' inside of critical sectionmtx_unlock(m1);sleep(10);// warn: Call to blocking function 'sleep' inside of critical section// still inside of the critical section of the std::lock_guard}

Limitations

  • Thetrylock andtimedlock versions of acquiring locks are currently assumed to always succeed.This can lead to false positives.

voidtrylock_example(pthread_mutex_t*m){if(pthread_mutex_trylock(m)==0){// assume trylock always succeedssleep(10);// warn: Call to blocking function 'sleep' inside of critical sectionpthread_mutex_unlock(m);}else{sleep(10);// false positive: Incorrect warning about blocking function inside critical section.}}

1.1.8.3.unix.Chroot (C)

Check improper use of chroot described by SEI Cert C recommendationPOS05-C.Limit access to files by creating a jail.The checker finds usage patterns wherechdir("/") is not called immediatelyafter a call tochroot(path).

voidf();voidtest_bad(){chroot("/usr/local");f();// warn: no call of chdir("/") immediately after chroot}voidtest_bad_path(){chroot("/usr/local");chdir("/usr");// warn: no call of chdir("/") immediately after chrootf();}voidtest_good(){chroot("/usr/local");chdir("/");// no warningf();}

1.1.8.4.unix.Errno (C)

Check for improper use oferrno.This checker implements partially CERT ruleERR30-C. Set errno to zero before calling a library function known to set errno,and check errno only after the function returns a value indicating failure.The checker can find the first read oferrno after successful standardfunction calls.

The C and POSIX standards often do not define if a standard library functionmay change value oferrno if the call does not fail.Therefore,errno should only be used if it is known from the return valueof a function that the call has failed.There are exceptions to this rule (for examplestrtol) but the affectedfunctions are not yet supported by the checker.The return values for the failure cases are documented in the standard Linux manpages of the functions and in thePOSIX standard.

intunsafe_errno_read(intsock,void*data,intdata_size){if(send(sock,data,data_size,0)!=data_size){// 'send' can be successful even if not all data was sentif(errno==1){// An undefined value may be read from 'errno'return0;}}return1;}

The checkerunix.StdCLibraryFunctions (C) must be turned on to get thewarnings from this checker. The supported functions are the same as byunix.StdCLibraryFunctions (C). TheModelPOSIX option of thatchecker affects the set of checked functions.

Parameters

TheAllowErrnoReadOutsideConditionExpressions option allows read of theerrno value if the value is not used in a condition (inif statements,loops, conditional expressions,switch statements). For exampleerrnocan be stored into a variable without getting a warning by the checker.

intunsafe_errno_read(intsock,void*data,intdata_size){if(send(sock,data,data_size,0)!=data_size){interr=errno;// warning if 'AllowErrnoReadOutsideConditionExpressions' is false// no warning if 'AllowErrnoReadOutsideConditionExpressions' is true}return1;}

Default value of this option istrue. This allows save of the errno valuefor possible later error handling.

Limitations

  • Only the very first usage oferrno is checked after an affected functioncall. Value oferrno is not followed when it is stored into a variableor returned from a function.

  • Documentation of functionlseek is not clear about what happens if thefunction returns different value than the expected file position but not -1.To avoid possible false-positiveserrno is allowed to be used in thiscase.

1.1.8.5.unix.Malloc (C)

Check for memory leaks, double free, and use-after-free problems. Traces memory managed by malloc()/free().

Custom allocation/deallocation functions can be defined usingownership attributes.

voidtest(){int*p=malloc(1);free(p);free(p);// warn: attempt to release already released memory}voidtest(){int*p=malloc(sizeof(int));free(p);*p=1;// warn: use after free}voidtest(){int*p=malloc(1);if(p)return;// warn: memory is never released}voidtest(){inta[]={1};free(a);// warn: argument is not allocated by malloc}voidtest(){int*p=malloc(sizeof(char));p=p-1;free(p);// warn: argument to free() is offset by -4 bytes}

1.1.8.6.unix.MallocSizeof (C)

Check for dubiousmalloc arguments involvingsizeof.

Custom allocation/deallocation functions can be defined usingownership attributes.

voidtest(){long*p=malloc(sizeof(short));// warn: result is converted to 'long *', which is// incompatible with operand type 'short'free(p);}

1.1.8.7.unix.MismatchedDeallocator (C, C++)

Check for mismatched deallocators.

Custom allocation/deallocation functions can be defined usingownership attributes.

// C, C++voidtest(){int*p=(int*)malloc(sizeof(int));deletep;// warn}// C, C++void__attribute((ownership_returns(malloc)))*user_malloc(size_t);void__attribute((ownership_takes(malloc,1)))*user_free(void*);void__attribute((ownership_returns(malloc1)))*user_malloc1(size_t);void__attribute((ownership_takes(malloc1,1)))*user_free1(void*);voidtest(){int*p=(int*)user_malloc(sizeof(int));deletep;// warn}// C, C++voidtest(){int*p=newint;free(p);// warn}// C, C++voidtest(){int*p=newint[1];realloc(p,sizeof(long));// warn}// C, C++voidtest(){int*p=user_malloc(10);user_free1(p);// warn}// C, C++template<typenameT>structSimpleSmartPointer{T*ptr;explicitSimpleSmartPointer(T*p=0):ptr(p){}~SimpleSmartPointer(){deleteptr;// warn}};voidtest(){SimpleSmartPointer<int>a((int*)malloc(4));}// C++voidtest(){int*p=(int*)operatornew(0);delete[]p;// warn}// Objective-C, C++voidtest(NSUIntegerdataLength){int*p=newint;NSData*d=[NSDatadataWithBytesNoCopy:plength:sizeof(int)freeWhenDone:1];// warn +dataWithBytesNoCopy:length:freeWhenDone: cannot take// ownership of memory allocated by 'new'}

1.1.8.8.unix.Vfork (C)

Check for proper usage ofvfork.

inttest(intx){pid_tpid=vfork();// warnif(pid!=0)return0;switch(x){case0:pid=1;execl("","",0);_exit(1);break;case1:x=0;// warn: this assignment is prohibitedbreak;case2:foo();// warn: this function call is prohibitedbreak;default:return0;// warn: return is prohibited}while(1);}

1.1.8.9.unix.cstring.BadSizeArg (C)

Check the size argument passed into C string functions for common erroneous patterns. Use-Wno-strncat-size compiler option to mute otherstrncat-related compiler warnings.

voidtest(){chardest[3];strncat(dest,"""""""""""""""""""""""""*",sizeof(dest));// warn: potential buffer overflow}

1.1.8.10.unix.cstring.NotNullTerminated (C)

Check for arguments which are not null-terminated strings;applies to thestrlen,strcpy,strcat,strcmp family of functions.

Only very fundamental cases are detected where the passed memory block isabsolutely different from a null-terminated string. This checker does notfind if a memory buffer is passed where the terminating zero characteris missing.

voidtest1(){intl=strlen((char*)&test1);// warn}voidtest2(){label:intl=strlen((char*)&&label);// warn}

1.1.8.11.unix.cstring.NullArg (C)

Check for null pointers being passed as arguments to C string functions:strlen,strnlen,strcpy,strncpy,strcat,strncat,strcmp,strncmp,strcasecmp,strncasecmp,wcslen,wcsnlen.

inttest(){returnstrlen(0);// warn}

1.1.8.12.unix.StdCLibraryFunctions (C)

Check for calls of standard library functions that violate predefined argumentconstraints. For example, according to the C standard the behavior of functionintisalnum(intch) is undefined if the value ofch is not representableasunsignedchar and is not equal toEOF.

You can think of this checker as defining restrictions (pre- and postconditions)on standard library functions. Preconditions are checked, and when they areviolated, a warning is emitted. Postconditions are added to the analysis, e.g.that the return value of a function is not greater than 255. Preconditions areadded to the analysis too, in the case when the affected values are not knownbefore the call.

For example, if an argument to a function must be in between 0 and 255, but thevalue of the argument is unknown, the analyzer will assume that it is in thisinterval. Similarly, if a function mustn’t be called with a null pointer and theanalyzer cannot prove that it is null, then it will assume that it is non-null.

These are the possible checks on the values passed as function arguments:
  • The argument has an allowed range (or multiple ranges) of values. The checkercan detect if a passed value is outside of the allowed range and show theactual and allowed values.

  • The argument has pointer type and is not allowed to be null pointer. Many(but not all) standard functions can produce undefined behavior if a nullpointer is passed, these cases can be detected by the checker.

  • The argument is a pointer to a memory block and the minimal size of thisbuffer is determined by another argument to the function, or bymultiplication of two arguments (like at functionfread), or is a fixedvalue (for exampleasctime_r requires at least a buffer of size 26). Thechecker can detect if the buffer size is too small and in optimal case showthe size of the buffer and the values of the corresponding arguments.

#define EOF -1voidtest_alnum_concrete(intv){intret=isalnum(256);// \  // warning: Function argument outside of allowed range(void)ret;}voidbuffer_size_violation(FILE*file){enum{BUFFER_SIZE=1024};wchar_twbuf[BUFFER_SIZE];constsize_tsize=sizeof(*wbuf);// 4constsize_tnitems=sizeof(wbuf);// 4096// Below we receive a warning because the 3rd parameter should be the// number of elements to read, not the size in bytes. This case is a known// vulnerability described by the ARR38-C SEI-CERT rule.fread(wbuf,size,nitems,file);}inttest_alnum_symbolic(intx){intret=isalnum(x);// after the call, ret is assumed to be in the range [-1, 255]if(ret>255)// impossible (infeasible branch)if(x==0)returnret/x;// division by zero is not reportedreturnret;}

Additionally to the argument and return value conditions, this checker also addsstate of the valueerrno if applicable to the analysis. Many systemfunctions set theerrno value only if an error occurs (together with aspecific return value of the function), otherwise it becomes undefined. Thischecker changes the analysis state to contain such information. This data isused by other checkers, for exampleunix.Errno (C).

Limitations

The checker can not always provide notes about the values of the arguments.Without this information it is hard to confirm if the constraint is indeedviolated. The argument values are shown if they are known constants or the valueis determined by previous (not too complicated) assumptions.

The checker can produce false positives in cases such as if the program hasinvariants not known to the analyzer engine or the bug report path containscalls to unknown functions. In these cases the analyzer fails to detect the realrange of the argument.

Parameters

TheModelPOSIX option controls if functions from the POSIX standard arerecognized by the checker.

WithModelPOSIX=true, many POSIX functions are modeled according to thePOSIX standard. This includes ranges of parameters and possible returnvalues. Furthermore the behavior related toerrno in the POSIX case isoften thaterrno is set only if a function call fails, and it becomesundefined after a successful function call.

WithModelPOSIX=false, this checker follows the C99 language standard andonly models the functions that are described there. It is possible that thesame functions are modeled differently in the two cases because differences inthe standards. The C standard specifies less aspects of the functions, forexample exacterrno behavior is often unspecified (and not modeled by thechecker).

Default value of the option istrue.

1.1.8.13.unix.Stream (C)

Check C stream handling functions:fopen,fdopen,freopen,tmpfile,fclose,fread,fwrite,fgetc,fgets,fputc,fputs,fprintf,fscanf,ungetc,getdelim,getline,fseek,fseeko,ftell,ftello,fflush,rewind,fgetpos,fsetpos,clearerr,feof,ferror,fileno.

The checker maintains information about the C stream objects (FILE*) andcan detect error conditions related to use of streams. The following conditionsare detected:

  • TheFILE* pointer passed to the function is NULL (the single exception isfflush where NULL is allowed).

  • Use of stream after close.

  • Opened stream is not closed.

  • Read from a stream after end-of-file. (This is not a fatal error but reportedby the checker. Stream remains in EOF state and the read operation fails.)

  • Use of stream when the file position is indeterminate after a previous failedoperation. Some functions (likeferror,clearerr,fseek) areallowed in this state.

  • Invalid 3rd (”whence”) argument tofseek.

The stream operations are by this checker usually split into two cases, a successand a failure case.On the success case it also assumes that the current value ofstdout,stderr, orstdin can’t be equal to the file pointer returned byfopen.Operations performed onstdout,stderr, orstdin are not checked bythis checker in contrast to the streams opened byfopen.

In the case of write operations (likefwrite,fprintf and evenfsetpos) this behavior could produce a large amount ofunwanted reports on projects that don’t have error checks around the writeoperations, so by default the checker assumes that write operations always succeed.This behavior can be controlled by thePedantic flag: With-analyzer-configunix.Stream:Pedantic=true the checker will model thecases where a write operation fails and report situations where this leads toerroneous behavior. (The default isPedantic=false, where write operationsare assumed to succeed.)

voidtest1(){FILE*p=fopen("foo","r");}// warn: opened file is never closedvoidtest2(){FILE*p=fopen("foo","r");fseek(p,1,SEEK_SET);// warn: stream pointer might be NULLfclose(p);}voidtest3(){FILE*p=fopen("foo","r");if(p){fseek(p,1,3);// warn: third arg should be SEEK_SET, SEEK_END, or SEEK_CURfclose(p);}}voidtest4(){FILE*p=fopen("foo","r");if(!p)return;fclose(p);fclose(p);// warn: stream already closed}voidtest5(){FILE*p=fopen("foo","r");if(!p)return;fgetc(p);if(!ferror(p))fgetc(p);// warn: possible read after end-of-filefclose(p);}voidtest6(){FILE*p=fopen("foo","r");if(!p)return;fgetc(p);if(!feof(p))fgetc(p);// warn: file position may be indeterminate after I/O errorfclose(p);}

Limitations

The checker does not track the correspondence between integer file descriptorsandFILE* pointers.

1.1.9.osx

macOS checkers.

1.1.9.1.osx.API (C)

Check for proper uses of various Apple APIs.

voidtest(){dispatch_once_tpred=0;dispatch_once(&pred,^(){});// warn: dispatch_once uses local}

1.1.9.2.osx.NumberObjectConversion (C, C++, ObjC)

Check for erroneous conversions of objects representing numbers into numbers.

NSNumber*photoCount=[albumDescriptorobjectForKey:@"PhotoCount"];// Warning: Comparing a pointer value of type 'NSNumber *'// to a scalar integer valueif(photoCount>0){[selfdisplayPhotos];}

1.1.9.3.osx.ObjCProperty (ObjC)

Check for proper uses of Objective-C properties.

NSNumber*photoCount=[albumDescriptorobjectForKey:@"PhotoCount"];// Warning: Comparing a pointer value of type 'NSNumber *'// to a scalar integer valueif(photoCount>0){[selfdisplayPhotos];}

1.1.9.4.osx.SecKeychainAPI (C)

Check for proper uses of Secure Keychain APIs.

voidtest(){unsignedint*ptr=0;UInt32length;SecKeychainItemFreeContent(ptr,&length);// warn: trying to free data which has not been allocated}voidtest(){unsignedint*ptr=0;UInt32*length=0;void*outData;OSStatusst=SecKeychainItemCopyContent(2,ptr,ptr,length,outData);// warn: data is not released}voidtest(){unsignedint*ptr=0;UInt32*length=0;void*outData;OSStatusst=SecKeychainItemCopyContent(2,ptr,ptr,length,&outData);SecKeychainItemFreeContent(ptr,outData);// warn: only call free if a non-NULL buffer was returned}voidtest(){unsignedint*ptr=0;UInt32*length=0;void*outData;OSStatusst=SecKeychainItemCopyContent(2,ptr,ptr,length,&outData);st=SecKeychainItemCopyContent(2,ptr,ptr,length,&outData);// warn: release data before another call to the allocatorif(st==noErr)SecKeychainItemFreeContent(ptr,outData);}voidtest(){SecKeychainItemRefitemRef=0;SecKeychainAttributeInfo*info=0;SecItemClass*itemClass=0;SecKeychainAttributeList*attrList=0;UInt32*length=0;void*outData=0;OSStatusst=SecKeychainItemCopyAttributesAndData(itemRef,info,itemClass,&attrList,length,&outData);SecKeychainItemFreeContent(attrList,outData);// warn: deallocator doesn't match the allocator}

1.1.9.5.osx.cocoa.AtSync (ObjC)

Check for nil pointers used as mutexes for @synchronized.

voidtest(idx){if(!x)@synchronized(x){}// warn: nil value used as mutex}voidtest(){idy;@synchronized(y){}// warn: uninitialized value used as mutex}

1.1.9.6.osx.cocoa.AutoreleaseWrite

Warn about potentially crashing writes to autoreleasing objects from different autoreleasing pools in Objective-C.

1.1.9.7.osx.cocoa.ClassRelease (ObjC)

Check for sending ‘retain’, ‘release’, or ‘autorelease’ directly to a Class.

@interfaceMyClass :NSObject@endvoidtest(void){[MyClassrelease];// warn}

1.1.9.8.osx.cocoa.Dealloc (ObjC)

Warn about Objective-C classes that lack a correct implementation of -dealloc

@interfaceMyObject :NSObject{id_myproperty;}@end@implementationMyObject// warn: lacks 'dealloc'@end@interfaceMyObject :NSObject{}@property(assign)idmyproperty;@end@implementationMyObject// warn: does not send 'dealloc' to super-(void)dealloc{self.myproperty=0;}@end@interfaceMyObject :NSObject{id_myproperty;}@property(retain)idmyproperty;@end@implementationMyObject@synthesizemyproperty=_myproperty;// warn: var was retained but wasn't released-(void)dealloc{[superdealloc];}@end@interfaceMyObject :NSObject{id_myproperty;}@property(assign)idmyproperty;@end@implementationMyObject@synthesizemyproperty=_myproperty;// warn: var wasn't retained but was released-(void)dealloc{[_mypropertyrelease];[superdealloc];}@end

1.1.9.9.osx.cocoa.IncompatibleMethodTypes (ObjC)

Warn about Objective-C method signatures with type incompatibilities.

@interfaceMyClass1 :NSObject-(int)foo;@end@implementationMyClass1-(int)foo{return1;}@end@interfaceMyClass2 :MyClass1-(float)foo;@end@implementationMyClass2-(float)foo{return1.0;}// warn@end

1.1.9.10.osx.cocoa.Loops

Improved modeling of loops using Cocoa collection types.

1.1.9.11.osx.cocoa.MissingSuperCall (ObjC)

Warn about Objective-C methods that lack a necessary call to super.

@interfaceTest :UIViewController@end@implementationtest-(void)viewDidLoad{}// warn@end

1.1.9.12.osx.cocoa.NSAutoreleasePool (ObjC)

Warn for suboptimal uses of NSAutoreleasePool in Objective-C GC mode.

voidtest(){NSAutoreleasePool*pool=[[NSAutoreleasePoolalloc]init];[poolrelease];// warn}

1.1.9.13.osx.cocoa.NSError (ObjC)

Check usage of NSError parameters.

@interfaceA :NSObject-(void)foo:(NSError"""""""""""""""""""""""")error;@end@implementationA-(void)foo:(NSError"""""""""""""""""""""""")error{// warn: method accepting NSError"""""""""""""""""""""""" should have a non-void// return value}@end@interfaceA :NSObject-(BOOL)foo:(NSError"""""""""""""""""""""""")error;@end@implementationA-(BOOL)foo:(NSError"""""""""""""""""""""""")error{*error=0;// warn: potential null dereferencereturn0;}@end

1.1.9.14.osx.cocoa.NilArg (ObjC)

Check for prohibited nil arguments to ObjC method calls.

  • caseInsensitiveCompare:

  • compare:

  • compare:options:

  • compare:options:range:

  • compare:options:range:locale:

  • componentsSeparatedByCharactersInSet:

  • initWithFormat:

NSComparisonResulttest(NSString*s){NSString*aString=nil;return[scaseInsensitiveCompare:aString];// warn: argument to 'NSString' method// 'caseInsensitiveCompare:' cannot be nil}

1.1.9.15.osx.cocoa.NonNilReturnValue

Models the APIs that are guaranteed to return a non-nil value.

1.1.9.16.osx.cocoa.ObjCGenerics (ObjC)

Check for type errors when using Objective-C generics.

NSMutableArray*names=[NSMutableArrayarray];NSMutableArray*birthDates=names;// Warning: Conversion from value of type 'NSDate *'// to incompatible type 'NSString *'[birthDatesaddObject:[NSDatedate]];

1.1.9.17.osx.cocoa.RetainCount (ObjC)

Check for leaks and improper reference count management

voidtest(){NSString*s=[[NSStringalloc]init];// warn}CFStringReftest(char*bytes){returnCFStringCreateWithCStringNoCopy(0,bytes,NSNEXTSTEPStringEncoding,0);// warn}

1.1.9.18.osx.cocoa.RunLoopAutoreleaseLeak

Check for leaked memory in autorelease pools that will never be drained.

1.1.9.19.osx.cocoa.SelfInit (ObjC)

Check that ‘self’ is properly initialized inside an initializer method.

@interfaceMyObj :NSObject{idx;}-(id)init;@end@implementationMyObj-(id)init{[superinit];x=0;// warn: instance variable used while 'self' is not// initializedreturn0;}@end@interfaceMyObj :NSObject-(id)init;@end@implementationMyObj-(id)init{[superinit];returnself;// warn: returning uninitialized 'self'}@end

1.1.9.20.osx.cocoa.SuperDealloc (ObjC)

Warn about improper use of ‘[super dealloc]’ in Objective-C.

@interfaceSuperDeallocThenReleaseIvarClass :NSObject{NSObject*_ivar;}@end@implementationSuperDeallocThenReleaseIvarClass-(void)dealloc{[superdealloc];[_ivarrelease];// warn}@end

1.1.9.21.osx.cocoa.UnusedIvars (ObjC)

Warn about private ivars that are never used.

@interfaceMyObj :NSObject{@privateidx;// warn}@end@implementationMyObj@end

1.1.9.22.osx.cocoa.VariadicMethodTypes (ObjC)

Check for passing non-Objective-C types to variadic collectioninitialization methods that expect only Objective-C types.

voidtest(){[NSSetsetWithObjects:@"Foo","Bar",nil];// warn: argument should be an ObjC pointer type, not 'char *'}

1.1.9.23.osx.coreFoundation.CFError (C)

Check usage of CFErrorRef* parameters

voidtest(CFErrorRef*error){// warn: function accepting CFErrorRef* should have a// non-void return}intfoo(CFErrorRef*error){*error=0;// warn: potential null dereferencereturn0;}

1.1.9.24.osx.coreFoundation.CFNumber (C)

Check for proper uses of CFNumber APIs.

CFNumberReftest(unsignedcharx){returnCFNumberCreate(0,kCFNumberSInt16Type,&x);// warn: 8-bit integer is used to initialize a 16-bit integer}

1.1.9.25.osx.coreFoundation.CFRetainRelease (C)

Check for null arguments to CFRetain/CFRelease/CFMakeCollectable.

voidtest(CFTypeRefp){if(!p)CFRetain(p);// warn}voidtest(intx,CFTypeRefp){if(p)return;CFRelease(p);// warn}

1.1.9.26.osx.coreFoundation.containers.OutOfBounds (C)

Checks for index out-of-bounds when using ‘CFArray’ API.

voidtest(){CFArrayRefA=CFArrayCreate(0,0,0,&kCFTypeArrayCallBacks);CFArrayGetValueAtIndex(A,0);// warn}

1.1.9.27.osx.coreFoundation.containers.PointerSizedValues (C)

Warns if ‘CFArray’, ‘CFDictionary’, ‘CFSet’ are created with non-pointer-size values.

voidtest(){intx[]={1};CFArrayRefA=CFArrayCreate(0,(constvoid"""""""""""""""""""""""")x,1,&kCFTypeArrayCallBacks);// warn}

1.1.10.Fuchsia

Fuchsia is an open source capability-based operating system currently beingdeveloped by Google. This section describes checkers that can find variousmisuses of Fuchsia APIs.

1.1.10.1.fuchsia.HandleChecker

Handles identify resources. Similar to pointers they can be leaked,double freed, or use after freed. This check attempts to find such problems.

voidcheckLeak08(inttag){zx_handle_tsa,sb;zx_channel_create(0,&sa,&sb);if(tag)zx_handle_close(sa);use(sb);// Warn: Potential leak of handlezx_handle_close(sb);}

1.1.11.WebKit

WebKit is an open-source web browser engine available for macOS, iOS and Linux.This section describes checkers that can find issues in WebKit codebase.

Most of the checkers focus on memory management for which WebKit uses custom implementation of reference counted smartpointers.

Checkers are formulated in terms related to ref-counting:
  • Ref-counted type is eitherRef<T> orRefPtr<T>.

  • Ref-countable type is any type that implementsref() andderef() methods asRefPtr<> is a template (i. e. relies on duck typing).

  • Uncounted type is ref-countable but not ref-counted type.

1.1.11.1.webkit.RefCntblBaseVirtualDtor

All uncounted types used as base classes must have a virtual destructor.

Ref-counted types hold their ref-countable data by a raw pointer and allow implicit upcasting from ref-counted pointer to derived type to ref-counted pointer to base type. This might lead to an object of (dynamic) derived type being deleted via pointer to the base class type which C++ standard defines as UB in case the base class doesn’t have virtual destructor[expr.delete].

structRefCntblBase{voidref(){}voidderef(){}};structDerived:RefCntblBase{};// warn

1.1.11.2.webkit.NoUncountedMemberChecker

Raw pointers and references to uncounted types can’t be used as class members. Only ref-counted types are allowed.

structRefCntbl{voidref(){}voidderef(){}};structFoo{RefCntbl*ptr;// warnRefCntbl&ptr;// warn// ...};

1.1.11.3.webkit.UncountedLambdaCapturesChecker

Raw pointers and references to uncounted types can’t be captured in lambdas. Only ref-counted types are allowed.

structRefCntbl{voidref(){}voidderef(){}};voidfoo(RefCntbl*a,RefCntbl&b){[&,a](){// warn about 'a'do_something(b);// warn about 'b'};};

1.2.Experimental Checkers

These are checkers with known issues or limitations that keep them from being on by default. They are likely to have false positives. Bug reports and especially patches are welcome.

1.2.1.alpha.clone

1.2.1.1.alpha.clone.CloneChecker (C, C++, ObjC)

Reports similar pieces of code.

voidlog();intmax(inta,intb){// warnlog();if(a>b)returna;returnb;}intmaxClone(intx,inty){// similar code herelog();if(x>y)returnx;returny;}

1.2.2.alpha.core

1.2.2.1.alpha.core.BoolAssignment (ObjC)

Warn about assigning non-{0,1} values to boolean variables.

voidtest(){BOOLb=-1;// warn}

1.2.2.2.alpha.core.C11Lock

Similarly toalpha.unix.PthreadLock, checks forthe locking/unlocking ofmtx_t mutexes.

mtx_tmtx1;voidbad1(void){mtx_lock(&mtx1);mtx_lock(&mtx1);// warn: This lock has already been acquired}

1.2.2.3.alpha.core.CastToStruct (C, C++)

Check for cast from non-struct pointer to struct pointer.

// Cstructs{};voidtest(int*p){structs*ps=(structs*)p;// warn}// C++classc{};voidtest(int*p){c*pc=(c*)p;// warn}

1.2.2.4.alpha.core.Conversion (C, C++, ObjC)

Loss of sign/precision in implicit conversions.

voidtest(unsignedU,signedS){if(S>10){if(U<S){}}if(S<-10){if(U<S){// warn (loss of sign)}}}voidtest(){longlongA=1LL<<60;shortX=A;// warn (loss of precision)}

1.2.2.5.alpha.core.DynamicTypeChecker (ObjC)

Check for cases where the dynamic and the static type of an object are unrelated.

iddate=[NSDatedate];// Warning: Object has a dynamic type 'NSDate *' which is// incompatible with static type 'NSNumber *'"NSNumber*number=date;[numberdoubleValue];

1.2.2.6.alpha.core.FixedAddr (C)

Check for assignment of a fixed address to a pointer.

voidtest(){int*p;p=(int*)0x10000;// warn}

1.2.2.7.alpha.core.PointerArithm (C)

Check for pointer arithmetic on locations other than array elements.

voidtest(){intx;int*p;p=&x+1;// warn}

1.2.2.8.alpha.core.StackAddressAsyncEscape (ObjC)

Check that addresses to stack memory do not escape the function that involves dispatch_after or dispatch_async.This checker is a part ofcore.StackAddressEscape, but is temporarily disabled until some false positives are fixed.

dispatch_block_ttest_block_inside_block_async_leak(){intx=123;void(^inner)(void)=^void(void){inty=x;++y;};void(^outer)(void)=^void(void){intz=x;++z;inner();};returnouter;// warn: address of stack-allocated block is captured by a//       returned block}

1.2.2.9.alpha.core.StdVariant (C++)

Check if a value of active type is retrieved from anstd::variant instance withstd::get.In case of bad variant type access (the accessed type differs from the active type)a warning is emitted. Currently, this checker does not take exception handling into account.

voidtest(){std::variant<int,char>v=25;charc=stg::get<char>(v);// warn: "int" is the active alternative}

1.2.2.10.alpha.core.TestAfterDivZero (C)

Check for division by variable that is later compared against 0.Either the comparison is useless or there is division by zero.

voidtest(intx){var=77/x;if(x==0){}// warn}

1.2.2.11.alpha.core.StoreToImmutable (C, C++)

Check for writes to immutable memory regions. This implements part of SEI CERT Rule ENV30-C.

This checker detects attempts to write to memory regions that are marked as immutable,including const variables, string literals, and other const-qualified memory.

constintglobal_const=42;structTestStruct{constintx;inty;};voidimmutable_violation_examples(){*(int*)&global_const=100;// warn: Trying to write to immutable memoryconstintlocal_const=42;*(int*)&local_const=43;// warn: Trying to write to immutable memory// NOTE: The following is reported in C++, but not in C, as the analyzer// treats string literals as non-const char arrays in C mode.char*ptr_to_str_literal=(char*)"hello";ptr_to_str_literal[0]='H';// warn: Trying to write to immutable memoryTestStructs={1,2};*(int*)&s.x=10;// warn: Trying to write to immutable memory}

Solution

Avoid writing to const-qualified memory regions. If you need to modify the data,remove the const qualifier from the original declaration or use a mutable copy.

1.2.3.alpha.cplusplus

1.2.3.1.alpha.cplusplus.DeleteWithNonVirtualDtor (C++)

Reports destructions of polymorphic objects with a non-virtual destructor in their base class.

classNonVirtual{};classNVDerived:publicNonVirtual{};NonVirtual*create(){NonVirtual*x=newNVDerived();// note: Casting from 'NVDerived' to//       'NonVirtual' herereturnx;}voidfoo(){NonVirtual*x=create();deletex;// warn: destruction of a polymorphic object with no virtual//       destructor}

1.2.3.2.alpha.cplusplus.InvalidatedIterator (C++)

Check for use of invalidated iterators.

voidbad_copy_assign_operator_list1(std::list&L1,conststd::list&L2){autoi0=L1.cbegin();L1=L2;*i0;// warn: invalidated iterator accessed}

1.2.3.3.alpha.cplusplus.IteratorRange (C++)

Check for iterators used outside their valid ranges.

voidsimple_bad_end(conststd::vector&v){autoi=v.end();*i;// warn: iterator accessed outside of its range}

1.2.3.4.alpha.cplusplus.MismatchedIterator (C++)

Check for use of iterators of different containers where iterators of the same container are expected.

voidbad_insert3(std::vector&v1,std::vector&v2){v2.insert(v1.cbegin(),v2.cbegin(),v2.cend());// warn: container accessed//       using foreign//       iterator argumentv1.insert(v1.cbegin(),v1.cbegin(),v2.cend());// warn: iterators of//       different containers//       used where the same//       container is//       expectedv1.insert(v1.cbegin(),v2.cbegin(),v1.cend());// warn: iterators of//       different containers//       used where the same//       container is//       expected}

1.2.3.5.alpha.cplusplus.SmartPtr (C++)

Check for dereference of null smart pointers.

voidderef_smart_ptr(){std::unique_ptr<int>P;*P;// warn: dereference of a default constructed smart unique_ptr}

1.2.4.alpha.deadcode

1.2.4.1.alpha.deadcode.UnreachableCode (C, C++)

Check unreachable code.

// Cinttest(){intx=1;while(x);returnx;// warn}// C++voidtest(){inta=2;while(a>1)a--;if(a>1)a++;// warn}// Objective-Cvoidtest(idx){return;[xretain];// warn}

1.2.5.alpha.fuchsia

1.2.5.1.alpha.fuchsia.Lock

Similarly toalpha.unix.PthreadLock, checks forthe locking/unlocking of fuchsia mutexes.

spin_lock_tmtx1;voidbad1(void){spin_lock(&mtx1);spin_lock(&mtx1);// warn: This lock has already been acquired}

1.2.6.alpha.llvm

1.2.6.1.alpha.llvm.Conventions

Check code for LLVM codebase conventions:

  • A StringRef should not be bound to a temporary std::string whose lifetime is shorter than the StringRef’s.

  • Clang AST nodes should not have fields that can allocate memory.

1.2.7.alpha.osx

1.2.7.1.alpha.osx.cocoa.DirectIvarAssignment (ObjC)

Check for direct assignments to instance variables.

@interfaceMyClass :NSObject{}@property(readonly)idA;-(void)foo;@end@implementationMyClass-(void)foo{_A=0;// warn}@end

1.2.7.2.alpha.osx.cocoa.DirectIvarAssignmentForAnnotatedFunctions (ObjC)

Check for direct assignments to instance variables inthe methods annotated withobjc_no_direct_instance_variable_assignment.

@interfaceMyClass :NSObject{}@property(readonly)idA;-(void)fAnnotated__attribute__((annotate("objc_no_direct_instance_variable_assignment")));-(void)fNotAnnotated;@end@implementationMyClass-(void)fAnnotated{_A=0;// warn}-(void)fNotAnnotated{_A=0;// no warn}@end

1.2.7.3.alpha.osx.cocoa.InstanceVariableInvalidation (ObjC)

Check that the invalidatable instance variables areinvalidated in the methods annotated with objc_instance_variable_invalidator.

@protocolInvalidation<NSObject>-(void)invalidate__attribute__((annotate("objc_instance_variable_invalidator")));@end@interfaceInvalidationImpObj :NSObject<Invalidation>@end@interfaceSubclassInvalidationImpObj :InvalidationImpObj{InvalidationImpObj*var;}-(void)invalidate;@end@implementationSubclassInvalidationImpObj-(void)invalidate{}@end// warn: var needs to be invalidated or set to nil

1.2.7.4.alpha.osx.cocoa.MissingInvalidationMethod (ObjC)

Check that the invalidation methods are present in classes that contain invalidatable instance variables.

@protocolInvalidation<NSObject>-(void)invalidate__attribute__((annotate("objc_instance_variable_invalidator")));@end@interfaceNeedInvalidation :NSObject<Invalidation>@end@interfaceMissingInvalidationMethodDecl :NSObject{NeedInvalidation*Var;// warn}@end@implementationMissingInvalidationMethodDecl@end

1.2.7.5.alpha.osx.cocoa.localizability.PluralMisuseChecker (ObjC)

Warns against using one vs. many plural pattern in code when generating localized strings.

NSString*reminderText=NSLocalizedString(@"None",@"Indicates no reminders");if(reminderCount==1){// Warning: Plural cases are not supported across all languages.// Use a .stringsdict file insteadreminderText=NSLocalizedString(@"1 Reminder",@"Indicates single reminder");}elseif(reminderCount>=2){// Warning: Plural cases are not supported across all languages.// Use a .stringsdict file insteadreminderText=[NSStringstringWithFormat:NSLocalizedString(@"%@ Reminders",@"Indicates multiple reminders"),reminderCount];}

1.2.8.alpha.security

1.2.8.1.alpha.security.ReturnPtrRange (C)

Check for an out-of-bound pointer being returned to callers.

staticintA[10];int*test(){int*p=A+10;returnp;// warn}inttest(void){intx;returnx;// warn: undefined or garbage returned}

1.2.9.alpha.unix

1.2.9.1.alpha.unix.PthreadLock (C)

Simple lock -> unlock checker.Applies to:pthread_mutex_lock,pthread_rwlock_rdlock,pthread_rwlock_wrlock,lck_mtx_lock,lck_rw_lock_exclusivelck_rw_lock_shared,pthread_mutex_trylock,pthread_rwlock_tryrdlock,pthread_rwlock_tryrwlock,lck_mtx_try_lock,lck_rw_try_lock_exclusive,lck_rw_try_lock_shared,pthread_mutex_unlock,pthread_rwlock_unlock,lck_mtx_unlock,lck_rw_done.

pthread_mutex_tmtx;voidtest(){pthread_mutex_lock(&mtx);pthread_mutex_lock(&mtx);// warn: this lock has already been acquired}lck_mtx_tlck1,lck2;voidtest(){lck_mtx_lock(&lck1);lck_mtx_lock(&lck2);lck_mtx_unlock(&lck1);// warn: this was not the most recently acquired lock}lck_mtx_tlck1,lck2;voidtest(){if(lck_mtx_try_lock(&lck1)==0)return;lck_mtx_lock(&lck2);lck_mtx_unlock(&lck1);// warn: this was not the most recently acquired lock}

1.2.9.2.alpha.unix.SimpleStream (C)

Check for misuses of stream APIs. Check for misuses of stream APIs:fopen,fclose(demo checker, the subject of the demo (Slides ,Video) by Anna Zaks and Jordan Rose presented at the2012 LLVM Developers’ Meeting).

voidtest(){FILE*F=fopen("myfile.txt","w");}// warn: opened file is never closedvoidtest(){FILE*F=fopen("myfile.txt","w");if(F)fclose(F);fclose(F);// warn: closing a previously closed file stream}

1.2.9.3.alpha.unix.cstring.BufferOverlap (C)

Checks for overlap in two buffer arguments. Applies to:memcpy,mempcpy,wmemcpy,wmempcpy.

voidtest(){inta[4]={0};memcpy(a+2,a+1,8);// warn}

1.2.9.4.alpha.unix.cstring.OutOfBounds (C)

Check for out-of-bounds access in string functions, such as:memcpy,bcopy,strcpy,strncpy,strcat,strncat,memmove,memcmp,memset and more.

This check also works with string literals, except there is a known bug in thatthe analyzer cannot detect embedded NULL characters when determining the string length.

voidtest1(){constcharstr[]="Hello world";charbuffer[]="Hello world";memcpy(buffer,str,sizeof(str)+1);// warn}voidtest2(){constcharstr[]="Hello world";charbuffer[]="Helloworld";memcpy(buffer,str,sizeof(str));// warn}

1.2.9.5.alpha.unix.cstring.UninitializedRead (C)

Check for uninitialized reads from common memory copy/manipulation functions such as:

memcpy,mempcpy,memmove,memcmp,strcmp,strncmp,strcpy,strlen,strsep and many more.

voidtest(){charsrc[10];chardst[5];memcpy(dst,src,sizeof(dst));// warn: Bytes string function accesses uninitialized/garbage values}

Limitations:

  • Due to limitations of the memory modeling in the analyzer, one can likelyobserve a lot of false-positive reports like this:

    voidfalse_positive(){intsrc[]={1,2,3,4};intdst[5]={0};memcpy(dst,src,4*sizeof(int));// false-positive:// The 'src' buffer was correctly initialized, yet we cannot conclude// that since the analyzer could not see a direct initialization of the// very last byte of the source buffer.}

    More details at the correspondingGitHub issue.

1.2.10.alpha.WebKit

1.2.10.1.alpha.webkit.ForwardDeclChecker

Check for local variables, member variables, and function arguments that are forward declared.

structObj;Obj*provide();structFoo{Obj*ptr;// warn};voidfoo(){Obj*obj=provide();// warnconsume(obj);// warn}

1.2.10.2.alpha.webkit.MemoryUnsafeCastChecker

Check for all casts from a base type to its derived type as these might be memory-unsafe.

Example:

classBase{};classDerived:publicBase{};voidf(Base*base){Derived*derived=static_cast<Derived*>(base);// ERROR}

For all cast operations (C-style casts, static_cast, reinterpret_cast, dynamic_cast), if the source type aBase* and the destination type isDerived*, whereDerived inherits fromBase, the static analyzer should signal an error.

This applies to:

  • C structs, C++ structs and classes, and Objective-C classes and protocols.

  • Pointers and references.

  • Inside template instantiations and macro expansions that are visible to the compiler.

For types like this, instead of using built in casts, the programmer will use helper functions that internally perform the appropriate type check and disable static analysis.

1.2.10.3.alpha.webkit.NoUncheckedPtrMemberChecker

Raw pointers and references to an object which supports CheckedPtr or CheckedRef can’t be used as class members. Only CheckedPtr, CheckedRef, RefPtr, or Ref are allowed.

structCheckableObj{voidincrementCheckedPtrCount(){}voiddecrementCheckedPtrCount(){}};structFoo{CheckableObj*ptr;// warnCheckableObj&ptr;// warn// ...};

SeeWebKit Guidelines for Safer C++ Programming for details.

1.2.10.4.alpha.webkit.NoUnretainedMemberChecker

Raw pointers and references to a NS or CF object can’t be used as class members or ivars. Only RetainPtr is allowed for CF types regardless of whether ARC is enabled or disabled. Only RetainPtr or OSObjectPtr is allowed for NS types when ARC is disabled.

structFoo{NSObject*ptr;// warndispatch_queue_tqueue;// warn// ...};

SeeWebKit Guidelines for Safer C++ Programming for details.

1.2.10.5.alpha.webkit.UnretainedLambdaCapturesChecker

Raw pointers and references to NS or CF types can’t be captured in lambdas. Only RetainPtr is allowed for CF types regardless of whether ARC is enabled or disabled, and only RetainPtr or OSObjectPtr is allowed for NS types when ARC is disabled.

voidfoo(NSObject*a,NSObject*b,dispatch_queue_tc){[&,a](){// warn about 'a'do_something(b);// warn about 'b'dispatch_queue_get_specific(c,"some");// warn about 'c'};};

1.2.10.6.alpha.webkit.UncountedCallArgsChecker

The goal of this rule is to make sure that lifetime of any dynamically allocated ref-countable object passed as a call argument spans past the end of the call. This applies to call to any function, method, lambda, function pointer or functor. Ref-countable types aren’t supposed to be allocated on stack so we check arguments for parameters of raw pointers and references to uncounted types.

Here are some examples of situations that we warn about as theymight be potentially unsafe. The logic is that either we’re able to guarantee that an argument is safe or it’s considered if not a bug then bug-prone.

RefCountable*provide_uncounted();voidconsume(RefCountable*);// In these cases we can't make sure callee won't directly or indirectly call `deref()` on the argument which could make it unsafe from such point until the end of the call.voidfoo1(){consume(provide_uncounted());// warn}voidfoo2(){RefCountable*uncounted=provide_uncounted();consume(uncounted);// warn}

Although we are enforcing member variables to be ref-counted bywebkit.NoUncountedMemberChecker any method of the same class still has unrestricted access to these. Since from a caller’s perspective we can’t guarantee a particular member won’t get modified by callee (directly or indirectly) we don’t consider values obtained from members safe.

Note: It’s likely this heuristic could be made more precise with fewer false positives - for example calls to free functions that don’t have any parameter other than the pointer should be safe as the callee won’t be able to tamper with the member unless it’s a global variable.

structFoo{RefPtr<RefCountable>member;voidconsume(RefCountable*){/* ... */}voidbugprone(){consume(member.get());// warn}};

The implementation of this rule is a heuristic - we define a whitelist of kinds of values that are considered safe to be passed as arguments. If we can’t prove an argument is safe it’s considered an error.

Allowed kinds of arguments:

  • values obtained from ref-counted objects (including temporaries as those survive the call too)

    RefCountable*provide_uncounted();voidconsume(RefCountable*);voidfoo(){RefPtr<RefCountable>rc=makeRef(provide_uncounted());consume(rc.get());// okconsume(makeRef(provide_uncounted()).get());// ok}
  • forwarding uncounted arguments from caller to callee

    voidfoo(RefCountable&a){bar(a);// ok}

    Caller offoo() is responsible fora’s lifetime.

  • this pointer

    voidFoo::foo(){baz(this);// ok}

    Caller offoo() is responsible for keeping the memory pointed to bythis pointer safe.

  • constants

    foo(nullptr,NULL,0);// ok

We also define a set of safe transformations which if passed a safe value as an input provide (usually it’s the return value) a safe value (or an object that provides safe values). This is also a heuristic.

  • constructors of ref-counted types (including factory methods)

  • getters of ref-counted types

  • member overloaded operators

  • casts

  • unary operators like& or*

1.2.10.7.alpha.webkit.UncheckedCallArgsChecker

The goal of this rule is to make sure that lifetime of any dynamically allocated CheckedPtr capable object passed as a call argument keeps its memory region past the end of the call. This applies to call to any function, method, lambda, function pointer or functor. CheckedPtr capable objects aren’t supposed to be allocated on stack so we check arguments for parameters of raw pointers and references to unchecked types.

The rules of when to use and not to use CheckedPtr / CheckedRef are same as alpha.webkit.UncountedCallArgsChecker for ref-counted objects.

1.2.10.8.alpha.webkit.UnretainedCallArgsChecker

The goal of this rule is to make sure that lifetime of any dynamically allocated NS or CF objects passed as a call argument keeps its memory region past the end of the call. This applies to call to any function, method, lambda, function pointer or functor. NS or CF objects aren’t supposed to be allocated on stack so we check arguments for parameters of raw pointers and references to unretained types.

The rules of when to use and not to use RetainPtr or OSObjectPtr are same as alpha.webkit.UncountedCallArgsChecker for ref-counted objects.

1.2.10.9.alpha.webkit.UncountedLocalVarsChecker

The goal of this rule is to make sure that any uncounted local variable is backed by a ref-counted object with lifetime that is strictly larger than the scope of the uncounted local variable. To be on the safe side we require the scope of an uncounted variable to be embedded in the scope of ref-counted object that backs it.

These are examples of cases that we consider safe:

voidfoo1(){RefPtr<RefCountable>counted;// The scope of uncounted is EMBEDDED in the scope of counted.{RefCountable*uncounted=counted.get();// ok}}voidfoo2(RefPtr<RefCountable>counted_param){RefCountable*uncounted=counted_param.get();// ok}voidFooClass::foo_method(){RefCountable*uncounted=this;// ok}

Here are some examples of situations that we warn about as theymight be potentially unsafe. The logic is that either we’re able to guarantee that a local variable is safe or it’s considered unsafe.

voidfoo1(){RefCountable*uncounted=newRefCountable;// warn}RefCountable*global_uncounted;voidfoo2(){RefCountable*uncounted=global_uncounted;// warn}voidfoo3(){RefPtr<RefCountable>counted;// The scope of uncounted is not EMBEDDED in the scope of counted.RefCountable*uncounted=counted.get();// warn}

1.2.10.10.alpha.webkit.UncheckedLocalVarsChecker

The goal of this rule is to make sure that any unchecked local variable is backed by a CheckedPtr or CheckedRef with lifetime that is strictly larger than the scope of the unchecked local variable. To be on the safe side we require the scope of an unchecked variable to be embedded in the scope of CheckedPtr/CheckRef object that backs it.

These are examples of cases that we consider safe:

voidfoo1(){CheckedPtr<RefCountable>counted;// The scope of uncounted is EMBEDDED in the scope of counted.{RefCountable*uncounted=counted.get();// ok}}voidfoo2(CheckedPtr<RefCountable>counted_param){RefCountable*uncounted=counted_param.get();// ok}voidFooClass::foo_method(){RefCountable*uncounted=this;// ok}

Here are some examples of situations that we warn about as theymight be potentially unsafe. The logic is that either we’re able to guarantee that a local variable is safe or it’s considered unsafe.

voidfoo1(){RefCountable*uncounted=newRefCountable;// warn}RefCountable*global_uncounted;voidfoo2(){RefCountable*uncounted=global_uncounted;// warn}voidfoo3(){RefPtr<RefCountable>counted;// The scope of uncounted is not EMBEDDED in the scope of counted.RefCountable*uncounted=counted.get();// warn}

1.2.10.11.alpha.webkit.UnretainedLocalVarsChecker

The goal of this rule is to make sure that any NS or CF local variable is backed by a RetainPtr or OSObjectPtr with lifetime that is strictly larger than the scope of the unretained local variable. To be on the safe side we require the scope of an unretained variable to be embedded in the scope of RetainPtr or OSObjectPtr object that backs it.

The rules of when to use and not to use RetainPtr or OSObjectPtr are same as alpha.webkit.UncountedCallArgsChecker for ref-counted objects.

These are examples of cases that we consider safe:

voidfoo1(){RetainPtr<NSObject>retained;// The scope of unretained is EMBEDDED in the scope of retained.{NSObject*unretained=retained.get();// ok}}voidfoo2(RetainPtr<NSObject>retained_param){NSObject*unretained=retained_param.get();// ok}voidFooClass::foo_method(){NSObject*unretained=this;// ok}

Here are some examples of situations that we warn about as theymight be potentially unsafe. The logic is that either we’re able to guarantee that a local variable is safe or it’s considered unsafe.

voidfoo1(){NSObject*unretained=[[NSObjectalloc]init];// warn}NSObject*global_unretained;voidfoo2(){NSObject*unretained=global_unretained;// warn}voidfoo3(){RetainPtr<NSObject>retained;// The scope of unretained is not EMBEDDED in the scope of retained.NSObject*unretained=retained.get();// warn}

1.2.10.12.webkit.RetainPtrCtorAdoptChecker

The goal of this rule is to make sure the constructors of RetainPtr and OSObjectPtr as well as adoptNS, adoptCF, and adoptOSObject are used correctly.When creating a RetainPtr or OSObjectPtr with +1 semantics, adoptNS, adoptCF, or adoptOSObject should be used, and in +0 semantics, RetainPtr or OSObjectPtr constructor should be used.Warn otherwise.

These are examples of cases that we consider correct:

RetainPtrptr=adoptNS([[NSObjectalloc]init]);// okRetainPtrptr=CGImageGetColorSpace(image);// okOSObjectPtrptr=adoptOSObject(dispatch_queue_create("some queue",nullptr));// ok

Here are some examples of cases that we consider incorrect use of RetainPtr constructor and adoptCF

RetainPtrptr=[[NSObjectalloc]init];// warnautoptr=adoptCF(CGImageGetColorSpace(image));// warnOSObjectPtrptr=dispatch_queue_create("some queue",nullptr);// warn

1.3.Debug Checkers

1.3.1.debug

Checkers used for debugging the analyzer.Debug Checks page contains a detailed description.

1.3.1.1.debug.AnalysisOrder

Print callbacks that are called during analysis in order.

1.3.1.2.debug.ConfigDumper

Dump config table.

1.3.1.3.debug.DumpCFG Display

Control-Flow Graphs.

1.3.1.4.debug.DumpCallGraph

Display Call Graph.

1.3.1.5.debug.DumpCalls

Print calls as they are traversed by the engine.

1.3.1.6.debug.DumpDominators

Print the dominance tree for a given CFG.

1.3.1.7.debug.DumpLiveVars

Print results of live variable analysis.

1.3.1.8.debug.DumpTraversal

Print branch conditions as they are traversed by the engine.

1.3.1.9.debug.ExprInspection

Check the analyzer’s understanding of expressions.

1.3.1.10.debug.Stats

Emit warnings with analyzer statistics.

1.3.1.11.debug.TaintTest

Mark tainted symbols as such.

1.3.1.12.debug.ViewCFG

View Control-Flow Graphs using GraphViz.

1.3.1.13.debug.ViewCallGraph

View Call Graph using GraphViz.

1.3.1.14.debug.ViewExplodedGraph

View Exploded Graphs using GraphViz.