Skip to content

Commit 995efc1

Browse files
gaojunhao0504wenlingz
authored andcommitted
dm: refine the check of return value of snprintf
int snprintf(char *str, size_t size, const char *format, ...) The functions snprintf() write at most size bytes (including the terminating null byte('\0')) to str. only when returned value of snprintf is non-negative and less than size, the string has been completely written. Tracked-On: #4087 Signed-off-by: Gao Junhao <junhao.gao@intel.com> Reviewed-by: Yonghua Huang <yonghua.huang@intel.com> Acked-by: Yu Wang <yu1.wang@intel.com>
1 parent 720a77c commit 995efc1

File tree

3 files changed

+9
-9
lines changed

3 files changed

+9
-9
lines changed

devicemodel/hw/pci/ahci.c

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2383,8 +2383,8 @@ pci_ahci_init(struct vmctx *ctx, struct pci_vdev *dev, char *opts, int atapi)
23832383
sizeof(ahci_dev->port[p].ident),
23842384
"ACRN--%02X%02X-%02X%02X-%02X%02X", digest[0],
23852385
digest[1], digest[2], digest[3], digest[4], digest[5]);
2386-
if (rc > sizeof(ahci_dev->port[p].ident))
2387-
WPRINTF("%s: digest is longer than ident\n", __func__);
2386+
if (rc >= sizeof(ahci_dev->port[p].ident) || rc < 0)
2387+
WPRINTF("%s: digest number is invalid!\n", __func__);
23882388

23892389
/*
23902390
* Allocate blockif request structures and add them

devicemodel/hw/pci/npk.c

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -243,8 +243,8 @@ static int pci_npk_init(struct vmctx *ctx, struct pci_vdev *dev, char *opts)
243243
/* read the host NPK configuration space */
244244
rc = snprintf(name, PATH_MAX, "%s/%s/config", NPK_DRV_SYSFS_PATH,
245245
dent->d_name);
246-
if (rc > PATH_MAX)
247-
WPRINTF(("NPK device name too long\n"));
246+
if (rc >= PATH_MAX || rc < 0)
247+
WPRINTF(("NPK device name is invalid!\n"));
248248

249249
closedir(dir);
250250
fd = open(name, O_RDONLY);

devicemodel/hw/pci/virtio/virtio_block.c

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -427,12 +427,12 @@ virtio_blk_init(struct vmctx *ctx, struct pci_vdev *dev, char *opts)
427427
MD5_Init(&mdctx);
428428
MD5_Update(&mdctx, opts, strnlen(opts, VIRTIO_BLK_MAX_OPTS_LEN));
429429
MD5_Final(digest, &mdctx);
430-
if (snprintf(blk->ident, sizeof(blk->ident),
430+
rc = snprintf(blk->ident, sizeof(blk->ident),
431431
"ACRN--%02X%02X-%02X%02X-%02X%02X", digest[0],
432-
digest[1], digest[2], digest[3], digest[4],
433-
digest[5]) >= sizeof(blk->ident)) {
434-
WPRINTF(("virtio_blk: block ident too long\n"));
435-
}
432+
digest[1], digest[2], digest[3], digest[4], digest[5]);
433+
434+
if (rc >= sizeof(blk->ident) || rc < 0)
435+
WPRINTF(("virtio_blk: block ident is invalid!\n"));
436436

437437
/* setup virtio block config space */
438438
blk->cfg.capacity = size / DEV_BSIZE; /* 512-byte units */

0 commit comments

Comments
 (0)