[PATCH nvme-cli] nvme : Don't seg fault if given device is not char/block device

Nilay Shroff nilay at linux.ibm.com
Sun Mar 17 04:36:22 PDT 2024


If the given device name is not char/block device then in
open_dev_direct() set errno to ENODEV and err to -1 before
returning to the dev_fd(). This would then ensure that in
case of error, dev_fd() returns the corerct negative error
code back to its callers. So now the callers of dev_fd()
would handle the error appropriately instead of try
accessing the nvme_dev which would be NULL.

Signed-off-by: Nilay Shroff <nilay at linux.ibm.com>
---
Hi all,

I was running nvme-cli command "id-ns" where I inadvertently
passed a device name which was neither char device nor block
device. Surprisingly, after running the above command I found 
that nvme-cli reported the device name is invalid but then it
crashed. Further debugging into it, I found that it requires 
a trivial fix to avoid the crash. Here's what I tried:

# nvme id-ns /sys/block/nvme0n1 
/sys/block/nvme0n1 is not a block or character device
Segmentation fault

And this is the corresponding gdb backtrace:

Program received signal SIGSEGV, Segmentation fault.
0x000000000040a6ca in __dev_fd (dev=0x0, func=0x8772e1 <__func__.36> "id_ns", line=3639) at ../nvme.h:76
76		if (dev->type != NVME_DEV_DIRECT) {
(gdb) bt
#0  0x000000000040a6ca in __dev_fd (dev=0x0, func=0x8772e1 <__func__.36> "id_ns", line=3639) at ../nvme.h:76
#1  0x000000000041620b in id_ns (argc=2, argv=0x7fffffffdeb0, cmd=0xa14280 <id_ns_cmd>, plugin=0xa15280 <builtin>) at ../nvme.c:3639
#2  0x00000000004482f5 in handle_plugin (argc=2, argv=0x7fffffffdeb0, plugin=0xa15280 <builtin>) at ../plugin.c:171
#3  0x000000000042a2bb in main (argc=3, argv=0x7fffffffdea8) at ../nvme.c:9040

This patch fixes the above seg fault.

Thanks,
--Nilay
---
 nvme.c | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)

diff --git a/nvme.c b/nvme.c
index 3f0f2ff4..00625151 100644
--- a/nvme.c
+++ b/nvme.c
@@ -254,7 +254,8 @@ static int open_dev_direct(struct nvme_dev **devp, char *devstr, int flags)
 	}
 	if (!is_chardev(dev) && !is_blkdev(dev)) {
 		nvme_show_error("%s is not a block or character device", devstr);
-		err = -ENODEV;
+		errno = ENODEV;
+		err = -1;
 		goto err_close;
 	}
 	*devp = dev;
-- 
2.43.0




More information about the Linux-nvme mailing list