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
1029 .. _unix-StdCLibraryFunctions:
1031 unix.StdCLibraryFunctions (C)
1032 """""""""""""""""""""""""""""
1033 Check for calls of standard library functions that violate predefined argument
1034 constraints. For example, according to the C standard the behavior of function
1035 ``int isalnum(int ch)`` is undefined if the value of ``ch`` is not representable
1036 as ``unsigned char`` and is not equal to ``EOF``.
1038 You can think of this checker as defining restrictions (pre- and postconditions)
1039 on standard library functions. Preconditions are checked, and when they are
1040 violated, a warning is emitted. Postconditions are added to the analysis, e.g.
1041 that the return value of a function is not greater than 255. Preconditions are
1042 added to the analysis too, in the case when the affected values are not known
1045 For example, if an argument to a function must be in between 0 and 255, but the
1046 value of the argument is unknown, the analyzer will assume that it is in this
1047 interval. Similarly, if a function mustn't be called with a null pointer and the
1048 analyzer cannot prove that it is null, then it will assume that it is non-null.
1050 These are the possible checks on the values passed as function arguments:
1051 - The argument has an allowed range (or multiple ranges) of values. The checker
1052 can detect if a passed value is outside of the allowed range and show the
1053 actual and allowed values.
1054 - The argument has pointer type and is not allowed to be null pointer. Many
1055 (but not all) standard functions can produce undefined behavior if a null
1056 pointer is passed, these cases can be detected by the checker.
1057 - The argument is a pointer to a memory block and the minimal size of this
1058 buffer is determined by another argument to the function, or by
1059 multiplication of two arguments (like at function ``fread``), or is a fixed
1060 value (for example ``asctime_r`` requires at least a buffer of size 26). The
1061 checker can detect if the buffer size is too small and in optimal case show
1062 the size of the buffer and the values of the corresponding arguments.
1067 void test_alnum_concrete(int v) {
1068 int ret = isalnum(256); // \
1069 // warning: Function argument outside of allowed range
1073 void buffer_size_violation(FILE *file) {
1074 enum { BUFFER_SIZE = 1024 };
1075 wchar_t wbuf[BUFFER_SIZE];
1077 const size_t size = sizeof(*wbuf); // 4
1078 const size_t nitems = sizeof(wbuf); // 4096
1080 // Below we receive a warning because the 3rd parameter should be the
1081 // number of elements to read, not the size in bytes. This case is a known
1082 // vulnerability described by the ARR38-C SEI-CERT rule.
1083 fread(wbuf, size, nitems, file);
1086 int test_alnum_symbolic(int x) {
1087 int ret = isalnum(x);
1088 // after the call, ret is assumed to be in the range [-1, 255]
1090 if (ret > 255) // impossible (infeasible branch)
1092 return ret / x; // division by zero is not reported
1096 Additionally to the argument and return value conditions, this checker also adds
1097 state of the value ``errno`` if applicable to the analysis. Many system
1098 functions set the ``errno`` value only if an error occurs (together with a
1099 specific return value of the function), otherwise it becomes undefined. This
1100 checker changes the analysis state to contain such information. This data is
1101 used by other checkers, for example :ref:`alpha-unix-Errno`.
1105 The checker can not always provide notes about the values of the arguments.
1106 Without this information it is hard to confirm if the constraint is indeed
1107 violated. The argument values are shown if they are known constants or the value
1108 is determined by previous (not too complicated) assumptions.
1110 The checker can produce false positives in cases such as if the program has
1111 invariants not known to the analyzer engine or the bug report path contains
1112 calls to unknown functions. In these cases the analyzer fails to detect the real
1113 range of the argument.
1117 The checker models functions (and emits diagnostics) from the C standard by
1118 default. The ``ModelPOSIX`` option enables modeling (and emit diagnostics) of
1119 additional functions that are defined in the POSIX standard. This option is
1120 disabled by default.
1132 Check for proper uses of various Apple APIs.
1134 .. code-block:: objc
1137 dispatch_once_t pred = 0;
1138 dispatch_once(&pred, ^(){}); // warn: dispatch_once uses local
1141 .. _osx-NumberObjectConversion:
1143 osx.NumberObjectConversion (C, C++, ObjC)
1144 """""""""""""""""""""""""""""""""""""""""
1145 Check for erroneous conversions of objects representing numbers into numbers.
1147 .. code-block:: objc
1149 NSNumber *photoCount = [albumDescriptor objectForKey:@"PhotoCount"];
1150 // Warning: Comparing a pointer value of type 'NSNumber *'
1151 // to a scalar integer value
1152 if (photoCount > 0) {
1153 [self displayPhotos];
1156 .. _osx-ObjCProperty:
1158 osx.ObjCProperty (ObjC)
1159 """""""""""""""""""""""
1160 Check for proper uses of Objective-C properties.
1162 .. code-block:: objc
1164 NSNumber *photoCount = [albumDescriptor objectForKey:@"PhotoCount"];
1165 // Warning: Comparing a pointer value of type 'NSNumber *'
1166 // to a scalar integer value
1167 if (photoCount > 0) {
1168 [self displayPhotos];
1172 .. _osx-SecKeychainAPI:
1174 osx.SecKeychainAPI (C)
1175 """"""""""""""""""""""
1176 Check for proper uses of Secure Keychain APIs.
1178 .. literalinclude:: checkers/seckeychainapi_example.m
1181 .. _osx-cocoa-AtSync:
1183 osx.cocoa.AtSync (ObjC)
1184 """""""""""""""""""""""
1185 Check for nil pointers used as mutexes for @synchronized.
1187 .. code-block:: objc
1191 @synchronized(x) {} // warn: nil value used as mutex
1196 @synchronized(y) {} // warn: uninitialized value used as mutex
1199 .. _osx-cocoa-AutoreleaseWrite:
1201 osx.cocoa.AutoreleaseWrite
1202 """"""""""""""""""""""""""
1203 Warn about potentially crashing writes to autoreleasing objects from different autoreleasing pools in Objective-C.
1205 .. _osx-cocoa-ClassRelease:
1207 osx.cocoa.ClassRelease (ObjC)
1208 """""""""""""""""""""""""""""
1209 Check for sending 'retain', 'release', or 'autorelease' directly to a Class.
1211 .. code-block:: objc
1213 @interface MyClass : NSObject
1217 [MyClass release]; // warn
1220 .. _osx-cocoa-Dealloc:
1222 osx.cocoa.Dealloc (ObjC)
1223 """"""""""""""""""""""""
1224 Warn about Objective-C classes that lack a correct implementation of -dealloc
1226 .. literalinclude:: checkers/dealloc_example.m
1229 .. _osx-cocoa-IncompatibleMethodTypes:
1231 osx.cocoa.IncompatibleMethodTypes (ObjC)
1232 """"""""""""""""""""""""""""""""""""""""
1233 Warn about Objective-C method signatures with type incompatibilities.
1235 .. code-block:: objc
1237 @interface MyClass1 : NSObject
1241 @implementation MyClass1
1242 - (int)foo { return 1; }
1245 @interface MyClass2 : MyClass1
1249 @implementation MyClass2
1250 - (float)foo { return 1.0; } // warn
1253 .. _osx-cocoa-Loops:
1257 Improved modeling of loops using Cocoa collection types.
1259 .. _osx-cocoa-MissingSuperCall:
1261 osx.cocoa.MissingSuperCall (ObjC)
1262 """""""""""""""""""""""""""""""""
1263 Warn about Objective-C methods that lack a necessary call to super.
1265 .. code-block:: objc
1267 @interface Test : UIViewController
1269 @implementation test
1270 - (void)viewDidLoad {} // warn
1274 .. _osx-cocoa-NSAutoreleasePool:
1276 osx.cocoa.NSAutoreleasePool (ObjC)
1277 """"""""""""""""""""""""""""""""""
1278 Warn for suboptimal uses of NSAutoreleasePool in Objective-C GC mode.
1280 .. code-block:: objc
1283 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
1284 [pool release]; // warn
1287 .. _osx-cocoa-NSError:
1289 osx.cocoa.NSError (ObjC)
1290 """"""""""""""""""""""""
1291 Check usage of NSError parameters.
1293 .. code-block:: objc
1295 @interface A : NSObject
1296 - (void)foo:(NSError """""""""""""""""""""""")error;
1300 - (void)foo:(NSError """""""""""""""""""""""")error {
1301 // warn: method accepting NSError"""""""""""""""""""""""" should have a non-void
1306 @interface A : NSObject
1307 - (BOOL)foo:(NSError """""""""""""""""""""""")error;
1311 - (BOOL)foo:(NSError """""""""""""""""""""""")error {
1312 *error = 0; // warn: potential null dereference
1317 .. _osx-cocoa-NilArg:
1319 osx.cocoa.NilArg (ObjC)
1320 """""""""""""""""""""""
1321 Check for prohibited nil arguments to ObjC method calls.
1323 - caseInsensitiveCompare:
1326 - compare:options:range:
1327 - compare:options:range:locale:
1328 - componentsSeparatedByCharactersInSet:
1331 .. code-block:: objc
1333 NSComparisonResult test(NSString *s) {
1334 NSString *aString = nil;
1335 return [s caseInsensitiveCompare:aString];
1336 // warn: argument to 'NSString' method
1337 // 'caseInsensitiveCompare:' cannot be nil
1341 .. _osx-cocoa-NonNilReturnValue:
1343 osx.cocoa.NonNilReturnValue
1344 """""""""""""""""""""""""""
1345 Models the APIs that are guaranteed to return a non-nil value.
1347 .. _osx-cocoa-ObjCGenerics:
1349 osx.cocoa.ObjCGenerics (ObjC)
1350 """""""""""""""""""""""""""""
1351 Check for type errors when using Objective-C generics.
1353 .. code-block:: objc
1355 NSMutableArray *names = [NSMutableArray array];
1356 NSMutableArray *birthDates = names;
1358 // Warning: Conversion from value of type 'NSDate *'
1359 // to incompatible type 'NSString *'
1360 [birthDates addObject: [NSDate date]];
1362 .. _osx-cocoa-RetainCount:
1364 osx.cocoa.RetainCount (ObjC)
1365 """"""""""""""""""""""""""""
1366 Check for leaks and improper reference count management
1368 .. code-block:: objc
1371 NSString *s = [[NSString alloc] init]; // warn
1374 CFStringRef test(char *bytes) {
1375 return CFStringCreateWithCStringNoCopy(
1376 0, bytes, NSNEXTSTEPStringEncoding, 0); // warn
1380 .. _osx-cocoa-RunLoopAutoreleaseLeak:
1382 osx.cocoa.RunLoopAutoreleaseLeak
1383 """"""""""""""""""""""""""""""""
1384 Check for leaked memory in autorelease pools that will never be drained.
1386 .. _osx-cocoa-SelfInit:
1388 osx.cocoa.SelfInit (ObjC)
1389 """""""""""""""""""""""""
1390 Check that 'self' is properly initialized inside an initializer method.
1392 .. code-block:: objc
1394 @interface MyObj : NSObject {
1400 @implementation MyObj
1403 x = 0; // warn: instance variable used while 'self' is not
1409 @interface MyObj : NSObject
1413 @implementation MyObj
1416 return self; // warn: returning uninitialized 'self'
1420 .. _osx-cocoa-SuperDealloc:
1422 osx.cocoa.SuperDealloc (ObjC)
1423 """""""""""""""""""""""""""""
1424 Warn about improper use of '[super dealloc]' in Objective-C.
1426 .. code-block:: objc
1428 @interface SuperDeallocThenReleaseIvarClass : NSObject {
1433 @implementation SuperDeallocThenReleaseIvarClass
1436 [_ivar release]; // warn
1440 .. _osx-cocoa-UnusedIvars:
1442 osx.cocoa.UnusedIvars (ObjC)
1443 """"""""""""""""""""""""""""
1444 Warn about private ivars that are never used.
1446 .. code-block:: objc
1448 @interface MyObj : NSObject {
1454 @implementation MyObj
1457 .. _osx-cocoa-VariadicMethodTypes:
1459 osx.cocoa.VariadicMethodTypes (ObjC)
1460 """"""""""""""""""""""""""""""""""""
1461 Check for passing non-Objective-C types to variadic collection
1462 initialization methods that expect only Objective-C types.
1464 .. code-block:: objc
1467 [NSSet setWithObjects:@"Foo", "Bar", nil];
1468 // warn: argument should be an ObjC pointer type, not 'char *'
1471 .. _osx-coreFoundation-CFError:
1473 osx.coreFoundation.CFError (C)
1474 """"""""""""""""""""""""""""""
1475 Check usage of CFErrorRef* parameters
1479 void test(CFErrorRef *error) {
1480 // warn: function accepting CFErrorRef* should have a
1484 int foo(CFErrorRef *error) {
1485 *error = 0; // warn: potential null dereference
1489 .. _osx-coreFoundation-CFNumber:
1491 osx.coreFoundation.CFNumber (C)
1492 """""""""""""""""""""""""""""""
1493 Check for proper uses of CFNumber APIs.
1497 CFNumberRef test(unsigned char x) {
1498 return CFNumberCreate(0, kCFNumberSInt16Type, &x);
1499 // warn: 8 bit integer is used to initialize a 16 bit integer
1502 .. _osx-coreFoundation-CFRetainRelease:
1504 osx.coreFoundation.CFRetainRelease (C)
1505 """"""""""""""""""""""""""""""""""""""
1506 Check for null arguments to CFRetain/CFRelease/CFMakeCollectable.
1510 void test(CFTypeRef p) {
1512 CFRetain(p); // warn
1515 void test(int x, CFTypeRef p) {
1519 CFRelease(p); // warn
1522 .. _osx-coreFoundation-containers-OutOfBounds:
1524 osx.coreFoundation.containers.OutOfBounds (C)
1525 """""""""""""""""""""""""""""""""""""""""""""
1526 Checks for index out-of-bounds when using 'CFArray' API.
1531 CFArrayRef A = CFArrayCreate(0, 0, 0, &kCFTypeArrayCallBacks);
1532 CFArrayGetValueAtIndex(A, 0); // warn
1535 .. _osx-coreFoundation-containers-PointerSizedValues:
1537 osx.coreFoundation.containers.PointerSizedValues (C)
1538 """"""""""""""""""""""""""""""""""""""""""""""""""""
1539 Warns if 'CFArray', 'CFDictionary', 'CFSet' are created with non-pointer-size values.
1545 CFArrayRef A = CFArrayCreate(0, (const void """""""""""""""""""""""")x, 1,
1546 &kCFTypeArrayCallBacks); // warn
1552 Fuchsia is an open source capability-based operating system currently being
1553 developed by Google. This section describes checkers that can find various
1554 misuses of Fuchsia APIs.
1556 .. _fuchsia-HandleChecker:
1558 fuchsia.HandleChecker
1559 """"""""""""""""""""""""""""
1560 Handles identify resources. Similar to pointers they can be leaked,
1561 double freed, or use after freed. This check attempts to find such problems.
1565 void checkLeak08(int tag) {
1567 zx_channel_create(0, &sa, &sb);
1569 zx_handle_close(sa);
1570 use(sb); // Warn: Potential leak of handle
1571 zx_handle_close(sb);
1577 WebKit is an open-source web browser engine available for macOS, iOS and Linux.
1578 This section describes checkers that can find issues in WebKit codebase.
1580 Most of the checkers focus on memory management for which WebKit uses custom implementation of reference counted smartpointers.
1582 Checkers are formulated in terms related to ref-counting:
1583 - *Ref-counted type* is either ``Ref<T>`` or ``RefPtr<T>``.
1584 - *Ref-countable type* is any type that implements ``ref()`` and ``deref()`` methods as ``RefPtr<>`` is a template (i. e. relies on duck typing).
1585 - *Uncounted type* is ref-countable but not ref-counted type.
1587 .. _webkit-RefCntblBaseVirtualDtor:
1589 webkit.RefCntblBaseVirtualDtor
1590 """"""""""""""""""""""""""""""""""""
1591 All uncounted types used as base classes must have a virtual destructor.
1593 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]``.
1597 struct RefCntblBase {
1602 struct Derived : RefCntblBase { }; // warn
1604 .. _webkit-NoUncountedMemberChecker:
1606 webkit.NoUncountedMemberChecker
1607 """""""""""""""""""""""""""""""""""""
1608 Raw pointers and references to uncounted types can't be used as class members. Only ref-counted types are allowed.
1618 RefCntbl * ptr; // warn
1619 RefCntbl & ptr; // warn
1623 .. _webkit-UncountedLambdaCapturesChecker:
1625 webkit.UncountedLambdaCapturesChecker
1626 """""""""""""""""""""""""""""""""""""
1627 Raw pointers and references to uncounted types can't be captured in lambdas. Only ref-counted types are allowed.
1636 void foo(RefCntbl* a, RefCntbl& b) {
1637 [&, a](){ // warn about 'a'
1638 do_something(b); // warn about 'b'
1644 Experimental Checkers
1645 ---------------------
1647 *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.*
1652 .. _alpha-clone-CloneChecker:
1654 alpha.clone.CloneChecker (C, C++, ObjC)
1655 """""""""""""""""""""""""""""""""""""""
1656 Reports similar pieces of code.
1662 int max(int a, int b) { // warn
1669 int maxClone(int x, int y) { // similar code here
1679 .. _alpha-core-BoolAssignment:
1681 alpha.core.BoolAssignment (ObjC)
1682 """"""""""""""""""""""""""""""""
1683 Warn about assigning non-{0,1} values to boolean variables.
1685 .. code-block:: objc
1688 BOOL b = -1; // warn
1691 .. _alpha-core-C11Lock:
1695 Similarly to :ref:`alpha.unix.PthreadLock <alpha-unix-PthreadLock>`, checks for
1696 the locking/unlocking of ``mtx_t`` mutexes.
1705 mtx_lock(&mtx1); // warn: This lock has already been acquired
1708 .. _alpha-core-CallAndMessageUnInitRefArg:
1710 alpha.core.CallAndMessageUnInitRefArg (C,C++, ObjC)
1711 """""""""""""""""""""""""""""""""""""""""""""""""""
1712 Check for logical errors for function calls and Objective-C
1713 message expressions (e.g., uninitialized arguments, null function pointers, and pointer to undefined variables).
1730 .. _alpha-core-CastSize:
1732 alpha.core.CastSize (C)
1733 """""""""""""""""""""""
1734 Check when casting a malloc'ed type ``T``, whether the size is a multiple of the size of ``T``.
1739 int *x = (int *) malloc(11); // warn
1742 .. _alpha-core-CastToStruct:
1744 alpha.core.CastToStruct (C, C++)
1745 """"""""""""""""""""""""""""""""
1746 Check for cast from non-struct pointer to struct pointer.
1754 struct s *ps = (struct s *) p; // warn
1761 c *pc = (c *) p; // warn
1764 .. _alpha-core-Conversion:
1766 alpha.core.Conversion (C, C++, ObjC)
1767 """"""""""""""""""""""""""""""""""""
1768 Loss of sign/precision in implicit conversions.
1772 void test(unsigned U, signed S) {
1778 if (U < S) { // warn (loss of sign)
1784 long long A = 1LL << 60;
1785 short X = A; // warn (loss of precision)
1788 .. _alpha-core-DynamicTypeChecker:
1790 alpha.core.DynamicTypeChecker (ObjC)
1791 """"""""""""""""""""""""""""""""""""
1792 Check for cases where the dynamic and the static type of an object are unrelated.
1795 .. code-block:: objc
1797 id date = [NSDate date];
1799 // Warning: Object has a dynamic type 'NSDate *' which is
1800 // incompatible with static type 'NSNumber *'"
1801 NSNumber *number = date;
1802 [number doubleValue];
1804 .. _alpha-core-FixedAddr:
1806 alpha.core.FixedAddr (C)
1807 """"""""""""""""""""""""
1808 Check for assignment of a fixed address to a pointer.
1814 p = (int *) 0x10000; // warn
1817 .. _alpha-core-IdenticalExpr:
1819 alpha.core.IdenticalExpr (C, C++)
1820 """""""""""""""""""""""""""""""""
1821 Warn about unintended use of identical expressions in operators.
1828 int b = a | 4 | a; // warn: identical expr on both sides
1836 if (f()) { // warn: true and false branches are identical
1847 .. _alpha-core-PointerArithm:
1849 alpha.core.PointerArithm (C)
1850 """"""""""""""""""""""""""""
1851 Check for pointer arithmetic on locations other than array elements.
1861 .. _alpha-core-PointerSub:
1863 alpha.core.PointerSub (C)
1864 """""""""""""""""""""""""
1865 Check for pointer subtractions on two pointers pointing to different memory chunks.
1871 int d = &y - &x; // warn
1874 .. _alpha-core-SizeofPtr:
1876 alpha.core.SizeofPtr (C)
1877 """"""""""""""""""""""""
1878 Warn about unintended use of ``sizeof()`` on pointer expressions.
1884 int test(struct s *p) {
1886 // warn: sizeof(ptr) can produce an unexpected result
1889 .. _alpha-core-StackAddressAsyncEscape:
1891 alpha.core.StackAddressAsyncEscape (C)
1892 """"""""""""""""""""""""""""""""""""""
1893 Check that addresses to stack memory do not escape the function that involves dispatch_after or dispatch_async.
1894 This checker is a part of ``core.StackAddressEscape``, but is temporarily disabled until some false positives are fixed.
1898 dispatch_block_t test_block_inside_block_async_leak() {
1900 void (^inner)(void) = ^void(void) {
1904 void (^outer)(void) = ^void(void) {
1909 return outer; // warn: address of stack-allocated block is captured by a
1913 .. _alpha-core-TestAfterDivZero:
1915 alpha.core.TestAfterDivZero (C)
1916 """""""""""""""""""""""""""""""
1917 Check for division by variable that is later compared against 0.
1918 Either the comparison is useless or there is division by zero.
1924 if (x == 0) { } // warn
1930 .. _alpha-cplusplus-ArrayDelete:
1932 alpha.cplusplus.ArrayDelete (C++)
1933 """""""""""""""""""""""""""""""""
1934 Reports destructions of arrays of polymorphic objects that are destructed as their base class.
1935 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>`_.
1942 class Derived : public Base {}
1945 Base *x = new Derived[10]; // note: Casting from 'Derived' to 'Base' here
1951 delete[] x; // warn: Deleting an array of 'Derived' objects as their base class 'Base' is undefined
1954 .. _alpha-cplusplus-DeleteWithNonVirtualDtor:
1956 alpha.cplusplus.DeleteWithNonVirtualDtor (C++)
1957 """"""""""""""""""""""""""""""""""""""""""""""
1958 Reports destructions of polymorphic objects with a non-virtual destructor in their base class.
1962 class NonVirtual {};
1963 class NVDerived : public NonVirtual {};
1965 NonVirtual *create() {
1966 NonVirtual *x = new NVDerived(); // note: Casting from 'NVDerived' to
1967 // 'NonVirtual' here
1972 NonVirtual *x = create();
1973 delete x; // warn: destruction of a polymorphic object with no virtual
1977 .. _alpha-cplusplus-EnumCastOutOfRange:
1979 alpha.cplusplus.EnumCastOutOfRange (C++)
1980 """"""""""""""""""""""""""""""""""""""""
1981 Check for integer to enumeration casts that could result in undefined values.
1990 TestEnum t = static_cast(-1);
1991 // warn: the value provided to the cast expression is not in
1992 // the valid range of values for the enum
1994 .. _alpha-cplusplus-InvalidatedIterator:
1996 alpha.cplusplus.InvalidatedIterator (C++)
1997 """""""""""""""""""""""""""""""""""""""""
1998 Check for use of invalidated iterators.
2002 void bad_copy_assign_operator_list1(std::list &L1,
2003 const std::list &L2) {
2004 auto i0 = L1.cbegin();
2006 *i0; // warn: invalidated iterator accessed
2010 .. _alpha-cplusplus-IteratorRange:
2012 alpha.cplusplus.IteratorRange (C++)
2013 """""""""""""""""""""""""""""""""""
2014 Check for iterators used outside their valid ranges.
2018 void simple_bad_end(const std::vector &v) {
2020 *i; // warn: iterator accessed outside of its range
2023 .. _alpha-cplusplus-MismatchedIterator:
2025 alpha.cplusplus.MismatchedIterator (C++)
2026 """"""""""""""""""""""""""""""""""""""""
2027 Check for use of iterators of different containers where iterators of the same container are expected.
2031 void bad_insert3(std::vector &v1, std::vector &v2) {
2032 v2.insert(v1.cbegin(), v2.cbegin(), v2.cend()); // warn: container accessed
2034 // iterator argument
2035 v1.insert(v1.cbegin(), v1.cbegin(), v2.cend()); // warn: iterators of
2036 // different containers
2037 // used where the same
2040 v1.insert(v1.cbegin(), v2.cbegin(), v1.cend()); // warn: iterators of
2041 // different containers
2042 // used where the same
2047 .. _alpha-cplusplus-MisusedMovedObject:
2049 alpha.cplusplus.MisusedMovedObject (C++)
2050 """"""""""""""""""""""""""""""""""""""""
2051 Method calls on a moved-from object and copying a moved-from object will be reported.
2062 A b = std::move(a); // note: 'a' became 'moved-from' here
2063 a.foo(); // warn: method call on a 'moved-from' object 'a'
2066 .. _alpha-cplusplus-SmartPtr:
2068 alpha.cplusplus.SmartPtr (C++)
2069 """"""""""""""""""""""""""""""
2070 Check for dereference of null smart pointers.
2074 void deref_smart_ptr() {
2075 std::unique_ptr<int> P;
2076 *P; // warn: dereference of a default constructed smart unique_ptr
2082 .. _alpha-deadcode-UnreachableCode:
2084 alpha.deadcode.UnreachableCode (C, C++)
2085 """""""""""""""""""""""""""""""""""""""
2086 Check unreachable code.
2117 .. _alpha-fuchsia-lock:
2121 Similarly to :ref:`alpha.unix.PthreadLock <alpha-unix-PthreadLock>`, checks for
2122 the locking/unlocking of fuchsia mutexes.
2131 spin_lock(&mtx1); // warn: This lock has already been acquired
2137 .. _alpha-llvm-Conventions:
2139 alpha.llvm.Conventions
2140 """"""""""""""""""""""
2142 Check code for LLVM codebase conventions:
2144 * A StringRef should not be bound to a temporary std::string whose lifetime is shorter than the StringRef's.
2145 * Clang AST nodes should not have fields that can allocate memory.
2151 .. _alpha-osx-cocoa-DirectIvarAssignment:
2153 alpha.osx.cocoa.DirectIvarAssignment (ObjC)
2154 """""""""""""""""""""""""""""""""""""""""""
2155 Check for direct assignments to instance variables.
2158 .. code-block:: objc
2160 @interface MyClass : NSObject {}
2161 @property (readonly) id A;
2165 @implementation MyClass
2171 .. _alpha-osx-cocoa-DirectIvarAssignmentForAnnotatedFunctions:
2173 alpha.osx.cocoa.DirectIvarAssignmentForAnnotatedFunctions (ObjC)
2174 """"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
2175 Check for direct assignments to instance variables in
2176 the methods annotated with ``objc_no_direct_instance_variable_assignment``.
2178 .. code-block:: objc
2180 @interface MyClass : NSObject {}
2181 @property (readonly) id A;
2182 - (void) fAnnotated __attribute__((
2183 annotate("objc_no_direct_instance_variable_assignment")));
2184 - (void) fNotAnnotated;
2187 @implementation MyClass
2188 - (void) fAnnotated {
2191 - (void) fNotAnnotated {
2197 .. _alpha-osx-cocoa-InstanceVariableInvalidation:
2199 alpha.osx.cocoa.InstanceVariableInvalidation (ObjC)
2200 """""""""""""""""""""""""""""""""""""""""""""""""""
2201 Check that the invalidatable instance variables are
2202 invalidated in the methods annotated with objc_instance_variable_invalidator.
2204 .. code-block:: objc
2206 @protocol Invalidation <NSObject>
2208 __attribute__((annotate("objc_instance_variable_invalidator")));
2211 @interface InvalidationImpObj : NSObject <Invalidation>
2214 @interface SubclassInvalidationImpObj : InvalidationImpObj {
2215 InvalidationImpObj *var;
2220 @implementation SubclassInvalidationImpObj
2221 - (void) invalidate {}
2223 // warn: var needs to be invalidated or set to nil
2225 .. _alpha-osx-cocoa-MissingInvalidationMethod:
2227 alpha.osx.cocoa.MissingInvalidationMethod (ObjC)
2228 """"""""""""""""""""""""""""""""""""""""""""""""
2229 Check that the invalidation methods are present in classes that contain invalidatable instance variables.
2231 .. code-block:: objc
2233 @protocol Invalidation <NSObject>
2235 __attribute__((annotate("objc_instance_variable_invalidator")));
2238 @interface NeedInvalidation : NSObject <Invalidation>
2241 @interface MissingInvalidationMethodDecl : NSObject {
2242 NeedInvalidation *Var; // warn
2246 @implementation MissingInvalidationMethodDecl
2249 .. _alpha-osx-cocoa-localizability-PluralMisuseChecker:
2251 alpha.osx.cocoa.localizability.PluralMisuseChecker (ObjC)
2252 """""""""""""""""""""""""""""""""""""""""""""""""""""""""
2253 Warns against using one vs. many plural pattern in code when generating localized strings.
2255 .. code-block:: objc
2257 NSString *reminderText =
2258 NSLocalizedString(@"None", @"Indicates no reminders");
2259 if (reminderCount == 1) {
2260 // Warning: Plural cases are not supported across all languages.
2261 // Use a .stringsdict file instead
2263 NSLocalizedString(@"1 Reminder", @"Indicates single reminder");
2264 } else if (reminderCount >= 2) {
2265 // Warning: Plural cases are not supported across all languages.
2266 // Use a .stringsdict file instead
2268 [NSString stringWithFormat:
2269 NSLocalizedString(@"%@ Reminders", @"Indicates multiple reminders"),
2276 .. _alpha-security-ArrayBound:
2278 alpha.security.ArrayBound (C)
2279 """""""""""""""""""""""""""""
2280 Warn about buffer overflows (older checker).
2286 char c = s[1]; // warn
2289 struct seven_words {
2294 struct seven_words a, *p;
2301 // note: requires unix.Malloc or
2302 // alpha.unix.MallocWithAnnotations checks enabled.
2304 int *p = malloc(12);
2314 .. _alpha-security-ArrayBoundV2:
2316 alpha.security.ArrayBoundV2 (C)
2317 """""""""""""""""""""""""""""""
2318 Warn about buffer overflows (newer checker).
2324 char c = s[1]; // warn
2334 // note: compiler has internal check for this.
2335 // Use -Wno-array-bounds to suppress compiler warning.
2338 buf[0][-1] = 1; // warn
2341 // note: requires alpha.security.taint check turned on.
2345 char c = s[x]; // warn: index is tainted
2348 .. _alpha-security-MallocOverflow:
2350 alpha.security.MallocOverflow (C)
2351 """""""""""""""""""""""""""""""""
2352 Check for overflows in the arguments to ``malloc()``.
2353 It tries to catch ``malloc(n * c)`` patterns, where:
2355 - ``n``: a variable or member access of an object
2356 - ``c``: a constant foldable integral
2358 This checker was designed for code audits, so expect false-positive reports.
2359 One is supposed to silence this checker by ensuring proper bounds checking on
2360 the variable in question using e.g. an ``assert()`` or a branch.
2365 void *p = malloc(n * sizeof(int)); // warn
2369 if (n > 100) // gives an upper-bound
2371 void *p = malloc(n * sizeof(int)); // no warning
2375 assert(n <= 100 && "Contract violated.");
2376 void *p = malloc(n * sizeof(int)); // no warning
2381 - The checker won't warn for variables involved in explicit casts,
2382 since that might limit the variable's domain.
2383 E.g.: ``(unsigned char)int x`` would limit the domain to ``[0,255]``.
2384 The checker will miss the true-positive cases when the explicit cast would
2385 not tighten the domain to prevent the overflow in the subsequent
2386 multiplication operation.
2388 - It is an AST-based checker, thus it does not make use of the
2389 path-sensitive taint-analysis.
2391 .. _alpha-security-MmapWriteExec:
2393 alpha.security.MmapWriteExec (C)
2394 """"""""""""""""""""""""""""""""
2395 Warn on mmap() calls that are both writable and executable.
2400 void *c = mmap(NULL, 32, PROT_READ | PROT_WRITE | PROT_EXEC,
2401 MAP_PRIVATE | MAP_ANON, -1, 0);
2402 // warn: Both PROT_WRITE and PROT_EXEC flags are set. This can lead to
2403 // exploitable memory regions, which could be overwritten with malicious
2407 .. _alpha-security-ReturnPtrRange:
2409 alpha.security.ReturnPtrRange (C)
2410 """""""""""""""""""""""""""""""""
2411 Check for an out-of-bound pointer being returned to callers.
2424 return x; // warn: undefined or garbage returned
2431 SEI CERT checkers which tries to find errors based on their `C coding rules <https://wiki.sei.cmu.edu/confluence/display/c/2+Rules>`_.
2433 .. _alpha-security-cert-pos-checkers:
2435 alpha.security.cert.pos
2436 ^^^^^^^^^^^^^^^^^^^^^^^
2438 SEI CERT checkers of `POSIX C coding rules <https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152405>`_.
2440 .. _alpha-security-cert-pos-34c:
2442 alpha.security.cert.pos.34c
2443 """""""""""""""""""""""""""
2444 Finds calls to the ``putenv`` function which pass a pointer to an automatic variable as the argument.
2448 int func(const char *var) {
2450 int retval = snprintf(env, sizeof(env),"TEST=%s", var);
2451 if (retval < 0 || (size_t)retval >= sizeof(env)) {
2455 return putenv(env); // putenv function should not be called with auto variables
2460 - Technically, one can pass automatic variables to ``putenv``,
2461 but one needs to ensure that the given environment key stays
2462 alive until it's removed or overwritten.
2463 Since the analyzer cannot keep track of which envvars get overwritten
2464 and when, it needs to be slightly more aggressive and warn for such
2465 cases too, leading in some cases to false-positive reports like this:
2470 char env[] = "NAME=value";
2471 putenv(env); // false-positive warning: putenv function should not be called...
2473 putenv((char *)"NAME=anothervalue");
2474 // This putenv call overwrites the previous entry, thus that can no longer dangle.
2475 } // 'env' array becomes dead only here.
2477 alpha.security.cert.env
2478 ^^^^^^^^^^^^^^^^^^^^^^^
2480 SEI CERT checkers of `Environment C coding rules <https://wiki.sei.cmu.edu/confluence/x/JdcxBQ>`_.
2482 .. _alpha-security-cert-env-InvalidPtr:
2484 alpha.security.cert.env.InvalidPtr
2485 """"""""""""""""""""""""""""""""""
2487 Corresponds to SEI CERT Rules ENV31-C and ENV34-C.
2490 Rule is about the possible problem with `main` function's third argument, environment pointer,
2491 "envp". When environment array is modified using some modification function
2492 such as putenv, setenv or others, It may happen that memory is reallocated,
2493 however "envp" is not updated to reflect the changes and points to old memory
2497 Some functions return a pointer to a statically allocated buffer.
2498 Consequently, subsequent call of these functions will invalidate previous
2499 pointer. These functions include: getenv, localeconv, asctime, setlocale, strerror
2503 int main(int argc, const char *argv[], const char *envp[]) {
2504 if (setenv("MY_NEW_VAR", "new_value", 1) != 0) {
2505 // setenv call may invalidate 'envp'
2509 for (size_t i = 0; envp[i] != NULL; ++i) {
2511 // envp may no longer point to the current environment
2512 // this program has unanticipated behavior, since envp
2513 // does not reflect changes made by setenv function.
2519 void previous_call_invalidation() {
2523 setenv("SOMEVAR", "VALUE", /*overwrite = */1);
2524 // call to 'setenv' may invalidate p
2527 // dereferencing invalid pointer
2531 The ``InvalidatingGetEnv`` option is available for treating getenv calls as
2532 invalidating. When enabled, the checker issues a warning if getenv is called
2533 multiple times and their results are used without first creating a copy.
2534 This level of strictness might be considered overly pedantic for the commonly
2535 used getenv implementations.
2537 To enable this option, use:
2538 ``-analyzer-config alpha.security.cert.env.InvalidPtr:InvalidatingGetEnv=true``.
2540 By default, this option is set to *false*.
2542 When this option is enabled, warnings will be generated for scenarios like the
2547 char* p = getenv("VAR");
2548 char* pp = getenv("VAR2"); // assumes this call can invalidate `env`
2549 strlen(p); // warns about accessing invalid ptr
2551 alpha.security.taint
2552 ^^^^^^^^^^^^^^^^^^^^
2554 Checkers implementing
2555 `taint analysis <https://en.wikipedia.org/wiki/Taint_checking>`_.
2557 .. _alpha-security-taint-TaintPropagation:
2559 alpha.security.taint.TaintPropagation (C, C++)
2560 """"""""""""""""""""""""""""""""""""""""""""""
2562 Taint analysis identifies potential security vulnerabilities where the
2563 attacker can inject malicious data to the program to execute an attack
2564 (privilege escalation, command injection, SQL injection etc.).
2566 The malicious data is injected at the taint source (e.g. ``getenv()`` call)
2567 which is then propagated through function calls and being used as arguments of
2568 sensitive operations, also called as taint sinks (e.g. ``system()`` call).
2570 One can defend against this type of vulnerability by always checking and
2571 sanitizing the potentially malicious, untrusted user input.
2573 The goal of the checker is to discover and show to the user these potential
2574 taint source-sink pairs and the propagation call chain.
2576 The most notable examples of taint sources are:
2579 - files or standard input
2580 - environment variables
2581 - data from databases
2583 Let us examine a practical example of a Command Injection attack.
2587 // Command Injection Vulnerability Example
2588 int main(int argc, char** argv) {
2589 char cmd[2048] = "/bin/cat ";
2590 char filename[1024];
2591 printf("Filename:");
2592 scanf (" %1023[^\n]", filename); // The attacker can inject a shell escape here
2593 strcat(cmd, filename);
2594 system(cmd); // Warning: Untrusted data is passed to a system call
2597 The program prints the content of any user specified file.
2598 Unfortunately the attacker can execute arbitrary commands
2599 with shell escapes. For example with the following input the `ls` command is also
2600 executed after the contents of `/etc/shadow` is printed.
2601 `Input: /etc/shadow ; ls /`
2603 The analysis implemented in this checker points out this problem.
2605 One can protect against such attack by for example checking if the provided
2606 input refers to a valid file and removing any invalid user input.
2610 // No vulnerability anymore, but we still get the warning
2611 void sanitizeFileName(char* filename){
2612 if (access(filename,F_OK)){// Verifying user input
2613 printf("File does not exist\n");
2617 int main(int argc, char** argv) {
2618 char cmd[2048] = "/bin/cat ";
2619 char filename[1024];
2620 printf("Filename:");
2621 scanf (" %1023[^\n]", filename); // The attacker can inject a shell escape here
2622 sanitizeFileName(filename);// filename is safe after this point
2625 strcat(cmd, filename);
2626 system(cmd); // Superfluous Warning: Untrusted data is passed to a system call
2629 Unfortunately, the checker cannot discover automatically that the programmer
2630 have performed data sanitation, so it still emits the warning.
2632 One can get rid of this superfluous warning by telling by specifying the
2633 sanitation functions in the taint configuration file (see
2634 :doc:`user-docs/TaintAnalysisConfiguration`).
2636 .. code-block:: YAML
2639 - Name: sanitizeFileName
2642 The clang invocation to pass the configuration file location:
2644 .. code-block:: bash
2646 clang --analyze -Xclang -analyzer-config -Xclang alpha.security.taint.TaintPropagation:Config=`pwd`/taint_config.yml ...
2648 If you are validating your inputs instead of sanitizing them, or don't want to
2649 mention each sanitizing function in our configuration,
2650 you can use a more generic approach.
2652 Introduce a generic no-op `csa_mark_sanitized(..)` function to
2653 tell the Clang Static Analyzer
2654 that the variable is safe to be used on that analysis path.
2658 // Marking sanitized variables safe.
2659 // No vulnerability anymore, no warning.
2661 // User csa_mark_sanitize function is for the analyzer only
2662 #ifdef __clang_analyzer__
2663 void csa_mark_sanitized(const void *);
2666 int main(int argc, char** argv) {
2667 char cmd[2048] = "/bin/cat ";
2668 char filename[1024];
2669 printf("Filename:");
2670 scanf (" %1023[^\n]", filename);
2671 if (access(filename,F_OK)){// Verifying user input
2672 printf("File does not exist\n");
2675 #ifdef __clang_analyzer__
2676 csa_mark_sanitized(filename); // Indicating to CSA that filename variable is safe to be used after this point
2678 strcat(cmd, filename);
2679 system(cmd); // No warning
2682 Similarly to the previous example, you need to
2683 define a `Filter` function in a `YAML` configuration file
2684 and add the `csa_mark_sanitized` function.
2686 .. code-block:: YAML
2689 - Name: csa_mark_sanitized
2692 Then calling `csa_mark_sanitized(X)` will tell the analyzer that `X` is safe to
2693 be used after this point, because its contents are verified. It is the
2694 responsibility of the programmer to ensure that this verification was indeed
2695 correct. Please note that `csa_mark_sanitized` function is only declared and
2696 used during Clang Static Analysis and skipped in (production) builds.
2698 Further examples of injection vulnerabilities this checker can find.
2703 char x = getchar(); // 'x' marked as tainted
2704 system(&x); // warn: untrusted data is passed to a system call
2707 // note: compiler internally checks if the second param to
2708 // sprintf is a string literal or not.
2709 // Use -Wno-format-security to suppress compiler warning.
2711 char s[10], buf[10];
2712 fscanf(stdin, "%s", s); // 's' marked as tainted
2714 sprintf(buf, s); // warn: untrusted data used as a format string
2719 scanf("%zd", &ts); // 'ts' marked as tainted
2720 int *p = (int *)malloc(ts * sizeof(int));
2721 // warn: untrusted data used as buffer size
2724 There are built-in sources, propagations and sinks even if no external taint
2725 configuration is provided.
2728 ``_IO_getc``, ``fdopen``, ``fopen``, ``freopen``, ``get_current_dir_name``,
2729 ``getch``, ``getchar``, ``getchar_unlocked``, ``getwd``, ``getcwd``,
2730 ``getgroups``, ``gethostname``, ``getlogin``, ``getlogin_r``, ``getnameinfo``,
2731 ``gets``, ``gets_s``, ``getseuserbyname``, ``readlink``, ``readlinkat``,
2732 ``scanf``, ``scanf_s``, ``socket``, ``wgetch``
2734 Default propagations rules:
2735 ``atoi``, ``atol``, ``atoll``, ``basename``, ``dirname``, ``fgetc``,
2736 ``fgetln``, ``fgets``, ``fnmatch``, ``fread``, ``fscanf``, ``fscanf_s``,
2737 ``index``, ``inflate``, ``isalnum``, ``isalpha``, ``isascii``, ``isblank``,
2738 ``iscntrl``, ``isdigit``, ``isgraph``, ``islower``, ``isprint``, ``ispunct``,
2739 ``isspace``, ``isupper``, ``isxdigit``, ``memchr``, ``memrchr``, ``sscanf``,
2740 ``getc``, ``getc_unlocked``, ``getdelim``, ``getline``, ``getw``, ``memcmp``,
2741 ``memcpy``, ``memmem``, ``memmove``, ``mbtowc``, ``pread``, ``qsort``,
2742 ``qsort_r``, ``rawmemchr``, ``read``, ``recv``, ``recvfrom``, ``rindex``,
2743 ``strcasestr``, ``strchr``, ``strchrnul``, ``strcasecmp``, ``strcmp``,
2744 ``strcspn``, ``strncasecmp``, ``strncmp``, ``strndup``,
2745 ``strndupa``, ``strpbrk``, ``strrchr``, ``strsep``, ``strspn``,
2746 ``strstr``, ``strtol``, ``strtoll``, ``strtoul``, ``strtoull``, ``tolower``,
2747 ``toupper``, ``ttyname``, ``ttyname_r``, ``wctomb``, ``wcwidth``
2750 ``printf``, ``setproctitle``, ``system``, ``popen``, ``execl``, ``execle``,
2751 ``execlp``, ``execv``, ``execvp``, ``execvP``, ``execve``, ``dlopen``,
2752 ``memcpy``, ``memmove``, ``strncpy``, ``strndup``, ``malloc``, ``calloc``,
2753 ``alloca``, ``memccpy``, ``realloc``, ``bcopy``
2755 Please note that there are no built-in filter functions.
2757 One can configure their own taint sources, sinks, and propagation rules by
2758 providing a configuration file via checker option
2759 ``alpha.security.taint.TaintPropagation:Config``. The configuration file is in
2760 `YAML <http://llvm.org/docs/YamlIO.html#introduction-to-yaml>`_ format. The
2761 taint-related options defined in the config file extend but do not override the
2762 built-in sources, rules, sinks. The format of the external taint configuration
2763 file is not stable, and could change without any notice even in a non-backward
2766 For a more detailed description of configuration options, please see the
2767 :doc:`user-docs/TaintAnalysisConfiguration`. For an example see
2768 :ref:`clangsa-taint-configuration-example`.
2772 * `Config` Specifies the name of the YAML configuration file. The user can
2773 define their own taint sources and sinks.
2775 **Related Guidelines**
2777 * `CWE Data Neutralization Issues
2778 <https://cwe.mitre.org/data/definitions/137.html>`_
2779 * `SEI Cert STR02-C. Sanitize data passed to complex subsystems
2780 <https://wiki.sei.cmu.edu/confluence/display/c/STR02-C.+Sanitize+data+passed+to+complex+subsystems>`_
2781 * `SEI Cert ENV33-C. Do not call system()
2782 <https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152177>`_
2783 * `ENV03-C. Sanitize the environment when invoking external programs
2784 <https://wiki.sei.cmu.edu/confluence/display/c/ENV03-C.+Sanitize+the+environment+when+invoking+external+programs>`_
2788 * The taintedness property is not propagated through function calls which are
2789 unknown (or too complex) to the analyzer, unless there is a specific
2790 propagation rule built-in to the checker or given in the YAML configuration
2791 file. This causes potential true positive findings to be lost.
2796 .. _alpha-unix-BlockInCriticalSection:
2798 alpha.unix.BlockInCriticalSection (C)
2799 """""""""""""""""""""""""""""""""""""
2800 Check for calls to blocking functions inside a critical section.
2801 Applies to: ``lock, unlock, sleep, getc, fgets, read, recv, pthread_mutex_lock,``
2802 `` pthread_mutex_unlock, mtx_lock, mtx_timedlock, mtx_trylock, mtx_unlock, lock_guard, unique_lock``
2809 sleep(3); // warn: a blocking function sleep is called inside a critical
2814 .. _alpha-unix-Chroot:
2816 alpha.unix.Chroot (C)
2817 """""""""""""""""""""
2818 Check improper use of chroot.
2825 chroot("/usr/local");
2826 f(); // warn: no call of chdir("/") immediately after chroot
2829 .. _alpha-unix-Errno:
2831 alpha.unix.Errno (C)
2832 """"""""""""""""""""
2834 Check for improper use of ``errno``.
2835 This checker implements partially CERT rule
2836 `ERR30-C. Set errno to zero before calling a library function known to set errno,
2837 and check errno only after the function returns a value indicating failure
2838 <https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152351>`_.
2839 The checker can find the first read of ``errno`` after successful standard
2842 The C and POSIX standards often do not define if a standard library function
2843 may change value of ``errno`` if the call does not fail.
2844 Therefore, ``errno`` should only be used if it is known from the return value
2845 of a function that the call has failed.
2846 There are exceptions to this rule (for example ``strtol``) but the affected
2847 functions are not yet supported by the checker.
2848 The return values for the failure cases are documented in the standard Linux man
2849 pages of the functions and in the `POSIX standard <https://pubs.opengroup.org/onlinepubs/9699919799/>`_.
2853 int unsafe_errno_read(int sock, void *data, int data_size) {
2854 if (send(sock, data, data_size, 0) != data_size) {
2855 // 'send' can be successful even if not all data was sent
2856 if (errno == 1) { // An undefined value may be read from 'errno'
2863 The checker :ref:`unix-StdCLibraryFunctions` must be turned on to get the
2864 warnings from this checker. The supported functions are the same as by
2865 :ref:`unix-StdCLibraryFunctions`. The ``ModelPOSIX`` option of that
2866 checker affects the set of checked functions.
2870 The ``AllowErrnoReadOutsideConditionExpressions`` option allows read of the
2871 errno value if the value is not used in a condition (in ``if`` statements,
2872 loops, conditional expressions, ``switch`` statements). For example ``errno``
2873 can be stored into a variable without getting a warning by the checker.
2877 int unsafe_errno_read(int sock, void *data, int data_size) {
2878 if (send(sock, data, data_size, 0) != data_size) {
2880 // warning if 'AllowErrnoReadOutsideConditionExpressions' is false
2881 // no warning if 'AllowErrnoReadOutsideConditionExpressions' is true
2886 Default value of this option is ``true``. This allows save of the errno value
2887 for possible later error handling.
2891 - Only the very first usage of ``errno`` is checked after an affected function
2892 call. Value of ``errno`` is not followed when it is stored into a variable
2893 or returned from a function.
2894 - Documentation of function ``lseek`` is not clear about what happens if the
2895 function returns different value than the expected file position but not -1.
2896 To avoid possible false-positives ``errno`` is allowed to be used in this
2899 .. _alpha-unix-PthreadLock:
2901 alpha.unix.PthreadLock (C)
2902 """"""""""""""""""""""""""
2903 Simple lock -> unlock checker.
2904 Applies to: ``pthread_mutex_lock, pthread_rwlock_rdlock, pthread_rwlock_wrlock, lck_mtx_lock, lck_rw_lock_exclusive``
2905 ``lck_rw_lock_shared, pthread_mutex_trylock, pthread_rwlock_tryrdlock, pthread_rwlock_tryrwlock, lck_mtx_try_lock,
2906 lck_rw_try_lock_exclusive, lck_rw_try_lock_shared, pthread_mutex_unlock, pthread_rwlock_unlock, lck_mtx_unlock, lck_rw_done``.
2911 pthread_mutex_t mtx;
2914 pthread_mutex_lock(&mtx);
2915 pthread_mutex_lock(&mtx);
2916 // warn: this lock has already been acquired
2919 lck_mtx_t lck1, lck2;
2922 lck_mtx_lock(&lck1);
2923 lck_mtx_lock(&lck2);
2924 lck_mtx_unlock(&lck1);
2925 // warn: this was not the most recently acquired lock
2928 lck_mtx_t lck1, lck2;
2931 if (lck_mtx_try_lock(&lck1) == 0)
2934 lck_mtx_lock(&lck2);
2935 lck_mtx_unlock(&lck1);
2936 // warn: this was not the most recently acquired lock
2939 .. _alpha-unix-SimpleStream:
2941 alpha.unix.SimpleStream (C)
2942 """""""""""""""""""""""""""
2943 Check for misuses of stream APIs. Check for misuses of stream APIs: ``fopen, fclose``
2944 (demo checker, the subject of the demo (`Slides <https://llvm.org/devmtg/2012-11/Zaks-Rose-Checker24Hours.pdf>`_ ,
2945 `Video <https://youtu.be/kdxlsP5QVPw>`_) by Anna Zaks and Jordan Rose presented at the
2946 `2012 LLVM Developers' Meeting <https://llvm.org/devmtg/2012-11/>`_).
2951 FILE *F = fopen("myfile.txt", "w");
2952 } // warn: opened file is never closed
2955 FILE *F = fopen("myfile.txt", "w");
2960 fclose(F); // warn: closing a previously closed file stream
2963 .. _alpha-unix-Stream:
2965 alpha.unix.Stream (C)
2966 """""""""""""""""""""
2967 Check stream handling functions: ``fopen, tmpfile, fclose, fread, fwrite, fseek, ftell, rewind, fgetpos,``
2968 ``fsetpos, clearerr, feof, ferror, fileno``.
2973 FILE *p = fopen("foo", "r");
2974 } // warn: opened file is never closed
2977 FILE *p = fopen("foo", "r");
2978 fseek(p, 1, SEEK_SET); // warn: stream pointer might be NULL
2983 FILE *p = fopen("foo", "r");
2987 // warn: third arg should be SEEK_SET, SEEK_END, or SEEK_CUR
2993 FILE *p = fopen("foo", "r");
2995 fclose(p); // warn: already closed
2999 FILE *p = tmpfile();
3000 ftell(p); // warn: stream pointer might be NULL
3005 .. _alpha-unix-cstring-BufferOverlap:
3007 alpha.unix.cstring.BufferOverlap (C)
3008 """"""""""""""""""""""""""""""""""""
3009 Checks for overlap in two buffer arguments. Applies to: ``memcpy, mempcpy, wmemcpy, wmempcpy``.
3015 memcpy(a + 2, a + 1, 8); // warn
3018 .. _alpha-unix-cstring-NotNullTerminated:
3020 alpha.unix.cstring.NotNullTerminated (C)
3021 """"""""""""""""""""""""""""""""""""""""
3022 Check for arguments which are not null-terminated strings; applies to: ``strlen, strnlen, strcpy, strncpy, strcat, strncat, wcslen, wcsnlen``.
3027 int y = strlen((char *)&test); // warn
3030 .. _alpha-unix-cstring-OutOfBounds:
3032 alpha.unix.cstring.OutOfBounds (C)
3033 """"""""""""""""""""""""""""""""""
3034 Check for out-of-bounds access in string functions, such as:
3035 ``memcpy, bcopy, strcpy, strncpy, strcat, strncat, memmove, memcmp, memset`` and more.
3037 This check also works with string literals, except there is a known bug in that
3038 the analyzer cannot detect embedded NULL characters when determining the string length.
3043 const char str[] = "Hello world";
3044 char buffer[] = "Hello world";
3045 memcpy(buffer, str, sizeof(str) + 1); // warn
3049 const char str[] = "Hello world";
3050 char buffer[] = "Helloworld";
3051 memcpy(buffer, str, sizeof(str)); // warn
3054 .. _alpha-unix-cstring-UninitializedRead:
3056 alpha.unix.cstring.UninitializedRead (C)
3057 """"""""""""""""""""""""""""""""""""""""
3058 Check for uninitialized reads from common memory copy/manipulation functions such as:
3059 ``memcpy, mempcpy, memmove, memcmp, strcmp, strncmp, strcpy, strlen, strsep`` and many more.
3066 memcpy(dst,src,sizeof(dst)); // warn: Bytes string function accesses uninitialized/garbage values
3071 - Due to limitations of the memory modeling in the analyzer, one can likely
3072 observe a lot of false-positive reports like this:
3076 void false_positive() {
3077 int src[] = {1, 2, 3, 4};
3079 memcpy(dst, src, 4 * sizeof(int)); // false-positive:
3080 // The 'src' buffer was correctly initialized, yet we cannot conclude
3081 // that since the analyzer could not see a direct initialization of the
3082 // very last byte of the source buffer.
3085 More details at the corresponding `GitHub issue <https://github.com/llvm/llvm-project/issues/43459>`_.
3087 .. _alpha-nondeterminism-PointerIteration:
3089 alpha.nondeterminism.PointerIteration (C++)
3090 """""""""""""""""""""""""""""""""""""""""""
3091 Check for non-determinism caused by iterating unordered containers of pointers.
3097 std::unordered_set<int *> UnorderedPtrSet = {&a, &b};
3099 for (auto i : UnorderedPtrSet) // warn
3103 .. _alpha-nondeterminism-PointerSorting:
3105 alpha.nondeterminism.PointerSorting (C++)
3106 """""""""""""""""""""""""""""""""""""""""
3107 Check for non-determinism caused by sorting of pointers.
3113 std::vector<int *> V = {&a, &b};
3114 std::sort(V.begin(), V.end()); // warn
3121 .. _alpha-webkit-UncountedCallArgsChecker:
3123 alpha.webkit.UncountedCallArgsChecker
3124 """""""""""""""""""""""""""""""""""""
3125 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.
3127 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.
3131 RefCountable* provide_uncounted();
3132 void consume(RefCountable*);
3134 // 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.
3137 consume(provide_uncounted()); // warn
3141 RefCountable* uncounted = provide_uncounted();
3142 consume(uncounted); // warn
3145 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.
3147 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.
3152 RefPtr<RefCountable> member;
3153 void consume(RefCountable*) { /* ... */ }
3155 consume(member.get()); // warn
3159 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.
3161 Allowed kinds of arguments:
3163 - values obtained from ref-counted objects (including temporaries as those survive the call too)
3167 RefCountable* provide_uncounted();
3168 void consume(RefCountable*);
3171 RefPtr<RefCountable> rc = makeRef(provide_uncounted());
3172 consume(rc.get()); // ok
3173 consume(makeRef(provide_uncounted()).get()); // ok
3176 - forwarding uncounted arguments from caller to callee
3180 void foo(RefCountable& a) {
3184 Caller of ``foo()`` is responsible for ``a``'s lifetime.
3194 Caller of ``foo()`` is responsible for keeping the memory pointed to by ``this`` pointer safe.
3200 foo(nullptr, NULL, 0); // ok
3202 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.
3204 - constructors of ref-counted types (including factory methods)
3205 - getters of ref-counted types
3206 - member overloaded operators
3208 - unary operators like ``&`` or ``*``
3210 alpha.webkit.UncountedLocalVarsChecker
3211 """"""""""""""""""""""""""""""""""""""
3212 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.
3214 These are examples of cases that we consider safe:
3219 RefPtr<RefCountable> counted;
3220 // The scope of uncounted is EMBEDDED in the scope of counted.
3222 RefCountable* uncounted = counted.get(); // ok
3226 void foo2(RefPtr<RefCountable> counted_param) {
3227 RefCountable* uncounted = counted_param.get(); // ok
3230 void FooClass::foo_method() {
3231 RefCountable* uncounted = this; // ok
3234 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.
3239 RefCountable* uncounted = new RefCountable; // warn
3242 RefCountable* global_uncounted;
3244 RefCountable* uncounted = global_uncounted; // warn
3248 RefPtr<RefCountable> counted;
3249 // The scope of uncounted is not EMBEDDED in the scope of counted.
3250 RefCountable* uncounted = counted.get(); // warn
3253 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:
3254 - variable defined in condition part of an ```if``` statement
3255 - variable defined in init statement condition of a ```for``` statement
3257 For the time being we also don't warn about uninitialized uncounted local variables.
3268 Checkers used for debugging the analyzer.
3269 :doc:`developer-docs/DebugChecks` page contains a detailed description.
3271 .. _debug-AnalysisOrder:
3275 Print callbacks that are called during analysis in order.
3277 .. _debug-ConfigDumper:
3283 .. _debug-DumpCFG Display:
3285 debug.DumpCFG Display
3286 """""""""""""""""""""
3287 Control-Flow Graphs.
3289 .. _debug-DumpCallGraph:
3295 .. _debug-DumpCalls:
3299 Print calls as they are traversed by the engine.
3301 .. _debug-DumpDominators:
3303 debug.DumpDominators
3304 """"""""""""""""""""
3305 Print the dominance tree for a given CFG.
3307 .. _debug-DumpLiveVars:
3311 Print results of live variable analysis.
3313 .. _debug-DumpTraversal:
3317 Print branch conditions as they are traversed by the engine.
3319 .. _debug-ExprInspection:
3321 debug.ExprInspection
3322 """"""""""""""""""""
3323 Check the analyzer's understanding of expressions.
3329 Emit warnings with analyzer statistics.
3331 .. _debug-TaintTest:
3335 Mark tainted symbols as such.
3341 View Control-Flow Graphs using GraphViz.
3343 .. _debug-ViewCallGraph:
3347 View Call Graph using GraphViz.
3349 .. _debug-ViewExplodedGraph:
3351 debug.ViewExplodedGraph
3352 """""""""""""""""""""""
3353 View Exploded Graphs using GraphViz.