Debian Codegraph @

clang/docs/analyzer/user-docs/FAQ.rst

raw
1 FAQ and How to Deal with Common False Positives
2 ===============================================
3
4 .. contents::
5 :local:
6
7 Custom Assertions
8 -----------------
9
10 Q: How do I tell the analyzer that I do not want the bug being reported here since my custom error handler will safely end the execution before the bug is reached?
11
12 .. image:: ../images/example_custom_assert.png
13
14 You can tell the analyzer that this path is unreachable by teaching it about your `custom assertion handlers <Annotations.html#custom-assertion-handlers>`__. For example, you can modify the code segment as following:
15
16 .. code-block:: c
17
18 void customAssert() __attribute__((analyzer_noreturn));
19 int foo(int *b) {
20 if (!b)
21 customAssert();
22 return *b;
23 }
24
25 Null Pointer Dereference
26 ------------------------
27
28 Q: The analyzer reports a null dereference, but I know that the pointer is never null. How can I tell the analyzer that a pointer can never be null?
29
30 .. image:: ../images/example_null_pointer.png
31
32 The reason the analyzer often thinks that a pointer can be null is because the preceding code checked compared it against null. If you are absolutely sure that it cannot be null, remove the preceding check and, preferably, add an assertion as well. For example:
33
34 .. code-block:: c
35
36 void usePointer(int *b);
37 int foo(int *b) {
38 usePointer(b);
39 return *b;
40 }
41
42 Dead Store
43 ----------
44
45 Q: How do I tell the static analyzer that I don't care about a specific dead store?
46
47 When the analyzer sees that a value stored into a variable is never used, it's going to produce a message similar to this one:
48
49 .. code-block:: none
50
51 Value stored to 'x' is never read
52
53 You can use the ``(void)x;`` idiom to acknowledge that there is a dead store in your code but you do not want it to be reported in the future.
54
55 Unused Instance Variable
56 ------------------------
57
58 Q: How do I tell the static analyzer that I don't care about a specific unused instance variable in Objective-C?
59
60 When the analyzer sees that a value stored into a variable is never used, it is going to produce a message similar to this one:
61
62 .. code-block:: none
63
64 Instance variable 'commonName' in class 'HappyBird' is never used by the methods in its @implementation
65
66 You can add ``__attribute__((unused))`` to the instance variable declaration to suppress the warning.
67
68 Unlocalized String
69 ------------------
70
71 Q: How do I tell the static analyzer that I don't care about a specific unlocalized string?
72
73 When the analyzer sees that an unlocalized string is passed to a method that will present that string to the user, it is going to produce a message similar to this one:
74
75 .. code-block:: none
76
77 User-facing text should use localized string macro
78
79 If your project deliberately uses unlocalized user-facing strings (for example, in a debugging UI that is never shown to users), you can suppress the analyzer warnings (and document your intent) with a function that just returns its input but is annotated to return a localized string:
80
81 .. code-block:: objc
82
83 __attribute__((annotate("returns_localized_nsstring")))
84 static inline NSString *LocalizationNotNeeded(NSString *s) {
85 return s;
86 }
87
88 You can then call this function when creating your debugging UI:
89
90 .. code-block:: objc
91
92 [field setStringValue:LocalizationNotNeeded(@"Debug")];
93
94 Some projects may also find it useful to use NSLocalizedString but add "DNL" or "Do Not Localize" to the string contents as a convention:
95
96 .. code-block:: objc
97
98 UILabel *testLabel = [[UILabel alloc] init];
99 NSString *s = NSLocalizedString(@"Hello <Do Not Localize>", @"For debug purposes");
100 [testLabel setText:s];
101
102 Dealloc in Manual Retain/Release
103 --------------------------------
104
105 Q: How do I tell the analyzer that my instance variable does not need to be released in -dealloc under Manual Retain/Release?
106
107 If your class only uses an instance variable for part of its lifetime, it may maintain an invariant guaranteeing that the instance variable is always released before -dealloc. In this case, you can silence a warning about a missing release by either adding ``assert(_ivar == nil)`` or an explicit release ``[_ivar release]`` (which will be a no-op when the variable is nil) in -dealloc.
108
109 Deciding Nullability
110 --------------------
111
112 Q: How do I decide whether a method's return type should be _Nullable or _Nonnull?
113
114 Depending on the implementation of the method, this puts you in one of five situations:
115
116 1. You actually never return nil.
117 2. You do return nil sometimes, and callers are supposed to handle that. This includes cases where your method is documented to return nil given certain inputs.
118 3. You return nil based on some external condition (such as an out-of-memory error), but the client can't do anything about it either.
119 4. You return nil only when the caller passes input documented to be invalid. That means it's the client's fault.
120 5. You return nil in some totally undocumented case.
121
122 In (1) you should annotate the method as returning a ``_Nonnull`` object.
123
124 In (2) the method should be marked ``_Nullable``.
125
126 In (3) you should probably annotate the method ``_Nonnull``. Why? Because no callers will actually check for nil, given that they can't do anything about the situation and don't know what went wrong. At this point things have gone so poorly that there's basically no way to recover.
127
128 The least happy case is (4) because the resulting program will almost certainly either crash or just silently do the wrong thing. If this is a new method or you control the callers, you can use ``NSParameterAssert()`` (or the equivalent) to check the precondition and remove the nil return. But if you don't control the callers and they rely on this behavior, you should return mark the method ``_Nonnull`` and return nil cast to _Nonnull anyway.
129
130 If you're in (5), document it, then figure out if you're now in (2), (3), or (4).
131
132 Intentional Nullability Violation
133 ---------------------------------
134
135 Q: How do I tell the analyzer that I am intentionally violating nullability?
136
137 In some cases, it may make sense for methods to intentionally violate nullability. For example, your method may — for reasons of backward compatibility — chose to return nil and log an error message in a method with a non-null return type when the client violated a documented precondition rather than check the precondition with ``NSAssert()``. In these cases, you can suppress the analyzer warning with a cast:
138
139 .. code-block:: objc
140
141 return (id _Nonnull)nil;
142
143 Note that this cast does not affect code generation.
144
145 Ensuring Loop Body Execution
146 ----------------------------
147
148 Q: The analyzer assumes that a loop body is never entered. How can I tell it that the loop body will be entered at least once?
149
150 .. image:: ../images/example_use_assert.png
151
152 In cases where you know that a loop will always be entered at least once, you can use assertions to inform the analyzer. For example:
153
154 .. code-block:: c
155
156 int foo(int length) {
157 int x = 0;
158 assert(length > 0);
159 for (int i = 0; i < length; i++)
160 x += 1;
161 return length/x;
162 }
163
164 By adding ``assert(length > 0)`` in the beginning of the function, you tell the analyzer that your code is never expecting a zero or a negative value, so it won't need to test the correctness of those paths.
165
166 Suppressing Specific Warnings
167 -----------------------------
168
169 Q: How can I suppress a specific analyzer warning?
170
171 When you encounter an analyzer bug/false positive, check if it's one of the issues discussed above or if the analyzer `annotations <Annotations.html#custom-assertion-handlers>`__ can resolve the issue by helping the static analyzer understand the code better. Second, please `report it <FilingBugs.html>`_ to help us improve user experience.
172
173 Sometimes there's really no "good" way to eliminate the issue. In such cases you can "silence" it directly by annotating the problematic line of code with the help of Clang attribute 'suppress':
174
175 .. code-block:: c
176
177 int foo() {
178 int *x = nullptr;
179 ...
180 [[clang::suppress]] {
181 // all warnings in this scope are suppressed
182 int y = *x;
183 }
184
185 // null pointer dereference warning suppressed on the next line
186 [[clang::suppress]]
187 return *x
188 }
189
190 int bar(bool coin_flip) {
191 // suppress all memory leak warnings about this allocation
192 [[clang::suppress]]
193 int *result = (int *)malloc(sizeof(int));
194
195 if (coin_flip)
196 return 0; // including this leak path
197
198 return *result; // as well as this leak path
199 }
200
201 .. _exclude_code:
202
203 Excluding Code from Analysis
204 ----------------------------
205
206 Q: How can I selectively exclude code the analyzer examines?
207
208 When the static analyzer is using clang to parse source files, it implicitly defines the preprocessor macro ``__clang_analyzer__``. One can use this macro to selectively exclude code the analyzer examines. Here is an example:
209
210 .. code-block:: c
211
212 #ifndef __clang_analyzer__
213 // Code not to be analyzed
214 #endif
215
216 This usage is discouraged because it makes the code dead to the analyzer from now on. Instead, we prefer that users file bugs against the analyzer when it flags false positives.