5 The analyzer performs checks that are categorized into families or "checkers".
7 The default set of checkers covers a variety of checks targeted at finding security and API usage bugs,
8 dead code, and other logic errors. See the :ref:`default-checkers` checkers list below.
10 In addition to these, the analyzer contains a number of :ref:`alpha-checkers` (aka *alpha* checkers).
11 These checkers are under development and are switched off by default. They may crash or emit a higher number of false positives.
13 The :ref:`debug-checkers` package contains checkers for analyzer developers for debugging purposes.
15 .. contents:: Table of Contents
28 Models core language features and contains general-purpose checkers such as division by zero,
29 null pointer dereference, usage of uninitialized values, etc.
30 *These checkers must be always switched on as other checker rely on them.*
32 .. _core-BitwiseShift:
34 core.BitwiseShift (C, C++)
35 """"""""""""""""""""""""""
37 Finds undefined behavior caused by the bitwise left- and right-shift operator
38 operating on integer types.
40 By default, this checker only reports situations when the right operand is
41 either negative or larger than the bit width of the type of the left operand;
42 these are logically unsound.
44 Moreover, if the pedantic mode is activated by
45 ``-analyzer-config core.BitwiseShift:Pedantic=true``, then this checker also
46 reports situations where the _left_ operand of a shift operator is negative or
47 overflow occurs during the right shift of a signed value. (Most compilers
48 handle these predictably, but the C standard and the C++ standards before C++20
49 say that they're undefined behavior. In the C++20 standard these constructs are
50 well-defined, so activating pedantic mode in C++20 has no effect.)
56 static_assert(sizeof(int) == 4, "assuming 32-bit int")
58 void basic_examples(int a, int b) {
60 b = a << b; // warn: right operand is negative in left shift
62 b = a >> b; // warn: right shift overflows the capacity of 'int'
66 int pedantic_examples(int a, int b) {
68 return a >> b; // warn: left operand is negative in right shift
70 a = 1000u << 31; // OK, overflow of unsigned value is well-defined, a == 0
72 a = b << 31; // this is undefined before C++20, but the checker doesn't
73 // warn because it doesn't know the exact value of b
75 return 1000 << 31; // warn: this overflows the capacity of 'int'
80 Ensure the shift operands are in proper range before shifting.
82 .. _core-CallAndMessage:
84 core.CallAndMessage (C, C++, ObjC)
85 """"""""""""""""""""""""""""""""""
86 Check for logical errors for function calls and Objective-C message expressions (e.g., uninitialized arguments, null function pointers).
88 .. literalinclude:: checkers/callandmessage_example.c
93 core.DivideZero (C, C++, ObjC)
94 """"""""""""""""""""""""""""""
95 Check for division by zero.
97 .. literalinclude:: checkers/dividezero_example.c
100 .. _core-NonNullParamChecker:
102 core.NonNullParamChecker (C, C++, ObjC)
103 """""""""""""""""""""""""""""""""""""""
104 Check for null pointers passed as arguments to a function whose arguments are references or marked with the 'nonnull' attribute.
108 int f(int *p) __attribute__((nonnull));
115 .. _core-NullDereference:
117 core.NullDereference (C, C++, ObjC)
118 """""""""""""""""""""""""""""""""""
119 Check for dereferences of null pointers.
121 This checker specifically does
122 not report null pointer dereferences for x86 and x86-64 targets when the
123 address space is 256 (x86 GS Segment), 257 (x86 FS Segment), or 258 (x86 SS
124 segment). See `X86/X86-64 Language Extensions
125 <https://clang.llvm.org/docs/LanguageExtensions.html#memory-references-to-specified-segments>`__
128 The ``SuppressAddressSpaces`` option suppresses
129 warnings for null dereferences of all pointers with address spaces. You can
130 disable this behavior with the option
131 ``-analyzer-config core.NullDereference:SuppressAddressSpaces=false``.
141 int x = p[0]; // warn
158 int k = pc->x; // warn
173 .. _core-StackAddressEscape:
175 core.StackAddressEscape (C)
176 """""""""""""""""""""""""""
177 Check that addresses to stack memory do not escape the function.
184 char const str[] = "string";
189 return __builtin_alloca(12); // warn
199 .. _core-UndefinedBinaryOperatorResult:
201 core.UndefinedBinaryOperatorResult (C)
202 """"""""""""""""""""""""""""""""""""""
203 Check for undefined results of binary operators.
209 int y = x + 1; // warn: left operand is garbage
216 Check for declarations of Variable Length Arrays of undefined or zero size.
218 Check for declarations of VLA of undefined or zero size.
224 int vla1[x]; // warn: garbage as size
229 int vla2[x]; // warn: zero size
232 .. _core-uninitialized-ArraySubscript:
234 core.uninitialized.ArraySubscript (C)
235 """""""""""""""""""""""""""""""""""""
236 Check for uninitialized values used as array subscripts.
242 int x = a[i]; // warn: array subscript is undefined
245 .. _core-uninitialized-Assign:
247 core.uninitialized.Assign (C)
248 """""""""""""""""""""""""""""
249 Check for assigning uninitialized values.
255 x |= 1; // warn: left expression is uninitialized
258 .. _core-uninitialized-Branch:
260 core.uninitialized.Branch (C)
261 """""""""""""""""""""""""""""
262 Check for uninitialized values used as branch conditions.
272 .. _core-uninitialized-CapturedBlockVariable:
274 core.uninitialized.CapturedBlockVariable (C)
275 """"""""""""""""""""""""""""""""""""""""""""
276 Check for blocks that capture uninitialized values.
282 ^{ int y = x; }(); // warn
285 .. _core-uninitialized-UndefReturn:
287 core.uninitialized.UndefReturn (C)
288 """"""""""""""""""""""""""""""""""
289 Check for uninitialized values being returned to the caller.
298 .. _core-uninitialized-NewArraySize:
300 core.uninitialized.NewArraySize (C++)
301 """""""""""""""""""""""""""""""""""""
303 Check if the element count in new[] is garbage or undefined.
309 int *arr = new int[n]; // warn: Element count in new[] is a garbage value
314 .. _cplusplus-checkers:
322 .. _cplusplus-InnerPointer:
324 cplusplus.InnerPointer (C++)
325 """"""""""""""""""""""""""""
326 Check for inner pointers of C++ containers used after re/deallocation.
328 Many container methods in the C++ standard library are known to invalidate
329 "references" (including actual references, iterators and raw pointers) to
330 elements of the container. Using such references after they are invalidated
331 causes undefined behavior, which is a common source of memory errors in C++ that
332 this checker is capable of finding.
334 The checker is currently limited to ``std::string`` objects and doesn't
335 recognize some of the more sophisticated approaches to passing unowned pointers
336 around, such as ``std::string_view``.
340 void deref_after_assignment() {
341 std::string s = "llvm";
342 const char *c = s.data(); // note: pointer to inner buffer of 'std::string' obtained here
343 s = "clang"; // note: inner buffer of 'std::string' reallocated by call to 'operator='
344 consume(c); // warn: inner pointer of container used after re/deallocation
347 const char *return_temp(int x) {
348 return std::to_string(x).c_str(); // warn: inner pointer of container used after re/deallocation
349 // note: pointer to inner buffer of 'std::string' obtained here
350 // note: inner buffer of 'std::string' deallocated by call to destructor
353 .. _cplusplus-NewDelete:
355 cplusplus.NewDelete (C++)
356 """""""""""""""""""""""""
357 Check for double-free and use-after-free problems. Traces memory managed by new/delete.
359 .. literalinclude:: checkers/newdelete_example.cpp
362 .. _cplusplus-NewDeleteLeaks:
364 cplusplus.NewDeleteLeaks (C++)
365 """"""""""""""""""""""""""""""
366 Check for memory leaks. Traces memory managed by new/delete.
374 .. _cplusplus-PlacementNew:
376 cplusplus.PlacementNew (C++)
377 """"""""""""""""""""""""""""
378 Check if default placement new is provided with pointers to sufficient storage capacity.
386 long *lp = ::new (&s) long; // warn
389 .. _cplusplus-SelfAssignment:
391 cplusplus.SelfAssignment (C++)
392 """"""""""""""""""""""""""""""
393 Checks C++ copy and move assignment operators for self assignment.
395 .. _cplusplus-StringChecker:
397 cplusplus.StringChecker (C++)
398 """""""""""""""""""""""""""""
399 Checks std::string operations.
401 Checks if the cstring pointer from which the ``std::string`` object is
402 constructed is ``NULL`` or not.
403 If the checker cannot reason about the nullness of the pointer it will assume
404 that it was non-null to satisfy the precondition of the constructor.
406 This checker is capable of checking the `SEI CERT C++ coding rule STR51-CPP.
407 Do not attempt to create a std::string from a null pointer
408 <https://wiki.sei.cmu.edu/confluence/x/E3s-BQ>`__.
414 void f(const char *p) {
416 std::string msg(p); // warn: The parameter must not be null
420 .. _deadcode-checkers:
427 .. _deadcode-DeadStores:
429 deadcode.DeadStores (C)
430 """""""""""""""""""""""
431 Check for values stored to variables that are never read afterwards.
440 The ``WarnForDeadNestedAssignments`` option enables the checker to emit
441 warnings for nested dead assignments. You can disable with the
442 ``-analyzer-config deadcode.DeadStores:WarnForDeadNestedAssignments=false``.
445 Would warn for this e.g.:
446 if ((y = make_int())) {
449 .. _nullability-checkers:
454 Objective C checkers that warn for null pointer passing and dereferencing errors.
456 .. _nullability-NullPassedToNonnull:
458 nullability.NullPassedToNonnull (ObjC)
459 """"""""""""""""""""""""""""""""""""""
460 Warns when a null pointer is passed to a pointer which has a _Nonnull type.
466 // Warning: nil passed to a callee that requires a non-null 1st parameter
467 NSString *greeting = [@"Hello " stringByAppendingString:name];
469 .. _nullability-NullReturnedFromNonnull:
471 nullability.NullReturnedFromNonnull (ObjC)
472 """"""""""""""""""""""""""""""""""""""""""
473 Warns when a null pointer is returned from a function that has _Nonnull return type.
477 - (nonnull id)firstChild {
479 if ([_children count] > 0)
480 result = _children[0];
482 // Warning: nil returned from a method that is expected
483 // to return a non-null value
487 .. _nullability-NullableDereferenced:
489 nullability.NullableDereferenced (ObjC)
490 """""""""""""""""""""""""""""""""""""""
491 Warns when a nullable pointer is dereferenced.
497 struct LinkedList *next;
500 struct LinkedList * _Nullable getNext(struct LinkedList *l);
502 void updateNextData(struct LinkedList *list, int newData) {
503 struct LinkedList *next = getNext(list);
504 // Warning: Nullable pointer is dereferenced
508 .. _nullability-NullablePassedToNonnull:
510 nullability.NullablePassedToNonnull (ObjC)
511 """"""""""""""""""""""""""""""""""""""""""
512 Warns when a nullable pointer is passed to a pointer which has a _Nonnull type.
516 typedef struct Dummy { int val; } Dummy;
517 Dummy *_Nullable returnsNullable();
518 void takesNonnull(Dummy *_Nonnull);
521 Dummy *p = returnsNullable();
522 takesNonnull(p); // warn
525 .. _nullability-NullableReturnedFromNonnull:
527 nullability.NullableReturnedFromNonnull (ObjC)
528 """"""""""""""""""""""""""""""""""""""""""""""
529 Warns when a nullable pointer is returned from a function that has _Nonnull return type.
536 Checkers for portability, performance or coding style specific rules.
538 .. _optin-cplusplus-UninitializedObject:
540 optin.cplusplus.UninitializedObject (C++)
541 """""""""""""""""""""""""""""""""""""""""
543 This checker reports uninitialized fields in objects created after a constructor
544 call. It doesn't only find direct uninitialized fields, but rather makes a deep
545 inspection of the object, analyzing all of its fields' subfields.
546 The checker regards inherited fields as direct fields, so one will receive
547 warnings for uninitialized inherited data members as well.
551 // With Pedantic and CheckPointeeInitialization set to true
555 int x; // note: uninitialized field 'this->b.x'
556 // note: uninitialized field 'this->bptr->x'
557 int y; // note: uninitialized field 'this->b.y'
558 // note: uninitialized field 'this->bptr->y'
560 int *iptr; // note: uninitialized pointer 'this->iptr'
563 char *cptr; // note: uninitialized pointee 'this->cptr'
565 A (B *bptr, char *cptr) : bptr(bptr), cptr(cptr) {}
571 A a(&b, &c); // warning: 6 uninitialized fields
572 // after the constructor call
575 // With Pedantic set to false and
576 // CheckPointeeInitialization set to true
577 // (every field is uninitialized)
589 A (B *bptr, char *cptr) : bptr(bptr), cptr(cptr) {}
595 A a(&b, &c); // no warning
598 // With Pedantic set to true and
599 // CheckPointeeInitialization set to false
600 // (pointees are regarded as initialized)
604 int x; // note: uninitialized field 'this->b.x'
605 int y; // note: uninitialized field 'this->b.y'
607 int *iptr; // note: uninitialized pointer 'this->iptr'
612 A (B *bptr, char *cptr) : bptr(bptr), cptr(cptr) {}
618 A a(&b, &c); // warning: 3 uninitialized fields
619 // after the constructor call
625 This checker has several options which can be set from command line (e.g.
626 ``-analyzer-config optin.cplusplus.UninitializedObject:Pedantic=true``):
628 * ``Pedantic`` (boolean). If to false, the checker won't emit warnings for
629 objects that don't have at least one initialized field. Defaults to false.
631 * ``NotesAsWarnings`` (boolean). If set to true, the checker will emit a
632 warning for each uninitialized field, as opposed to emitting one warning per
633 constructor call, and listing the uninitialized fields that belongs to it in
634 notes. *Defaults to false*.
636 * ``CheckPointeeInitialization`` (boolean). If set to false, the checker will
637 not analyze the pointee of pointer/reference fields, and will only check
638 whether the object itself is initialized. *Defaults to false*.
640 * ``IgnoreRecordsWithField`` (string). If supplied, the checker will not analyze
641 structures that have a field with a name or type name that matches the given
642 pattern. *Defaults to ""*.
644 .. _optin-cplusplus-VirtualCall:
646 optin.cplusplus.VirtualCall (C++)
647 """""""""""""""""""""""""""""""""
648 Check virtual function calls during construction or destruction.
668 .. _optin-mpi-MPI-Checker:
670 optin.mpi.MPI-Checker (C)
671 """""""""""""""""""""""""
678 MPI_Request sendReq1;
679 MPI_Ireduce(MPI_IN_PLACE, &buf, 1, MPI_DOUBLE, MPI_SUM,
680 0, MPI_COMM_WORLD, &sendReq1);
681 } // warn: request 'sendReq1' has no matching wait.
686 MPI_Isend(&buf, 1, MPI_DOUBLE, 0, 0, MPI_COMM_WORLD, &sendReq);
687 MPI_Irecv(&buf, 1, MPI_DOUBLE, 0, 0, MPI_COMM_WORLD, &sendReq); // warn
688 MPI_Isend(&buf, 1, MPI_DOUBLE, 0, 0, MPI_COMM_WORLD, &sendReq); // warn
689 MPI_Wait(&sendReq, MPI_STATUS_IGNORE);
692 void missingNonBlocking() {
694 MPI_Comm_rank(MPI_COMM_WORLD, &rank);
695 MPI_Request sendReq1[10][10][10];
696 MPI_Wait(&sendReq1[1][7][9], MPI_STATUS_IGNORE); // warn
699 .. _optin-osx-cocoa-localizability-EmptyLocalizationContextChecker:
701 optin.osx.cocoa.localizability.EmptyLocalizationContextChecker (ObjC)
702 """""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
703 Check that NSLocalizedString macros include a comment for context.
708 NSString *string = NSLocalizedString(@"LocalizedString", nil); // warn
709 NSString *string2 = NSLocalizedString(@"LocalizedString", @" "); // warn
710 NSString *string3 = NSLocalizedStringWithDefaultValue(
711 @"LocalizedString", nil, [[NSBundle alloc] init], nil,@""); // warn
714 .. _optin-osx-cocoa-localizability-NonLocalizedStringChecker:
716 optin.osx.cocoa.localizability.NonLocalizedStringChecker (ObjC)
717 """""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
718 Warns about uses of non-localized NSStrings passed to UI methods expecting localized NSStrings.
722 NSString *alarmText =
723 NSLocalizedString(@"Enabled", @"Indicates alarm is turned on");
725 alarmText = @"Disabled";
727 UILabel *alarmStateLabel = [[UILabel alloc] init];
729 // Warning: User-facing text should use localized string macro
730 [alarmStateLabel setText:alarmText];
732 .. _optin-performance-GCDAntipattern:
734 optin.performance.GCDAntipattern
735 """"""""""""""""""""""""""""""""
736 Check for performance anti-patterns when using Grand Central Dispatch.
738 .. _optin-performance-Padding:
740 optin.performance.Padding
741 """""""""""""""""""""""""
742 Check for excessively padded structs.
744 .. _optin-portability-UnixAPI:
746 optin.portability.UnixAPI
747 """""""""""""""""""""""""
748 Finds implementation-defined behavior in UNIX/Posix functions.
751 .. _security-checkers:
756 Security related checkers.
758 .. _security-FloatLoopCounter:
760 security.FloatLoopCounter (C)
761 """""""""""""""""""""""""""""
762 Warn on using a floating point value as a loop counter (CERT: FLP30-C, FLP30-CPP).
767 for (float x = 0.1f; x <= 1.0f; x += 0.1f) {} // warn
770 .. _security-insecureAPI-UncheckedReturn:
772 security.insecureAPI.UncheckedReturn (C)
773 """"""""""""""""""""""""""""""""""""""""
774 Warn on uses of functions whose return values must be always checked.
782 .. _security-insecureAPI-bcmp:
784 security.insecureAPI.bcmp (C)
785 """""""""""""""""""""""""""""
786 Warn on uses of the 'bcmp' function.
791 bcmp(ptr0, ptr1, n); // warn
794 .. _security-insecureAPI-bcopy:
796 security.insecureAPI.bcopy (C)
797 """"""""""""""""""""""""""""""
798 Warn on uses of the 'bcopy' function.
803 bcopy(src, dst, n); // warn
806 .. _security-insecureAPI-bzero:
808 security.insecureAPI.bzero (C)
809 """"""""""""""""""""""""""""""
810 Warn on uses of the 'bzero' function.
815 bzero(ptr, n); // warn
818 .. _security-insecureAPI-getpw:
820 security.insecureAPI.getpw (C)
821 """"""""""""""""""""""""""""""
822 Warn on uses of the 'getpw' function.
828 getpw(2, buff); // warn
831 .. _security-insecureAPI-gets:
833 security.insecureAPI.gets (C)
834 """""""""""""""""""""""""""""
835 Warn on uses of the 'gets' function.
844 .. _security-insecureAPI-mkstemp:
846 security.insecureAPI.mkstemp (C)
847 """"""""""""""""""""""""""""""""
848 Warn when 'mkstemp' is passed fewer than 6 X's in the format string.
853 mkstemp("XX"); // warn
856 .. _security-insecureAPI-mktemp:
858 security.insecureAPI.mktemp (C)
859 """""""""""""""""""""""""""""""
860 Warn on uses of the ``mktemp`` function.
865 char *x = mktemp("/tmp/zxcv"); // warn: insecure, use mkstemp
868 .. _security-insecureAPI-rand:
870 security.insecureAPI.rand (C)
871 """""""""""""""""""""""""""""
872 Warn on uses of inferior random number generating functions (only if arc4random function is available):
873 ``drand48, erand48, jrand48, lcong48, lrand48, mrand48, nrand48, random, rand_r``.
881 .. _security-insecureAPI-strcpy:
883 security.insecureAPI.strcpy (C)
884 """""""""""""""""""""""""""""""
885 Warn on uses of the ``strcpy`` and ``strcat`` functions.
893 strcpy(x, y); // warn
897 .. _security-insecureAPI-vfork:
899 security.insecureAPI.vfork (C)
900 """"""""""""""""""""""""""""""
901 Warn on uses of the 'vfork' function.
909 .. _security-insecureAPI-DeprecatedOrUnsafeBufferHandling:
911 security.insecureAPI.DeprecatedOrUnsafeBufferHandling (C)
912 """""""""""""""""""""""""""""""""""""""""""""""""""""""""
913 Warn on occurrences of unsafe or deprecated buffer handling functions, which now have a secure variant: ``sprintf, vsprintf, scanf, wscanf, fscanf, fwscanf, vscanf, vwscanf, vfscanf, vfwscanf, sscanf, swscanf, vsscanf, vswscanf, swprintf, snprintf, vswprintf, vsnprintf, memcpy, memmove, strncpy, strncat, memset``
919 strncpy(buf, "a", 1); // warn
932 Check calls to various UNIX/Posix functions: ``open, pthread_once, calloc, malloc, realloc, alloca``.
934 .. literalinclude:: checkers/unix_api_example.c
941 Check for memory leaks, double free, and use-after-free problems. Traces memory managed by malloc()/free().
943 .. literalinclude:: checkers/unix_malloc_example.c
946 .. _unix-MallocSizeof:
948 unix.MallocSizeof (C)
949 """""""""""""""""""""
950 Check for dubious ``malloc`` arguments involving ``sizeof``.
955 long *p = malloc(sizeof(short));
956 // warn: result is converted to 'long *', which is
957 // incompatible with operand type 'short'
961 .. _unix-MismatchedDeallocator:
963 unix.MismatchedDeallocator (C, C++)
964 """""""""""""""""""""""""""""""""""
965 Check for mismatched deallocators.
967 .. literalinclude:: checkers/mismatched_deallocator_example.cpp
974 Check for proper usage of ``vfork``.
979 pid_t pid = vfork(); // warn
990 x = 0; // warn: this assignment is prohibited
993 foo(); // warn: this function call is prohibited
996 return 0; // warn: return is prohibited
1002 .. _unix-cstring-BadSizeArg:
1004 unix.cstring.BadSizeArg (C)
1005 """""""""""""""""""""""""""
1006 Check the size argument passed into C string functions for common erroneous patterns. Use ``-Wno-strncat-size`` compiler option to mute other ``strncat``-related compiler warnings.
1012 strncat(dest, """""""""""""""""""""""""*", sizeof(dest));
1013 // warn: potential buffer overflow
1016 .. _unix-cstring-NullArg:
1018 unix.cstring.NullArg (C)
1019 """""""""""""""""""""""""
1020 Check for null pointers being passed as arguments to C string functions:
1021 ``strlen, strnlen, strcpy, strncpy, strcat, strncat, strcmp, strncmp, strcasecmp, strncasecmp, wcslen, wcsnlen``.
1026 return strlen(0); // warn
1039 Check for proper uses of various Apple APIs.
1041 .. code-block:: objc
1044 dispatch_once_t pred = 0;
1045 dispatch_once(&pred, ^(){}); // warn: dispatch_once uses local
1048 .. _osx-NumberObjectConversion:
1050 osx.NumberObjectConversion (C, C++, ObjC)
1051 """""""""""""""""""""""""""""""""""""""""
1052 Check for erroneous conversions of objects representing numbers into numbers.
1054 .. code-block:: objc
1056 NSNumber *photoCount = [albumDescriptor objectForKey:@"PhotoCount"];
1057 // Warning: Comparing a pointer value of type 'NSNumber *'
1058 // to a scalar integer value
1059 if (photoCount > 0) {
1060 [self displayPhotos];
1063 .. _osx-ObjCProperty:
1065 osx.ObjCProperty (ObjC)
1066 """""""""""""""""""""""
1067 Check for proper uses of Objective-C properties.
1069 .. code-block:: objc
1071 NSNumber *photoCount = [albumDescriptor objectForKey:@"PhotoCount"];
1072 // Warning: Comparing a pointer value of type 'NSNumber *'
1073 // to a scalar integer value
1074 if (photoCount > 0) {
1075 [self displayPhotos];
1079 .. _osx-SecKeychainAPI:
1081 osx.SecKeychainAPI (C)
1082 """"""""""""""""""""""
1083 Check for proper uses of Secure Keychain APIs.
1085 .. literalinclude:: checkers/seckeychainapi_example.m
1088 .. _osx-cocoa-AtSync:
1090 osx.cocoa.AtSync (ObjC)
1091 """""""""""""""""""""""
1092 Check for nil pointers used as mutexes for @synchronized.
1094 .. code-block:: objc
1098 @synchronized(x) {} // warn: nil value used as mutex
1103 @synchronized(y) {} // warn: uninitialized value used as mutex
1106 .. _osx-cocoa-AutoreleaseWrite:
1108 osx.cocoa.AutoreleaseWrite
1109 """"""""""""""""""""""""""
1110 Warn about potentially crashing writes to autoreleasing objects from different autoreleasing pools in Objective-C.
1112 .. _osx-cocoa-ClassRelease:
1114 osx.cocoa.ClassRelease (ObjC)
1115 """""""""""""""""""""""""""""
1116 Check for sending 'retain', 'release', or 'autorelease' directly to a Class.
1118 .. code-block:: objc
1120 @interface MyClass : NSObject
1124 [MyClass release]; // warn
1127 .. _osx-cocoa-Dealloc:
1129 osx.cocoa.Dealloc (ObjC)
1130 """"""""""""""""""""""""
1131 Warn about Objective-C classes that lack a correct implementation of -dealloc
1133 .. literalinclude:: checkers/dealloc_example.m
1136 .. _osx-cocoa-IncompatibleMethodTypes:
1138 osx.cocoa.IncompatibleMethodTypes (ObjC)
1139 """"""""""""""""""""""""""""""""""""""""
1140 Warn about Objective-C method signatures with type incompatibilities.
1142 .. code-block:: objc
1144 @interface MyClass1 : NSObject
1148 @implementation MyClass1
1149 - (int)foo { return 1; }
1152 @interface MyClass2 : MyClass1
1156 @implementation MyClass2
1157 - (float)foo { return 1.0; } // warn
1160 .. _osx-cocoa-Loops:
1164 Improved modeling of loops using Cocoa collection types.
1166 .. _osx-cocoa-MissingSuperCall:
1168 osx.cocoa.MissingSuperCall (ObjC)
1169 """""""""""""""""""""""""""""""""
1170 Warn about Objective-C methods that lack a necessary call to super.
1172 .. code-block:: objc
1174 @interface Test : UIViewController
1176 @implementation test
1177 - (void)viewDidLoad {} // warn
1181 .. _osx-cocoa-NSAutoreleasePool:
1183 osx.cocoa.NSAutoreleasePool (ObjC)
1184 """"""""""""""""""""""""""""""""""
1185 Warn for suboptimal uses of NSAutoreleasePool in Objective-C GC mode.
1187 .. code-block:: objc
1190 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
1191 [pool release]; // warn
1194 .. _osx-cocoa-NSError:
1196 osx.cocoa.NSError (ObjC)
1197 """"""""""""""""""""""""
1198 Check usage of NSError parameters.
1200 .. code-block:: objc
1202 @interface A : NSObject
1203 - (void)foo:(NSError """""""""""""""""""""""")error;
1207 - (void)foo:(NSError """""""""""""""""""""""")error {
1208 // warn: method accepting NSError"""""""""""""""""""""""" should have a non-void
1213 @interface A : NSObject
1214 - (BOOL)foo:(NSError """""""""""""""""""""""")error;
1218 - (BOOL)foo:(NSError """""""""""""""""""""""")error {
1219 *error = 0; // warn: potential null dereference
1224 .. _osx-cocoa-NilArg:
1226 osx.cocoa.NilArg (ObjC)
1227 """""""""""""""""""""""
1228 Check for prohibited nil arguments to ObjC method calls.
1230 - caseInsensitiveCompare:
1233 - compare:options:range:
1234 - compare:options:range:locale:
1235 - componentsSeparatedByCharactersInSet:
1238 .. code-block:: objc
1240 NSComparisonResult test(NSString *s) {
1241 NSString *aString = nil;
1242 return [s caseInsensitiveCompare:aString];
1243 // warn: argument to 'NSString' method
1244 // 'caseInsensitiveCompare:' cannot be nil
1248 .. _osx-cocoa-NonNilReturnValue:
1250 osx.cocoa.NonNilReturnValue
1251 """""""""""""""""""""""""""
1252 Models the APIs that are guaranteed to return a non-nil value.
1254 .. _osx-cocoa-ObjCGenerics:
1256 osx.cocoa.ObjCGenerics (ObjC)
1257 """""""""""""""""""""""""""""
1258 Check for type errors when using Objective-C generics.
1260 .. code-block:: objc
1262 NSMutableArray *names = [NSMutableArray array];
1263 NSMutableArray *birthDates = names;
1265 // Warning: Conversion from value of type 'NSDate *'
1266 // to incompatible type 'NSString *'
1267 [birthDates addObject: [NSDate date]];
1269 .. _osx-cocoa-RetainCount:
1271 osx.cocoa.RetainCount (ObjC)
1272 """"""""""""""""""""""""""""
1273 Check for leaks and improper reference count management
1275 .. code-block:: objc
1278 NSString *s = [[NSString alloc] init]; // warn
1281 CFStringRef test(char *bytes) {
1282 return CFStringCreateWithCStringNoCopy(
1283 0, bytes, NSNEXTSTEPStringEncoding, 0); // warn
1287 .. _osx-cocoa-RunLoopAutoreleaseLeak:
1289 osx.cocoa.RunLoopAutoreleaseLeak
1290 """"""""""""""""""""""""""""""""
1291 Check for leaked memory in autorelease pools that will never be drained.
1293 .. _osx-cocoa-SelfInit:
1295 osx.cocoa.SelfInit (ObjC)
1296 """""""""""""""""""""""""
1297 Check that 'self' is properly initialized inside an initializer method.
1299 .. code-block:: objc
1301 @interface MyObj : NSObject {
1307 @implementation MyObj
1310 x = 0; // warn: instance variable used while 'self' is not
1316 @interface MyObj : NSObject
1320 @implementation MyObj
1323 return self; // warn: returning uninitialized 'self'
1327 .. _osx-cocoa-SuperDealloc:
1329 osx.cocoa.SuperDealloc (ObjC)
1330 """""""""""""""""""""""""""""
1331 Warn about improper use of '[super dealloc]' in Objective-C.
1333 .. code-block:: objc
1335 @interface SuperDeallocThenReleaseIvarClass : NSObject {
1340 @implementation SuperDeallocThenReleaseIvarClass
1343 [_ivar release]; // warn
1347 .. _osx-cocoa-UnusedIvars:
1349 osx.cocoa.UnusedIvars (ObjC)
1350 """"""""""""""""""""""""""""
1351 Warn about private ivars that are never used.
1353 .. code-block:: objc
1355 @interface MyObj : NSObject {
1361 @implementation MyObj
1364 .. _osx-cocoa-VariadicMethodTypes:
1366 osx.cocoa.VariadicMethodTypes (ObjC)
1367 """"""""""""""""""""""""""""""""""""
1368 Check for passing non-Objective-C types to variadic collection
1369 initialization methods that expect only Objective-C types.
1371 .. code-block:: objc
1374 [NSSet setWithObjects:@"Foo", "Bar", nil];
1375 // warn: argument should be an ObjC pointer type, not 'char *'
1378 .. _osx-coreFoundation-CFError:
1380 osx.coreFoundation.CFError (C)
1381 """"""""""""""""""""""""""""""
1382 Check usage of CFErrorRef* parameters
1386 void test(CFErrorRef *error) {
1387 // warn: function accepting CFErrorRef* should have a
1391 int foo(CFErrorRef *error) {
1392 *error = 0; // warn: potential null dereference
1396 .. _osx-coreFoundation-CFNumber:
1398 osx.coreFoundation.CFNumber (C)
1399 """""""""""""""""""""""""""""""
1400 Check for proper uses of CFNumber APIs.
1404 CFNumberRef test(unsigned char x) {
1405 return CFNumberCreate(0, kCFNumberSInt16Type, &x);
1406 // warn: 8 bit integer is used to initialize a 16 bit integer
1409 .. _osx-coreFoundation-CFRetainRelease:
1411 osx.coreFoundation.CFRetainRelease (C)
1412 """"""""""""""""""""""""""""""""""""""
1413 Check for null arguments to CFRetain/CFRelease/CFMakeCollectable.
1417 void test(CFTypeRef p) {
1419 CFRetain(p); // warn
1422 void test(int x, CFTypeRef p) {
1426 CFRelease(p); // warn
1429 .. _osx-coreFoundation-containers-OutOfBounds:
1431 osx.coreFoundation.containers.OutOfBounds (C)
1432 """""""""""""""""""""""""""""""""""""""""""""
1433 Checks for index out-of-bounds when using 'CFArray' API.
1438 CFArrayRef A = CFArrayCreate(0, 0, 0, &kCFTypeArrayCallBacks);
1439 CFArrayGetValueAtIndex(A, 0); // warn
1442 .. _osx-coreFoundation-containers-PointerSizedValues:
1444 osx.coreFoundation.containers.PointerSizedValues (C)
1445 """"""""""""""""""""""""""""""""""""""""""""""""""""
1446 Warns if 'CFArray', 'CFDictionary', 'CFSet' are created with non-pointer-size values.
1452 CFArrayRef A = CFArrayCreate(0, (const void """""""""""""""""""""""")x, 1,
1453 &kCFTypeArrayCallBacks); // warn
1459 Fuchsia is an open source capability-based operating system currently being
1460 developed by Google. This section describes checkers that can find various
1461 misuses of Fuchsia APIs.
1463 .. _fuchsia-HandleChecker:
1465 fuchsia.HandleChecker
1466 """"""""""""""""""""""""""""
1467 Handles identify resources. Similar to pointers they can be leaked,
1468 double freed, or use after freed. This check attempts to find such problems.
1472 void checkLeak08(int tag) {
1474 zx_channel_create(0, &sa, &sb);
1476 zx_handle_close(sa);
1477 use(sb); // Warn: Potential leak of handle
1478 zx_handle_close(sb);
1484 WebKit is an open-source web browser engine available for macOS, iOS and Linux.
1485 This section describes checkers that can find issues in WebKit codebase.
1487 Most of the checkers focus on memory management for which WebKit uses custom implementation of reference counted smartpointers.
1489 Checkers are formulated in terms related to ref-counting:
1490 - *Ref-counted type* is either ``Ref<T>`` or ``RefPtr<T>``.
1491 - *Ref-countable type* is any type that implements ``ref()`` and ``deref()`` methods as ``RefPtr<>`` is a template (i. e. relies on duck typing).
1492 - *Uncounted type* is ref-countable but not ref-counted type.
1494 .. _webkit-RefCntblBaseVirtualDtor:
1496 webkit.RefCntblBaseVirtualDtor
1497 """"""""""""""""""""""""""""""""""""
1498 All uncounted types used as base classes must have a virtual destructor.
1500 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]``.
1504 struct RefCntblBase {
1509 struct Derived : RefCntblBase { }; // warn
1511 .. _webkit-NoUncountedMemberChecker:
1513 webkit.NoUncountedMemberChecker
1514 """""""""""""""""""""""""""""""""""""
1515 Raw pointers and references to uncounted types can't be used as class members. Only ref-counted types are allowed.
1525 RefCntbl * ptr; // warn
1526 RefCntbl & ptr; // warn
1530 .. _webkit-UncountedLambdaCapturesChecker:
1532 webkit.UncountedLambdaCapturesChecker
1533 """""""""""""""""""""""""""""""""""""
1534 Raw pointers and references to uncounted types can't be captured in lambdas. Only ref-counted types are allowed.
1543 void foo(RefCntbl* a, RefCntbl& b) {
1544 [&, a](){ // warn about 'a'
1545 do_something(b); // warn about 'b'
1551 Experimental Checkers
1552 ---------------------
1554 *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.*
1559 .. _alpha-clone-CloneChecker:
1561 alpha.clone.CloneChecker (C, C++, ObjC)
1562 """""""""""""""""""""""""""""""""""""""
1563 Reports similar pieces of code.
1569 int max(int a, int b) { // warn
1576 int maxClone(int x, int y) { // similar code here
1586 .. _alpha-core-BoolAssignment:
1588 alpha.core.BoolAssignment (ObjC)
1589 """"""""""""""""""""""""""""""""
1590 Warn about assigning non-{0,1} values to boolean variables.
1592 .. code-block:: objc
1595 BOOL b = -1; // warn
1598 .. _alpha-core-C11Lock:
1602 Similarly to :ref:`alpha.unix.PthreadLock <alpha-unix-PthreadLock>`, checks for
1603 the locking/unlocking of ``mtx_t`` mutexes.
1612 mtx_lock(&mtx1); // warn: This lock has already been acquired
1615 .. _alpha-core-CallAndMessageUnInitRefArg:
1617 alpha.core.CallAndMessageUnInitRefArg (C,C++, ObjC)
1618 """""""""""""""""""""""""""""""""""""""""""""""""""
1619 Check for logical errors for function calls and Objective-C
1620 message expressions (e.g., uninitialized arguments, null function pointers, and pointer to undefined variables).
1637 .. _alpha-core-CastSize:
1639 alpha.core.CastSize (C)
1640 """""""""""""""""""""""
1641 Check when casting a malloc'ed type ``T``, whether the size is a multiple of the size of ``T``.
1646 int *x = (int *) malloc(11); // warn
1649 .. _alpha-core-CastToStruct:
1651 alpha.core.CastToStruct (C, C++)
1652 """"""""""""""""""""""""""""""""
1653 Check for cast from non-struct pointer to struct pointer.
1661 struct s *ps = (struct s *) p; // warn
1668 c *pc = (c *) p; // warn
1671 .. _alpha-core-Conversion:
1673 alpha.core.Conversion (C, C++, ObjC)
1674 """"""""""""""""""""""""""""""""""""
1675 Loss of sign/precision in implicit conversions.
1679 void test(unsigned U, signed S) {
1685 if (U < S) { // warn (loss of sign)
1691 long long A = 1LL << 60;
1692 short X = A; // warn (loss of precision)
1695 .. _alpha-core-DynamicTypeChecker:
1697 alpha.core.DynamicTypeChecker (ObjC)
1698 """"""""""""""""""""""""""""""""""""
1699 Check for cases where the dynamic and the static type of an object are unrelated.
1702 .. code-block:: objc
1704 id date = [NSDate date];
1706 // Warning: Object has a dynamic type 'NSDate *' which is
1707 // incompatible with static type 'NSNumber *'"
1708 NSNumber *number = date;
1709 [number doubleValue];
1711 .. _alpha-core-FixedAddr:
1713 alpha.core.FixedAddr (C)
1714 """"""""""""""""""""""""
1715 Check for assignment of a fixed address to a pointer.
1721 p = (int *) 0x10000; // warn
1724 .. _alpha-core-IdenticalExpr:
1726 alpha.core.IdenticalExpr (C, C++)
1727 """""""""""""""""""""""""""""""""
1728 Warn about unintended use of identical expressions in operators.
1735 int b = a | 4 | a; // warn: identical expr on both sides
1743 if (f()) { // warn: true and false branches are identical
1754 .. _alpha-core-PointerArithm:
1756 alpha.core.PointerArithm (C)
1757 """"""""""""""""""""""""""""
1758 Check for pointer arithmetic on locations other than array elements.
1768 .. _alpha-core-PointerSub:
1770 alpha.core.PointerSub (C)
1771 """""""""""""""""""""""""
1772 Check for pointer subtractions on two pointers pointing to different memory chunks.
1778 int d = &y - &x; // warn
1781 .. _alpha-core-SizeofPtr:
1783 alpha.core.SizeofPtr (C)
1784 """"""""""""""""""""""""
1785 Warn about unintended use of ``sizeof()`` on pointer expressions.
1791 int test(struct s *p) {
1793 // warn: sizeof(ptr) can produce an unexpected result
1796 .. _alpha-core-StackAddressAsyncEscape:
1798 alpha.core.StackAddressAsyncEscape (C)
1799 """"""""""""""""""""""""""""""""""""""
1800 Check that addresses to stack memory do not escape the function that involves dispatch_after or dispatch_async.
1801 This checker is a part of ``core.StackAddressEscape``, but is temporarily disabled until some false positives are fixed.
1805 dispatch_block_t test_block_inside_block_async_leak() {
1807 void (^inner)(void) = ^void(void) {
1811 void (^outer)(void) = ^void(void) {
1816 return outer; // warn: address of stack-allocated block is captured by a
1820 .. _alpha-core-TestAfterDivZero:
1822 alpha.core.TestAfterDivZero (C)
1823 """""""""""""""""""""""""""""""
1824 Check for division by variable that is later compared against 0.
1825 Either the comparison is useless or there is division by zero.
1831 if (x == 0) { } // warn
1837 .. _alpha-cplusplus-ArrayDelete:
1839 alpha.cplusplus.ArrayDelete (C++)
1840 """""""""""""""""""""""""""""""""
1841 Reports destructions of arrays of polymorphic objects that are destructed as their base class.
1842 This checker corresponds to the CERT rule `EXP51-CPP: Do not delete an array through a pointer of the incorrect type <https://wiki.sei.cmu.edu/confluence/display/cplusplus/EXP51-CPP.+Do+not+delete+an+array+through+a+pointer+of+the+incorrect+type>`_.
1849 class Derived : public Base {}
1852 Base *x = new Derived[10]; // note: Casting from 'Derived' to 'Base' here
1858 delete[] x; // warn: Deleting an array of 'Derived' objects as their base class 'Base' is undefined
1861 .. _alpha-cplusplus-DeleteWithNonVirtualDtor:
1863 alpha.cplusplus.DeleteWithNonVirtualDtor (C++)
1864 """"""""""""""""""""""""""""""""""""""""""""""
1865 Reports destructions of polymorphic objects with a non-virtual destructor in their base class.
1869 class NonVirtual {};
1870 class NVDerived : public NonVirtual {};
1872 NonVirtual *create() {
1873 NonVirtual *x = new NVDerived(); // note: Casting from 'NVDerived' to
1874 // 'NonVirtual' here
1879 NonVirtual *x = create();
1880 delete x; // warn: destruction of a polymorphic object with no virtual
1884 .. _alpha-cplusplus-EnumCastOutOfRange:
1886 alpha.cplusplus.EnumCastOutOfRange (C++)
1887 """"""""""""""""""""""""""""""""""""""""
1888 Check for integer to enumeration casts that could result in undefined values.
1897 TestEnum t = static_cast(-1);
1898 // warn: the value provided to the cast expression is not in
1899 // the valid range of values for the enum
1901 .. _alpha-cplusplus-InvalidatedIterator:
1903 alpha.cplusplus.InvalidatedIterator (C++)
1904 """""""""""""""""""""""""""""""""""""""""
1905 Check for use of invalidated iterators.
1909 void bad_copy_assign_operator_list1(std::list &L1,
1910 const std::list &L2) {
1911 auto i0 = L1.cbegin();
1913 *i0; // warn: invalidated iterator accessed
1917 .. _alpha-cplusplus-IteratorRange:
1919 alpha.cplusplus.IteratorRange (C++)
1920 """""""""""""""""""""""""""""""""""
1921 Check for iterators used outside their valid ranges.
1925 void simple_bad_end(const std::vector &v) {
1927 *i; // warn: iterator accessed outside of its range
1930 .. _alpha-cplusplus-MismatchedIterator:
1932 alpha.cplusplus.MismatchedIterator (C++)
1933 """"""""""""""""""""""""""""""""""""""""
1934 Check for use of iterators of different containers where iterators of the same container are expected.
1938 void bad_insert3(std::vector &v1, std::vector &v2) {
1939 v2.insert(v1.cbegin(), v2.cbegin(), v2.cend()); // warn: container accessed
1941 // iterator argument
1942 v1.insert(v1.cbegin(), v1.cbegin(), v2.cend()); // warn: iterators of
1943 // different containers
1944 // used where the same
1947 v1.insert(v1.cbegin(), v2.cbegin(), v1.cend()); // warn: iterators of
1948 // different containers
1949 // used where the same
1954 .. _alpha-cplusplus-MisusedMovedObject:
1956 alpha.cplusplus.MisusedMovedObject (C++)
1957 """"""""""""""""""""""""""""""""""""""""
1958 Method calls on a moved-from object and copying a moved-from object will be reported.
1969 A b = std::move(a); // note: 'a' became 'moved-from' here
1970 a.foo(); // warn: method call on a 'moved-from' object 'a'
1973 .. _alpha-cplusplus-SmartPtr:
1975 alpha.cplusplus.SmartPtr (C++)
1976 """"""""""""""""""""""""""""""
1977 Check for dereference of null smart pointers.
1981 void deref_smart_ptr() {
1982 std::unique_ptr<int> P;
1983 *P; // warn: dereference of a default constructed smart unique_ptr
1989 .. _alpha-deadcode-UnreachableCode:
1991 alpha.deadcode.UnreachableCode (C, C++)
1992 """""""""""""""""""""""""""""""""""""""
1993 Check unreachable code.
2024 .. _alpha-fuchsia-lock:
2028 Similarly to :ref:`alpha.unix.PthreadLock <alpha-unix-PthreadLock>`, checks for
2029 the locking/unlocking of fuchsia mutexes.
2038 spin_lock(&mtx1); // warn: This lock has already been acquired
2044 .. _alpha-llvm-Conventions:
2046 alpha.llvm.Conventions
2047 """"""""""""""""""""""
2049 Check code for LLVM codebase conventions:
2051 * A StringRef should not be bound to a temporary std::string whose lifetime is shorter than the StringRef's.
2052 * Clang AST nodes should not have fields that can allocate memory.
2058 .. _alpha-osx-cocoa-DirectIvarAssignment:
2060 alpha.osx.cocoa.DirectIvarAssignment (ObjC)
2061 """""""""""""""""""""""""""""""""""""""""""
2062 Check for direct assignments to instance variables.
2065 .. code-block:: objc
2067 @interface MyClass : NSObject {}
2068 @property (readonly) id A;
2072 @implementation MyClass
2078 .. _alpha-osx-cocoa-DirectIvarAssignmentForAnnotatedFunctions:
2080 alpha.osx.cocoa.DirectIvarAssignmentForAnnotatedFunctions (ObjC)
2081 """"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
2082 Check for direct assignments to instance variables in
2083 the methods annotated with ``objc_no_direct_instance_variable_assignment``.
2085 .. code-block:: objc
2087 @interface MyClass : NSObject {}
2088 @property (readonly) id A;
2089 - (void) fAnnotated __attribute__((
2090 annotate("objc_no_direct_instance_variable_assignment")));
2091 - (void) fNotAnnotated;
2094 @implementation MyClass
2095 - (void) fAnnotated {
2098 - (void) fNotAnnotated {
2104 .. _alpha-osx-cocoa-InstanceVariableInvalidation:
2106 alpha.osx.cocoa.InstanceVariableInvalidation (ObjC)
2107 """""""""""""""""""""""""""""""""""""""""""""""""""
2108 Check that the invalidatable instance variables are
2109 invalidated in the methods annotated with objc_instance_variable_invalidator.
2111 .. code-block:: objc
2113 @protocol Invalidation <NSObject>
2115 __attribute__((annotate("objc_instance_variable_invalidator")));
2118 @interface InvalidationImpObj : NSObject <Invalidation>
2121 @interface SubclassInvalidationImpObj : InvalidationImpObj {
2122 InvalidationImpObj *var;
2127 @implementation SubclassInvalidationImpObj
2128 - (void) invalidate {}
2130 // warn: var needs to be invalidated or set to nil
2132 .. _alpha-osx-cocoa-MissingInvalidationMethod:
2134 alpha.osx.cocoa.MissingInvalidationMethod (ObjC)
2135 """"""""""""""""""""""""""""""""""""""""""""""""
2136 Check that the invalidation methods are present in classes that contain invalidatable instance variables.
2138 .. code-block:: objc
2140 @protocol Invalidation <NSObject>
2142 __attribute__((annotate("objc_instance_variable_invalidator")));
2145 @interface NeedInvalidation : NSObject <Invalidation>
2148 @interface MissingInvalidationMethodDecl : NSObject {
2149 NeedInvalidation *Var; // warn
2153 @implementation MissingInvalidationMethodDecl
2156 .. _alpha-osx-cocoa-localizability-PluralMisuseChecker:
2158 alpha.osx.cocoa.localizability.PluralMisuseChecker (ObjC)
2159 """""""""""""""""""""""""""""""""""""""""""""""""""""""""
2160 Warns against using one vs. many plural pattern in code when generating localized strings.
2162 .. code-block:: objc
2164 NSString *reminderText =
2165 NSLocalizedString(@"None", @"Indicates no reminders");
2166 if (reminderCount == 1) {
2167 // Warning: Plural cases are not supported across all languages.
2168 // Use a .stringsdict file instead
2170 NSLocalizedString(@"1 Reminder", @"Indicates single reminder");
2171 } else if (reminderCount >= 2) {
2172 // Warning: Plural cases are not supported across all languages.
2173 // Use a .stringsdict file instead
2175 [NSString stringWithFormat:
2176 NSLocalizedString(@"%@ Reminders", @"Indicates multiple reminders"),
2183 .. _alpha-security-ArrayBound:
2185 alpha.security.ArrayBound (C)
2186 """""""""""""""""""""""""""""
2187 Warn about buffer overflows (older checker).
2193 char c = s[1]; // warn
2196 struct seven_words {
2201 struct seven_words a, *p;
2208 // note: requires unix.Malloc or
2209 // alpha.unix.MallocWithAnnotations checks enabled.
2211 int *p = malloc(12);
2221 .. _alpha-security-ArrayBoundV2:
2223 alpha.security.ArrayBoundV2 (C)
2224 """""""""""""""""""""""""""""""
2225 Warn about buffer overflows (newer checker).
2231 char c = s[1]; // warn
2241 // note: compiler has internal check for this.
2242 // Use -Wno-array-bounds to suppress compiler warning.
2245 buf[0][-1] = 1; // warn
2248 // note: requires alpha.security.taint check turned on.
2252 char c = s[x]; // warn: index is tainted
2255 .. _alpha-security-MallocOverflow:
2257 alpha.security.MallocOverflow (C)
2258 """""""""""""""""""""""""""""""""
2259 Check for overflows in the arguments to ``malloc()``.
2260 It tries to catch ``malloc(n * c)`` patterns, where:
2262 - ``n``: a variable or member access of an object
2263 - ``c``: a constant foldable integral
2265 This checker was designed for code audits, so expect false-positive reports.
2266 One is supposed to silence this checker by ensuring proper bounds checking on
2267 the variable in question using e.g. an ``assert()`` or a branch.
2272 void *p = malloc(n * sizeof(int)); // warn
2276 if (n > 100) // gives an upper-bound
2278 void *p = malloc(n * sizeof(int)); // no warning
2282 assert(n <= 100 && "Contract violated.");
2283 void *p = malloc(n * sizeof(int)); // no warning
2288 - The checker won't warn for variables involved in explicit casts,
2289 since that might limit the variable's domain.
2290 E.g.: ``(unsigned char)int x`` would limit the domain to ``[0,255]``.
2291 The checker will miss the true-positive cases when the explicit cast would
2292 not tighten the domain to prevent the overflow in the subsequent
2293 multiplication operation.
2295 - It is an AST-based checker, thus it does not make use of the
2296 path-sensitive taint-analysis.
2298 .. _alpha-security-MmapWriteExec:
2300 alpha.security.MmapWriteExec (C)
2301 """"""""""""""""""""""""""""""""
2302 Warn on mmap() calls that are both writable and executable.
2307 void *c = mmap(NULL, 32, PROT_READ | PROT_WRITE | PROT_EXEC,
2308 MAP_PRIVATE | MAP_ANON, -1, 0);
2309 // warn: Both PROT_WRITE and PROT_EXEC flags are set. This can lead to
2310 // exploitable memory regions, which could be overwritten with malicious
2314 .. _alpha-security-ReturnPtrRange:
2316 alpha.security.ReturnPtrRange (C)
2317 """""""""""""""""""""""""""""""""
2318 Check for an out-of-bound pointer being returned to callers.
2331 return x; // warn: undefined or garbage returned
2338 SEI CERT checkers which tries to find errors based on their `C coding rules <https://wiki.sei.cmu.edu/confluence/display/c/2+Rules>`_.
2340 .. _alpha-security-cert-pos-checkers:
2342 alpha.security.cert.pos
2343 ^^^^^^^^^^^^^^^^^^^^^^^
2345 SEI CERT checkers of `POSIX C coding rules <https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152405>`_.
2347 .. _alpha-security-cert-pos-34c:
2349 alpha.security.cert.pos.34c
2350 """""""""""""""""""""""""""
2351 Finds calls to the ``putenv`` function which pass a pointer to an automatic variable as the argument.
2355 int func(const char *var) {
2357 int retval = snprintf(env, sizeof(env),"TEST=%s", var);
2358 if (retval < 0 || (size_t)retval >= sizeof(env)) {
2362 return putenv(env); // putenv function should not be called with auto variables
2367 - Technically, one can pass automatic variables to ``putenv``,
2368 but one needs to ensure that the given environment key stays
2369 alive until it's removed or overwritten.
2370 Since the analyzer cannot keep track of which envvars get overwritten
2371 and when, it needs to be slightly more aggressive and warn for such
2372 cases too, leading in some cases to false-positive reports like this:
2377 char env[] = "NAME=value";
2378 putenv(env); // false-positive warning: putenv function should not be called...
2380 putenv((char *)"NAME=anothervalue");
2381 // This putenv call overwrites the previous entry, thus that can no longer dangle.
2382 } // 'env' array becomes dead only here.
2384 alpha.security.cert.env
2385 ^^^^^^^^^^^^^^^^^^^^^^^
2387 SEI CERT checkers of `Environment C coding rules <https://wiki.sei.cmu.edu/confluence/x/JdcxBQ>`_.
2389 .. _alpha-security-cert-env-InvalidPtr:
2391 alpha.security.cert.env.InvalidPtr
2392 """"""""""""""""""""""""""""""""""
2394 Corresponds to SEI CERT Rules ENV31-C and ENV34-C.
2397 Rule is about the possible problem with `main` function's third argument, environment pointer,
2398 "envp". When environment array is modified using some modification function
2399 such as putenv, setenv or others, It may happen that memory is reallocated,
2400 however "envp" is not updated to reflect the changes and points to old memory
2404 Some functions return a pointer to a statically allocated buffer.
2405 Consequently, subsequent call of these functions will invalidate previous
2406 pointer. These functions include: getenv, localeconv, asctime, setlocale, strerror
2410 int main(int argc, const char *argv[], const char *envp[]) {
2411 if (setenv("MY_NEW_VAR", "new_value", 1) != 0) {
2412 // setenv call may invalidate 'envp'
2416 for (size_t i = 0; envp[i] != NULL; ++i) {
2418 // envp may no longer point to the current environment
2419 // this program has unanticipated behavior, since envp
2420 // does not reflect changes made by setenv function.
2426 void previous_call_invalidation() {
2430 pp = getenv("VAR2");
2431 // subsequent call to 'getenv' invalidated previous one
2434 // dereferencing invalid pointer
2437 alpha.security.taint
2438 ^^^^^^^^^^^^^^^^^^^^
2440 Checkers implementing
2441 `taint analysis <https://en.wikipedia.org/wiki/Taint_checking>`_.
2443 .. _alpha-security-taint-TaintPropagation:
2445 alpha.security.taint.TaintPropagation (C, C++)
2446 """"""""""""""""""""""""""""""""""""""""""""""
2448 Taint analysis identifies potential security vulnerabilities where the
2449 attacker can inject malicious data to the program to execute an attack
2450 (privilege escalation, command injection, SQL injection etc.).
2452 The malicious data is injected at the taint source (e.g. ``getenv()`` call)
2453 which is then propagated through function calls and being used as arguments of
2454 sensitive operations, also called as taint sinks (e.g. ``system()`` call).
2456 One can defend against this type of vulnerability by always checking and
2457 sanitizing the potentially malicious, untrusted user input.
2459 The goal of the checker is to discover and show to the user these potential
2460 taint source-sink pairs and the propagation call chain.
2462 The most notable examples of taint sources are:
2465 - files or standard input
2466 - environment variables
2467 - data from databases
2469 Let us examine a practical example of a Command Injection attack.
2473 // Command Injection Vulnerability Example
2474 int main(int argc, char** argv) {
2475 char cmd[2048] = "/bin/cat ";
2476 char filename[1024];
2477 printf("Filename:");
2478 scanf (" %1023[^\n]", filename); // The attacker can inject a shell escape here
2479 strcat(cmd, filename);
2480 system(cmd); // Warning: Untrusted data is passed to a system call
2483 The program prints the content of any user specified file.
2484 Unfortunately the attacker can execute arbitrary commands
2485 with shell escapes. For example with the following input the `ls` command is also
2486 executed after the contents of `/etc/shadow` is printed.
2487 `Input: /etc/shadow ; ls /`
2489 The analysis implemented in this checker points out this problem.
2491 One can protect against such attack by for example checking if the provided
2492 input refers to a valid file and removing any invalid user input.
2496 // No vulnerability anymore, but we still get the warning
2497 void sanitizeFileName(char* filename){
2498 if (access(filename,F_OK)){// Verifying user input
2499 printf("File does not exist\n");
2503 int main(int argc, char** argv) {
2504 char cmd[2048] = "/bin/cat ";
2505 char filename[1024];
2506 printf("Filename:");
2507 scanf (" %1023[^\n]", filename); // The attacker can inject a shell escape here
2508 sanitizeFileName(filename);// filename is safe after this point
2511 strcat(cmd, filename);
2512 system(cmd); // Superfluous Warning: Untrusted data is passed to a system call
2515 Unfortunately, the checker cannot discover automatically that the programmer
2516 have performed data sanitation, so it still emits the warning.
2518 One can get rid of this superfluous warning by telling by specifying the
2519 sanitation functions in the taint configuration file (see
2520 :doc:`user-docs/TaintAnalysisConfiguration`).
2522 .. code-block:: YAML
2525 - Name: sanitizeFileName
2528 The clang invocation to pass the configuration file location:
2530 .. code-block:: bash
2532 clang --analyze -Xclang -analyzer-config -Xclang alpha.security.taint.TaintPropagation:Config=`pwd`/taint_config.yml ...
2534 If you are validating your inputs instead of sanitizing them, or don't want to
2535 mention each sanitizing function in our configuration,
2536 you can use a more generic approach.
2538 Introduce a generic no-op `csa_mark_sanitized(..)` function to
2539 tell the Clang Static Analyzer
2540 that the variable is safe to be used on that analysis path.
2544 // Marking sanitized variables safe.
2545 // No vulnerability anymore, no warning.
2547 // User csa_mark_sanitize function is for the analyzer only
2548 #ifdef __clang_analyzer__
2549 void csa_mark_sanitized(const void *);
2552 int main(int argc, char** argv) {
2553 char cmd[2048] = "/bin/cat ";
2554 char filename[1024];
2555 printf("Filename:");
2556 scanf (" %1023[^\n]", filename);
2557 if (access(filename,F_OK)){// Verifying user input
2558 printf("File does not exist\n");
2561 #ifdef __clang_analyzer__
2562 csa_mark_sanitized(filename); // Indicating to CSA that filename variable is safe to be used after this point
2564 strcat(cmd, filename);
2565 system(cmd); // No warning
2568 Similarly to the previous example, you need to
2569 define a `Filter` function in a `YAML` configuration file
2570 and add the `csa_mark_sanitized` function.
2572 .. code-block:: YAML
2575 - Name: csa_mark_sanitized
2578 Then calling `csa_mark_sanitized(X)` will tell the analyzer that `X` is safe to
2579 be used after this point, because its contents are verified. It is the
2580 responsibility of the programmer to ensure that this verification was indeed
2581 correct. Please note that `csa_mark_sanitized` function is only declared and
2582 used during Clang Static Analysis and skipped in (production) builds.
2584 Further examples of injection vulnerabilities this checker can find.
2589 char x = getchar(); // 'x' marked as tainted
2590 system(&x); // warn: untrusted data is passed to a system call
2593 // note: compiler internally checks if the second param to
2594 // sprintf is a string literal or not.
2595 // Use -Wno-format-security to suppress compiler warning.
2597 char s[10], buf[10];
2598 fscanf(stdin, "%s", s); // 's' marked as tainted
2600 sprintf(buf, s); // warn: untrusted data used as a format string
2605 scanf("%zd", &ts); // 'ts' marked as tainted
2606 int *p = (int *)malloc(ts * sizeof(int));
2607 // warn: untrusted data used as buffer size
2610 There are built-in sources, propagations and sinks even if no external taint
2611 configuration is provided.
2614 ``_IO_getc``, ``fdopen``, ``fopen``, ``freopen``, ``get_current_dir_name``,
2615 ``getch``, ``getchar``, ``getchar_unlocked``, ``getwd``, ``getcwd``,
2616 ``getgroups``, ``gethostname``, ``getlogin``, ``getlogin_r``, ``getnameinfo``,
2617 ``gets``, ``gets_s``, ``getseuserbyname``, ``readlink``, ``readlinkat``,
2618 ``scanf``, ``scanf_s``, ``socket``, ``wgetch``
2620 Default propagations rules:
2621 ``atoi``, ``atol``, ``atoll``, ``basename``, ``dirname``, ``fgetc``,
2622 ``fgetln``, ``fgets``, ``fnmatch``, ``fread``, ``fscanf``, ``fscanf_s``,
2623 ``index``, ``inflate``, ``isalnum``, ``isalpha``, ``isascii``, ``isblank``,
2624 ``iscntrl``, ``isdigit``, ``isgraph``, ``islower``, ``isprint``, ``ispunct``,
2625 ``isspace``, ``isupper``, ``isxdigit``, ``memchr``, ``memrchr``, ``sscanf``,
2626 ``getc``, ``getc_unlocked``, ``getdelim``, ``getline``, ``getw``, ``memcmp``,
2627 ``memcpy``, ``memmem``, ``memmove``, ``mbtowc``, ``pread``, ``qsort``,
2628 ``qsort_r``, ``rawmemchr``, ``read``, ``recv``, ``recvfrom``, ``rindex``,
2629 ``strcasestr``, ``strchr``, ``strchrnul``, ``strcasecmp``, ``strcmp``,
2630 ``strcspn``, ``strncasecmp``, ``strncmp``, ``strndup``,
2631 ``strndupa``, ``strpbrk``, ``strrchr``, ``strsep``, ``strspn``,
2632 ``strstr``, ``strtol``, ``strtoll``, ``strtoul``, ``strtoull``, ``tolower``,
2633 ``toupper``, ``ttyname``, ``ttyname_r``, ``wctomb``, ``wcwidth``
2636 ``printf``, ``setproctitle``, ``system``, ``popen``, ``execl``, ``execle``,
2637 ``execlp``, ``execv``, ``execvp``, ``execvP``, ``execve``, ``dlopen``,
2638 ``memcpy``, ``memmove``, ``strncpy``, ``strndup``, ``malloc``, ``calloc``,
2639 ``alloca``, ``memccpy``, ``realloc``, ``bcopy``
2641 Please note that there are no built-in filter functions.
2643 One can configure their own taint sources, sinks, and propagation rules by
2644 providing a configuration file via checker option
2645 ``alpha.security.taint.TaintPropagation:Config``. The configuration file is in
2646 `YAML <http://llvm.org/docs/YamlIO.html#introduction-to-yaml>`_ format. The
2647 taint-related options defined in the config file extend but do not override the
2648 built-in sources, rules, sinks. The format of the external taint configuration
2649 file is not stable, and could change without any notice even in a non-backward
2652 For a more detailed description of configuration options, please see the
2653 :doc:`user-docs/TaintAnalysisConfiguration`. For an example see
2654 :ref:`clangsa-taint-configuration-example`.
2658 * `Config` Specifies the name of the YAML configuration file. The user can
2659 define their own taint sources and sinks.
2661 **Related Guidelines**
2663 * `CWE Data Neutralization Issues
2664 <https://cwe.mitre.org/data/definitions/137.html>`_
2665 * `SEI Cert STR02-C. Sanitize data passed to complex subsystems
2666 <https://wiki.sei.cmu.edu/confluence/display/c/STR02-C.+Sanitize+data+passed+to+complex+subsystems>`_
2667 * `SEI Cert ENV33-C. Do not call system()
2668 <https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152177>`_
2669 * `ENV03-C. Sanitize the environment when invoking external programs
2670 <https://wiki.sei.cmu.edu/confluence/display/c/ENV03-C.+Sanitize+the+environment+when+invoking+external+programs>`_
2674 * The taintedness property is not propagated through function calls which are
2675 unknown (or too complex) to the analyzer, unless there is a specific
2676 propagation rule built-in to the checker or given in the YAML configuration
2677 file. This causes potential true positive findings to be lost.
2682 .. _alpha-unix-StdCLibraryFunctions:
2684 alpha.unix.StdCLibraryFunctions (C)
2685 """""""""""""""""""""""""""""""""""
2686 Check for calls of standard library functions that violate predefined argument
2687 constraints. For example, it is stated in the C standard that for the ``int
2688 isalnum(int ch)`` function the behavior is undefined if the value of ``ch`` is
2689 not representable as unsigned char and is not equal to ``EOF``.
2694 void test_alnum_concrete(int v) {
2695 int ret = isalnum(256); // \
2696 // warning: Function argument outside of allowed range
2700 void buffer_size_violation(FILE *file) {
2701 enum { BUFFER_SIZE = 1024 };
2702 wchar_t wbuf[BUFFER_SIZE];
2704 const size_t size = sizeof(*wbuf); // 4
2705 const size_t nitems = sizeof(wbuf); // 4096
2707 // Below we receive a warning because the 3rd parameter should be the
2708 // number of elements to read, not the size in bytes. This case is a known
2709 // vulnerability described by the ARR38-C SEI-CERT rule.
2710 fread(wbuf, size, nitems, file);
2713 You can think of this checker as defining restrictions (pre- and postconditions)
2714 on standard library functions. Preconditions are checked, and when they are
2715 violated, a warning is emitted. Post conditions are added to the analysis, e.g.
2716 that the return value must be no greater than 255.
2718 For example if an argument to a function must be in between 0 and 255, but the
2719 value of the argument is unknown, the analyzer will conservatively assume that
2720 it is in this interval. Similarly, if a function mustn't be called with a null
2721 pointer and the null value of the argument can not be proven, the analyzer will
2722 assume that it is non-null.
2724 These are the possible checks on the values passed as function arguments:
2725 - The argument has an allowed range (or multiple ranges) of values. The checker
2726 can detect if a passed value is outside of the allowed range and show the
2727 actual and allowed values.
2728 - The argument has pointer type and is not allowed to be null pointer. Many
2729 (but not all) standard functions can produce undefined behavior if a null
2730 pointer is passed, these cases can be detected by the checker.
2731 - The argument is a pointer to a memory block and the minimal size of this
2732 buffer is determined by another argument to the function, or by
2733 multiplication of two arguments (like at function ``fread``), or is a fixed
2734 value (for example ``asctime_r`` requires at least a buffer of size 26). The
2735 checker can detect if the buffer size is too small and in optimal case show
2736 the size of the buffer and the values of the corresponding arguments.
2740 int test_alnum_symbolic(int x) {
2741 int ret = isalnum(x);
2742 // after the call, ret is assumed to be in the range [-1, 255]
2744 if (ret > 255) // impossible (infeasible branch)
2746 return ret / x; // division by zero is not reported
2750 Additionally to the argument and return value conditions, this checker also adds
2751 state of the value ``errno`` if applicable to the analysis. Many system
2752 functions set the ``errno`` value only if an error occurs (together with a
2753 specific return value of the function), otherwise it becomes undefined. This
2754 checker changes the analysis state to contain such information. This data is
2755 used by other checkers, for example :ref:`alpha-unix-Errno`.
2759 The checker can not always provide notes about the values of the arguments.
2760 Without this information it is hard to confirm if the constraint is indeed
2761 violated. The argument values are shown if they are known constants or the value
2762 is determined by previous (not too complicated) assumptions.
2764 The checker can produce false positives in cases such as if the program has
2765 invariants not known to the analyzer engine or the bug report path contains
2766 calls to unknown functions. In these cases the analyzer fails to detect the real
2767 range of the argument.
2771 The checker models functions (and emits diagnostics) from the C standard by
2772 default. The ``ModelPOSIX`` option enables modeling (and emit diagnostics) of
2773 additional functions that are defined in the POSIX standard. This option is
2774 disabled by default.
2776 .. _alpha-unix-BlockInCriticalSection:
2778 alpha.unix.BlockInCriticalSection (C)
2779 """""""""""""""""""""""""""""""""""""
2780 Check for calls to blocking functions inside a critical section.
2781 Applies to: ``lock, unlock, sleep, getc, fgets, read, recv, pthread_mutex_lock,``
2782 `` pthread_mutex_unlock, mtx_lock, mtx_timedlock, mtx_trylock, mtx_unlock, lock_guard, unique_lock``
2789 sleep(3); // warn: a blocking function sleep is called inside a critical
2794 .. _alpha-unix-Chroot:
2796 alpha.unix.Chroot (C)
2797 """""""""""""""""""""
2798 Check improper use of chroot.
2805 chroot("/usr/local");
2806 f(); // warn: no call of chdir("/") immediately after chroot
2809 .. _alpha-unix-Errno:
2811 alpha.unix.Errno (C)
2812 """"""""""""""""""""
2814 Check for improper use of ``errno``.
2815 This checker implements partially CERT rule
2816 `ERR30-C. Set errno to zero before calling a library function known to set errno,
2817 and check errno only after the function returns a value indicating failure
2818 <https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152351>`_.
2819 The checker can find the first read of ``errno`` after successful standard
2822 The C and POSIX standards often do not define if a standard library function
2823 may change value of ``errno`` if the call does not fail.
2824 Therefore, ``errno`` should only be used if it is known from the return value
2825 of a function that the call has failed.
2826 There are exceptions to this rule (for example ``strtol``) but the affected
2827 functions are not yet supported by the checker.
2828 The return values for the failure cases are documented in the standard Linux man
2829 pages of the functions and in the `POSIX standard <https://pubs.opengroup.org/onlinepubs/9699919799/>`_.
2833 int unsafe_errno_read(int sock, void *data, int data_size) {
2834 if (send(sock, data, data_size, 0) != data_size) {
2835 // 'send' can be successful even if not all data was sent
2836 if (errno == 1) { // An undefined value may be read from 'errno'
2843 The checker :ref:`alpha-unix-StdCLibraryFunctions` must be turned on to get the
2844 warnings from this checker. The supported functions are the same as by
2845 :ref:`alpha-unix-StdCLibraryFunctions`. The ``ModelPOSIX`` option of that
2846 checker affects the set of checked functions.
2850 The ``AllowErrnoReadOutsideConditionExpressions`` option allows read of the
2851 errno value if the value is not used in a condition (in ``if`` statements,
2852 loops, conditional expressions, ``switch`` statements). For example ``errno``
2853 can be stored into a variable without getting a warning by the checker.
2857 int unsafe_errno_read(int sock, void *data, int data_size) {
2858 if (send(sock, data, data_size, 0) != data_size) {
2860 // warning if 'AllowErrnoReadOutsideConditionExpressions' is false
2861 // no warning if 'AllowErrnoReadOutsideConditionExpressions' is true
2866 Default value of this option is ``true``. This allows save of the errno value
2867 for possible later error handling.
2871 - Only the very first usage of ``errno`` is checked after an affected function
2872 call. Value of ``errno`` is not followed when it is stored into a variable
2873 or returned from a function.
2874 - Documentation of function ``lseek`` is not clear about what happens if the
2875 function returns different value than the expected file position but not -1.
2876 To avoid possible false-positives ``errno`` is allowed to be used in this
2879 .. _alpha-unix-PthreadLock:
2881 alpha.unix.PthreadLock (C)
2882 """"""""""""""""""""""""""
2883 Simple lock -> unlock checker.
2884 Applies to: ``pthread_mutex_lock, pthread_rwlock_rdlock, pthread_rwlock_wrlock, lck_mtx_lock, lck_rw_lock_exclusive``
2885 ``lck_rw_lock_shared, pthread_mutex_trylock, pthread_rwlock_tryrdlock, pthread_rwlock_tryrwlock, lck_mtx_try_lock,
2886 lck_rw_try_lock_exclusive, lck_rw_try_lock_shared, pthread_mutex_unlock, pthread_rwlock_unlock, lck_mtx_unlock, lck_rw_done``.
2891 pthread_mutex_t mtx;
2894 pthread_mutex_lock(&mtx);
2895 pthread_mutex_lock(&mtx);
2896 // warn: this lock has already been acquired
2899 lck_mtx_t lck1, lck2;
2902 lck_mtx_lock(&lck1);
2903 lck_mtx_lock(&lck2);
2904 lck_mtx_unlock(&lck1);
2905 // warn: this was not the most recently acquired lock
2908 lck_mtx_t lck1, lck2;
2911 if (lck_mtx_try_lock(&lck1) == 0)
2914 lck_mtx_lock(&lck2);
2915 lck_mtx_unlock(&lck1);
2916 // warn: this was not the most recently acquired lock
2919 .. _alpha-unix-SimpleStream:
2921 alpha.unix.SimpleStream (C)
2922 """""""""""""""""""""""""""
2923 Check for misuses of stream APIs. Check for misuses of stream APIs: ``fopen, fclose``
2924 (demo checker, the subject of the demo (`Slides <https://llvm.org/devmtg/2012-11/Zaks-Rose-Checker24Hours.pdf>`_ ,
2925 `Video <https://youtu.be/kdxlsP5QVPw>`_) by Anna Zaks and Jordan Rose presented at the
2926 `2012 LLVM Developers' Meeting <https://llvm.org/devmtg/2012-11/>`_).
2931 FILE *F = fopen("myfile.txt", "w");
2932 } // warn: opened file is never closed
2935 FILE *F = fopen("myfile.txt", "w");
2940 fclose(F); // warn: closing a previously closed file stream
2943 .. _alpha-unix-Stream:
2945 alpha.unix.Stream (C)
2946 """""""""""""""""""""
2947 Check stream handling functions: ``fopen, tmpfile, fclose, fread, fwrite, fseek, ftell, rewind, fgetpos,``
2948 ``fsetpos, clearerr, feof, ferror, fileno``.
2953 FILE *p = fopen("foo", "r");
2954 } // warn: opened file is never closed
2957 FILE *p = fopen("foo", "r");
2958 fseek(p, 1, SEEK_SET); // warn: stream pointer might be NULL
2963 FILE *p = fopen("foo", "r");
2967 // warn: third arg should be SEEK_SET, SEEK_END, or SEEK_CUR
2973 FILE *p = fopen("foo", "r");
2975 fclose(p); // warn: already closed
2979 FILE *p = tmpfile();
2980 ftell(p); // warn: stream pointer might be NULL
2985 .. _alpha-unix-cstring-BufferOverlap:
2987 alpha.unix.cstring.BufferOverlap (C)
2988 """"""""""""""""""""""""""""""""""""
2989 Checks for overlap in two buffer arguments. Applies to: ``memcpy, mempcpy, wmemcpy, wmempcpy``.
2995 memcpy(a + 2, a + 1, 8); // warn
2998 .. _alpha-unix-cstring-NotNullTerminated:
3000 alpha.unix.cstring.NotNullTerminated (C)
3001 """"""""""""""""""""""""""""""""""""""""
3002 Check for arguments which are not null-terminated strings; applies to: ``strlen, strnlen, strcpy, strncpy, strcat, strncat, wcslen, wcsnlen``.
3007 int y = strlen((char *)&test); // warn
3010 .. _alpha-unix-cstring-OutOfBounds:
3012 alpha.unix.cstring.OutOfBounds (C)
3013 """"""""""""""""""""""""""""""""""
3014 Check for out-of-bounds access in string functions, such as:
3015 ``memcpy, bcopy, strcpy, strncpy, strcat, strncat, memmove, memcmp, memset`` and more.
3017 This check also works with string literals, except there is a known bug in that
3018 the analyzer cannot detect embedded NULL characters when determining the string length.
3023 const char str[] = "Hello world";
3024 char buffer[] = "Hello world";
3025 memcpy(buffer, str, sizeof(str) + 1); // warn
3029 const char str[] = "Hello world";
3030 char buffer[] = "Helloworld";
3031 memcpy(buffer, str, sizeof(str)); // warn
3034 .. _alpha-unix-cstring-UninitializedRead:
3036 alpha.unix.cstring.UninitializedRead (C)
3037 """"""""""""""""""""""""""""""""""""""""
3038 Check for uninitialized reads from common memory copy/manipulation functions such as:
3039 ``memcpy, mempcpy, memmove, memcmp, strcmp, strncmp, strcpy, strlen, strsep`` and many more.
3046 memcpy(dst,src,sizeof(dst)); // warn: Bytes string function accesses uninitialized/garbage values
3051 - Due to limitations of the memory modeling in the analyzer, one can likely
3052 observe a lot of false-positive reports like this:
3056 void false_positive() {
3057 int src[] = {1, 2, 3, 4};
3059 memcpy(dst, src, 4 * sizeof(int)); // false-positive:
3060 // The 'src' buffer was correctly initialized, yet we cannot conclude
3061 // that since the analyzer could not see a direct initialization of the
3062 // very last byte of the source buffer.
3065 More details at the corresponding `GitHub issue <https://github.com/llvm/llvm-project/issues/43459>`_.
3067 .. _alpha-nondeterminism-PointerIteration:
3069 alpha.nondeterminism.PointerIteration (C++)
3070 """""""""""""""""""""""""""""""""""""""""""
3071 Check for non-determinism caused by iterating unordered containers of pointers.
3077 std::unordered_set<int *> UnorderedPtrSet = {&a, &b};
3079 for (auto i : UnorderedPtrSet) // warn
3083 .. _alpha-nondeterminism-PointerSorting:
3085 alpha.nondeterminism.PointerSorting (C++)
3086 """""""""""""""""""""""""""""""""""""""""
3087 Check for non-determinism caused by sorting of pointers.
3093 std::vector<int *> V = {&a, &b};
3094 std::sort(V.begin(), V.end()); // warn
3101 .. _alpha-webkit-UncountedCallArgsChecker:
3103 alpha.webkit.UncountedCallArgsChecker
3104 """""""""""""""""""""""""""""""""""""
3105 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.
3107 Here are some examples of situations that we warn about as they *might* 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.
3111 RefCountable* provide_uncounted();
3112 void consume(RefCountable*);
3114 // 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.
3117 consume(provide_uncounted()); // warn
3121 RefCountable* uncounted = provide_uncounted();
3122 consume(uncounted); // warn
3125 Although we are enforcing member variables to be ref-counted by `webkit.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.
3127 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.
3132 RefPtr<RefCountable> member;
3133 void consume(RefCountable*) { /* ... */ }
3135 consume(member.get()); // warn
3139 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.
3141 Allowed kinds of arguments:
3143 - values obtained from ref-counted objects (including temporaries as those survive the call too)
3147 RefCountable* provide_uncounted();
3148 void consume(RefCountable*);
3151 RefPtr<RefCountable> rc = makeRef(provide_uncounted());
3152 consume(rc.get()); // ok
3153 consume(makeRef(provide_uncounted()).get()); // ok
3156 - forwarding uncounted arguments from caller to callee
3160 void foo(RefCountable& a) {
3164 Caller of ``foo()`` is responsible for ``a``'s lifetime.
3174 Caller of ``foo()`` is responsible for keeping the memory pointed to by ``this`` pointer safe.
3180 foo(nullptr, NULL, 0); // ok
3182 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.
3184 - constructors of ref-counted types (including factory methods)
3185 - getters of ref-counted types
3186 - member overloaded operators
3188 - unary operators like ``&`` or ``*``
3190 alpha.webkit.UncountedLocalVarsChecker
3191 """"""""""""""""""""""""""""""""""""""
3192 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.
3194 These are examples of cases that we consider safe:
3199 RefPtr<RefCountable> counted;
3200 // The scope of uncounted is EMBEDDED in the scope of counted.
3202 RefCountable* uncounted = counted.get(); // ok
3206 void foo2(RefPtr<RefCountable> counted_param) {
3207 RefCountable* uncounted = counted_param.get(); // ok
3210 void FooClass::foo_method() {
3211 RefCountable* uncounted = this; // ok
3214 Here are some examples of situations that we warn about as they *might* 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.
3219 RefCountable* uncounted = new RefCountable; // warn
3222 RefCountable* global_uncounted;
3224 RefCountable* uncounted = global_uncounted; // warn
3228 RefPtr<RefCountable> counted;
3229 // The scope of uncounted is not EMBEDDED in the scope of counted.
3230 RefCountable* uncounted = counted.get(); // warn
3233 We don't warn about these cases - we don't consider them necessarily safe but since they are very common and usually safe we'd introduce a lot of false positives otherwise:
3234 - variable defined in condition part of an ```if``` statement
3235 - variable defined in init statement condition of a ```for``` statement
3237 For the time being we also don't warn about uninitialized uncounted local variables.
3248 Checkers used for debugging the analyzer.
3249 :doc:`developer-docs/DebugChecks` page contains a detailed description.
3251 .. _debug-AnalysisOrder:
3255 Print callbacks that are called during analysis in order.
3257 .. _debug-ConfigDumper:
3263 .. _debug-DumpCFG Display:
3265 debug.DumpCFG Display
3266 """""""""""""""""""""
3267 Control-Flow Graphs.
3269 .. _debug-DumpCallGraph:
3275 .. _debug-DumpCalls:
3279 Print calls as they are traversed by the engine.
3281 .. _debug-DumpDominators:
3283 debug.DumpDominators
3284 """"""""""""""""""""
3285 Print the dominance tree for a given CFG.
3287 .. _debug-DumpLiveVars:
3291 Print results of live variable analysis.
3293 .. _debug-DumpTraversal:
3297 Print branch conditions as they are traversed by the engine.
3299 .. _debug-ExprInspection:
3301 debug.ExprInspection
3302 """"""""""""""""""""
3303 Check the analyzer's understanding of expressions.
3309 Emit warnings with analyzer statistics.
3311 .. _debug-TaintTest:
3315 Mark tainted symbols as such.
3321 View Control-Flow Graphs using GraphViz.
3323 .. _debug-ViewCallGraph:
3327 View Call Graph using GraphViz.
3329 .. _debug-ViewExplodedGraph:
3331 debug.ViewExplodedGraph
3332 """""""""""""""""""""""
3333 View Exploded Graphs using GraphViz.