diff mbox

[4/6] kpartx: Improve reliability of find_loop_by_file()

Message ID 20180301192935.14643-5-bart.vanassche@wdc.com (mailing list archive)
State Not Applicable, archived
Delegated to: christophe varoqui
Headers show

Commit Message

Bart Van Assche March 1, 2018, 7:29 p.m. UTC
Avoid that the strchr() call in this function examines uninitialized
data on the stack. This patch avoids that Coverity reports the following:

    CID 173252:  Error handling issues  (CHECKED_RETURN)
    "read(int, void *, size_t)" returns the number of bytes read, but it is ignored.

Signed-off-by: Bart Van Assche <bart.vanassche@wdc.com>
---
 kpartx/lopart.c | 7 ++++---
 1 file changed, 4 insertions(+), 3 deletions(-)

Comments

Martin Wilck March 5, 2018, 6:38 p.m. UTC | #1
On Thu, 2018-03-01 at 11:29 -0800, Bart Van Assche wrote:
> Avoid that the strchr() call in this function examines uninitialized
> data on the stack. This patch avoids that Coverity reports the
> following:
> 
>     CID 173252:  Error handling issues  (CHECKED_RETURN)
>     "read(int, void *, size_t)" returns the number of bytes read, but
> it is ignored.
> 
> Signed-off-by: Bart Van Assche <bart.vanassche@wdc.com>

Reviewed-by: Martin Wilck <mwilck@suse.com>


> ---
>  kpartx/lopart.c | 7 ++++---
>  1 file changed, 4 insertions(+), 3 deletions(-)
> 
> diff --git a/kpartx/lopart.c b/kpartx/lopart.c
> index 02b29e8cf91d..69c1eda1cc5c 100644
> --- a/kpartx/lopart.c
> +++ b/kpartx/lopart.c
> @@ -64,7 +64,7 @@ char *find_loop_by_file(const char *filename)
>  	DIR *dir;
>  	struct dirent *dent;
>  	char dev[64], *found = NULL, *p;
> -	int fd;
> +	int fd, bytes_read;
>  	struct stat statbuf;
>  	struct loop_info loopinfo;
>  	const char VIRT_BLOCK[] = "/sys/devices/virtual/block";
> @@ -86,14 +86,15 @@ char *find_loop_by_file(const char *filename)
>  		if (fd < 0)
>  			continue;
>  
> -		if (read(fd, dev, sizeof(dev)) <= 0) {
> +		bytes_read = read(fd, dev, sizeof(dev) - 1);
> +		if (bytes_read <= 0) {
>  			close(fd);
>  			continue;
>  		}
>  
>  		close(fd);
>  
> -		dev[sizeof(dev)-1] = '\0';
> +		dev[bytes_read] = '\0';
>  		p = strchr(dev, '\n');
>  		if (p != NULL)
>  			*p = '\0';
diff mbox

Patch

diff --git a/kpartx/lopart.c b/kpartx/lopart.c
index 02b29e8cf91d..69c1eda1cc5c 100644
--- a/kpartx/lopart.c
+++ b/kpartx/lopart.c
@@ -64,7 +64,7 @@  char *find_loop_by_file(const char *filename)
 	DIR *dir;
 	struct dirent *dent;
 	char dev[64], *found = NULL, *p;
-	int fd;
+	int fd, bytes_read;
 	struct stat statbuf;
 	struct loop_info loopinfo;
 	const char VIRT_BLOCK[] = "/sys/devices/virtual/block";
@@ -86,14 +86,15 @@  char *find_loop_by_file(const char *filename)
 		if (fd < 0)
 			continue;
 
-		if (read(fd, dev, sizeof(dev)) <= 0) {
+		bytes_read = read(fd, dev, sizeof(dev) - 1);
+		if (bytes_read <= 0) {
 			close(fd);
 			continue;
 		}
 
 		close(fd);
 
-		dev[sizeof(dev)-1] = '\0';
+		dev[bytes_read] = '\0';
 		p = strchr(dev, '\n');
 		if (p != NULL)
 			*p = '\0';