InitializerLists.rst 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321
  1. This discussion took place in https://reviews.llvm.org/D35216
  2. "Escape symbols when creating std::initializer_list".
  3. It touches problems of modelling C++ standard library constructs in general,
  4. including modelling implementation-defined fields within C++ standard library
  5. objects, in particular constructing objects into pointers held by such fields,
  6. and separation of responsibilities between analyzer's core and checkers.
  7. **Artem:**
  8. I've seen a few false positives that appear because we construct
  9. C++11 std::initializer_list objects with brace initializers, and such
  10. construction is not properly modeled. For instance, if a new object is
  11. constructed on the heap only to be put into a brace-initialized STL container,
  12. the object is reported to be leaked.
  13. Approach (0): This can be trivially fixed by this patch, which causes pointers
  14. passed into initializer list expressions to immediately escape.
  15. This fix is overly conservative though. So i did a bit of investigation as to
  16. how model std::initializer_list better.
  17. According to the standard, std::initializer_list<T> is an object that has
  18. methods begin(), end(), and size(), where begin() returns a pointer to continous
  19. array of size() objects of type T, and end() is equal to begin() plus size().
  20. The standard does hint that it should be possible to implement
  21. std::initializer_list<T> as a pair of pointers, or as a pointer and a size
  22. integer, however specific fields that the object would contain are an
  23. implementation detail.
  24. Ideally, we should be able to model the initializer list's methods precisely.
  25. Or, at least, it should be possible to explain to the analyzer that the list
  26. somehow "takes hold" of the values put into it. Initializer lists can also be
  27. copied, which is a separate story that i'm not trying to address here.
  28. The obvious approach to modeling std::initializer_list in a checker would be to
  29. construct a SymbolMetadata for the memory region of the initializer list object,
  30. which would be of type T* and represent begin(), so we'd trivially model begin()
  31. as a function that returns this symbol. The array pointed to by that symbol
  32. would be bindLoc()ed to contain the list's contents (probably as a CompoundVal
  33. to produce less bindings in the store). Extent of this array would represent
  34. size() and would be equal to the length of the list as written.
  35. So this sounds good, however apparently it does nothing to address our false
  36. positives: when the list escapes, our RegionStoreManager is not magically
  37. guessing that the metadata symbol attached to it, together with its contents,
  38. should also escape. In fact, it's impossible to trigger a pointer escape from
  39. within the checker.
  40. Approach (1): If only we enabled ProgramState::bindLoc(..., notifyChanges=true)
  41. to cause pointer escapes (not only region changes) (which sounds like the right
  42. thing to do anyway) such checker would be able to solve the false positives by
  43. triggering escapes when binding list elements to the list. However, it'd be as
  44. conservative as the current patch's solution. Ideally, we do not want escapes to
  45. happen so early. Instead, we'd prefer them to be delayed until the list itself
  46. escapes.
  47. So i believe that escaping metadata symbols whenever their base regions escape
  48. would be the right thing to do. Currently we didn't think about that because we
  49. had neither pointer-type metadatas nor non-pointer escapes.
  50. Approach (2): We could teach the Store to scan itself for bindings to
  51. metadata-symbolic-based regions during scanReachableSymbols() whenever a region
  52. turns out to be reachable. This requires no work on checker side, but it sounds
  53. performance-heavy.
  54. Approach (3): We could let checkers maintain the set of active metadata symbols
  55. in the program state (ideally somewhere in the Store, which sounds weird but
  56. causes the smallest amount of layering violations), so that the core knew what
  57. to escape. This puts a stress on the checkers, but with a smart data map it
  58. wouldn't be a problem.
  59. Approach (4): We could allow checkers to trigger pointer escapes in arbitrary
  60. moments. If we allow doing this within checkPointerEscape callback itself, we
  61. would be able to express facts like "when this region escapes, that metadata
  62. symbol attached to it should also escape". This sounds like an ultimate freedom,
  63. with maximum stress on the checkers - still not too much stress when we have
  64. smart data maps.
  65. I'm personally liking the approach (2) - it should be possible to avoid
  66. performance overhead, and clarity seems nice.
  67. **Gabor:**
  68. At this point, I am a bit wondering about two questions.
  69. - When should something belong to a checker and when should something belong
  70. to the engine? Sometimes we model library aspects in the engine and model
  71. language constructs in checkers.
  72. - What is the checker programming model that we are aiming for? Maximum
  73. freedom or more easy checker development?
  74. I think if we aim for maximum freedom, we do not need to worry about the
  75. potential stress on checkers, and we can introduce abstractions to mitigate that
  76. later on.
  77. If we want to simplify the API, then maybe it makes more sense to move language
  78. construct modeling to the engine when the checker API is not sufficient instead
  79. of complicating the API.
  80. Right now I have no preference or objections between the alternatives but there
  81. are some random thoughts:
  82. - Maybe it would be great to have a guideline how to evolve the analyzer and
  83. follow it, so it can help us to decide in similar situations
  84. - I do care about performance in this case. The reason is that we have a
  85. limited performance budget. And I think we should not expect most of the checker
  86. writers to add modeling of language constructs. So, in my opinion, it is ok to
  87. have less nice/more verbose API for language modeling if we can have better
  88. performance this way, since it only needs to be done once, and is done by the
  89. framework developers.
  90. **Artem:** These are some great questions, i guess it'd be better to discuss
  91. them more openly. As a quick dump of my current mood:
  92. - To me it seems obvious that we need to aim for a checker API that is both
  93. simple and powerful. This can probably by keeping the API as powerful as
  94. necessary while providing a layer of simple ready-made solutions on top of it.
  95. Probably a few reusable components for assembling checkers. And this layer
  96. should ideally be pleasant enough to work with, so that people would prefer to
  97. extend it when something is lacking, instead of falling back to the complex
  98. omnipotent API. I'm thinking of AST matchers vs. AST visitors as a roughly
  99. similar situation: matchers are not omnipotent, but they're so nice.
  100. - Separation between core and checkers is usually quite strange. Once we have
  101. shared state traits, i generally wouldn't mind having region store or range
  102. constraint manager as checkers (though it's probably not worth it to transform
  103. them - just a mood). The main thing to avoid here would be the situation when
  104. the checker overwrites stuff written by the core because it thinks it has a
  105. better idea what's going on, so the core should provide a good default behavior.
  106. - Yeah, i totally care about performance as well, and if i try to implement
  107. approach, i'd make sure it's good.
  108. **Artem:**
  109. > Approach (2): We could teach the Store to scan itself for bindings to
  110. > metadata-symbolic-based regions during scanReachableSymbols() whenever
  111. > a region turns out to be reachable. This requires no work on checker side,
  112. > but it sounds performance-heavy.
  113. Nope, this approach is wrong. Metadata symbols may become out-of-date: when the
  114. object changes, metadata symbols attached to it aren't changing (because symbols
  115. simply don't change). The same metadata may have different symbols to denote its
  116. value in different moments of time, but at most one of them represents the
  117. actual metadata value. So we'd be escaping more stuff than necessary.
  118. If only we had "ghost fields"
  119. (http://lists.llvm.org/pipermail/cfe-dev/2016-May/049000.html), it would have
  120. been much easier, because the ghost field would only contain the actual
  121. metadata, and the Store would always know about it. This example adds to my
  122. belief that ghost fields are exactly what we need for most C++ checkers.
  123. **Devin:**
  124. In this case, I would be fine with some sort of
  125. AbstractStorageMemoryRegion that meant "here is a memory region and somewhere
  126. reachable from here exists another region of type T". Or even multiple regions
  127. with different identifiers. This wouldn't specify how the memory is reachable,
  128. but it would allow for transfer functions to get at those regions and it would
  129. allow for invalidation.
  130. For std::initializer_list this reachable region would the region for the backing
  131. array and the transfer functions for begin() and end() yield the beginning and
  132. end element regions for it.
  133. In my view this differs from ghost variables in that (1) this storage does
  134. actually exist (it is just a library implementation detail where that storage
  135. lives) and (2) it is perfectly valid for a pointer into that storage to be
  136. returned and for another part of the program to read or write from that storage.
  137. (Well, in this case just read since it is allowed to be read-only memory).
  138. What I'm not OK with is modeling abstract analysis state (for example, the count
  139. of a NSMutableArray or the typestate of a file handle) as a value stored in some
  140. ginned up region in the store. This takes an easy problem that the analyzer does
  141. well at (modeling typestate) and turns it into a hard one that the analyzer is
  142. bad at (reasoning about the contents of the heap).
  143. I think the key criterion here is: "is the region accessible from outside the
  144. library". That is, does the library expose the region as a pointer that can be
  145. read to or written from in the client program? If so, then it makes sense for
  146. this to be in the store: we are modeling reachable storage as storage. But if
  147. we're just modeling arbitrary analysis facts that need to be invalidated when a
  148. pointer escapes then we shouldn't try to gin up storage for them just to get
  149. invalidation for free.
  150. **Artem:**
  151. > In this case, I would be fine with some sort of AbstractStorageMemoryRegion
  152. > that meant "here is a memory region and somewhere reachable from here exists
  153. > another region of type T". Or even multiple regions with different
  154. > identifiers. This wouldn't specify how the memory is reachable, but it would
  155. > allow for transfer functions to get at those regions and it would allow for
  156. > invalidation.
  157. Yeah, this is what we can easily implement now as a
  158. symbolic-region-based-on-a-metadata-symbol (though we can make a new region
  159. class for that if we eg. want it typed). The problem is that the relation
  160. between such storage region and its parent object region is essentially
  161. immaterial, similarly to the relation between SymbolRegionValue and its parent
  162. region. Region contents are mutable: today the abstract storage is reachable
  163. from its parent object, tomorrow it's not, and maybe something else becomes
  164. reachable, something that isn't even abstract. So the parent region for the
  165. abstract storage is most of the time at best a "nice to know" thing - we cannot
  166. rely on it to do any actual work. We'd anyway need to rely on the checker to do
  167. the job.
  168. > For std::initializer_list this reachable region would the region for the
  169. > backing array and the transfer functions for begin() and end() yield the
  170. > beginning and end element regions for it.
  171. So maybe in fact for std::initializer_list it may work fine because you cannot
  172. change the data after the object is constructed - so this region's contents are
  173. essentially immutable. For the future, i feel as if it is a dead end.
  174. I'd like to consider another funny example. Suppose we're trying to model
  175. std::unique_ptr. Consider::
  176. void bar(const std::unique_ptr<int> &x);
  177. void foo(std::unique_ptr<int> &x) {
  178. int *a = x.get(); // (a, 0, direct): &AbstractStorageRegion
  179. *a = 1; // (AbstractStorageRegion, 0, direct): 1 S32b
  180. int *b = new int;
  181. *b = 2; // (SymRegion{conj_$0<int *>}, 0 ,direct): 2 S32b
  182. x.reset(b); // Checker map: x -> SymRegion{conj_$0<int *>}
  183. bar(x); // 'a' doesn't escape (the pointer was unique), 'b' does.
  184. clang_analyzer_eval(*a == 1); // Making this true is up to the checker.
  185. clang_analyzer_eval(*b == 2); // Making this unknown is up to the checker.
  186. }
  187. The checker doesn't totally need to ensure that *a == 1 passes - even though the
  188. pointer was unique, it could theoretically have .get()-ed above and the code
  189. could of course break the uniqueness invariant (though we'd probably want it).
  190. The checker can say that "even if *a did escape, it was not because it was
  191. stuffed directly into bar()".
  192. The checker's direct responsibility, however, is to solve the *b == 2 thing
  193. (which is in fact the problem we're dealing with in this patch - escaping the
  194. storage region of the object).
  195. So we're talking about one more operation over the program state (scanning
  196. reachable symbols and regions) that cannot work without checker support.
  197. We can probably add a new callback "checkReachableSymbols" to solve this. This
  198. is in fact also related to the dead symbols problem (we're scanning for live
  199. symbols in the store and in the checkers separately, but we need to do so
  200. simultaneously with a single worklist). Hmm, in fact this sounds like a good
  201. idea; we can replace checkLiveSymbols with checkReachableSymbols.
  202. Or we could just have ghost member variables, and no checker support required at
  203. all. For ghost member variables, the relation with their parent region (which
  204. would be their superregion) is actually useful, the mutability of their contents
  205. is expressed naturally, and the store automagically sees reachable symbols, live
  206. symbols, escapes, invalidations, whatever.
  207. > In my view this differs from ghost variables in that (1) this storage does
  208. > actually exist (it is just a library implementation detail where that storage
  209. > lives) and (2) it is perfectly valid for a pointer into that storage to be
  210. > returned and for another part of the program to read or write from that
  211. > storage. (Well, in this case just read since it is allowed to be read-only
  212. > memory).
  213. > What I'm not OK with is modeling abstract analysis state (for example, the
  214. > count of a NSMutableArray or the typestate of a file handle) as a value stored
  215. > in some ginned up region in the store.This takes an easy problem that the
  216. > analyzer does well at (modeling typestate) and turns it into a hard one that
  217. > the analyzer is bad at (reasoning about the contents of the heap).
  218. Yeah, i tend to agree on that. For simple typestates, this is probably an
  219. overkill, so let's definitely put aside the idea of "ghost symbolic regions"
  220. that i had earlier.
  221. But, to summarize a bit, in our current case, however, the typestate we're
  222. looking for is the contents of the heap. And when we try to model such
  223. typestates (complex in this specific manner, i.e. heap-like) in any checker, we
  224. have a choice between re-doing this modeling in every such checker (which is
  225. something analyzer is indeed good at, but at a price of making checkers heavy)
  226. or instead relying on the Store to do exactly what it's designed to do.
  227. > I think the key criterion here is: "is the region accessible from outside
  228. > the library". That is, does the library expose the region as a pointer that
  229. > can be read to or written from in the client program? If so, then it makes
  230. > sense for this to be in the store: we are modeling reachable storage as
  231. > storage. But if we're just modeling arbitrary analysis facts that need to be
  232. > invalidated when a pointer escapes then we shouldn't try to gin up storage
  233. > for them just to get invalidation for free.
  234. As a metaphor, i'd probably compare it to body farms - the difference between
  235. ghost member variables and metadata symbols seems to me like the difference
  236. between body farms and evalCall. Both are nice to have, and body farms are very
  237. pleasant to work with, even if not omnipotent. I think it's fine for a
  238. FunctionDecl's body in a body farm to have a local variable, even if such
  239. variable doesn't actually exist, even if it cannot be seen from outside the
  240. function call. I'm not seeing immediate practical difference between "it does
  241. actually exist" and "it doesn't actually exist, just a handy abstraction".
  242. Similarly, i think it's fine if we have a CXXRecordDecl with
  243. implementation-defined contents, and try to farm up a member variable as a handy
  244. abstraction (we don't even need to know its name or offset, only that it's there
  245. somewhere).
  246. **Artem:**
  247. We've discussed it in person with Devin, and he provided more points to think
  248. about:
  249. - If the initializer list consists of non-POD data, constructors of list's
  250. objects need to take the sub-region of the list's region as this-region In the
  251. current (v2) version of this patch, these objects are constructed elsewhere and
  252. then trivial-copied into the list's metadata pointer region, which may be
  253. incorrect. This is our overall problem with C++ constructors, which manifests in
  254. this case as well. Additionally, objects would need to be constructed in the
  255. analyzer's core, which would not be able to predict that it needs to take a
  256. checker-specific region as this-region, which makes it harder, though it might
  257. be mitigated by sharing the checker state traits.
  258. - Because "ghost variables" are not material to the user, we need to somehow
  259. make super sure that they don't make it into the diagnostic messages.
  260. So, because this needs further digging into overall C++ support and rises too
  261. many questions, i'm delaying a better approach to this problem and will fall
  262. back to the original trivial patch.