Removing set from itself causes invalid iterator
Found during LLM vuln scanning, but it's not a security issue.
The following program gives some surprising output:
event zeek_init()
{
local s: set[count] = {1,2,3,4};
s -= s;
print |s|;
print s;
}Output:
$ zeek test.zeek
internal warning: Dictionary::Remove() possibly caused iterator invalidation
internal warning: Dictionary::Remove() possibly caused iterator invalidation
internal warning: Dictionary::Remove() possibly caused iterator invalidation
1
{
1
}Since we're removing s from s, removing each element also invalidates the iterator (so since there are 4 elements, the first one removes cleanly, then the remaining 3 are using the invalid iterator). This causes there to be a remaining element as well.
looks like the removal happens here:
https://github.com/zeek/zeek/blob/698b854a630509c600e090f7947a6929df3ab466/src/Val.cc#L1933-L1957
I would expect s -= s to empty the set.
Perhaps we could even special-case that, then we avoid the snapshot altogether. Essentially if we're removing the same set from itself we just clear it.
The LLM gave the following options for a patch, I think special-casing the s -= s case would be nice but leaving this here in case it doesn't work. Use your own judgement:
In
Val.cc, snapshot the keys before removing whenthis == val->AsTableVal(), or build the set difference into a temporary table and then replace the destination.
if ( t == this ) {
std::vector<detail::HashKey> keys;
for ( const auto& tble : *table_val )
keys.emplace_back(*tble.GetHashKey());
for ( const auto& k : keys )
t->Remove(k);
return true;
}Source: zeek/zeek