Skip to contentSkip to conversation

scsi: aacraid: Prevent premature freeing and improve memory allocation checks for fsa_dev

PATCH New Riyan Dhiman 1 participant 1 message Sep 3, 2024

Subsystems (2)
lore
Share & tools
lore
#0 lore raw

PATCH 1/1 scsi: aacraid: Prevent premature freeing and improve memory allocation checks for fsa_dev

Refactor the allocation and freeing sequence of fsa_dev to ensure that memory is not prematurely freed, which could lead to use-after-free errors or undefined behavior.

Changes:
- Modified the order of memory operations by allocating new memory for fsa_dev first and checking for success before freeing the old fsa_dev pointer.
- Updated the error handling to ensure -ENOMEM is returned if allocation fails, preserving the existing valid memory.

---
 drivers/scsi/aacraid/aachba.c | 14 +++++---------
 1 file changed, 5 insertions(+), 9 deletions(-)
drivers/scsi/aacraid/aachba.c +5 -9
index b22857c6f3f4..f3fc9b622aee 100644
@@ -490,18 +490,14 @@ int aac_get_containers(struct aac_dev *dev)
 	if (dev->fsa_dev == NULL ||
 		dev->maximum_num_containers != maximum_num_containers) {
 
-		fsa_dev_ptr = dev->fsa_dev;
-
-		dev->fsa_dev = kcalloc(maximum_num_containers,
+		fsa_dev_ptr = kcalloc(maximum_num_containers,
 					sizeof(*fsa_dev_ptr), GFP_KERNEL);
-
-		kfree(fsa_dev_ptr);
-		fsa_dev_ptr = NULL;
-
-
-		if (!dev->fsa_dev)
+		if(!fsa_dev_ptr)
 			return -ENOMEM;
 
+		kfree(dev->fsa_dev);
+		dev->fsa_dev = fsa_dev_ptr;
+
 		dev->maximum_num_containers = maximum_num_containers;
 	}
 	for (index = 0; index < dev->maximum_num_containers; index++) {
Signature · 1 line
2.46.0