I think I am right.
At this point we have "count" elements in the array.
That means the last element in the array is at arr[count - 1].
We want to make room for the new element at index, so we move
all the elements from index to index + 1.
The first element we should move is arr[count - 1] to arr[count].
But the code moved arr[count] to arr [count + 1].
This move is not needed.
We currently have count elements in the
array, so we cannot normally access the element *at* count. However, we
are extending the array right now, therefore we can assign (store) the
element at count (and then we'll increment count later). But accessing
an element at (count+1) is wrong.
@@ -833,7 +833,6 @@ void *fw_cfg_modify_file(FWCfgState *s, const
char *filename,
assert(s->files);
index = be32_to_cpu(s->files->count);
- assert(index < fw_cfg_file_slots(s));
for (i = 0; i < index; i++) {
if (strcmp(filename, s->files->f[i].name) == 0) {
@@ -843,6 +842,9 @@ void *fw_cfg_modify_file(FWCfgState *s, const
char *filename,
return ptr;
}
}
+
+ assert(index < fw_cfg_file_slots(s));
+
/* add new one */
fw_cfg_add_file_callback(s, filename, NULL, NULL, NULL, data,
len, true);
return NULL;
I think I agree with Marc-André here, when I say, replace the assert
with a comment instead? (About the fact that fw_cfg_add_file_callback()
will assert(), *if* we reach that far.)
Hmm, what should we add to the comment? "We lost, brace for impact :)"
My point, if we are going to abort, let's abort as early as we can.
But if is a consensus, I'll get rid of it.
No, it's going to be another assert, just later. Assume that at this
point we have (index == fw_cfg_file_slots(s)), because the function
didn't find the element to modify, so it decides to add a new one, but
also we do not have room for the new one. So, with the suggested removal
of the assert, we call fw_cfg_add_file_callback().
Then, fw_cfg_add_file_callback() does:
if (!s->files) {
dsize = sizeof(uint32_t) + sizeof(FWCfgFile) * fw_cfg_file_slots(s);
s->files = g_malloc0(dsize);
fw_cfg_add_bytes(s, FW_CFG_FILE_DIR, s->files, dsize);
}
count = be32_to_cpu(s->files->count);
assert(count < fw_cfg_file_slots(s));
The (!s->files) condition is expected to eval to false (our table is
full, so we do have a table).
And then, the assert() below the "if" will fire.
Am I missing something?