Debian Codegraph @

clang/docs/analyzer/checkers.rst

raw
1 ==================
2 Available Checkers
3 ==================
4
5 The analyzer performs checks that are categorized into families or "checkers".
6
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.
9
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.
12
13 The :ref:`debug-checkers` package contains checkers for analyzer developers for debugging purposes.
14
15 .. contents:: Table of Contents
16 :depth: 4
17
18
19 .. _default-checkers:
20
21 Default Checkers
22 ----------------
23
24 .. _core-checkers:
25
26 core
27 ^^^^
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.*
31
32 .. _core-BitwiseShift:
33
34 core.BitwiseShift (C, C++)
35 """"""""""""""""""""""""""
36
37 Finds undefined behavior caused by the bitwise left- and right-shift operator
38 operating on integer types.
39
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.
43
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.)
51
52 **Examples**
53
54 .. code-block:: cpp
55
56 static_assert(sizeof(int) == 4, "assuming 32-bit int")
57
58 void basic_examples(int a, int b) {
59 if (b < 0) {
60 b = a << b; // warn: right operand is negative in left shift
61 } else if (b >= 32) {
62 b = a >> b; // warn: right shift overflows the capacity of 'int'
63 }
64 }
65
66 int pedantic_examples(int a, int b) {
67 if (a < 0) {
68 return a >> b; // warn: left operand is negative in right shift
69 }
70 a = 1000u << 31; // OK, overflow of unsigned value is well-defined, a == 0
71 if (b > 10) {
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
74 }
75 return 1000 << 31; // warn: this overflows the capacity of 'int'
76 }
77
78 **Solution**
79
80 Ensure the shift operands are in proper range before shifting.
81
82 .. _core-CallAndMessage:
83
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).
87
88 .. literalinclude:: checkers/callandmessage_example.c
89 :language: objc
90
91 .. _core-DivideZero:
92
93 core.DivideZero (C, C++, ObjC)
94 """"""""""""""""""""""""""""""
95 Check for division by zero.
96
97 .. literalinclude:: checkers/dividezero_example.c
98 :language: c
99
100 .. _core-NonNullParamChecker:
101
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.
105
106 .. code-block:: cpp
107
108 int f(int *p) __attribute__((nonnull));
109
110 void test(int *p) {
111 if (!p)
112 f(p); // warn
113 }
114
115 .. _core-NullDereference:
116
117 core.NullDereference (C, C++, ObjC)
118 """""""""""""""""""""""""""""""""""
119 Check for dereferences of null pointers.
120
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>`__
126 for reference.
127
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``.
132 *Defaults to true*.
133
134 .. code-block:: objc
135
136 // C
137 void test(int *p) {
138 if (p)
139 return;
140
141 int x = p[0]; // warn
142 }
143
144 // C
145 void test(int *p) {
146 if (!p)
147 *p = 0; // warn
148 }
149
150 // C++
151 class C {
152 public:
153 int x;
154 };
155
156 void test() {
157 C *pc = 0;
158 int k = pc->x; // warn
159 }
160
161 // Objective-C
162 @interface MyClass {
163 @public
164 int x;
165 }
166 @end
167
168 void test() {
169 MyClass *obj = 0;
170 obj->x = 1; // warn
171 }
172
173 .. _core-StackAddressEscape:
174
175 core.StackAddressEscape (C)
176 """""""""""""""""""""""""""
177 Check that addresses to stack memory do not escape the function.
178
179 .. code-block:: c
180
181 char const *p;
182
183 void test() {
184 char const str[] = "string";
185 p = str; // warn
186 }
187
188 void* test() {
189 return __builtin_alloca(12); // warn
190 }
191
192 void test() {
193 static int *x;
194 int y;
195 x = &y; // warn
196 }
197
198
199 .. _core-UndefinedBinaryOperatorResult:
200
201 core.UndefinedBinaryOperatorResult (C)
202 """"""""""""""""""""""""""""""""""""""
203 Check for undefined results of binary operators.
204
205 .. code-block:: c
206
207 void test() {
208 int x;
209 int y = x + 1; // warn: left operand is garbage
210 }
211
212 .. _core-VLASize:
213
214 core.VLASize (C)
215 """"""""""""""""
216 Check for declarations of Variable Length Arrays (VLA) of undefined, zero or negative
217 size.
218
219 .. code-block:: c
220
221 void test() {
222 int x;
223 int vla1[x]; // warn: garbage as size
224 }
225
226 void test() {
227 int x = 0;
228 int vla2[x]; // warn: zero size
229 }
230
231
232 The checker also gives warning if the `TaintPropagation` checker is switched on
233 and an unbound, attacker controlled (tainted) value is used to define
234 the size of the VLA.
235
236 .. code-block:: c
237
238 void taintedVLA(void) {
239 int x;
240 scanf("%d", &x);
241 int vla[x]; // Declared variable-length array (VLA) has tainted (attacker controlled) size, that can be 0 or negative
242 }
243
244 void taintedVerfieidVLA(void) {
245 int x;
246 scanf("%d", &x);
247 if (x<1)
248 return;
249 int vla[x]; // no-warning. The analyzer can prove that x must be positive.
250 }
251
252
253 .. _core-uninitialized-ArraySubscript:
254
255 core.uninitialized.ArraySubscript (C)
256 """""""""""""""""""""""""""""""""""""
257 Check for uninitialized values used as array subscripts.
258
259 .. code-block:: c
260
261 void test() {
262 int i, a[10];
263 int x = a[i]; // warn: array subscript is undefined
264 }
265
266 .. _core-uninitialized-Assign:
267
268 core.uninitialized.Assign (C)
269 """""""""""""""""""""""""""""
270 Check for assigning uninitialized values.
271
272 .. code-block:: c
273
274 void test() {
275 int x;
276 x |= 1; // warn: left expression is uninitialized
277 }
278
279 .. _core-uninitialized-Branch:
280
281 core.uninitialized.Branch (C)
282 """""""""""""""""""""""""""""
283 Check for uninitialized values used as branch conditions.
284
285 .. code-block:: c
286
287 void test() {
288 int x;
289 if (x) // warn
290 return;
291 }
292
293 .. _core-uninitialized-CapturedBlockVariable:
294
295 core.uninitialized.CapturedBlockVariable (C)
296 """"""""""""""""""""""""""""""""""""""""""""
297 Check for blocks that capture uninitialized values.
298
299 .. code-block:: c
300
301 void test() {
302 int x;
303 ^{ int y = x; }(); // warn
304 }
305
306 .. _core-uninitialized-UndefReturn:
307
308 core.uninitialized.UndefReturn (C)
309 """"""""""""""""""""""""""""""""""
310 Check for uninitialized values being returned to the caller.
311
312 .. code-block:: c
313
314 int test() {
315 int x;
316 return x; // warn
317 }
318
319 .. _core-uninitialized-NewArraySize:
320
321 core.uninitialized.NewArraySize (C++)
322 """""""""""""""""""""""""""""""""""""
323
324 Check if the element count in new[] is garbage or undefined.
325
326 .. code-block:: cpp
327
328 void test() {
329 int n;
330 int *arr = new int[n]; // warn: Element count in new[] is a garbage value
331 delete[] arr;
332 }
333
334
335 .. _cplusplus-checkers:
336
337
338 cplusplus
339 ^^^^^^^^^
340
341 C++ Checkers.
342
343 .. _cplusplus-ArrayDelete:
344
345 cplusplus.ArrayDelete (C++)
346 """""""""""""""""""""""""""
347
348 Reports destructions of arrays of polymorphic objects that are destructed as
349 their base class. If the dynamic type of the array is different from its static
350 type, calling `delete[]` is undefined.
351
352 This checker corresponds to the SEI 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>`_.
353
354 .. code-block:: cpp
355
356 class Base {
357 public:
358 virtual ~Base() {}
359 };
360 class Derived : public Base {};
361
362 Base *create() {
363 Base *x = new Derived[10]; // note: Casting from 'Derived' to 'Base' here
364 return x;
365 }
366
367 void foo() {
368 Base *x = create();
369 delete[] x; // warn: Deleting an array of 'Derived' objects as their base class 'Base' is undefined
370 }
371
372 **Limitations**
373
374 The checker does not emit note tags when casting to and from reference types,
375 even though the pointer values are tracked across references.
376
377 .. code-block:: cpp
378
379 void foo() {
380 Derived *d = new Derived[10];
381 Derived &dref = *d;
382
383 Base &bref = static_cast<Base&>(dref); // no note
384 Base *b = &bref;
385 delete[] b; // warn: Deleting an array of 'Derived' objects as their base class 'Base' is undefined
386 }
387
388 .. _cplusplus-InnerPointer:
389
390 cplusplus.InnerPointer (C++)
391 """"""""""""""""""""""""""""
392 Check for inner pointers of C++ containers used after re/deallocation.
393
394 Many container methods in the C++ standard library are known to invalidate
395 "references" (including actual references, iterators and raw pointers) to
396 elements of the container. Using such references after they are invalidated
397 causes undefined behavior, which is a common source of memory errors in C++ that
398 this checker is capable of finding.
399
400 The checker is currently limited to ``std::string`` objects and doesn't
401 recognize some of the more sophisticated approaches to passing unowned pointers
402 around, such as ``std::string_view``.
403
404 .. code-block:: cpp
405
406 void deref_after_assignment() {
407 std::string s = "llvm";
408 const char *c = s.data(); // note: pointer to inner buffer of 'std::string' obtained here
409 s = "clang"; // note: inner buffer of 'std::string' reallocated by call to 'operator='
410 consume(c); // warn: inner pointer of container used after re/deallocation
411 }
412
413 const char *return_temp(int x) {
414 return std::to_string(x).c_str(); // warn: inner pointer of container used after re/deallocation
415 // note: pointer to inner buffer of 'std::string' obtained here
416 // note: inner buffer of 'std::string' deallocated by call to destructor
417 }
418
419 .. _cplusplus-Move:
420
421 cplusplus.Move (C++)
422 """"""""""""""""""""
423 Find use-after-move bugs in C++. This includes method calls on moved-from
424 objects, assignment of a moved-from object, and repeated move of a moved-from
425 object.
426
427 .. code-block:: cpp
428
429 struct A {
430 void foo() {}
431 };
432
433 void f1() {
434 A a;
435 A b = std::move(a); // note: 'a' became 'moved-from' here
436 a.foo(); // warn: method call on a 'moved-from' object 'a'
437 }
438
439 void f2() {
440 A a;
441 A b = std::move(a);
442 A c(std::move(a)); // warn: move of an already moved-from object
443 }
444
445 void f3() {
446 A a;
447 A b = std::move(a);
448 b = a; // warn: copy of moved-from object
449 }
450
451 The checker option ``WarnOn`` controls on what objects the use-after-move is
452 checked:
453
454 * The most strict value is ``KnownsOnly``, in this mode only objects are
455 checked whose type is known to be move-unsafe. These include most STL objects
456 (but excluding move-safe ones) and smart pointers.
457 * With option value ``KnownsAndLocals`` local variables (of any type) are
458 additionally checked. The idea behind this is that local variables are
459 usually not tempting to be re-used so an use after move is more likely a bug
460 than with member variables.
461 * With option value ``All`` any use-after move condition is checked on all
462 kinds of variables, excluding global variables and known move-safe cases.
463
464 Default value is ``KnownsAndLocals``.
465
466 Calls of methods named ``empty()`` or ``isEmpty()`` are allowed on moved-from
467 objects because these methods are considered as move-safe. Functions called
468 ``reset()``, ``destroy()``, ``clear()``, ``assign``, ``resize``, ``shrink`` are
469 treated as state-reset functions and are allowed on moved-from objects, these
470 make the object valid again. This applies to any type of object (not only STL
471 ones).
472
473 .. _cplusplus-NewDelete:
474
475 cplusplus.NewDelete (C++)
476 """""""""""""""""""""""""
477 Check for double-free and use-after-free problems. Traces memory managed by new/delete.
478
479 .. literalinclude:: checkers/newdelete_example.cpp
480 :language: cpp
481
482 .. _cplusplus-NewDeleteLeaks:
483
484 cplusplus.NewDeleteLeaks (C++)
485 """"""""""""""""""""""""""""""
486 Check for memory leaks. Traces memory managed by new/delete.
487
488 .. code-block:: cpp
489
490 void test() {
491 int *p = new int;
492 } // warn
493
494 .. _cplusplus-PlacementNew:
495
496 cplusplus.PlacementNew (C++)
497 """"""""""""""""""""""""""""
498 Check if default placement new is provided with pointers to sufficient storage capacity.
499
500 .. code-block:: cpp
501
502 #include <new>
503
504 void f() {
505 short s;
506 long *lp = ::new (&s) long; // warn
507 }
508
509 .. _cplusplus-SelfAssignment:
510
511 cplusplus.SelfAssignment (C++)
512 """"""""""""""""""""""""""""""
513 Checks C++ copy and move assignment operators for self assignment.
514
515 .. _cplusplus-StringChecker:
516
517 cplusplus.StringChecker (C++)
518 """""""""""""""""""""""""""""
519 Checks std::string operations.
520
521 Checks if the cstring pointer from which the ``std::string`` object is
522 constructed is ``NULL`` or not.
523 If the checker cannot reason about the nullness of the pointer it will assume
524 that it was non-null to satisfy the precondition of the constructor.
525
526 This checker is capable of checking the `SEI CERT C++ coding rule STR51-CPP.
527 Do not attempt to create a std::string from a null pointer
528 <https://wiki.sei.cmu.edu/confluence/x/E3s-BQ>`__.
529
530 .. code-block:: cpp
531
532 #include <string>
533
534 void f(const char *p) {
535 if (!p) {
536 std::string msg(p); // warn: The parameter must not be null
537 }
538 }
539
540 .. _deadcode-checkers:
541
542 deadcode
543 ^^^^^^^^
544
545 Dead Code Checkers.
546
547 .. _deadcode-DeadStores:
548
549 deadcode.DeadStores (C)
550 """""""""""""""""""""""
551 Check for values stored to variables that are never read afterwards.
552
553 .. code-block:: c
554
555 void test() {
556 int x;
557 x = 1; // warn
558 }
559
560 The ``WarnForDeadNestedAssignments`` option enables the checker to emit
561 warnings for nested dead assignments. You can disable with the
562 ``-analyzer-config deadcode.DeadStores:WarnForDeadNestedAssignments=false``.
563 *Defaults to true*.
564
565 Would warn for this e.g.:
566 if ((y = make_int())) {
567 }
568
569 .. _nullability-checkers:
570
571 nullability
572 ^^^^^^^^^^^
573
574 Objective C checkers that warn for null pointer passing and dereferencing errors.
575
576 .. _nullability-NullPassedToNonnull:
577
578 nullability.NullPassedToNonnull (ObjC)
579 """"""""""""""""""""""""""""""""""""""
580 Warns when a null pointer is passed to a pointer which has a _Nonnull type.
581
582 .. code-block:: objc
583
584 if (name != nil)
585 return;
586 // Warning: nil passed to a callee that requires a non-null 1st parameter
587 NSString *greeting = [@"Hello " stringByAppendingString:name];
588
589 .. _nullability-NullReturnedFromNonnull:
590
591 nullability.NullReturnedFromNonnull (ObjC)
592 """"""""""""""""""""""""""""""""""""""""""
593 Warns when a null pointer is returned from a function that has _Nonnull return type.
594
595 .. code-block:: objc
596
597 - (nonnull id)firstChild {
598 id result = nil;
599 if ([_children count] > 0)
600 result = _children[0];
601
602 // Warning: nil returned from a method that is expected
603 // to return a non-null value
604 return result;
605 }
606
607 .. _nullability-NullableDereferenced:
608
609 nullability.NullableDereferenced (ObjC)
610 """""""""""""""""""""""""""""""""""""""
611 Warns when a nullable pointer is dereferenced.
612
613 .. code-block:: objc
614
615 struct LinkedList {
616 int data;
617 struct LinkedList *next;
618 };
619
620 struct LinkedList * _Nullable getNext(struct LinkedList *l);
621
622 void updateNextData(struct LinkedList *list, int newData) {
623 struct LinkedList *next = getNext(list);
624 // Warning: Nullable pointer is dereferenced
625 next->data = 7;
626 }
627
628 .. _nullability-NullablePassedToNonnull:
629
630 nullability.NullablePassedToNonnull (ObjC)
631 """"""""""""""""""""""""""""""""""""""""""
632 Warns when a nullable pointer is passed to a pointer which has a _Nonnull type.
633
634 .. code-block:: objc
635
636 typedef struct Dummy { int val; } Dummy;
637 Dummy *_Nullable returnsNullable();
638 void takesNonnull(Dummy *_Nonnull);
639
640 void test() {
641 Dummy *p = returnsNullable();
642 takesNonnull(p); // warn
643 }
644
645 .. _nullability-NullableReturnedFromNonnull:
646
647 nullability.NullableReturnedFromNonnull (ObjC)
648 """"""""""""""""""""""""""""""""""""""""""""""
649 Warns when a nullable pointer is returned from a function that has _Nonnull return type.
650
651 .. _optin-checkers:
652
653 optin
654 ^^^^^
655
656 Checkers for portability, performance, optional security and coding style specific rules.
657
658 .. _optin-core-EnumCastOutOfRange:
659
660 optin.core.EnumCastOutOfRange (C, C++)
661 """"""""""""""""""""""""""""""""""""""
662 Check for integer to enumeration casts that would produce a value with no
663 corresponding enumerator. This is not necessarily undefined behavior, but can
664 lead to nasty surprises, so projects may decide to use a coding standard that
665 disallows these "unusual" conversions.
666
667 Note that no warnings are produced when the enum type (e.g. `std::byte`) has no
668 enumerators at all.
669
670 .. code-block:: cpp
671
672 enum WidgetKind { A=1, B, C, X=99 };
673
674 void foo() {
675 WidgetKind c = static_cast<WidgetKind>(3); // OK
676 WidgetKind x = static_cast<WidgetKind>(99); // OK
677 WidgetKind d = static_cast<WidgetKind>(4); // warn
678 }
679
680 **Limitations**
681
682 This checker does not accept the coding pattern where an enum type is used to
683 store combinations of flag values:
684
685 .. code-block:: cpp
686
687 enum AnimalFlags
688 {
689 HasClaws = 1,
690 CanFly = 2,
691 EatsFish = 4,
692 Endangered = 8
693 };
694
695 AnimalFlags operator|(AnimalFlags a, AnimalFlags b)
696 {
697 return static_cast<AnimalFlags>(static_cast<int>(a) | static_cast<int>(b));
698 }
699
700 auto flags = HasClaws | CanFly;
701
702 Projects that use this pattern should not enable this optin checker.
703
704 .. _optin-cplusplus-UninitializedObject:
705
706 optin.cplusplus.UninitializedObject (C++)
707 """""""""""""""""""""""""""""""""""""""""
708
709 This checker reports uninitialized fields in objects created after a constructor
710 call. It doesn't only find direct uninitialized fields, but rather makes a deep
711 inspection of the object, analyzing all of its fields' subfields.
712 The checker regards inherited fields as direct fields, so one will receive
713 warnings for uninitialized inherited data members as well.
714
715 .. code-block:: cpp
716
717 // With Pedantic and CheckPointeeInitialization set to true
718
719 struct A {
720 struct B {
721 int x; // note: uninitialized field 'this->b.x'
722 // note: uninitialized field 'this->bptr->x'
723 int y; // note: uninitialized field 'this->b.y'
724 // note: uninitialized field 'this->bptr->y'
725 };
726 int *iptr; // note: uninitialized pointer 'this->iptr'
727 B b;
728 B *bptr;
729 char *cptr; // note: uninitialized pointee 'this->cptr'
730
731 A (B *bptr, char *cptr) : bptr(bptr), cptr(cptr) {}
732 };
733
734 void f() {
735 A::B b;
736 char c;
737 A a(&b, &c); // warning: 6 uninitialized fields
738 // after the constructor call
739 }
740
741 // With Pedantic set to false and
742 // CheckPointeeInitialization set to true
743 // (every field is uninitialized)
744
745 struct A {
746 struct B {
747 int x;
748 int y;
749 };
750 int *iptr;
751 B b;
752 B *bptr;
753 char *cptr;
754
755 A (B *bptr, char *cptr) : bptr(bptr), cptr(cptr) {}
756 };
757
758 void f() {
759 A::B b;
760 char c;
761 A a(&b, &c); // no warning
762 }
763
764 // With Pedantic set to true and
765 // CheckPointeeInitialization set to false
766 // (pointees are regarded as initialized)
767
768 struct A {
769 struct B {
770 int x; // note: uninitialized field 'this->b.x'
771 int y; // note: uninitialized field 'this->b.y'
772 };
773 int *iptr; // note: uninitialized pointer 'this->iptr'
774 B b;
775 B *bptr;
776 char *cptr;
777
778 A (B *bptr, char *cptr) : bptr(bptr), cptr(cptr) {}
779 };
780
781 void f() {
782 A::B b;
783 char c;
784 A a(&b, &c); // warning: 3 uninitialized fields
785 // after the constructor call
786 }
787
788
789 **Options**
790
791 This checker has several options which can be set from command line (e.g.
792 ``-analyzer-config optin.cplusplus.UninitializedObject:Pedantic=true``):
793
794 * ``Pedantic`` (boolean). If to false, the checker won't emit warnings for
795 objects that don't have at least one initialized field. Defaults to false.
796
797 * ``NotesAsWarnings`` (boolean). If set to true, the checker will emit a
798 warning for each uninitialized field, as opposed to emitting one warning per
799 constructor call, and listing the uninitialized fields that belongs to it in
800 notes. *Defaults to false*.
801
802 * ``CheckPointeeInitialization`` (boolean). If set to false, the checker will
803 not analyze the pointee of pointer/reference fields, and will only check
804 whether the object itself is initialized. *Defaults to false*.
805
806 * ``IgnoreRecordsWithField`` (string). If supplied, the checker will not analyze
807 structures that have a field with a name or type name that matches the given
808 pattern. *Defaults to ""*.
809
810 .. _optin-cplusplus-VirtualCall:
811
812 optin.cplusplus.VirtualCall (C++)
813 """""""""""""""""""""""""""""""""
814 Check virtual function calls during construction or destruction.
815
816 .. code-block:: cpp
817
818 class A {
819 public:
820 A() {
821 f(); // warn
822 }
823 virtual void f();
824 };
825
826 class A {
827 public:
828 ~A() {
829 this->f(); // warn
830 }
831 virtual void f();
832 };
833
834 .. _optin-mpi-MPI-Checker:
835
836 optin.mpi.MPI-Checker (C)
837 """""""""""""""""""""""""
838 Checks MPI code.
839
840 .. code-block:: c
841
842 void test() {
843 double buf = 0;
844 MPI_Request sendReq1;
845 MPI_Ireduce(MPI_IN_PLACE, &buf, 1, MPI_DOUBLE, MPI_SUM,
846 0, MPI_COMM_WORLD, &sendReq1);
847 } // warn: request 'sendReq1' has no matching wait.
848
849 void test() {
850 double buf = 0;
851 MPI_Request sendReq;
852 MPI_Isend(&buf, 1, MPI_DOUBLE, 0, 0, MPI_COMM_WORLD, &sendReq);
853 MPI_Irecv(&buf, 1, MPI_DOUBLE, 0, 0, MPI_COMM_WORLD, &sendReq); // warn
854 MPI_Isend(&buf, 1, MPI_DOUBLE, 0, 0, MPI_COMM_WORLD, &sendReq); // warn
855 MPI_Wait(&sendReq, MPI_STATUS_IGNORE);
856 }
857
858 void missingNonBlocking() {
859 int rank = 0;
860 MPI_Comm_rank(MPI_COMM_WORLD, &rank);
861 MPI_Request sendReq1[10][10][10];
862 MPI_Wait(&sendReq1[1][7][9], MPI_STATUS_IGNORE); // warn
863 }
864
865 .. _optin-osx-cocoa-localizability-EmptyLocalizationContextChecker:
866
867 optin.osx.cocoa.localizability.EmptyLocalizationContextChecker (ObjC)
868 """""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
869 Check that NSLocalizedString macros include a comment for context.
870
871 .. code-block:: objc
872
873 - (void)test {
874 NSString *string = NSLocalizedString(@"LocalizedString", nil); // warn
875 NSString *string2 = NSLocalizedString(@"LocalizedString", @" "); // warn
876 NSString *string3 = NSLocalizedStringWithDefaultValue(
877 @"LocalizedString", nil, [[NSBundle alloc] init], nil,@""); // warn
878 }
879
880 .. _optin-osx-cocoa-localizability-NonLocalizedStringChecker:
881
882 optin.osx.cocoa.localizability.NonLocalizedStringChecker (ObjC)
883 """""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
884 Warns about uses of non-localized NSStrings passed to UI methods expecting localized NSStrings.
885
886 .. code-block:: objc
887
888 NSString *alarmText =
889 NSLocalizedString(@"Enabled", @"Indicates alarm is turned on");
890 if (!isEnabled) {
891 alarmText = @"Disabled";
892 }
893 UILabel *alarmStateLabel = [[UILabel alloc] init];
894
895 // Warning: User-facing text should use localized string macro
896 [alarmStateLabel setText:alarmText];
897
898 .. _optin-performance-GCDAntipattern:
899
900 optin.performance.GCDAntipattern
901 """"""""""""""""""""""""""""""""
902 Check for performance anti-patterns when using Grand Central Dispatch.
903
904 .. _optin-performance-Padding:
905
906 optin.performance.Padding (C, C++, ObjC)
907 """"""""""""""""""""""""""""""""""""""""
908 Check for excessively padded structs.
909
910 This checker detects structs with excessive padding, which can lead to wasted
911 memory thus decreased performance by reducing the effectiveness of the
912 processor cache. Padding bytes are added by compilers to align data accesses
913 as some processors require data to be aligned to certain boundaries. On others,
914 unaligned data access are possible, but impose significantly larger latencies.
915
916 To avoid padding bytes, the fields of a struct should be ordered by decreasing
917 by alignment. Usually, its easier to think of the ``sizeof`` of the fields, and
918 ordering the fields by ``sizeof`` would usually also lead to the same optimal
919 layout.
920
921 In rare cases, one can use the ``#pragma pack(1)`` directive to enforce a packed
922 layout too, but it can significantly increase the access times, so reordering the
923 fields is usually a better solution.
924
925
926 .. code-block:: cpp
927
928 // warn: Excessive padding in 'struct NonOptimal' (35 padding bytes, where 3 is optimal)
929 struct NonOptimal {
930 char c1;
931 // 7 bytes of padding
932 std::int64_t big1; // 8 bytes
933 char c2;
934 // 7 bytes of padding
935 std::int64_t big2; // 8 bytes
936 char c3;
937 // 7 bytes of padding
938 std::int64_t big3; // 8 bytes
939 char c4;
940 // 7 bytes of padding
941 std::int64_t big4; // 8 bytes
942 char c5;
943 // 7 bytes of padding
944 };
945 static_assert(sizeof(NonOptimal) == 4*8+5+5*7);
946
947 // no-warning: The fields are nicely aligned to have the minimal amount of padding bytes.
948 struct Optimal {
949 std::int64_t big1; // 8 bytes
950 std::int64_t big2; // 8 bytes
951 std::int64_t big3; // 8 bytes
952 std::int64_t big4; // 8 bytes
953 char c1;
954 char c2;
955 char c3;
956 char c4;
957 char c5;
958 // 3 bytes of padding
959 };
960 static_assert(sizeof(Optimal) == 4*8+5+3);
961
962 // no-warning: Bit packing representation is also accepted by this checker, but
963 // it can significantly increase access times, so prefer reordering the fields.
964 #pragma pack(1)
965 struct BitPacked {
966 char c1;
967 std::int64_t big1; // 8 bytes
968 char c2;
969 std::int64_t big2; // 8 bytes
970 char c3;
971 std::int64_t big3; // 8 bytes
972 char c4;
973 std::int64_t big4; // 8 bytes
974 char c5;
975 };
976 static_assert(sizeof(BitPacked) == 4*8+5);
977
978 The ``AllowedPad`` option can be used to specify a threshold for the number
979 padding bytes raising the warning. If the number of padding bytes of the struct
980 and the optimal number of padding bytes differ by more than the threshold value,
981 a warning will be raised.
982
983 By default, the ``AllowedPad`` threshold is 24 bytes.
984
985 To override this threshold to e.g. 4 bytes, use the
986 ``-analyzer-config optin.performance.Padding:AllowedPad=4`` option.
987
988
989 .. _optin-portability-UnixAPI:
990
991 optin.portability.UnixAPI
992 """""""""""""""""""""""""
993 Finds implementation-defined behavior in UNIX/Posix functions.
994
995 .. _optin-taint-TaintedAlloc:
996
997 optin.taint.TaintedAlloc (C, C++)
998 """""""""""""""""""""""""""""""""
999
1000 This checker warns for cases when the ``size`` parameter of the ``malloc`` ,
1001 ``calloc``, ``realloc``, ``alloca`` or the size parameter of the
1002 array new C++ operator is tainted (potentially attacker controlled).
1003 If an attacker can inject a large value as the size parameter, memory exhaustion
1004 denial of service attack can be carried out.
1005
1006 The analyzer emits warning only if it cannot prove that the size parameter is
1007 within reasonable bounds (``<= SIZE_MAX/4``). This functionality partially
1008 covers the SEI Cert coding standard rule `INT04-C
1009 <https://wiki.sei.cmu.edu/confluence/display/c/INT04-C.+Enforce+limits+on+integer+values+originating+from+tainted+sources>`_.
1010
1011 You can silence this warning either by bound checking the ``size`` parameter, or
1012 by explicitly marking the ``size`` parameter as sanitized. See the
1013 :ref:`alpha-security-taint-GenericTaint` checker for an example.
1014
1015 .. code-block:: c
1016
1017 void vulnerable(void) {
1018 size_t size = 0;
1019 scanf("%zu", &size);
1020 int *p = malloc(size); // warn: malloc is called with a tainted (potentially attacker controlled) value
1021 free(p);
1022 }
1023
1024 void not_vulnerable(void) {
1025 size_t size = 0;
1026 scanf("%zu", &size);
1027 if (1024 < size)
1028 return;
1029 int *p = malloc(size); // No warning expected as the the user input is bound
1030 free(p);
1031 }
1032
1033 void vulnerable_cpp(void) {
1034 size_t size = 0;
1035 scanf("%zu", &size);
1036 int *ptr = new int[size];// warn: Memory allocation function is called with a tainted (potentially attacker controlled) value
1037 delete[] ptr;
1038 }
1039
1040 .. _security-checkers:
1041
1042 security
1043 ^^^^^^^^
1044
1045 Security related checkers.
1046
1047 .. _security-cert-env-InvalidPtr:
1048
1049 security.cert.env.InvalidPtr
1050 """"""""""""""""""""""""""""""""""
1051
1052 Corresponds to SEI CERT Rules `ENV31-C <https://wiki.sei.cmu.edu/confluence/display/c/ENV31-C.+Do+not+rely+on+an+environment+pointer+following+an+operation+that+may+invalidate+it>`_ and `ENV34-C <https://wiki.sei.cmu.edu/confluence/display/c/ENV34-C.+Do+not+store+pointers+returned+by+certain+functions>`_.
1053
1054 * **ENV31-C**:
1055 Rule is about the possible problem with ``main`` function's third argument, environment pointer,
1056 "envp". When environment array is modified using some modification function
1057 such as ``putenv``, ``setenv`` or others, It may happen that memory is reallocated,
1058 however "envp" is not updated to reflect the changes and points to old memory
1059 region.
1060
1061 * **ENV34-C**:
1062 Some functions return a pointer to a statically allocated buffer.
1063 Consequently, subsequent call of these functions will invalidate previous
1064 pointer. These functions include: ``getenv``, ``localeconv``, ``asctime``, ``setlocale``, ``strerror``
1065
1066 .. code-block:: c
1067
1068 int main(int argc, const char *argv[], const char *envp[]) {
1069 if (setenv("MY_NEW_VAR", "new_value", 1) != 0) {
1070 // setenv call may invalidate 'envp'
1071 /* Handle error */
1072 }
1073 if (envp != NULL) {
1074 for (size_t i = 0; envp[i] != NULL; ++i) {
1075 puts(envp[i]);
1076 // envp may no longer point to the current environment
1077 // this program has unanticipated behavior, since envp
1078 // does not reflect changes made by setenv function.
1079 }
1080 }
1081 return 0;
1082 }
1083
1084 void previous_call_invalidation() {
1085 char *p, *pp;
1086
1087 p = getenv("VAR");
1088 setenv("SOMEVAR", "VALUE", /*overwrite = */1);
1089 // call to 'setenv' may invalidate p
1090
1091 *p;
1092 // dereferencing invalid pointer
1093 }
1094
1095
1096 The ``InvalidatingGetEnv`` option is available for treating ``getenv`` calls as
1097 invalidating. When enabled, the checker issues a warning if ``getenv`` is called
1098 multiple times and their results are used without first creating a copy.
1099 This level of strictness might be considered overly pedantic for the commonly
1100 used ``getenv`` implementations.
1101
1102 To enable this option, use:
1103 ``-analyzer-config security.cert.env.InvalidPtr:InvalidatingGetEnv=true``.
1104
1105 By default, this option is set to *false*.
1106
1107 When this option is enabled, warnings will be generated for scenarios like the
1108 following:
1109
1110 .. code-block:: c
1111
1112 char* p = getenv("VAR");
1113 char* pp = getenv("VAR2"); // assumes this call can invalidate `env`
1114 strlen(p); // warns about accessing invalid ptr
1115
1116 .. _security-FloatLoopCounter:
1117
1118 security.FloatLoopCounter (C)
1119 """""""""""""""""""""""""""""
1120 Warn on using a floating point value as a loop counter (CERT: FLP30-C, FLP30-CPP).
1121
1122 .. code-block:: c
1123
1124 void test() {
1125 for (float x = 0.1f; x <= 1.0f; x += 0.1f) {} // warn
1126 }
1127
1128 .. _security-insecureAPI-UncheckedReturn:
1129
1130 security.insecureAPI.UncheckedReturn (C)
1131 """"""""""""""""""""""""""""""""""""""""
1132 Warn on uses of functions whose return values must be always checked.
1133
1134 .. code-block:: c
1135
1136 void test() {
1137 setuid(1); // warn
1138 }
1139
1140 .. _security-insecureAPI-bcmp:
1141
1142 security.insecureAPI.bcmp (C)
1143 """""""""""""""""""""""""""""
1144 Warn on uses of the 'bcmp' function.
1145
1146 .. code-block:: c
1147
1148 void test() {
1149 bcmp(ptr0, ptr1, n); // warn
1150 }
1151
1152 .. _security-insecureAPI-bcopy:
1153
1154 security.insecureAPI.bcopy (C)
1155 """"""""""""""""""""""""""""""
1156 Warn on uses of the 'bcopy' function.
1157
1158 .. code-block:: c
1159
1160 void test() {
1161 bcopy(src, dst, n); // warn
1162 }
1163
1164 .. _security-insecureAPI-bzero:
1165
1166 security.insecureAPI.bzero (C)
1167 """"""""""""""""""""""""""""""
1168 Warn on uses of the 'bzero' function.
1169
1170 .. code-block:: c
1171
1172 void test() {
1173 bzero(ptr, n); // warn
1174 }
1175
1176 .. _security-insecureAPI-getpw:
1177
1178 security.insecureAPI.getpw (C)
1179 """"""""""""""""""""""""""""""
1180 Warn on uses of the 'getpw' function.
1181
1182 .. code-block:: c
1183
1184 void test() {
1185 char buff[1024];
1186 getpw(2, buff); // warn
1187 }
1188
1189 .. _security-insecureAPI-gets:
1190
1191 security.insecureAPI.gets (C)
1192 """""""""""""""""""""""""""""
1193 Warn on uses of the 'gets' function.
1194
1195 .. code-block:: c
1196
1197 void test() {
1198 char buff[1024];
1199 gets(buff); // warn
1200 }
1201
1202 .. _security-insecureAPI-mkstemp:
1203
1204 security.insecureAPI.mkstemp (C)
1205 """"""""""""""""""""""""""""""""
1206 Warn when 'mkstemp' is passed fewer than 6 X's in the format string.
1207
1208 .. code-block:: c
1209
1210 void test() {
1211 mkstemp("XX"); // warn
1212 }
1213
1214 .. _security-insecureAPI-mktemp:
1215
1216 security.insecureAPI.mktemp (C)
1217 """""""""""""""""""""""""""""""
1218 Warn on uses of the ``mktemp`` function.
1219
1220 .. code-block:: c
1221
1222 void test() {
1223 char *x = mktemp("/tmp/zxcv"); // warn: insecure, use mkstemp
1224 }
1225
1226 .. _security-insecureAPI-rand:
1227
1228 security.insecureAPI.rand (C)
1229 """""""""""""""""""""""""""""
1230 Warn on uses of inferior random number generating functions (only if arc4random function is available):
1231 ``drand48, erand48, jrand48, lcong48, lrand48, mrand48, nrand48, random, rand_r``.
1232
1233 .. code-block:: c
1234
1235 void test() {
1236 random(); // warn
1237 }
1238
1239 .. _security-insecureAPI-strcpy:
1240
1241 security.insecureAPI.strcpy (C)
1242 """""""""""""""""""""""""""""""
1243 Warn on uses of the ``strcpy`` and ``strcat`` functions.
1244
1245 .. code-block:: c
1246
1247 void test() {
1248 char x[4];
1249 char *y = "abcd";
1250
1251 strcpy(x, y); // warn
1252 }
1253
1254
1255 .. _security-insecureAPI-vfork:
1256
1257 security.insecureAPI.vfork (C)
1258 """"""""""""""""""""""""""""""
1259 Warn on uses of the 'vfork' function.
1260
1261 .. code-block:: c
1262
1263 void test() {
1264 vfork(); // warn
1265 }
1266
1267 .. _security-insecureAPI-DeprecatedOrUnsafeBufferHandling:
1268
1269 security.insecureAPI.DeprecatedOrUnsafeBufferHandling (C)
1270 """""""""""""""""""""""""""""""""""""""""""""""""""""""""
1271 Warn on occurrences of unsafe or deprecated buffer handling functions, which now have a secure variant: ``sprintf, fprintf, vsprintf, scanf, wscanf, fscanf, fwscanf, vscanf, vwscanf, vfscanf, vfwscanf, sscanf, swscanf, vsscanf, vswscanf, swprintf, snprintf, vswprintf, vsnprintf, memcpy, memmove, strncpy, strncat, memset``
1272
1273 .. code-block:: c
1274
1275 void test() {
1276 char buf [5];
1277 strncpy(buf, "a", 1); // warn
1278 }
1279
1280 .. _security-putenv-stack-array:
1281
1282 security.PutenvStackArray (C)
1283 """""""""""""""""""""""""""""
1284 Finds calls to the ``putenv`` function which pass a pointer to a stack-allocated
1285 (automatic) array as the argument. Function ``putenv`` does not copy the passed
1286 string, only a pointer to the data is stored and this data can be read even by
1287 other threads. Content of a stack-allocated array is likely to be overwritten
1288 after exiting from the function.
1289
1290 The problem can be solved by using a static array variable or dynamically
1291 allocated memory. Even better is to avoid using ``putenv`` (it has other
1292 problems related to memory leaks) and use ``setenv`` instead.
1293
1294 The check corresponds to CERT rule
1295 `POS34-C. Do not call putenv() with a pointer to an automatic variable as the argument
1296 <https://wiki.sei.cmu.edu/confluence/display/c/POS34-C.+Do+not+call+putenv%28%29+with+a+pointer+to+an+automatic+variable+as+the+argument>`_.
1297
1298 .. code-block:: c
1299
1300 int f() {
1301 char env[] = "NAME=value";
1302 return putenv(env); // putenv function should not be called with stack-allocated string
1303 }
1304
1305 There is one case where the checker can report a false positive. This is when
1306 the stack-allocated array is used at `putenv` in a function or code branch that
1307 does not return (process is terminated on all execution paths).
1308
1309 Another special case is if the `putenv` is called from function `main`. Here
1310 the stack is deallocated at the end of the program and it should be no problem
1311 to use the stack-allocated string (a multi-threaded program may require more
1312 attention). The checker does not warn for cases when stack space of `main` is
1313 used at the `putenv` call.
1314
1315 security.SetgidSetuidOrder (C)
1316 """"""""""""""""""""""""""""""
1317 When dropping user-level and group-level privileges in a program by using
1318 ``setuid`` and ``setgid`` calls, it is important to reset the group-level
1319 privileges (with ``setgid``) first. Function ``setgid`` will likely fail if
1320 the superuser privileges are already dropped.
1321
1322 The checker checks for sequences of ``setuid(getuid())`` and
1323 ``setgid(getgid())`` calls (in this order). If such a sequence is found and
1324 there is no other privilege-changing function call (``seteuid``, ``setreuid``,
1325 ``setresuid`` and the GID versions of these) in between, a warning is
1326 generated. The checker finds only exactly ``setuid(getuid())`` calls (and the
1327 GID versions), not for example if the result of ``getuid()`` is stored in a
1328 variable.
1329
1330 .. code-block:: c
1331
1332 void test1() {
1333 // ...
1334 // end of section with elevated privileges
1335 // reset privileges (user and group) to normal user
1336 if (setuid(getuid()) != 0) {
1337 handle_error();
1338 return;
1339 }
1340 if (setgid(getgid()) != 0) { // warning: A 'setgid(getgid())' call following a 'setuid(getuid())' call is likely to fail
1341 handle_error();
1342 return;
1343 }
1344 // user-ID and group-ID are reset to normal user now
1345 // ...
1346 }
1347
1348 In the code above the problem is that ``setuid(getuid())`` removes superuser
1349 privileges before ``setgid(getgid())`` is called. To fix the problem the
1350 ``setgid(getgid())`` should be called first. Further attention is needed to
1351 avoid code like ``setgid(getuid())`` (this checker does not detect bugs like
1352 this) and always check the return value of these calls.
1353
1354 This check corresponds to SEI CERT Rule `POS36-C <https://wiki.sei.cmu.edu/confluence/display/c/POS36-C.+Observe+correct+revocation+order+while+relinquishing+privileges>`_.
1355
1356 .. _unix-checkers:
1357
1358 unix
1359 ^^^^
1360 POSIX/Unix checkers.
1361
1362 .. _unix-API:
1363
1364 unix.API (C)
1365 """"""""""""
1366 Check calls to various UNIX/Posix functions: ``open, pthread_once, calloc, malloc, realloc, alloca``.
1367
1368 .. literalinclude:: checkers/unix_api_example.c
1369 :language: c
1370
1371 .. _unix-BlockInCriticalSection:
1372
1373 unix.BlockInCriticalSection (C, C++)
1374 """"""""""""""""""""""""""""""""""""
1375 Check for calls to blocking functions inside a critical section.
1376 Blocking functions detected by this checker: ``sleep, getc, fgets, read, recv``.
1377 Critical section handling functions modeled by this checker:
1378 ``lock, unlock, pthread_mutex_lock, pthread_mutex_trylock, pthread_mutex_unlock, mtx_lock, mtx_timedlock, mtx_trylock, mtx_unlock, lock_guard, unique_lock``.
1379
1380 .. code-block:: c
1381
1382 void pthread_lock_example(pthread_mutex_t *m) {
1383 pthread_mutex_lock(m); // note: entering critical section here
1384 sleep(10); // warn: Call to blocking function 'sleep' inside of critical section
1385 pthread_mutex_unlock(m);
1386 }
1387
1388 .. code-block:: cpp
1389
1390 void overlapping_critical_sections(mtx_t *m1, std::mutex &m2) {
1391 std::lock_guard lg{m2}; // note: entering critical section here
1392 mtx_lock(m1); // note: entering critical section here
1393 sleep(10); // warn: Call to blocking function 'sleep' inside of critical section
1394 mtx_unlock(m1);
1395 sleep(10); // warn: Call to blocking function 'sleep' inside of critical section
1396 // still inside of the critical section of the std::lock_guard
1397 }
1398
1399 **Limitations**
1400
1401 * The ``trylock`` and ``timedlock`` versions of acquiring locks are currently assumed to always succeed.
1402 This can lead to false positives.
1403
1404 .. code-block:: c
1405
1406 void trylock_example(pthread_mutex_t *m) {
1407 if (pthread_mutex_trylock(m) == 0) { // assume trylock always succeeds
1408 sleep(10); // warn: Call to blocking function 'sleep' inside of critical section
1409 pthread_mutex_unlock(m);
1410 } else {
1411 sleep(10); // false positive: Incorrect warning about blocking function inside critical section.
1412 }
1413 }
1414
1415 .. _unix-Errno:
1416
1417 unix.Errno (C)
1418 """"""""""""""
1419
1420 Check for improper use of ``errno``.
1421 This checker implements partially CERT rule
1422 `ERR30-C. Set errno to zero before calling a library function known to set errno,
1423 and check errno only after the function returns a value indicating failure
1424 <https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152351>`_.
1425 The checker can find the first read of ``errno`` after successful standard
1426 function calls.
1427
1428 The C and POSIX standards often do not define if a standard library function
1429 may change value of ``errno`` if the call does not fail.
1430 Therefore, ``errno`` should only be used if it is known from the return value
1431 of a function that the call has failed.
1432 There are exceptions to this rule (for example ``strtol``) but the affected
1433 functions are not yet supported by the checker.
1434 The return values for the failure cases are documented in the standard Linux man
1435 pages of the functions and in the `POSIX standard <https://pubs.opengroup.org/onlinepubs/9699919799/>`_.
1436
1437 .. code-block:: c
1438
1439 int unsafe_errno_read(int sock, void *data, int data_size) {
1440 if (send(sock, data, data_size, 0) != data_size) {
1441 // 'send' can be successful even if not all data was sent
1442 if (errno == 1) { // An undefined value may be read from 'errno'
1443 return 0;
1444 }
1445 }
1446 return 1;
1447 }
1448
1449 The checker :ref:`unix-StdCLibraryFunctions` must be turned on to get the
1450 warnings from this checker. The supported functions are the same as by
1451 :ref:`unix-StdCLibraryFunctions`. The ``ModelPOSIX`` option of that
1452 checker affects the set of checked functions.
1453
1454 **Parameters**
1455
1456 The ``AllowErrnoReadOutsideConditionExpressions`` option allows read of the
1457 errno value if the value is not used in a condition (in ``if`` statements,
1458 loops, conditional expressions, ``switch`` statements). For example ``errno``
1459 can be stored into a variable without getting a warning by the checker.
1460
1461 .. code-block:: c
1462
1463 int unsafe_errno_read(int sock, void *data, int data_size) {
1464 if (send(sock, data, data_size, 0) != data_size) {
1465 int err = errno;
1466 // warning if 'AllowErrnoReadOutsideConditionExpressions' is false
1467 // no warning if 'AllowErrnoReadOutsideConditionExpressions' is true
1468 }
1469 return 1;
1470 }
1471
1472 Default value of this option is ``true``. This allows save of the errno value
1473 for possible later error handling.
1474
1475 **Limitations**
1476
1477 - Only the very first usage of ``errno`` is checked after an affected function
1478 call. Value of ``errno`` is not followed when it is stored into a variable
1479 or returned from a function.
1480 - Documentation of function ``lseek`` is not clear about what happens if the
1481 function returns different value than the expected file position but not -1.
1482 To avoid possible false-positives ``errno`` is allowed to be used in this
1483 case.
1484
1485 .. _unix-Malloc:
1486
1487 unix.Malloc (C)
1488 """""""""""""""
1489 Check for memory leaks, double free, and use-after-free problems. Traces memory managed by malloc()/free().
1490
1491 .. literalinclude:: checkers/unix_malloc_example.c
1492 :language: c
1493
1494 .. _unix-MallocSizeof:
1495
1496 unix.MallocSizeof (C)
1497 """""""""""""""""""""
1498 Check for dubious ``malloc`` arguments involving ``sizeof``.
1499
1500 .. code-block:: c
1501
1502 void test() {
1503 long *p = malloc(sizeof(short));
1504 // warn: result is converted to 'long *', which is
1505 // incompatible with operand type 'short'
1506 free(p);
1507 }
1508
1509 .. _unix-MismatchedDeallocator:
1510
1511 unix.MismatchedDeallocator (C, C++)
1512 """""""""""""""""""""""""""""""""""
1513 Check for mismatched deallocators.
1514
1515 .. literalinclude:: checkers/mismatched_deallocator_example.cpp
1516 :language: c
1517
1518 .. _unix-Vfork:
1519
1520 unix.Vfork (C)
1521 """"""""""""""
1522 Check for proper usage of ``vfork``.
1523
1524 .. code-block:: c
1525
1526 int test(int x) {
1527 pid_t pid = vfork(); // warn
1528 if (pid != 0)
1529 return 0;
1530
1531 switch (x) {
1532 case 0:
1533 pid = 1;
1534 execl("", "", 0);
1535 _exit(1);
1536 break;
1537 case 1:
1538 x = 0; // warn: this assignment is prohibited
1539 break;
1540 case 2:
1541 foo(); // warn: this function call is prohibited
1542 break;
1543 default:
1544 return 0; // warn: return is prohibited
1545 }
1546
1547 while(1);
1548 }
1549
1550 .. _unix-cstring-BadSizeArg:
1551
1552 unix.cstring.BadSizeArg (C)
1553 """""""""""""""""""""""""""
1554 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.
1555
1556 .. code-block:: c
1557
1558 void test() {
1559 char dest[3];
1560 strncat(dest, """""""""""""""""""""""""*", sizeof(dest));
1561 // warn: potential buffer overflow
1562 }
1563
1564 .. _unix-cstring-NullArg:
1565
1566 unix.cstring.NullArg (C)
1567 """"""""""""""""""""""""
1568 Check for null pointers being passed as arguments to C string functions:
1569 ``strlen, strnlen, strcpy, strncpy, strcat, strncat, strcmp, strncmp, strcasecmp, strncasecmp, wcslen, wcsnlen``.
1570
1571 .. code-block:: c
1572
1573 int test() {
1574 return strlen(0); // warn
1575 }
1576
1577 .. _unix-StdCLibraryFunctions:
1578
1579 unix.StdCLibraryFunctions (C)
1580 """""""""""""""""""""""""""""
1581 Check for calls of standard library functions that violate predefined argument
1582 constraints. For example, according to the C standard the behavior of function
1583 ``int isalnum(int ch)`` is undefined if the value of ``ch`` is not representable
1584 as ``unsigned char`` and is not equal to ``EOF``.
1585
1586 You can think of this checker as defining restrictions (pre- and postconditions)
1587 on standard library functions. Preconditions are checked, and when they are
1588 violated, a warning is emitted. Postconditions are added to the analysis, e.g.
1589 that the return value of a function is not greater than 255. Preconditions are
1590 added to the analysis too, in the case when the affected values are not known
1591 before the call.
1592
1593 For example, if an argument to a function must be in between 0 and 255, but the
1594 value of the argument is unknown, the analyzer will assume that it is in this
1595 interval. Similarly, if a function mustn't be called with a null pointer and the
1596 analyzer cannot prove that it is null, then it will assume that it is non-null.
1597
1598 These are the possible checks on the values passed as function arguments:
1599 - The argument has an allowed range (or multiple ranges) of values. The checker
1600 can detect if a passed value is outside of the allowed range and show the
1601 actual and allowed values.
1602 - The argument has pointer type and is not allowed to be null pointer. Many
1603 (but not all) standard functions can produce undefined behavior if a null
1604 pointer is passed, these cases can be detected by the checker.
1605 - The argument is a pointer to a memory block and the minimal size of this
1606 buffer is determined by another argument to the function, or by
1607 multiplication of two arguments (like at function ``fread``), or is a fixed
1608 value (for example ``asctime_r`` requires at least a buffer of size 26). The
1609 checker can detect if the buffer size is too small and in optimal case show
1610 the size of the buffer and the values of the corresponding arguments.
1611
1612 .. code-block:: c
1613
1614 #define EOF -1
1615 void test_alnum_concrete(int v) {
1616 int ret = isalnum(256); // \
1617 // warning: Function argument outside of allowed range
1618 (void)ret;
1619 }
1620
1621 void buffer_size_violation(FILE *file) {
1622 enum { BUFFER_SIZE = 1024 };
1623 wchar_t wbuf[BUFFER_SIZE];
1624
1625 const size_t size = sizeof(*wbuf); // 4
1626 const size_t nitems = sizeof(wbuf); // 4096
1627
1628 // Below we receive a warning because the 3rd parameter should be the
1629 // number of elements to read, not the size in bytes. This case is a known
1630 // vulnerability described by the ARR38-C SEI-CERT rule.
1631 fread(wbuf, size, nitems, file);
1632 }
1633
1634 int test_alnum_symbolic(int x) {
1635 int ret = isalnum(x);
1636 // after the call, ret is assumed to be in the range [-1, 255]
1637
1638 if (ret > 255) // impossible (infeasible branch)
1639 if (x == 0)
1640 return ret / x; // division by zero is not reported
1641 return ret;
1642 }
1643
1644 Additionally to the argument and return value conditions, this checker also adds
1645 state of the value ``errno`` if applicable to the analysis. Many system
1646 functions set the ``errno`` value only if an error occurs (together with a
1647 specific return value of the function), otherwise it becomes undefined. This
1648 checker changes the analysis state to contain such information. This data is
1649 used by other checkers, for example :ref:`unix-Errno`.
1650
1651 **Limitations**
1652
1653 The checker can not always provide notes about the values of the arguments.
1654 Without this information it is hard to confirm if the constraint is indeed
1655 violated. The argument values are shown if they are known constants or the value
1656 is determined by previous (not too complicated) assumptions.
1657
1658 The checker can produce false positives in cases such as if the program has
1659 invariants not known to the analyzer engine or the bug report path contains
1660 calls to unknown functions. In these cases the analyzer fails to detect the real
1661 range of the argument.
1662
1663 **Parameters**
1664
1665 The ``ModelPOSIX`` option controls if functions from the POSIX standard are
1666 recognized by the checker.
1667
1668 With ``ModelPOSIX=true``, many POSIX functions are modeled according to the
1669 `POSIX standard`_. This includes ranges of parameters and possible return
1670 values. Furthermore the behavior related to ``errno`` in the POSIX case is
1671 often that ``errno`` is set only if a function call fails, and it becomes
1672 undefined after a successful function call.
1673
1674 With ``ModelPOSIX=false``, this checker follows the C99 language standard and
1675 only models the functions that are described there. It is possible that the
1676 same functions are modeled differently in the two cases because differences in
1677 the standards. The C standard specifies less aspects of the functions, for
1678 example exact ``errno`` behavior is often unspecified (and not modeled by the
1679 checker).
1680
1681 Default value of the option is ``true``.
1682
1683 .. _unix-Stream:
1684
1685 unix.Stream (C)
1686 """""""""""""""
1687 Check C stream handling functions:
1688 ``fopen, fdopen, freopen, tmpfile, fclose, fread, fwrite, fgetc, fgets, fputc, fputs, fprintf, fscanf, ungetc, getdelim, getline, fseek, fseeko, ftell, ftello, fflush, rewind, fgetpos, fsetpos, clearerr, feof, ferror, fileno``.
1689
1690 The checker maintains information about the C stream objects (``FILE *``) and
1691 can detect error conditions related to use of streams. The following conditions
1692 are detected:
1693
1694 * The ``FILE *`` pointer passed to the function is NULL (the single exception is
1695 ``fflush`` where NULL is allowed).
1696 * Use of stream after close.
1697 * Opened stream is not closed.
1698 * Read from a stream after end-of-file. (This is not a fatal error but reported
1699 by the checker. Stream remains in EOF state and the read operation fails.)
1700 * Use of stream when the file position is indeterminate after a previous failed
1701 operation. Some functions (like ``ferror``, ``clearerr``, ``fseek``) are
1702 allowed in this state.
1703 * Invalid 3rd ("``whence``") argument to ``fseek``.
1704
1705 The stream operations are by this checker usually split into two cases, a success
1706 and a failure case. However, in the case of write operations (like ``fwrite``,
1707 ``fprintf`` and even ``fsetpos``) this behavior could produce a large amount of
1708 unwanted reports on projects that don't have error checks around the write
1709 operations, so by default the checker assumes that write operations always succeed.
1710 This behavior can be controlled by the ``Pedantic`` flag: With
1711 ``-analyzer-config unix.Stream:Pedantic=true`` the checker will model the
1712 cases where a write operation fails and report situations where this leads to
1713 erroneous behavior. (The default is ``Pedantic=false``, where write operations
1714 are assumed to succeed.)
1715
1716 .. code-block:: c
1717
1718 void test1() {
1719 FILE *p = fopen("foo", "r");
1720 } // warn: opened file is never closed
1721
1722 void test2() {
1723 FILE *p = fopen("foo", "r");
1724 fseek(p, 1, SEEK_SET); // warn: stream pointer might be NULL
1725 fclose(p);
1726 }
1727
1728 void test3() {
1729 FILE *p = fopen("foo", "r");
1730 if (p) {
1731 fseek(p, 1, 3); // warn: third arg should be SEEK_SET, SEEK_END, or SEEK_CUR
1732 fclose(p);
1733 }
1734 }
1735
1736 void test4() {
1737 FILE *p = fopen("foo", "r");
1738 if (!p)
1739 return;
1740
1741 fclose(p);
1742 fclose(p); // warn: stream already closed
1743 }
1744
1745 void test5() {
1746 FILE *p = fopen("foo", "r");
1747 if (!p)
1748 return;
1749
1750 fgetc(p);
1751 if (!ferror(p))
1752 fgetc(p); // warn: possible read after end-of-file
1753
1754 fclose(p);
1755 }
1756
1757 void test6() {
1758 FILE *p = fopen("foo", "r");
1759 if (!p)
1760 return;
1761
1762 fgetc(p);
1763 if (!feof(p))
1764 fgetc(p); // warn: file position may be indeterminate after I/O error
1765
1766 fclose(p);
1767 }
1768
1769 **Limitations**
1770
1771 The checker does not track the correspondence between integer file descriptors
1772 and ``FILE *`` pointers. Operations on standard streams like ``stdin`` are not
1773 treated specially and are therefore often not recognized (because these streams
1774 are usually not opened explicitly by the program, and are global variables).
1775
1776 .. _osx-checkers:
1777
1778 osx
1779 ^^^
1780 macOS checkers.
1781
1782 .. _osx-API:
1783
1784 osx.API (C)
1785 """""""""""
1786 Check for proper uses of various Apple APIs.
1787
1788 .. code-block:: objc
1789
1790 void test() {
1791 dispatch_once_t pred = 0;
1792 dispatch_once(&pred, ^(){}); // warn: dispatch_once uses local
1793 }
1794
1795 .. _osx-NumberObjectConversion:
1796
1797 osx.NumberObjectConversion (C, C++, ObjC)
1798 """""""""""""""""""""""""""""""""""""""""
1799 Check for erroneous conversions of objects representing numbers into numbers.
1800
1801 .. code-block:: objc
1802
1803 NSNumber *photoCount = [albumDescriptor objectForKey:@"PhotoCount"];
1804 // Warning: Comparing a pointer value of type 'NSNumber *'
1805 // to a scalar integer value
1806 if (photoCount > 0) {
1807 [self displayPhotos];
1808 }
1809
1810 .. _osx-ObjCProperty:
1811
1812 osx.ObjCProperty (ObjC)
1813 """""""""""""""""""""""
1814 Check for proper uses of Objective-C properties.
1815
1816 .. code-block:: objc
1817
1818 NSNumber *photoCount = [albumDescriptor objectForKey:@"PhotoCount"];
1819 // Warning: Comparing a pointer value of type 'NSNumber *'
1820 // to a scalar integer value
1821 if (photoCount > 0) {
1822 [self displayPhotos];
1823 }
1824
1825
1826 .. _osx-SecKeychainAPI:
1827
1828 osx.SecKeychainAPI (C)
1829 """"""""""""""""""""""
1830 Check for proper uses of Secure Keychain APIs.
1831
1832 .. literalinclude:: checkers/seckeychainapi_example.m
1833 :language: objc
1834
1835 .. _osx-cocoa-AtSync:
1836
1837 osx.cocoa.AtSync (ObjC)
1838 """""""""""""""""""""""
1839 Check for nil pointers used as mutexes for @synchronized.
1840
1841 .. code-block:: objc
1842
1843 void test(id x) {
1844 if (!x)
1845 @synchronized(x) {} // warn: nil value used as mutex
1846 }
1847
1848 void test() {
1849 id y;
1850 @synchronized(y) {} // warn: uninitialized value used as mutex
1851 }
1852
1853 .. _osx-cocoa-AutoreleaseWrite:
1854
1855 osx.cocoa.AutoreleaseWrite
1856 """"""""""""""""""""""""""
1857 Warn about potentially crashing writes to autoreleasing objects from different autoreleasing pools in Objective-C.
1858
1859 .. _osx-cocoa-ClassRelease:
1860
1861 osx.cocoa.ClassRelease (ObjC)
1862 """""""""""""""""""""""""""""
1863 Check for sending 'retain', 'release', or 'autorelease' directly to a Class.
1864
1865 .. code-block:: objc
1866
1867 @interface MyClass : NSObject
1868 @end
1869
1870 void test(void) {
1871 [MyClass release]; // warn
1872 }
1873
1874 .. _osx-cocoa-Dealloc:
1875
1876 osx.cocoa.Dealloc (ObjC)
1877 """"""""""""""""""""""""
1878 Warn about Objective-C classes that lack a correct implementation of -dealloc
1879
1880 .. literalinclude:: checkers/dealloc_example.m
1881 :language: objc
1882
1883 .. _osx-cocoa-IncompatibleMethodTypes:
1884
1885 osx.cocoa.IncompatibleMethodTypes (ObjC)
1886 """"""""""""""""""""""""""""""""""""""""
1887 Warn about Objective-C method signatures with type incompatibilities.
1888
1889 .. code-block:: objc
1890
1891 @interface MyClass1 : NSObject
1892 - (int)foo;
1893 @end
1894
1895 @implementation MyClass1
1896 - (int)foo { return 1; }
1897 @end
1898
1899 @interface MyClass2 : MyClass1
1900 - (float)foo;
1901 @end
1902
1903 @implementation MyClass2
1904 - (float)foo { return 1.0; } // warn
1905 @end
1906
1907 .. _osx-cocoa-Loops:
1908
1909 osx.cocoa.Loops
1910 """""""""""""""
1911 Improved modeling of loops using Cocoa collection types.
1912
1913 .. _osx-cocoa-MissingSuperCall:
1914
1915 osx.cocoa.MissingSuperCall (ObjC)
1916 """""""""""""""""""""""""""""""""
1917 Warn about Objective-C methods that lack a necessary call to super.
1918
1919 .. code-block:: objc
1920
1921 @interface Test : UIViewController
1922 @end
1923 @implementation test
1924 - (void)viewDidLoad {} // warn
1925 @end
1926
1927
1928 .. _osx-cocoa-NSAutoreleasePool:
1929
1930 osx.cocoa.NSAutoreleasePool (ObjC)
1931 """"""""""""""""""""""""""""""""""
1932 Warn for suboptimal uses of NSAutoreleasePool in Objective-C GC mode.
1933
1934 .. code-block:: objc
1935
1936 void test() {
1937 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
1938 [pool release]; // warn
1939 }
1940
1941 .. _osx-cocoa-NSError:
1942
1943 osx.cocoa.NSError (ObjC)
1944 """"""""""""""""""""""""
1945 Check usage of NSError parameters.
1946
1947 .. code-block:: objc
1948
1949 @interface A : NSObject
1950 - (void)foo:(NSError """""""""""""""""""""""")error;
1951 @end
1952
1953 @implementation A
1954 - (void)foo:(NSError """""""""""""""""""""""")error {
1955 // warn: method accepting NSError"""""""""""""""""""""""" should have a non-void
1956 // return value
1957 }
1958 @end
1959
1960 @interface A : NSObject
1961 - (BOOL)foo:(NSError """""""""""""""""""""""")error;
1962 @end
1963
1964 @implementation A
1965 - (BOOL)foo:(NSError """""""""""""""""""""""")error {
1966 *error = 0; // warn: potential null dereference
1967 return 0;
1968 }
1969 @end
1970
1971 .. _osx-cocoa-NilArg:
1972
1973 osx.cocoa.NilArg (ObjC)
1974 """""""""""""""""""""""
1975 Check for prohibited nil arguments to ObjC method calls.
1976
1977 - caseInsensitiveCompare:
1978 - compare:
1979 - compare:options:
1980 - compare:options:range:
1981 - compare:options:range:locale:
1982 - componentsSeparatedByCharactersInSet:
1983 - initWithFormat:
1984
1985 .. code-block:: objc
1986
1987 NSComparisonResult test(NSString *s) {
1988 NSString *aString = nil;
1989 return [s caseInsensitiveCompare:aString];
1990 // warn: argument to 'NSString' method
1991 // 'caseInsensitiveCompare:' cannot be nil
1992 }
1993
1994
1995 .. _osx-cocoa-NonNilReturnValue:
1996
1997 osx.cocoa.NonNilReturnValue
1998 """""""""""""""""""""""""""
1999 Models the APIs that are guaranteed to return a non-nil value.
2000
2001 .. _osx-cocoa-ObjCGenerics:
2002
2003 osx.cocoa.ObjCGenerics (ObjC)
2004 """""""""""""""""""""""""""""
2005 Check for type errors when using Objective-C generics.
2006
2007 .. code-block:: objc
2008
2009 NSMutableArray *names = [NSMutableArray array];
2010 NSMutableArray *birthDates = names;
2011
2012 // Warning: Conversion from value of type 'NSDate *'
2013 // to incompatible type 'NSString *'
2014 [birthDates addObject: [NSDate date]];
2015
2016 .. _osx-cocoa-RetainCount:
2017
2018 osx.cocoa.RetainCount (ObjC)
2019 """"""""""""""""""""""""""""
2020 Check for leaks and improper reference count management
2021
2022 .. code-block:: objc
2023
2024 void test() {
2025 NSString *s = [[NSString alloc] init]; // warn
2026 }
2027
2028 CFStringRef test(char *bytes) {
2029 return CFStringCreateWithCStringNoCopy(
2030 0, bytes, NSNEXTSTEPStringEncoding, 0); // warn
2031 }
2032
2033
2034 .. _osx-cocoa-RunLoopAutoreleaseLeak:
2035
2036 osx.cocoa.RunLoopAutoreleaseLeak
2037 """"""""""""""""""""""""""""""""
2038 Check for leaked memory in autorelease pools that will never be drained.
2039
2040 .. _osx-cocoa-SelfInit:
2041
2042 osx.cocoa.SelfInit (ObjC)
2043 """""""""""""""""""""""""
2044 Check that 'self' is properly initialized inside an initializer method.
2045
2046 .. code-block:: objc
2047
2048 @interface MyObj : NSObject {
2049 id x;
2050 }
2051 - (id)init;
2052 @end
2053
2054 @implementation MyObj
2055 - (id)init {
2056 [super init];
2057 x = 0; // warn: instance variable used while 'self' is not
2058 // initialized
2059 return 0;
2060 }
2061 @end
2062
2063 @interface MyObj : NSObject
2064 - (id)init;
2065 @end
2066
2067 @implementation MyObj
2068 - (id)init {
2069 [super init];
2070 return self; // warn: returning uninitialized 'self'
2071 }
2072 @end
2073
2074 .. _osx-cocoa-SuperDealloc:
2075
2076 osx.cocoa.SuperDealloc (ObjC)
2077 """""""""""""""""""""""""""""
2078 Warn about improper use of '[super dealloc]' in Objective-C.
2079
2080 .. code-block:: objc
2081
2082 @interface SuperDeallocThenReleaseIvarClass : NSObject {
2083 NSObject *_ivar;
2084 }
2085 @end
2086
2087 @implementation SuperDeallocThenReleaseIvarClass
2088 - (void)dealloc {
2089 [super dealloc];
2090 [_ivar release]; // warn
2091 }
2092 @end
2093
2094 .. _osx-cocoa-UnusedIvars:
2095
2096 osx.cocoa.UnusedIvars (ObjC)
2097 """"""""""""""""""""""""""""
2098 Warn about private ivars that are never used.
2099
2100 .. code-block:: objc
2101
2102 @interface MyObj : NSObject {
2103 @private
2104 id x; // warn
2105 }
2106 @end
2107
2108 @implementation MyObj
2109 @end
2110
2111 .. _osx-cocoa-VariadicMethodTypes:
2112
2113 osx.cocoa.VariadicMethodTypes (ObjC)
2114 """"""""""""""""""""""""""""""""""""
2115 Check for passing non-Objective-C types to variadic collection
2116 initialization methods that expect only Objective-C types.
2117
2118 .. code-block:: objc
2119
2120 void test() {
2121 [NSSet setWithObjects:@"Foo", "Bar", nil];
2122 // warn: argument should be an ObjC pointer type, not 'char *'
2123 }
2124
2125 .. _osx-coreFoundation-CFError:
2126
2127 osx.coreFoundation.CFError (C)
2128 """"""""""""""""""""""""""""""
2129 Check usage of CFErrorRef* parameters
2130
2131 .. code-block:: c
2132
2133 void test(CFErrorRef *error) {
2134 // warn: function accepting CFErrorRef* should have a
2135 // non-void return
2136 }
2137
2138 int foo(CFErrorRef *error) {
2139 *error = 0; // warn: potential null dereference
2140 return 0;
2141 }
2142
2143 .. _osx-coreFoundation-CFNumber:
2144
2145 osx.coreFoundation.CFNumber (C)
2146 """""""""""""""""""""""""""""""
2147 Check for proper uses of CFNumber APIs.
2148
2149 .. code-block:: c
2150
2151 CFNumberRef test(unsigned char x) {
2152 return CFNumberCreate(0, kCFNumberSInt16Type, &x);
2153 // warn: 8 bit integer is used to initialize a 16 bit integer
2154 }
2155
2156 .. _osx-coreFoundation-CFRetainRelease:
2157
2158 osx.coreFoundation.CFRetainRelease (C)
2159 """"""""""""""""""""""""""""""""""""""
2160 Check for null arguments to CFRetain/CFRelease/CFMakeCollectable.
2161
2162 .. code-block:: c
2163
2164 void test(CFTypeRef p) {
2165 if (!p)
2166 CFRetain(p); // warn
2167 }
2168
2169 void test(int x, CFTypeRef p) {
2170 if (p)
2171 return;
2172
2173 CFRelease(p); // warn
2174 }
2175
2176 .. _osx-coreFoundation-containers-OutOfBounds:
2177
2178 osx.coreFoundation.containers.OutOfBounds (C)
2179 """""""""""""""""""""""""""""""""""""""""""""
2180 Checks for index out-of-bounds when using 'CFArray' API.
2181
2182 .. code-block:: c
2183
2184 void test() {
2185 CFArrayRef A = CFArrayCreate(0, 0, 0, &kCFTypeArrayCallBacks);
2186 CFArrayGetValueAtIndex(A, 0); // warn
2187 }
2188
2189 .. _osx-coreFoundation-containers-PointerSizedValues:
2190
2191 osx.coreFoundation.containers.PointerSizedValues (C)
2192 """"""""""""""""""""""""""""""""""""""""""""""""""""
2193 Warns if 'CFArray', 'CFDictionary', 'CFSet' are created with non-pointer-size values.
2194
2195 .. code-block:: c
2196
2197 void test() {
2198 int x[] = { 1 };
2199 CFArrayRef A = CFArrayCreate(0, (const void """""""""""""""""""""""")x, 1,
2200 &kCFTypeArrayCallBacks); // warn
2201 }
2202
2203 Fuchsia
2204 ^^^^^^^
2205
2206 Fuchsia is an open source capability-based operating system currently being
2207 developed by Google. This section describes checkers that can find various
2208 misuses of Fuchsia APIs.
2209
2210 .. _fuchsia-HandleChecker:
2211
2212 fuchsia.HandleChecker
2213 """"""""""""""""""""""""""""
2214 Handles identify resources. Similar to pointers they can be leaked,
2215 double freed, or use after freed. This check attempts to find such problems.
2216
2217 .. code-block:: cpp
2218
2219 void checkLeak08(int tag) {
2220 zx_handle_t sa, sb;
2221 zx_channel_create(0, &sa, &sb);
2222 if (tag)
2223 zx_handle_close(sa);
2224 use(sb); // Warn: Potential leak of handle
2225 zx_handle_close(sb);
2226 }
2227
2228 WebKit
2229 ^^^^^^
2230
2231 WebKit is an open-source web browser engine available for macOS, iOS and Linux.
2232 This section describes checkers that can find issues in WebKit codebase.
2233
2234 Most of the checkers focus on memory management for which WebKit uses custom implementation of reference counted smartpointers.
2235
2236 Checkers are formulated in terms related to ref-counting:
2237 - *Ref-counted type* is either ``Ref<T>`` or ``RefPtr<T>``.
2238 - *Ref-countable type* is any type that implements ``ref()`` and ``deref()`` methods as ``RefPtr<>`` is a template (i. e. relies on duck typing).
2239 - *Uncounted type* is ref-countable but not ref-counted type.
2240
2241 .. _webkit-RefCntblBaseVirtualDtor:
2242
2243 webkit.RefCntblBaseVirtualDtor
2244 """"""""""""""""""""""""""""""""""""
2245 All uncounted types used as base classes must have a virtual destructor.
2246
2247 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]``.
2248
2249 .. code-block:: cpp
2250
2251 struct RefCntblBase {
2252 void ref() {}
2253 void deref() {}
2254 };
2255
2256 struct Derived : RefCntblBase { }; // warn
2257
2258 .. _webkit-NoUncountedMemberChecker:
2259
2260 webkit.NoUncountedMemberChecker
2261 """""""""""""""""""""""""""""""""""""
2262 Raw pointers and references to uncounted types can't be used as class members. Only ref-counted types are allowed.
2263
2264 .. code-block:: cpp
2265
2266 struct RefCntbl {
2267 void ref() {}
2268 void deref() {}
2269 };
2270
2271 struct Foo {
2272 RefCntbl * ptr; // warn
2273 RefCntbl & ptr; // warn
2274 // ...
2275 };
2276
2277 .. _webkit-UncountedLambdaCapturesChecker:
2278
2279 webkit.UncountedLambdaCapturesChecker
2280 """""""""""""""""""""""""""""""""""""
2281 Raw pointers and references to uncounted types can't be captured in lambdas. Only ref-counted types are allowed.
2282
2283 .. code-block:: cpp
2284
2285 struct RefCntbl {
2286 void ref() {}
2287 void deref() {}
2288 };
2289
2290 void foo(RefCntbl* a, RefCntbl& b) {
2291 [&, a](){ // warn about 'a'
2292 do_something(b); // warn about 'b'
2293 };
2294 };
2295
2296 .. _alpha-checkers:
2297
2298 Experimental Checkers
2299 ---------------------
2300
2301 *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.*
2302
2303 alpha.clone
2304 ^^^^^^^^^^^
2305
2306 .. _alpha-clone-CloneChecker:
2307
2308 alpha.clone.CloneChecker (C, C++, ObjC)
2309 """""""""""""""""""""""""""""""""""""""
2310 Reports similar pieces of code.
2311
2312 .. code-block:: c
2313
2314 void log();
2315
2316 int max(int a, int b) { // warn
2317 log();
2318 if (a > b)
2319 return a;
2320 return b;
2321 }
2322
2323 int maxClone(int x, int y) { // similar code here
2324 log();
2325 if (x > y)
2326 return x;
2327 return y;
2328 }
2329
2330 alpha.core
2331 ^^^^^^^^^^
2332
2333 .. _alpha-core-BoolAssignment:
2334
2335 alpha.core.BoolAssignment (ObjC)
2336 """"""""""""""""""""""""""""""""
2337 Warn about assigning non-{0,1} values to boolean variables.
2338
2339 .. code-block:: objc
2340
2341 void test() {
2342 BOOL b = -1; // warn
2343 }
2344
2345 .. _alpha-core-C11Lock:
2346
2347 alpha.core.C11Lock
2348 """"""""""""""""""
2349 Similarly to :ref:`alpha.unix.PthreadLock <alpha-unix-PthreadLock>`, checks for
2350 the locking/unlocking of ``mtx_t`` mutexes.
2351
2352 .. code-block:: cpp
2353
2354 mtx_t mtx1;
2355
2356 void bad1(void)
2357 {
2358 mtx_lock(&mtx1);
2359 mtx_lock(&mtx1); // warn: This lock has already been acquired
2360 }
2361
2362 .. _alpha-core-CastSize:
2363
2364 alpha.core.CastSize (C)
2365 """""""""""""""""""""""
2366 Check when casting a malloc'ed type ``T``, whether the size is a multiple of the size of ``T``.
2367
2368 .. code-block:: c
2369
2370 void test() {
2371 int *x = (int *) malloc(11); // warn
2372 }
2373
2374 .. _alpha-core-CastToStruct:
2375
2376 alpha.core.CastToStruct (C, C++)
2377 """"""""""""""""""""""""""""""""
2378 Check for cast from non-struct pointer to struct pointer.
2379
2380 .. code-block:: cpp
2381
2382 // C
2383 struct s {};
2384
2385 void test(int *p) {
2386 struct s *ps = (struct s *) p; // warn
2387 }
2388
2389 // C++
2390 class c {};
2391
2392 void test(int *p) {
2393 c *pc = (c *) p; // warn
2394 }
2395
2396 .. _alpha-core-Conversion:
2397
2398 alpha.core.Conversion (C, C++, ObjC)
2399 """"""""""""""""""""""""""""""""""""
2400 Loss of sign/precision in implicit conversions.
2401
2402 .. code-block:: c
2403
2404 void test(unsigned U, signed S) {
2405 if (S > 10) {
2406 if (U < S) {
2407 }
2408 }
2409 if (S < -10) {
2410 if (U < S) { // warn (loss of sign)
2411 }
2412 }
2413 }
2414
2415 void test() {
2416 long long A = 1LL << 60;
2417 short X = A; // warn (loss of precision)
2418 }
2419
2420 .. _alpha-core-DynamicTypeChecker:
2421
2422 alpha.core.DynamicTypeChecker (ObjC)
2423 """"""""""""""""""""""""""""""""""""
2424 Check for cases where the dynamic and the static type of an object are unrelated.
2425
2426
2427 .. code-block:: objc
2428
2429 id date = [NSDate date];
2430
2431 // Warning: Object has a dynamic type 'NSDate *' which is
2432 // incompatible with static type 'NSNumber *'"
2433 NSNumber *number = date;
2434 [number doubleValue];
2435
2436 .. _alpha-core-FixedAddr:
2437
2438 alpha.core.FixedAddr (C)
2439 """"""""""""""""""""""""
2440 Check for assignment of a fixed address to a pointer.
2441
2442 .. code-block:: c
2443
2444 void test() {
2445 int *p;
2446 p = (int *) 0x10000; // warn
2447 }
2448
2449 .. _alpha-core-IdenticalExpr:
2450
2451 alpha.core.IdenticalExpr (C, C++)
2452 """""""""""""""""""""""""""""""""
2453 Warn about unintended use of identical expressions in operators.
2454
2455 .. code-block:: cpp
2456
2457 // C
2458 void test() {
2459 int a = 5;
2460 int b = a | 4 | a; // warn: identical expr on both sides
2461 }
2462
2463 // C++
2464 bool f(void);
2465
2466 void test(bool b) {
2467 int i = 10;
2468 if (f()) { // warn: true and false branches are identical
2469 do {
2470 i--;
2471 } while (f());
2472 } else {
2473 do {
2474 i--;
2475 } while (f());
2476 }
2477 }
2478
2479 .. _alpha-core-PointerArithm:
2480
2481 alpha.core.PointerArithm (C)
2482 """"""""""""""""""""""""""""
2483 Check for pointer arithmetic on locations other than array elements.
2484
2485 .. code-block:: c
2486
2487 void test() {
2488 int x;
2489 int *p;
2490 p = &x + 1; // warn
2491 }
2492
2493 .. _alpha-core-PointerSub:
2494
2495 alpha.core.PointerSub (C)
2496 """""""""""""""""""""""""
2497 Check for pointer subtractions on two pointers pointing to different memory chunks.
2498
2499 .. code-block:: c
2500
2501 void test() {
2502 int x, y;
2503 int d = &y - &x; // warn
2504 }
2505
2506 .. _alpha-core-StackAddressAsyncEscape:
2507
2508 alpha.core.StackAddressAsyncEscape (C)
2509 """"""""""""""""""""""""""""""""""""""
2510 Check that addresses to stack memory do not escape the function that involves dispatch_after or dispatch_async.
2511 This checker is a part of ``core.StackAddressEscape``, but is temporarily disabled until some false positives are fixed.
2512
2513 .. code-block:: c
2514
2515 dispatch_block_t test_block_inside_block_async_leak() {
2516 int x = 123;
2517 void (^inner)(void) = ^void(void) {
2518 int y = x;
2519 ++y;
2520 };
2521 void (^outer)(void) = ^void(void) {
2522 int z = x;
2523 ++z;
2524 inner();
2525 };
2526 return outer; // warn: address of stack-allocated block is captured by a
2527 // returned block
2528 }
2529
2530 .. _alpha-core-StdVariant:
2531
2532 alpha.core.StdVariant (C++)
2533 """""""""""""""""""""""""""
2534 Check if a value of active type is retrieved from an ``std::variant`` instance with ``std::get``.
2535 In case of bad variant type access (the accessed type differs from the active type)
2536 a warning is emitted. Currently, this checker does not take exception handling into account.
2537
2538 .. code-block:: cpp
2539
2540 void test() {
2541 std::variant<int, char> v = 25;
2542 char c = stg::get<char>(v); // warn: "int" is the active alternative
2543 }
2544
2545 .. _alpha-core-TestAfterDivZero:
2546
2547 alpha.core.TestAfterDivZero (C)
2548 """""""""""""""""""""""""""""""
2549 Check for division by variable that is later compared against 0.
2550 Either the comparison is useless or there is division by zero.
2551
2552 .. code-block:: c
2553
2554 void test(int x) {
2555 var = 77 / x;
2556 if (x == 0) { } // warn
2557 }
2558
2559 alpha.cplusplus
2560 ^^^^^^^^^^^^^^^
2561
2562 .. _alpha-cplusplus-DeleteWithNonVirtualDtor:
2563
2564 alpha.cplusplus.DeleteWithNonVirtualDtor (C++)
2565 """"""""""""""""""""""""""""""""""""""""""""""
2566 Reports destructions of polymorphic objects with a non-virtual destructor in their base class.
2567
2568 .. code-block:: cpp
2569
2570 class NonVirtual {};
2571 class NVDerived : public NonVirtual {};
2572
2573 NonVirtual *create() {
2574 NonVirtual *x = new NVDerived(); // note: Casting from 'NVDerived' to
2575 // 'NonVirtual' here
2576 return x;
2577 }
2578
2579 void foo() {
2580 NonVirtual *x = create();
2581 delete x; // warn: destruction of a polymorphic object with no virtual
2582 // destructor
2583 }
2584
2585 .. _alpha-cplusplus-InvalidatedIterator:
2586
2587 alpha.cplusplus.InvalidatedIterator (C++)
2588 """""""""""""""""""""""""""""""""""""""""
2589 Check for use of invalidated iterators.
2590
2591 .. code-block:: cpp
2592
2593 void bad_copy_assign_operator_list1(std::list &L1,
2594 const std::list &L2) {
2595 auto i0 = L1.cbegin();
2596 L1 = L2;
2597 *i0; // warn: invalidated iterator accessed
2598 }
2599
2600
2601 .. _alpha-cplusplus-IteratorRange:
2602
2603 alpha.cplusplus.IteratorRange (C++)
2604 """""""""""""""""""""""""""""""""""
2605 Check for iterators used outside their valid ranges.
2606
2607 .. code-block:: cpp
2608
2609 void simple_bad_end(const std::vector &v) {
2610 auto i = v.end();
2611 *i; // warn: iterator accessed outside of its range
2612 }
2613
2614 .. _alpha-cplusplus-MismatchedIterator:
2615
2616 alpha.cplusplus.MismatchedIterator (C++)
2617 """"""""""""""""""""""""""""""""""""""""
2618 Check for use of iterators of different containers where iterators of the same container are expected.
2619
2620 .. code-block:: cpp
2621
2622 void bad_insert3(std::vector &v1, std::vector &v2) {
2623 v2.insert(v1.cbegin(), v2.cbegin(), v2.cend()); // warn: container accessed
2624 // using foreign
2625 // iterator argument
2626 v1.insert(v1.cbegin(), v1.cbegin(), v2.cend()); // warn: iterators of
2627 // different containers
2628 // used where the same
2629 // container is
2630 // expected
2631 v1.insert(v1.cbegin(), v2.cbegin(), v1.cend()); // warn: iterators of
2632 // different containers
2633 // used where the same
2634 // container is
2635 // expected
2636 }
2637
2638 .. _alpha-cplusplus-SmartPtr:
2639
2640 alpha.cplusplus.SmartPtr (C++)
2641 """"""""""""""""""""""""""""""
2642 Check for dereference of null smart pointers.
2643
2644 .. code-block:: cpp
2645
2646 void deref_smart_ptr() {
2647 std::unique_ptr<int> P;
2648 *P; // warn: dereference of a default constructed smart unique_ptr
2649 }
2650
2651
2652 alpha.deadcode
2653 ^^^^^^^^^^^^^^
2654 .. _alpha-deadcode-UnreachableCode:
2655
2656 alpha.deadcode.UnreachableCode (C, C++)
2657 """""""""""""""""""""""""""""""""""""""
2658 Check unreachable code.
2659
2660 .. code-block:: cpp
2661
2662 // C
2663 int test() {
2664 int x = 1;
2665 while(x);
2666 return x; // warn
2667 }
2668
2669 // C++
2670 void test() {
2671 int a = 2;
2672
2673 while (a > 1)
2674 a--;
2675
2676 if (a > 1)
2677 a++; // warn
2678 }
2679
2680 // Objective-C
2681 void test(id x) {
2682 return;
2683 [x retain]; // warn
2684 }
2685
2686 alpha.fuchsia
2687 ^^^^^^^^^^^^^
2688
2689 .. _alpha-fuchsia-lock:
2690
2691 alpha.fuchsia.Lock
2692 """"""""""""""""""
2693 Similarly to :ref:`alpha.unix.PthreadLock <alpha-unix-PthreadLock>`, checks for
2694 the locking/unlocking of fuchsia mutexes.
2695
2696 .. code-block:: cpp
2697
2698 spin_lock_t mtx1;
2699
2700 void bad1(void)
2701 {
2702 spin_lock(&mtx1);
2703 spin_lock(&mtx1); // warn: This lock has already been acquired
2704 }
2705
2706 alpha.llvm
2707 ^^^^^^^^^^
2708
2709 .. _alpha-llvm-Conventions:
2710
2711 alpha.llvm.Conventions
2712 """"""""""""""""""""""
2713
2714 Check code for LLVM codebase conventions:
2715
2716 * A StringRef should not be bound to a temporary std::string whose lifetime is shorter than the StringRef's.
2717 * Clang AST nodes should not have fields that can allocate memory.
2718
2719
2720 alpha.osx
2721 ^^^^^^^^^
2722
2723 .. _alpha-osx-cocoa-DirectIvarAssignment:
2724
2725 alpha.osx.cocoa.DirectIvarAssignment (ObjC)
2726 """""""""""""""""""""""""""""""""""""""""""
2727 Check for direct assignments to instance variables.
2728
2729
2730 .. code-block:: objc
2731
2732 @interface MyClass : NSObject {}
2733 @property (readonly) id A;
2734 - (void) foo;
2735 @end
2736
2737 @implementation MyClass
2738 - (void) foo {
2739 _A = 0; // warn
2740 }
2741 @end
2742
2743 .. _alpha-osx-cocoa-DirectIvarAssignmentForAnnotatedFunctions:
2744
2745 alpha.osx.cocoa.DirectIvarAssignmentForAnnotatedFunctions (ObjC)
2746 """"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
2747 Check for direct assignments to instance variables in
2748 the methods annotated with ``objc_no_direct_instance_variable_assignment``.
2749
2750 .. code-block:: objc
2751
2752 @interface MyClass : NSObject {}
2753 @property (readonly) id A;
2754 - (void) fAnnotated __attribute__((
2755 annotate("objc_no_direct_instance_variable_assignment")));
2756 - (void) fNotAnnotated;
2757 @end
2758
2759 @implementation MyClass
2760 - (void) fAnnotated {
2761 _A = 0; // warn
2762 }
2763 - (void) fNotAnnotated {
2764 _A = 0; // no warn
2765 }
2766 @end
2767
2768
2769 .. _alpha-osx-cocoa-InstanceVariableInvalidation:
2770
2771 alpha.osx.cocoa.InstanceVariableInvalidation (ObjC)
2772 """""""""""""""""""""""""""""""""""""""""""""""""""
2773 Check that the invalidatable instance variables are
2774 invalidated in the methods annotated with objc_instance_variable_invalidator.
2775
2776 .. code-block:: objc
2777
2778 @protocol Invalidation <NSObject>
2779 - (void) invalidate
2780 __attribute__((annotate("objc_instance_variable_invalidator")));
2781 @end
2782
2783 @interface InvalidationImpObj : NSObject <Invalidation>
2784 @end
2785
2786 @interface SubclassInvalidationImpObj : InvalidationImpObj {
2787 InvalidationImpObj *var;
2788 }
2789 - (void)invalidate;
2790 @end
2791
2792 @implementation SubclassInvalidationImpObj
2793 - (void) invalidate {}
2794 @end
2795 // warn: var needs to be invalidated or set to nil
2796
2797 .. _alpha-osx-cocoa-MissingInvalidationMethod:
2798
2799 alpha.osx.cocoa.MissingInvalidationMethod (ObjC)
2800 """"""""""""""""""""""""""""""""""""""""""""""""
2801 Check that the invalidation methods are present in classes that contain invalidatable instance variables.
2802
2803 .. code-block:: objc
2804
2805 @protocol Invalidation <NSObject>
2806 - (void)invalidate
2807 __attribute__((annotate("objc_instance_variable_invalidator")));
2808 @end
2809
2810 @interface NeedInvalidation : NSObject <Invalidation>
2811 @end
2812
2813 @interface MissingInvalidationMethodDecl : NSObject {
2814 NeedInvalidation *Var; // warn
2815 }
2816 @end
2817
2818 @implementation MissingInvalidationMethodDecl
2819 @end
2820
2821 .. _alpha-osx-cocoa-localizability-PluralMisuseChecker:
2822
2823 alpha.osx.cocoa.localizability.PluralMisuseChecker (ObjC)
2824 """""""""""""""""""""""""""""""""""""""""""""""""""""""""
2825 Warns against using one vs. many plural pattern in code when generating localized strings.
2826
2827 .. code-block:: objc
2828
2829 NSString *reminderText =
2830 NSLocalizedString(@"None", @"Indicates no reminders");
2831 if (reminderCount == 1) {
2832 // Warning: Plural cases are not supported across all languages.
2833 // Use a .stringsdict file instead
2834 reminderText =
2835 NSLocalizedString(@"1 Reminder", @"Indicates single reminder");
2836 } else if (reminderCount >= 2) {
2837 // Warning: Plural cases are not supported across all languages.
2838 // Use a .stringsdict file instead
2839 reminderText =
2840 [NSString stringWithFormat:
2841 NSLocalizedString(@"%@ Reminders", @"Indicates multiple reminders"),
2842 reminderCount];
2843 }
2844
2845 alpha.security
2846 ^^^^^^^^^^^^^^
2847
2848 .. _alpha-security-ArrayBound:
2849
2850 alpha.security.ArrayBound (C)
2851 """""""""""""""""""""""""""""
2852 Warn about buffer overflows (older checker).
2853
2854 .. code-block:: c
2855
2856 void test() {
2857 char *s = "";
2858 char c = s[1]; // warn
2859 }
2860
2861 struct seven_words {
2862 int c[7];
2863 };
2864
2865 void test() {
2866 struct seven_words a, *p;
2867 p = &a;
2868 p[0] = a;
2869 p[1] = a;
2870 p[2] = a; // warn
2871 }
2872
2873 // note: requires unix.Malloc or
2874 // alpha.unix.MallocWithAnnotations checks enabled.
2875 void test() {
2876 int *p = malloc(12);
2877 p[3] = 4; // warn
2878 }
2879
2880 void test() {
2881 char a[2];
2882 int *b = (int*)a;
2883 b[1] = 3; // warn
2884 }
2885
2886 .. _alpha-security-ArrayBoundV2:
2887
2888 alpha.security.ArrayBoundV2 (C)
2889 """""""""""""""""""""""""""""""
2890 Warn about buffer overflows (newer checker).
2891
2892 .. code-block:: c
2893
2894 void test() {
2895 char *s = "";
2896 char c = s[1]; // warn
2897 }
2898
2899 void test() {
2900 int buf[100];
2901 int *p = buf;
2902 p = p + 99;
2903 p[1] = 1; // warn
2904 }
2905
2906 // note: compiler has internal check for this.
2907 // Use -Wno-array-bounds to suppress compiler warning.
2908 void test() {
2909 int buf[100][100];
2910 buf[0][-1] = 1; // warn
2911 }
2912
2913 // note: requires alpha.security.taint check turned on.
2914 void test() {
2915 char s[] = "abc";
2916 int x = getchar();
2917 char c = s[x]; // warn: index is tainted
2918 }
2919
2920 .. _alpha-security-MallocOverflow:
2921
2922 alpha.security.MallocOverflow (C)
2923 """""""""""""""""""""""""""""""""
2924 Check for overflows in the arguments to ``malloc()``.
2925 It tries to catch ``malloc(n * c)`` patterns, where:
2926
2927 - ``n``: a variable or member access of an object
2928 - ``c``: a constant foldable integral
2929
2930 This checker was designed for code audits, so expect false-positive reports.
2931 One is supposed to silence this checker by ensuring proper bounds checking on
2932 the variable in question using e.g. an ``assert()`` or a branch.
2933
2934 .. code-block:: c
2935
2936 void test(int n) {
2937 void *p = malloc(n * sizeof(int)); // warn
2938 }
2939
2940 void test2(int n) {
2941 if (n > 100) // gives an upper-bound
2942 return;
2943 void *p = malloc(n * sizeof(int)); // no warning
2944 }
2945
2946 void test3(int n) {
2947 assert(n <= 100 && "Contract violated.");
2948 void *p = malloc(n * sizeof(int)); // no warning
2949 }
2950
2951 Limitations:
2952
2953 - The checker won't warn for variables involved in explicit casts,
2954 since that might limit the variable's domain.
2955 E.g.: ``(unsigned char)int x`` would limit the domain to ``[0,255]``.
2956 The checker will miss the true-positive cases when the explicit cast would
2957 not tighten the domain to prevent the overflow in the subsequent
2958 multiplication operation.
2959
2960 - It is an AST-based checker, thus it does not make use of the
2961 path-sensitive taint-analysis.
2962
2963 .. _alpha-security-MmapWriteExec:
2964
2965 alpha.security.MmapWriteExec (C)
2966 """"""""""""""""""""""""""""""""
2967 Warn on mmap() calls that are both writable and executable.
2968
2969 .. code-block:: c
2970
2971 void test(int n) {
2972 void *c = mmap(NULL, 32, PROT_READ | PROT_WRITE | PROT_EXEC,
2973 MAP_PRIVATE | MAP_ANON, -1, 0);
2974 // warn: Both PROT_WRITE and PROT_EXEC flags are set. This can lead to
2975 // exploitable memory regions, which could be overwritten with malicious
2976 // code
2977 }
2978
2979 .. _alpha-security-ReturnPtrRange:
2980
2981 alpha.security.ReturnPtrRange (C)
2982 """""""""""""""""""""""""""""""""
2983 Check for an out-of-bound pointer being returned to callers.
2984
2985 .. code-block:: c
2986
2987 static int A[10];
2988
2989 int *test() {
2990 int *p = A + 10;
2991 return p; // warn
2992 }
2993
2994 int test(void) {
2995 int x;
2996 return x; // warn: undefined or garbage returned
2997 }
2998
2999
3000 alpha.security.cert
3001 ^^^^^^^^^^^^^^^^^^^
3002
3003 SEI CERT checkers which tries to find errors based on their `C coding rules <https://wiki.sei.cmu.edu/confluence/display/c/2+Rules>`_.
3004
3005 alpha.security.taint
3006 ^^^^^^^^^^^^^^^^^^^^
3007
3008 Checkers implementing
3009 `taint analysis <https://en.wikipedia.org/wiki/Taint_checking>`_.
3010
3011 .. _alpha-security-taint-GenericTaint:
3012
3013 alpha.security.taint.GenericTaint (C, C++)
3014 """"""""""""""""""""""""""""""""""""""""""
3015
3016 Taint analysis identifies potential security vulnerabilities where the
3017 attacker can inject malicious data to the program to execute an attack
3018 (privilege escalation, command injection, SQL injection etc.).
3019
3020 The malicious data is injected at the taint source (e.g. ``getenv()`` call)
3021 which is then propagated through function calls and being used as arguments of
3022 sensitive operations, also called as taint sinks (e.g. ``system()`` call).
3023
3024 One can defend against this type of vulnerability by always checking and
3025 sanitizing the potentially malicious, untrusted user input.
3026
3027 The goal of the checker is to discover and show to the user these potential
3028 taint source-sink pairs and the propagation call chain.
3029
3030 The most notable examples of taint sources are:
3031
3032 - data from network
3033 - files or standard input
3034 - environment variables
3035 - data from databases
3036
3037 Let us examine a practical example of a Command Injection attack.
3038
3039 .. code-block:: c
3040
3041 // Command Injection Vulnerability Example
3042 int main(int argc, char** argv) {
3043 char cmd[2048] = "/bin/cat ";
3044 char filename[1024];
3045 printf("Filename:");
3046 scanf (" %1023[^\n]", filename); // The attacker can inject a shell escape here
3047 strcat(cmd, filename);
3048 system(cmd); // Warning: Untrusted data is passed to a system call
3049 }
3050
3051 The program prints the content of any user specified file.
3052 Unfortunately the attacker can execute arbitrary commands
3053 with shell escapes. For example with the following input the `ls` command is also
3054 executed after the contents of `/etc/shadow` is printed.
3055 `Input: /etc/shadow ; ls /`
3056
3057 The analysis implemented in this checker points out this problem.
3058
3059 One can protect against such attack by for example checking if the provided
3060 input refers to a valid file and removing any invalid user input.
3061
3062 .. code-block:: c
3063
3064 // No vulnerability anymore, but we still get the warning
3065 void sanitizeFileName(char* filename){
3066 if (access(filename,F_OK)){// Verifying user input
3067 printf("File does not exist\n");
3068 filename[0]='\0';
3069 }
3070 }
3071 int main(int argc, char** argv) {
3072 char cmd[2048] = "/bin/cat ";
3073 char filename[1024];
3074 printf("Filename:");
3075 scanf (" %1023[^\n]", filename); // The attacker can inject a shell escape here
3076 sanitizeFileName(filename);// filename is safe after this point
3077 if (!filename[0])
3078 return -1;
3079 strcat(cmd, filename);
3080 system(cmd); // Superfluous Warning: Untrusted data is passed to a system call
3081 }
3082
3083 Unfortunately, the checker cannot discover automatically that the programmer
3084 have performed data sanitation, so it still emits the warning.
3085
3086 One can get rid of this superfluous warning by telling by specifying the
3087 sanitation functions in the taint configuration file (see
3088 :doc:`user-docs/TaintAnalysisConfiguration`).
3089
3090 .. code-block:: YAML
3091
3092 Filters:
3093 - Name: sanitizeFileName
3094 Args: [0]
3095
3096 The clang invocation to pass the configuration file location:
3097
3098 .. code-block:: bash
3099
3100 clang --analyze -Xclang -analyzer-config -Xclang alpha.security.taint.TaintPropagation:Config=`pwd`/taint_config.yml ...
3101
3102 If you are validating your inputs instead of sanitizing them, or don't want to
3103 mention each sanitizing function in our configuration,
3104 you can use a more generic approach.
3105
3106 Introduce a generic no-op `csa_mark_sanitized(..)` function to
3107 tell the Clang Static Analyzer
3108 that the variable is safe to be used on that analysis path.
3109
3110 .. code-block:: c
3111
3112 // Marking sanitized variables safe.
3113 // No vulnerability anymore, no warning.
3114
3115 // User csa_mark_sanitize function is for the analyzer only
3116 #ifdef __clang_analyzer__
3117 void csa_mark_sanitized(const void *);
3118 #endif
3119
3120 int main(int argc, char** argv) {
3121 char cmd[2048] = "/bin/cat ";
3122 char filename[1024];
3123 printf("Filename:");
3124 scanf (" %1023[^\n]", filename);
3125 if (access(filename,F_OK)){// Verifying user input
3126 printf("File does not exist\n");
3127 return -1;
3128 }
3129 #ifdef __clang_analyzer__
3130 csa_mark_sanitized(filename); // Indicating to CSA that filename variable is safe to be used after this point
3131 #endif
3132 strcat(cmd, filename);
3133 system(cmd); // No warning
3134 }
3135
3136 Similarly to the previous example, you need to
3137 define a `Filter` function in a `YAML` configuration file
3138 and add the `csa_mark_sanitized` function.
3139
3140 .. code-block:: YAML
3141
3142 Filters:
3143 - Name: csa_mark_sanitized
3144 Args: [0]
3145
3146 Then calling `csa_mark_sanitized(X)` will tell the analyzer that `X` is safe to
3147 be used after this point, because its contents are verified. It is the
3148 responsibility of the programmer to ensure that this verification was indeed
3149 correct. Please note that `csa_mark_sanitized` function is only declared and
3150 used during Clang Static Analysis and skipped in (production) builds.
3151
3152 Further examples of injection vulnerabilities this checker can find.
3153
3154 .. code-block:: c
3155
3156 void test() {
3157 char x = getchar(); // 'x' marked as tainted
3158 system(&x); // warn: untrusted data is passed to a system call
3159 }
3160
3161 // note: compiler internally checks if the second param to
3162 // sprintf is a string literal or not.
3163 // Use -Wno-format-security to suppress compiler warning.
3164 void test() {
3165 char s[10], buf[10];
3166 fscanf(stdin, "%s", s); // 's' marked as tainted
3167
3168 sprintf(buf, s); // warn: untrusted data used as a format string
3169 }
3170
3171 There are built-in sources, propagations and sinks even if no external taint
3172 configuration is provided.
3173
3174 Default sources:
3175 ``_IO_getc``, ``fdopen``, ``fopen``, ``freopen``, ``get_current_dir_name``,
3176 ``getch``, ``getchar``, ``getchar_unlocked``, ``getwd``, ``getcwd``,
3177 ``getgroups``, ``gethostname``, ``getlogin``, ``getlogin_r``, ``getnameinfo``,
3178 ``gets``, ``gets_s``, ``getseuserbyname``, ``readlink``, ``readlinkat``,
3179 ``scanf``, ``scanf_s``, ``socket``, ``wgetch``
3180
3181 Default propagations rules:
3182 ``atoi``, ``atol``, ``atoll``, ``basename``, ``dirname``, ``fgetc``,
3183 ``fgetln``, ``fgets``, ``fnmatch``, ``fread``, ``fscanf``, ``fscanf_s``,
3184 ``index``, ``inflate``, ``isalnum``, ``isalpha``, ``isascii``, ``isblank``,
3185 ``iscntrl``, ``isdigit``, ``isgraph``, ``islower``, ``isprint``, ``ispunct``,
3186 ``isspace``, ``isupper``, ``isxdigit``, ``memchr``, ``memrchr``, ``sscanf``,
3187 ``getc``, ``getc_unlocked``, ``getdelim``, ``getline``, ``getw``, ``memcmp``,
3188 ``memcpy``, ``memmem``, ``memmove``, ``mbtowc``, ``pread``, ``qsort``,
3189 ``qsort_r``, ``rawmemchr``, ``read``, ``recv``, ``recvfrom``, ``rindex``,
3190 ``strcasestr``, ``strchr``, ``strchrnul``, ``strcasecmp``, ``strcmp``,
3191 ``strcspn``, ``strncasecmp``, ``strncmp``, ``strndup``,
3192 ``strndupa``, ``strpbrk``, ``strrchr``, ``strsep``, ``strspn``,
3193 ``strstr``, ``strtol``, ``strtoll``, ``strtoul``, ``strtoull``, ``tolower``,
3194 ``toupper``, ``ttyname``, ``ttyname_r``, ``wctomb``, ``wcwidth``
3195
3196 Default sinks:
3197 ``printf``, ``setproctitle``, ``system``, ``popen``, ``execl``, ``execle``,
3198 ``execlp``, ``execv``, ``execvp``, ``execvP``, ``execve``, ``dlopen``
3199
3200 Please note that there are no built-in filter functions.
3201
3202 One can configure their own taint sources, sinks, and propagation rules by
3203 providing a configuration file via checker option
3204 ``alpha.security.taint.TaintPropagation:Config``. The configuration file is in
3205 `YAML <http://llvm.org/docs/YamlIO.html#introduction-to-yaml>`_ format. The
3206 taint-related options defined in the config file extend but do not override the
3207 built-in sources, rules, sinks. The format of the external taint configuration
3208 file is not stable, and could change without any notice even in a non-backward
3209 compatible way.
3210
3211 For a more detailed description of configuration options, please see the
3212 :doc:`user-docs/TaintAnalysisConfiguration`. For an example see
3213 :ref:`clangsa-taint-configuration-example`.
3214
3215 **Configuration**
3216
3217 * `Config` Specifies the name of the YAML configuration file. The user can
3218 define their own taint sources and sinks.
3219
3220 **Related Guidelines**
3221
3222 * `CWE Data Neutralization Issues
3223 <https://cwe.mitre.org/data/definitions/137.html>`_
3224 * `SEI Cert STR02-C. Sanitize data passed to complex subsystems
3225 <https://wiki.sei.cmu.edu/confluence/display/c/STR02-C.+Sanitize+data+passed+to+complex+subsystems>`_
3226 * `SEI Cert ENV33-C. Do not call system()
3227 <https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152177>`_
3228 * `ENV03-C. Sanitize the environment when invoking external programs
3229 <https://wiki.sei.cmu.edu/confluence/display/c/ENV03-C.+Sanitize+the+environment+when+invoking+external+programs>`_
3230
3231 **Limitations**
3232
3233 * The taintedness property is not propagated through function calls which are
3234 unknown (or too complex) to the analyzer, unless there is a specific
3235 propagation rule built-in to the checker or given in the YAML configuration
3236 file. This causes potential true positive findings to be lost.
3237
3238 alpha.unix
3239 ^^^^^^^^^^
3240
3241 .. _alpha-unix-Chroot:
3242
3243 alpha.unix.Chroot (C)
3244 """""""""""""""""""""
3245 Check improper use of chroot.
3246
3247 .. code-block:: c
3248
3249 void f();
3250
3251 void test() {
3252 chroot("/usr/local");
3253 f(); // warn: no call of chdir("/") immediately after chroot
3254 }
3255
3256 .. _alpha-unix-PthreadLock:
3257
3258 alpha.unix.PthreadLock (C)
3259 """"""""""""""""""""""""""
3260 Simple lock -> unlock checker.
3261 Applies to: ``pthread_mutex_lock, pthread_rwlock_rdlock, pthread_rwlock_wrlock, lck_mtx_lock, lck_rw_lock_exclusive``
3262 ``lck_rw_lock_shared, pthread_mutex_trylock, pthread_rwlock_tryrdlock, pthread_rwlock_tryrwlock, lck_mtx_try_lock,
3263 lck_rw_try_lock_exclusive, lck_rw_try_lock_shared, pthread_mutex_unlock, pthread_rwlock_unlock, lck_mtx_unlock, lck_rw_done``.
3264
3265
3266 .. code-block:: c
3267
3268 pthread_mutex_t mtx;
3269
3270 void test() {
3271 pthread_mutex_lock(&mtx);
3272 pthread_mutex_lock(&mtx);
3273 // warn: this lock has already been acquired
3274 }
3275
3276 lck_mtx_t lck1, lck2;
3277
3278 void test() {
3279 lck_mtx_lock(&lck1);
3280 lck_mtx_lock(&lck2);
3281 lck_mtx_unlock(&lck1);
3282 // warn: this was not the most recently acquired lock
3283 }
3284
3285 lck_mtx_t lck1, lck2;
3286
3287 void test() {
3288 if (lck_mtx_try_lock(&lck1) == 0)
3289 return;
3290
3291 lck_mtx_lock(&lck2);
3292 lck_mtx_unlock(&lck1);
3293 // warn: this was not the most recently acquired lock
3294 }
3295
3296 .. _alpha-unix-SimpleStream:
3297
3298 alpha.unix.SimpleStream (C)
3299 """""""""""""""""""""""""""
3300 Check for misuses of stream APIs. Check for misuses of stream APIs: ``fopen, fclose``
3301 (demo checker, the subject of the demo (`Slides <https://llvm.org/devmtg/2012-11/Zaks-Rose-Checker24Hours.pdf>`_ ,
3302 `Video <https://youtu.be/kdxlsP5QVPw>`_) by Anna Zaks and Jordan Rose presented at the
3303 `2012 LLVM Developers' Meeting <https://llvm.org/devmtg/2012-11/>`_).
3304
3305 .. code-block:: c
3306
3307 void test() {
3308 FILE *F = fopen("myfile.txt", "w");
3309 } // warn: opened file is never closed
3310
3311 void test() {
3312 FILE *F = fopen("myfile.txt", "w");
3313
3314 if (F)
3315 fclose(F);
3316
3317 fclose(F); // warn: closing a previously closed file stream
3318 }
3319
3320 .. _alpha-unix-cstring-BufferOverlap:
3321
3322 alpha.unix.cstring.BufferOverlap (C)
3323 """"""""""""""""""""""""""""""""""""
3324 Checks for overlap in two buffer arguments. Applies to: ``memcpy, mempcpy, wmemcpy, wmempcpy``.
3325
3326 .. code-block:: c
3327
3328 void test() {
3329 int a[4] = {0};
3330 memcpy(a + 2, a + 1, 8); // warn
3331 }
3332
3333 .. _alpha-unix-cstring-NotNullTerminated:
3334
3335 alpha.unix.cstring.NotNullTerminated (C)
3336 """"""""""""""""""""""""""""""""""""""""
3337 Check for arguments which are not null-terminated strings; applies to: ``strlen, strnlen, strcpy, strncpy, strcat, strncat, wcslen, wcsnlen``.
3338
3339 .. code-block:: c
3340
3341 void test() {
3342 int y = strlen((char *)&test); // warn
3343 }
3344
3345 .. _alpha-unix-cstring-OutOfBounds:
3346
3347 alpha.unix.cstring.OutOfBounds (C)
3348 """"""""""""""""""""""""""""""""""
3349 Check for out-of-bounds access in string functions, such as:
3350 ``memcpy, bcopy, strcpy, strncpy, strcat, strncat, memmove, memcmp, memset`` and more.
3351
3352 This check also works with string literals, except there is a known bug in that
3353 the analyzer cannot detect embedded NULL characters when determining the string length.
3354
3355 .. code-block:: c
3356
3357 void test1() {
3358 const char str[] = "Hello world";
3359 char buffer[] = "Hello world";
3360 memcpy(buffer, str, sizeof(str) + 1); // warn
3361 }
3362
3363 void test2() {
3364 const char str[] = "Hello world";
3365 char buffer[] = "Helloworld";
3366 memcpy(buffer, str, sizeof(str)); // warn
3367 }
3368
3369 .. _alpha-unix-cstring-UninitializedRead:
3370
3371 alpha.unix.cstring.UninitializedRead (C)
3372 """"""""""""""""""""""""""""""""""""""""
3373 Check for uninitialized reads from common memory copy/manipulation functions such as:
3374 ``memcpy, mempcpy, memmove, memcmp, strcmp, strncmp, strcpy, strlen, strsep`` and many more.
3375
3376 .. code-block:: c
3377
3378 void test() {
3379 char src[10];
3380 char dst[5];
3381 memcpy(dst,src,sizeof(dst)); // warn: Bytes string function accesses uninitialized/garbage values
3382 }
3383
3384 Limitations:
3385
3386 - Due to limitations of the memory modeling in the analyzer, one can likely
3387 observe a lot of false-positive reports like this:
3388
3389 .. code-block:: c
3390
3391 void false_positive() {
3392 int src[] = {1, 2, 3, 4};
3393 int dst[5] = {0};
3394 memcpy(dst, src, 4 * sizeof(int)); // false-positive:
3395 // The 'src' buffer was correctly initialized, yet we cannot conclude
3396 // that since the analyzer could not see a direct initialization of the
3397 // very last byte of the source buffer.
3398 }
3399
3400 More details at the corresponding `GitHub issue <https://github.com/llvm/llvm-project/issues/43459>`_.
3401
3402 .. _alpha-nondeterminism-PointerIteration:
3403
3404 alpha.nondeterminism.PointerIteration (C++)
3405 """""""""""""""""""""""""""""""""""""""""""
3406 Check for non-determinism caused by iterating unordered containers of pointers.
3407
3408 .. code-block:: c
3409
3410 void test() {
3411 int a = 1, b = 2;
3412 std::unordered_set<int *> UnorderedPtrSet = {&a, &b};
3413
3414 for (auto i : UnorderedPtrSet) // warn
3415 f(i);
3416 }
3417
3418 .. _alpha-nondeterminism-PointerSorting:
3419
3420 alpha.nondeterminism.PointerSorting (C++)
3421 """""""""""""""""""""""""""""""""""""""""
3422 Check for non-determinism caused by sorting of pointers.
3423
3424 .. code-block:: c
3425
3426 void test() {
3427 int a = 1, b = 2;
3428 std::vector<int *> V = {&a, &b};
3429 std::sort(V.begin(), V.end()); // warn
3430 }
3431
3432
3433 alpha.WebKit
3434 ^^^^^^^^^^^^
3435
3436 .. _alpha-webkit-UncountedCallArgsChecker:
3437
3438 alpha.webkit.UncountedCallArgsChecker
3439 """""""""""""""""""""""""""""""""""""
3440 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.
3441
3442 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.
3443
3444 .. code-block:: cpp
3445
3446 RefCountable* provide_uncounted();
3447 void consume(RefCountable*);
3448
3449 // 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.
3450
3451 void foo1() {
3452 consume(provide_uncounted()); // warn
3453 }
3454
3455 void foo2() {
3456 RefCountable* uncounted = provide_uncounted();
3457 consume(uncounted); // warn
3458 }
3459
3460 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.
3461
3462 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.
3463
3464 .. code-block:: cpp
3465
3466 struct Foo {
3467 RefPtr<RefCountable> member;
3468 void consume(RefCountable*) { /* ... */ }
3469 void bugprone() {
3470 consume(member.get()); // warn
3471 }
3472 };
3473
3474 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.
3475
3476 Allowed kinds of arguments:
3477
3478 - values obtained from ref-counted objects (including temporaries as those survive the call too)
3479
3480 .. code-block:: cpp
3481
3482 RefCountable* provide_uncounted();
3483 void consume(RefCountable*);
3484
3485 void foo() {
3486 RefPtr<RefCountable> rc = makeRef(provide_uncounted());
3487 consume(rc.get()); // ok
3488 consume(makeRef(provide_uncounted()).get()); // ok
3489 }
3490
3491 - forwarding uncounted arguments from caller to callee
3492
3493 .. code-block:: cpp
3494
3495 void foo(RefCountable& a) {
3496 bar(a); // ok
3497 }
3498
3499 Caller of ``foo()`` is responsible for ``a``'s lifetime.
3500
3501 - ``this`` pointer
3502
3503 .. code-block:: cpp
3504
3505 void Foo::foo() {
3506 baz(this); // ok
3507 }
3508
3509 Caller of ``foo()`` is responsible for keeping the memory pointed to by ``this`` pointer safe.
3510
3511 - constants
3512
3513 .. code-block:: cpp
3514
3515 foo(nullptr, NULL, 0); // ok
3516
3517 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.
3518
3519 - constructors of ref-counted types (including factory methods)
3520 - getters of ref-counted types
3521 - member overloaded operators
3522 - casts
3523 - unary operators like ``&`` or ``*``
3524
3525 alpha.webkit.UncountedLocalVarsChecker
3526 """"""""""""""""""""""""""""""""""""""
3527 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.
3528
3529 These are examples of cases that we consider safe:
3530
3531 .. code-block:: cpp
3532
3533 void foo1() {
3534 RefPtr<RefCountable> counted;
3535 // The scope of uncounted is EMBEDDED in the scope of counted.
3536 {
3537 RefCountable* uncounted = counted.get(); // ok
3538 }
3539 }
3540
3541 void foo2(RefPtr<RefCountable> counted_param) {
3542 RefCountable* uncounted = counted_param.get(); // ok
3543 }
3544
3545 void FooClass::foo_method() {
3546 RefCountable* uncounted = this; // ok
3547 }
3548
3549 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.
3550
3551 .. code-block:: cpp
3552
3553 void foo1() {
3554 RefCountable* uncounted = new RefCountable; // warn
3555 }
3556
3557 RefCountable* global_uncounted;
3558 void foo2() {
3559 RefCountable* uncounted = global_uncounted; // warn
3560 }
3561
3562 void foo3() {
3563 RefPtr<RefCountable> counted;
3564 // The scope of uncounted is not EMBEDDED in the scope of counted.
3565 RefCountable* uncounted = counted.get(); // warn
3566 }
3567
3568 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:
3569 - variable defined in condition part of an ```if``` statement
3570 - variable defined in init statement condition of a ```for``` statement
3571
3572 For the time being we also don't warn about uninitialized uncounted local variables.
3573
3574 Debug Checkers
3575 ---------------
3576
3577 .. _debug-checkers:
3578
3579
3580 debug
3581 ^^^^^
3582
3583 Checkers used for debugging the analyzer.
3584 :doc:`developer-docs/DebugChecks` page contains a detailed description.
3585
3586 .. _debug-AnalysisOrder:
3587
3588 debug.AnalysisOrder
3589 """""""""""""""""""
3590 Print callbacks that are called during analysis in order.
3591
3592 .. _debug-ConfigDumper:
3593
3594 debug.ConfigDumper
3595 """"""""""""""""""
3596 Dump config table.
3597
3598 .. _debug-DumpCFG Display:
3599
3600 debug.DumpCFG Display
3601 """""""""""""""""""""
3602 Control-Flow Graphs.
3603
3604 .. _debug-DumpCallGraph:
3605
3606 debug.DumpCallGraph
3607 """""""""""""""""""
3608 Display Call Graph.
3609
3610 .. _debug-DumpCalls:
3611
3612 debug.DumpCalls
3613 """""""""""""""
3614 Print calls as they are traversed by the engine.
3615
3616 .. _debug-DumpDominators:
3617
3618 debug.DumpDominators
3619 """"""""""""""""""""
3620 Print the dominance tree for a given CFG.
3621
3622 .. _debug-DumpLiveVars:
3623
3624 debug.DumpLiveVars
3625 """"""""""""""""""
3626 Print results of live variable analysis.
3627
3628 .. _debug-DumpTraversal:
3629
3630 debug.DumpTraversal
3631 """""""""""""""""""
3632 Print branch conditions as they are traversed by the engine.
3633
3634 .. _debug-ExprInspection:
3635
3636 debug.ExprInspection
3637 """"""""""""""""""""
3638 Check the analyzer's understanding of expressions.
3639
3640 .. _debug-Stats:
3641
3642 debug.Stats
3643 """""""""""
3644 Emit warnings with analyzer statistics.
3645
3646 .. _debug-TaintTest:
3647
3648 debug.TaintTest
3649 """""""""""""""
3650 Mark tainted symbols as such.
3651
3652 .. _debug-ViewCFG:
3653
3654 debug.ViewCFG
3655 """""""""""""
3656 View Control-Flow Graphs using GraphViz.
3657
3658 .. _debug-ViewCallGraph:
3659
3660 debug.ViewCallGraph
3661 """""""""""""""""""
3662 View Call Graph using GraphViz.
3663
3664 .. _debug-ViewExplodedGraph:
3665
3666 debug.ViewExplodedGraph
3667 """""""""""""""""""""""
3668 View Exploded Graphs using GraphViz.