[Umbrella] Pointer cast representation problems.
| Bugzilla Link | 43364 |
| Version | trunk |
| OS | All |
| CC | @dkrupp,@devincoughlin |
Extended Description
An umbrella bug for figuring out how to fix our representation of pointer casts. The main problem with the current representation is that there are multiple ways of representing the same pointer, however there's no canonical way of representing a pointer, so different parts of the Analyzer are doing this differently and only accidentally work together more or less nicely.
Here are a few examples of how they don't really work together nicely:
(1) In http://lists.llvm.org/pipermail/cfe-dev/2019-September/063308.html we have two different symbolic values for the same actual pointer value, which wear different constraints after dereferencing:
reg_$1<int Element{SymRegion{reg_$0<const Item * items>},0 S64b,Item}->xxs>: { [-2147483648, 0] }
reg_$2<int SymRegion{reg_$0<const Item * items>}->xxs>: { [1, 2147483647] }
(2) Here's another example that's a bit more controversial due to strict aliasing violation, but still problematic and slightly more obvious:
typedef struct { int RetCode; } A;
typedef struct { int RetCode; } B;
int blah(A *param, int *x) { if (param->RetCode != 0) // reg_$1<SymRegion{reg_$0}->RetCode> return ((B *) param)->RetCode; // reg_$2{element{B, 0 S32b, SymRegion{reg_$0}->RetCore} *x = 1; return 0; }
int foo(A* param) { int x; if (blah(param, &x) != 0) { return 0; } return x; // false positive: "returning garbage value". }
Here we have in the following:
param->RetCode: reg_$1<SymRegion{reg_$0}->RetCode> ((B *) param)->RetCode: reg_$2{element{B, 0 S32b, SymRegion{reg_$0}->RetCore}
(3) The following bugs of this kind are already fixed in a non-principled manner:
https://reviews.llvm.org/D38797 https://reviews.llvm.org/D46224 https://reviews.llvm.org/D46415 https://reviews.llvm.org/D51191 https://reviews.llvm.org/D52189 https://reviews.llvm.org/D55875
(4) This is also a piece of technical debt that causes annoyance when writing new code:
https://reviews.llvm.org/D40939 https://reviews.llvm.org/D41250 https://reviews.llvm.org/D67079#inline-602514
assigned to @haoNoQ
#62663 is another problem related to uselessness of region types.
https://reviews.llvm.org/D150446 is also concerned about uselessness of ElementRegion for the purposes of array bound checking.
@haoNoQ I'm replying to your comment on D150446 where you introduced your plans as
I believe the ideal solution is to remove all non-base regions (ElementRegion, FieldRegion, CXXBaseObjectRegion, CXXDerivedObjectRegion) entirely, and instead represent all single-location values as (base region, offset) pairs (where offset can be an arbitrary SVal of appropriate numeric type), and represent regions as (base region, begin offset, end offset) triples.
So for example the
SymbolRegionValue{FieldRegion{VarRegion}}objectreg_$0<int var->field>would be turned into aSymbolRegionValue{VarRegion, Offset}objectreg_$0<int var @+32>where 32 is the bit offset of field field in the struct. We could preserve the end offset here as well, but the int part already tells us that it's 64 or something like that.
I really like that this canonical representation would significantly improve the the handling of regions (comparing them, reasoning about the stored value etc.), but I fear that perhaps it'd be difficult to use this representation when we're creating the error messages.
For example, the current system can report things like "invalid value taken from obj.member[3].submember" (if e.g. we're analyzing complicated object-oriented code), while a message like "invalid value taken from int obj @+224" would be almost useless for a human reader (decoding it may require understanding the memory layout of several classes).
How would you handle these questions? Would you pass around both kinds of representations ("this region was reached as obj.member[3].submember and it's canonical representation is {obj, +224}") or would you prefer a system where the core engine only knows the canonical base+offset representations and the user-friendly name is reconstructed by a "frontend" layer afterwards?
Would you pass around both kinds of representations ("this region was reached as
obj.member[3].submemberand it's canonical representation is{obj, +224}") or would you prefer a system where the core engine only knows the canonical base+offset representations and the user-friendly name is reconstructed by a "frontend" layer afterwards?
I think "reconstructing" is better, even regardless of the engine's internal MemRegion representation! There could also be different approaches to "reconstructing", depending on what exactly you're reconstructing.
If you want to explain to the user how a given pointer end up pointing to a given location on the current path, introspecting the MemRegion structure isn't the ideal solution for that anyway. Yes MemRegion carries some memory of how the location was computed. But a good bug report typically tells the user not only "this is how it was computed", but also "this is where it was computed". Which usually means path notes.
For example:
void foo() {
Struct obj { ... };
// (1) path note: Object 'obj' is allocated
SubStruct &subobj = bar(&obj, 3);
// (2) path note: Passing pointer to variable 'obj' as parameter 'ptr'
// which now points into 'obj' at offset +0
// (3) path note: Passing value 3 through parameter 'idx'
// which participates in offset calculation later
// (5) path note: Return value bound to reference 'subobj'
// which now points into variable 'obj' at offset +216
int x = subobj.submember;
// (6) warning: Access to field 'subobj.submember' leads to invalid read
// from variable 'obj' at offset +224
...
}
SubStruct &bar(Struct *ptr, size_t idx) {
return ptr->member[idx];
// (4) path note: Returning a reference to array element 'ptr->member[3]',
// which points into 'obj' at offset +216
}
In the general case, without such notes, the user won't be able to understand why we think that the pointer points to obj.member[3].submember on the current path. The notes need to be there, and essential stack frames such as bar() should never be "pruned" from it. But once you have these notes, the user pretty much has all the information they need to reason about the pointer value. And you don't need to introspect the MemRegion's internal representation in order to deliver these notes. Instead, you tie your notes to something much more tangible: the source code that participated in computing it!
Is it still desirable to combine field submember and object 'obj' at offset +224 in the final warning into the fancier object 'obj.member[3].submember'? Maybe. Is it strictly necessary? Probably not. Path notes were definitely strictly necessary, and once they're there, they allow the user to reconstruct the chain of operations that led to offset +224. And even though it's hard to tell without seeing the actual checker, I suspect that the specific operation chain isn't the actual problem you're trying to warn the user about. it's much more likely that any read from offset +224 is invalid, no matter how the offset was computed. Because these operation chains are usually immaterial at runtime; the runtime behavior relies entirely on offset values. So I'm arguing that it's better for the static analyzer to deal with offset values as well.
Another thing you might want to reconstruct, is the actual layout of the object that the pointer value represents. For example, you may be trying to warn the user that the offset +224 doesn't actually correspond to a 32-bit integer field in obj; so you want to demonstrate that offset +224 actually points into the middle of a 64-bit pointer stored at offset +220.
For this purpose, again, the internal structure of MemRegion is irrelevant, as it captures the layout assumed by the programmer, as opposed to the actual layout that contradicts the programmer's assumptions.
In such cases you can't really do anything better than actually introspecting ASTRecordLayout and printing out the relevant bits and pieces to the user. So it probably has to be a non-path note (scan-build's blue bubble):
void foo() {
Struct obj { ... };
// (1) path note: Object 'obj' is allocated
Struct2 *ptr = bar(&obj);
// (2) path note: Passing pointer to variable 'obj' as parameter 'param'
// which now points into 'obj' at offset +0
// (4) path note: Return value stored in pointer 'ptr'
// which now points into variable 'obj' at offset +0
SubStruct &subobj = ptr->member[3];
// (5) path note: Reference 'subobj' refers to array element 'ptr->member[3]'
// located inside variable 'obj' at offset +216
int x = ptr->submember;
// (6) warning: Access to field 'subobj.submember' leads to invalid read
// from variable 'obj' at offset +224
// (7) NON-path note: Offset +224 into 'obj' corresponds to
// offset +4 into 'obj.completely_different.ptr_field' (!!!)
}
Struct2 *bar(Struct *param) {
return reinterpret_cast<Struct2 *>(param);
// (3) path note: Reinterpreting pointer into 'obj' at offset 0
// as a pointer to an object of type 'Struct 2'
// with incompatible layout (!!!)
}
So we will probably eventually build a converter from offsets to fancy field chains, in order to build checkers of that second kind. Then if we decide that it's actually a good idea for user-friendliness, we can plug it into checkers of the first kind. In our first example this may result in a similar non-path note:
// (7) NON-path note: Offset +224 into 'obj' corresponds to
// field 'obj.member[3].submember'
This will have the benefit of describing the actual layout, no matter how weirdly the offset was computed in the code.
Such ASTRecordLayout-based field chain reconstruction procedure obviously struggles with unions and other forms of type punning / storage reuse. But, again, the structure of MemRegion isn't the right solution for dealing with them; instead, dynamic type information in the ProgramState needs to be consulted in order to figure out what object is currently stored at that location. Which may change throughout the path, so it can't be recorded as part of something immutable such as the identity of MemRegion. Currently dynamic type information doesn't actually track runtime interpretation of unions, and maybe it's better to build a different data structure for this purpose than to reuse the dynamic type infrastructure, but one way or another it has to be a state trait that should be allowed to mutate.
So ultimately, the only situation in which MemRegion's internal representation matters is when you're trying to reason about the storage, aka the origins, of the object.
It makes perfect sense to have the checker act differently when the region has symbolic base, as opposed to "concrete" base such as a stack variable. It makes sense to call SymExpr::getOriginRegion() in order to find out if the symbol represents the initial value of a location of a certain kind (eg. value of a function parameter we've received at the entry point of our analysis).
But all of that logic only cares about the base region, not about how the offsets inside it are computed. So when you're representing pointers as (base region, offset) pairs, you aren't really losing anything.
@haoNoQ As I resumed my work on ArrayBoundsCheckerV2, I thought about these problems again and discussed them with my colleagues. It seems that our team could allocate significant capacity (very rough estimate: 1 developer-year) to this issue if there are actionable plans for improving the situation.
In your opinion, where does this issue fall on the scale between "we only know that it's bad" and "we know what to do"? Could you draft a rough roadmap for replacing the current MemRegion architecture with something better? What are the most important questions or potential pitfalls that we need to be aware of?
(I also have my own ideas for improving this situation, but as you have a deeper understanding of the situation I'd guess that you already thought of something similar to them.)