From e6e0e277884e7b5292a7c623c0aab035d0ed1bda Mon Sep 17 00:00:00 2001 From: Gao Junhao Date: Sat, 12 Oct 2019 03:18:52 +0000 Subject: [PATCH] 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: #3789 Signed-off-by: Junhao Gao Reviewed-by: Yonghua Huang Acked-by: Yu Wang --- devicemodel/hw/pci/ahci.c | 4 ++-- devicemodel/hw/pci/npk.c | 4 ++-- devicemodel/hw/pci/virtio/virtio_block.c | 9 ++++----- 3 files changed, 8 insertions(+), 9 deletions(-) diff --git a/devicemodel/hw/pci/ahci.c b/devicemodel/hw/pci/ahci.c index 994761c20..b5c89db1b 100644 --- a/devicemodel/hw/pci/ahci.c +++ b/devicemodel/hw/pci/ahci.c @@ -2419,8 +2419,8 @@ pci_ahci_init(struct vmctx *ctx, struct pci_vdev *dev, char *opts, int atapi) sizeof(ahci_dev->port[p].ident), "ACRN--%02X%02X-%02X%02X-%02X%02X", digest[0], digest[1], digest[2], digest[3], digest[4], digest[5]); - if (rc > sizeof(ahci_dev->port[p].ident)) - WPRINTF("%s: digest is longer than ident\n", __func__); + if (rc >= sizeof(ahci_dev->port[p].ident) || rc < 0) + WPRINTF("%s: digest number is invalid!\n", __func__); /* * Allocate blockif request structures and add them diff --git a/devicemodel/hw/pci/npk.c b/devicemodel/hw/pci/npk.c index 7dce94630..7ef3520dd 100644 --- a/devicemodel/hw/pci/npk.c +++ b/devicemodel/hw/pci/npk.c @@ -244,8 +244,8 @@ static int pci_npk_init(struct vmctx *ctx, struct pci_vdev *dev, char *opts) /* read the host NPK configuration space */ rc = snprintf(name, PATH_MAX, "%s/%s/config", NPK_DRV_SYSFS_PATH, dent->d_name); - if (rc > PATH_MAX) - WPRINTF(("NPK device name too long\n")); + if (rc >= PATH_MAX || rc < 0) + WPRINTF(("NPK device name is invalid!\n")); fd = open(name, O_RDONLY); if (fd == -1) { WPRINTF(("Cannot open host NPK config\n")); diff --git a/devicemodel/hw/pci/virtio/virtio_block.c b/devicemodel/hw/pci/virtio/virtio_block.c index 21fecff3c..991af4c4f 100644 --- a/devicemodel/hw/pci/virtio/virtio_block.c +++ b/devicemodel/hw/pci/virtio/virtio_block.c @@ -524,12 +524,11 @@ virtio_blk_init(struct vmctx *ctx, struct pci_vdev *dev, char *opts) MD5_Init(&mdctx); MD5_Update(&mdctx, opts, strnlen(opts, VIRTIO_BLK_MAX_OPTS_LEN)); MD5_Final(digest, &mdctx); - if (snprintf(blk->ident, sizeof(blk->ident), + rc = snprintf(blk->ident, sizeof(blk->ident), "ACRN--%02X%02X-%02X%02X-%02X%02X", digest[0], - digest[1], digest[2], digest[3], digest[4], - digest[5]) >= sizeof(blk->ident)) { - WPRINTF(("virtio_blk: block ident too long\n")); - } + digest[1], digest[2], digest[3], digest[4], digest[5]); + if (rc >= sizeof(blk->ident) || rc < 0) + WPRINTF(("virtio_blk: device name is invalid!\n")); /* Setup virtio block config space only for valid backend file*/ if (!blk->dummy_bctxt)