Question about memory allocation in btree_paths_realloc
Dear BCACHEFS maintainers,
We encountered an unusual usage of kzalloc in btree_paths_realloc while performing a static analysis for kernel code.
https://elixir.bootlin.com/linux/latest/source/fs/bcachefs/btree_iter.c#L1523
```
static noinline void btree_paths_realloc(struct btree_trans *trans)
{
unsigned nr = trans->nr_paths * 2;
void *p = kzalloc(BITS_TO_LONGS(nr) * sizeof(unsigned long) +
sizeof(struct btree_trans_paths) +
nr * sizeof(struct btree_path) +
nr * sizeof(btree_path_idx_t) + 8 +
nr * sizeof(struct btree_insert_entry), GFP_KERNEL|__GFP_NOFAIL);
unsigned long *paths_allocated = p;
memcpy(paths_allocated, trans->paths_allocated,
BITS_TO_LONGS(trans->nr_paths) * sizeof(unsigned long));
...
}
```Here kzalloc might return NULL in case of out-of-memory, making memcpy(NULL,...) to have undefined behavior. Would a NULL check be needed here?
Please let us know if we missed any key information or assumption! We appreciate your time!
Best,
Zijie
Quoted 26 lines · Zijie Zhao
Dear BCACHEFS maintainers,
We encountered an unusual usage of kzalloc in
btree_paths_reallocwhile performing a static analysis for kernel code.https://elixir.bootlin.com/linux/latest/source/fs/bcachefs/btree_iter.c#L1523
``` static noinline void btree_paths_realloc(struct btree_trans *trans) { unsigned nr = trans->nr_paths * 2; void *p = kzalloc(BITS_TO_LONGS(nr) * sizeof(unsigned long) + sizeof(struct btree_trans_paths) + nr * sizeof(struct btree_path) + nr * sizeof(btree_path_idx_t) + 8 + nr * sizeof(struct btree_insert_entry), GFP_KERNEL|__GFP_NOFAIL); unsigned long *paths_allocated = p; memcpy(paths_allocated, trans->paths_allocated, BITS_TO_LONGS(trans->nr_paths) * sizeof(unsigned long)); ... } ```
Quoted 3 lines
Here kzalloc might return NULL in case of out-of-memory, making
memcpy(NULL,...)to have undefined behavior. Would a NULL check be needed here?
See that __GFP_NOFAIL?
Quoted 27 lines · Kent Overstreet
Quoted 26 lines · Zijie Zhao
Dear BCACHEFS maintainers,
We encountered an unusual usage of kzalloc in
btree_paths_reallocwhile performing a static analysis for kernel code.https://elixir.bootlin.com/linux/latest/source/fs/bcachefs/btree_iter.c#L1523
``` static noinline void btree_paths_realloc(struct btree_trans *trans) { unsigned nr = trans->nr_paths * 2; void *p = kzalloc(BITS_TO_LONGS(nr) * sizeof(unsigned long) + sizeof(struct btree_trans_paths) + nr * sizeof(struct btree_path) + nr * sizeof(btree_path_idx_t) + 8 + nr * sizeof(struct btree_insert_entry), GFP_KERNEL|__GFP_NOFAIL); unsigned long *paths_allocated = p; memcpy(paths_allocated, trans->paths_allocated, BITS_TO_LONGS(trans->nr_paths) * sizeof(unsigned long)); ... } ```
Quoted 5 lines
Quoted 3 lines
Here kzalloc might return NULL in case of out-of-memory, making
memcpy(NULL,...)to have undefined behavior. Would a NULL check be needed here?See that
__GFP_NOFAIL?
Thanks! Just realized that!