Skip to contentSkip to conversation

misc: Remove sprintf() due to macOS deprecation

PATCH Superseded Philippe Mathieu-Daudé 10 participants 25 messages Apr 10, 2024 – Apr 19, 2024

v1 of 2 Superseded Latest is v2 →

lore
Share & tools
lore
#0 lore raw

cover misc: Remove sprintf() due to macOS deprecation

Hi,

sprintf() is deprecated on Darwin since macOS 13.0 / XCode 14.1, resulting in painful developper experience.

Suggestion to avoid the super-noisy warning on macOS forum are [*]:

* use -Wno-deprecated-declarations on the whole build
* surgically add #pragma clang diagnostic around each use.

None of these options seem reasonable, so we are somehow forced to spend time converting each sprintf() call, even if they are safe enough.

I'm so tired of seeing them than I started the conversion. This is the first part. Help for the rest is welcomed.

Regards,

Phil.

[*] https://forums.developer.apple.com/forums/thread/714675

Philippe Mathieu-Daudé (12):
ui/console-vc: Replace sprintf() by g_strdup_printf() hw/vfio/pci: Replace sprintf() by g_strdup_printf() hw/ppc/spapr: Replace sprintf() by g_strdup_printf() hw/mips/malta: Replace sprintf() by g_string_append_printf() system/qtest: Replace sprintf() by g_string_append_printf() util/hexdump: Rename @offset argument in qemu_hexdump_line() util/hexdump: Have qemu_hexdump_line() return heap allocated buffer util/hexdump: Replace sprintf() by g_string_append_printf() hw/scsi/scsi-disk: Use qemu_hexdump_line() to avoid sprintf() hw/ide/atapi: Use qemu_hexdump_line() to avoid sprintf() hw/dma/pl330: Use qemu_hexdump_line() to avoid sprintf() backends/tpm: Use qemu_hexdump_line() to avoid sprintf()

 include/qemu/cutils.h   | 17 ++++++++++++++---
 backends/tpm/tpm_util.c | 24 ++++++++----------------
 hw/dma/pl330.c          | 12 +++---------
 hw/ide/atapi.c          |  8 ++------
 hw/mips/malta.c         | 22 +++++++++++++---------
 hw/ppc/spapr.c          |  4 ++--
 hw/scsi/scsi-disk.c     |  8 ++------
 hw/vfio/pci.c           |  7 +++----
 hw/virtio/vhost-vdpa.c  | 11 ++++++-----
 system/qtest.c          |  8 +++-----
 ui/console-vc.c         |  4 ++--
 util/hexdump.c          | 33 ++++++++++++++++++---------------
 12 files changed, 76 insertions(+), 82 deletions(-)
Signature · 1 line
2.41.0
#1 lore raw

PATCH 1/12 ui/console-vc: Replace sprintf() by g_strdup_printf()

sprintf() is deprecated on Darwin since macOS 13.0 / XCode 14.1, resulting in painful developper experience.

Replace sprintf() by g_strdup_printf() in order to avoid:

[702/1310] Compiling C object libcommon.fa.p/ui_console-vc.c.o ui/console-vc.c:824:21: warning: 'sprintf' is deprecated:
This function is provided for compatibility reasons only. Due to security concerns inherent in the design of sprintf(3), it is highly recommended that you use snprintf(3) instead. [-Wdeprecated-declarations]
sprintf(response, "\033[%d;%dR",
^
1 warning generated.

---
 ui/console-vc.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
ui/console-vc.c +2 -2
index 899fa11c94..b455db436d 100644
@@ -648,7 +648,7 @@ static void vc_putchar(VCChardev *vc, int ch)
     QemuTextConsole *s = vc->console;
     int i;
     int x, y;
-    char response[40];
+    g_autofree char *response = NULL;
 
     switch(vc->state) {
     case TTY_STATE_NORM:
@@ -821,7 +821,7 @@ static void vc_putchar(VCChardev *vc, int ch)
                     break;
                 case 6:
                     /* report cursor position */
-                    sprintf(response, "\033[%d;%dR",
+                    response = g_strdup_printf("\033[%d;%dR",
                            (s->y_base + s->y) % s->total_height + 1,
                             s->x + 1);
                     vc_respond_str(vc, response);
Signature · 1 line
2.41.0
Reviewed-by on v1 1/12
#2 lore raw

Re: [PATCH 01/12] ui/console-vc: Replace sprintf() by g_strdup_printf()

Quoted 16 lines · Philippe Mathieu-Daudé

sprintf() is deprecated on Darwin since macOS 13.0 / XCode 14.1, resulting in painful developper experience.

Replace sprintf() by g_strdup_printf() in order to avoid:

[702/1310] Compiling C object libcommon.fa.p/ui_console-vc.c.o ui/console-vc.c:824:21: warning: 'sprintf' is deprecated:
This function is provided for compatibility reasons only. Due to security concerns inherent in the design of sprintf(3), it is highly recommended that you use snprintf(3) instead. [-Wdeprecated-declarations]
sprintf(response, "\033[%d;%dR",
^
1 warning generated.

Quoted 1 line
Quoted 29 lines
---
 ui/console-vc.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
ui/console-vc.c +2 -3
index 899fa11c94..b455db436d 100644
@@ -648,7 +648,7 @@ static void vc_putchar(VCChardev *vc, int ch)
     QemuTextConsole *s = vc->console;
     int i;
     int x, y;
-    char response[40];
+    g_autofree char *response = NULL;
 
     switch(vc->state) {
     case TTY_STATE_NORM:
@@ -821,7 +821,7 @@ static void vc_putchar(VCChardev *vc, int ch)
                     break;
                 case 6:
                     /* report cursor position */
-                    sprintf(response, "\033[%d;%dR",
+                    response = g_strdup_printf("\033[%d;%dR",
                            (s->y_base + s->y) % s->total_height + 1,
                             s->x + 1);
                     vc_respond_str(vc, response);
--

2.41.0

#3 lore raw

Re: [PATCH 01/12] ui/console-vc: Replace sprintf() by g_strdup_printf()

In reply to Philippe Mathieu-Daudé

Hi,

ui/console-vc.c static void vc_putchar(VCChardev *vc, int ch)

Quoted 8 lines

Due to security concerns inherent in the design of sprintf(3), it is highly recommended that you use snprintf(3) instead.

ui/console-vc.c +2 -2
-    char response[40];
+    g_autofree char *response = NULL;
 
-                    sprintf(response, "\033[%d;%dR",
+                    response = g_strdup_printf("\033[%d;%dR",

Any specific reason why you don't go with the recommendation above?

While using g_strdup_printf() isn't wrong it allocates memory which is not needed here because you can continue to use the stack buffer this way:

	snprintf(response, sizeof(response), ...);

take care,
Gerd

#4 lore raw

Re: [PATCH 01/12] ui/console-vc: Replace sprintf() by g_strdup_printf()

Quoted 11 lines · Gerd Hoffmann
   Hi,

ui/console-vc.c static void vc_putchar(VCChardev *vc, int ch)

Quoted 8 lines

Due to security concerns inherent in the design of sprintf(3), it is highly recommended that you use snprintf(3) instead.

ui/console-vc.c +2 -2
-    char response[40];
+    g_autofree char *response = NULL;
 
-                    sprintf(response, "\033[%d;%dR",
+                    response = g_strdup_printf("\033[%d;%dR",
Quoted 7 lines

Any specific reason why you don't go with the recommendation above?

While using g_strdup_printf() isn't wrong it allocates memory which is not needed here because you can continue to use the stack buffer this way:

	snprintf(response, sizeof(response), ...);

I thought GLib/GString was recommended for formatting, so choose this thinking mostly about style. Indeed in this case snprintf() is sufficient. I'll respin, thanks.

Quoted 4 lines

take care,
Gerd

#5 lore raw

Re: [PATCH 01/12] ui/console-vc: Replace sprintf() by g_strdup_printf()

Quoted 14 lines · Philippe Mathieu-Daudé
Quoted 13 lines · Gerd Hoffmann
   Hi,

ui/console-vc.c static void vc_putchar(VCChardev *vc, int ch)

Quoted 8 lines

Due to security concerns inherent in the design of sprintf(3), it is highly recommended that you use snprintf(3) instead.

ui/console-vc.c +2 -2
-    char response[40];
+    g_autofree char *response = NULL;
 
-                    sprintf(response, "\033[%d;%dR",
+                    response = g_strdup_printf("\033[%d;%dR",

Any specific reason why you don't go with the recommendation above?

Quoted 7 lines
Quoted 5 lines

While using g_strdup_printf() isn't wrong it allocates memory which is not needed here because you can continue to use the stack buffer this way:

	snprintf(response, sizeof(response), ...);

I thought GLib/GString was recommended for formatting,

If you allocate the output buffer anyway (and there are patches in this series where this is the case) it's clearly better to use g_strdup_printf instead of malloc + snprintf.

In case a fixed-size buffer can be used I wouldn't switch to dynamic allocation ...

take care,
Gerd

#6 lore raw

PATCH 2/12 hw/vfio/pci: Replace sprintf() by g_strdup_printf()

In reply to Philippe Mathieu-Daudé

sprintf() is deprecated on Darwin since macOS 13.0 / XCode 14.1, resulting in painful developper experience. Use g_strdup_printf() instead.

---
 hw/vfio/pci.c | 7 +++----
 1 file changed, 3 insertions(+), 4 deletions(-)
hw/vfio/pci.c +3 -4
index 64780d1b79..cc3cc89122 100644
@@ -2442,10 +2442,9 @@ void vfio_pci_post_reset(VFIOPCIDevice *vdev)
 
 bool vfio_pci_host_match(PCIHostDeviceAddress *addr, const char *name)
 {
-    char tmp[13];
-
-    sprintf(tmp, "%04x:%02x:%02x.%1x", addr->domain,
-            addr->bus, addr->slot, addr->function);
+    g_autofree char *tmp = g_strdup_printf("%04x:%02x:%02x.%1x",
+                                           addr->domain, addr->bus,
+                                           addr->slot, addr->function);
 
     return (strcmp(tmp, name) == 0);
 }
Signature · 1 line
2.41.0
#7 lore raw

Re: [PATCH 02/12] hw/vfio/pci: Replace sprintf() by g_strdup_printf()

Quoted 3 lines · On Wed, 10 Apr 2024 18:06:03 +0200 Philippe Mathieu-Daudé <[email protected]>…

sprintf() is deprecated on Darwin since macOS 13.0 / XCode 14.1, resulting in painful developper experience. Use g_strdup_printf() instead.

Isn't this code only compiled for Linux hosts? Maybe still a valid change, but the rationale seems irrelevant. Thanks,

Alex

Quoted 24 lines
---
 hw/vfio/pci.c | 7 +++----
 1 file changed, 3 insertions(+), 4 deletions(-)
hw/vfio/pci.c +3 -4
index 64780d1b79..cc3cc89122 100644
@@ -2442,10 +2442,9 @@ void vfio_pci_post_reset(VFIOPCIDevice *vdev)
 
 bool vfio_pci_host_match(PCIHostDeviceAddress *addr, const char *name)
 {
-    char tmp[13];
-
-    sprintf(tmp, "%04x:%02x:%02x.%1x", addr->domain,
-            addr->bus, addr->slot, addr->function);
+    g_autofree char *tmp = g_strdup_printf("%04x:%02x:%02x.%1x",
+                                           addr->domain, addr->bus,
+                                           addr->slot, addr->function);
 
     return (strcmp(tmp, name) == 0);
 }
#8 lore raw

Re: [PATCH 02/12] hw/vfio/pci: Replace sprintf() by g_strdup_printf()

Quoted 8 lines · Alex Williamson
Quoted 3 lines · On Wed, 10 Apr 2024 18:06:03 +0200 Philippe Mathieu-Daudé <[email protected]>…

sprintf() is deprecated on Darwin since macOS 13.0 / XCode 14.1, resulting in painful developper experience. Use g_strdup_printf() instead.

Isn't this code only compiled for Linux hosts?

It is not.

Quoted 1 line

Maybe still a valid change, but the rationale seems irrelevant.

I agree the commit log should be rephrased.

There is also a v2 doing a different change :

https://lore.kernel.org/qemu-devel/[email protected]/

This is a bit confusing.

Thanks,

C.

#9 lore raw

PATCH 3/12 hw/ppc/spapr: Replace sprintf() by g_strdup_printf()

In reply to Philippe Mathieu-Daudé

sprintf() is deprecated on Darwin since macOS 13.0 / XCode 14.1, resulting in painful developper experience.

Replace sprintf() by g_strdup_printf() in order to avoid:

hw/ppc/spapr.c:385:5: warning: 'sprintf' is deprecated:
This function is provided for compatibility reasons only. Due to security concerns inherent in the design of sprintf(3), it is highly recommended that you use snprintf(3) instead. [-Wdeprecated-declarations]
sprintf(mem_name, "memory@%" HWADDR_PRIx, start); ^
1 warning generated.

---
 hw/ppc/spapr.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
hw/ppc/spapr.c +2 -2
index e9bc97fee0..9807f47690 100644
@@ -375,14 +375,14 @@ static void add_str(GString *s, const gchar *s1)
 static int spapr_dt_memory_node(SpaprMachineState *spapr, void *fdt, int nodeid,
                                 hwaddr start, hwaddr size)
 {
-    char mem_name[32];
+    g_autofree char *mem_name = NULL;
     uint64_t mem_reg_property[2];
     int off;
 
     mem_reg_property[0] = cpu_to_be64(start);
     mem_reg_property[1] = cpu_to_be64(size);
 
-    sprintf(mem_name, "memory@%" HWADDR_PRIx, start);
+    mem_name = g_strdup_printf("memory@%" HWADDR_PRIx, start);
     off = fdt_add_subnode(fdt, 0, mem_name);
     _FDT(off);
     _FDT((fdt_setprop_string(fdt, off, "device_type", "memory")));
Signature · 1 line
2.41.0
#10 lore raw

PATCH 4/12 hw/mips/malta: Replace sprintf() by g_string_append_printf()

In reply to Philippe Mathieu-Daudé

sprintf() is deprecated on Darwin since macOS 13.0 / XCode 14.1, resulting in painful developper experience.

Extract common code to get_rng_seed_hex(), replacing the sprintf() calls by GString API ones in order to avoid:

[120/169] Compiling C object libcommon.fa.p/system_qtest.c.o hw/mips/malta.c:860:9: warning: 'sprintf' is deprecated:
sprintf(rng_seed_hex + i * 2, "%02x", rng_seed[i]); ^
This function is provided for compatibility reasons only. Due to security concerns inherent in the design of sprintf(3), it is highly recommended that you use snprintf(3) instead. [-Wdeprecated-declarations]
hw/mips/malta.c:951:9: warning: 'sprintf' is deprecated:

          sprintf(rng_seed_hex + i * 2, "%02x", rng_seed[i]);
          ^
---
 hw/mips/malta.c | 22 +++++++++++++---------
 1 file changed, 13 insertions(+), 9 deletions(-)
hw/mips/malta.c +13 -9
index af74008c82..095abbf0ec 100644
@@ -850,15 +850,24 @@ static void G_GNUC_PRINTF(3, 4) prom_set(uint32_t *prom_buf, int index,
     va_end(ap);
 }
 
-static void reinitialize_rng_seed(void *opaque)
+static char *get_rng_seed_hex(void)
 {
-    char *rng_seed_hex = opaque;
+    g_autoptr(GString) gs = g_string_new("");
     uint8_t rng_seed[32];
 
     qemu_guest_getrandom_nofail(rng_seed, sizeof(rng_seed));
     for (size_t i = 0; i < sizeof(rng_seed); ++i) {
-        sprintf(rng_seed_hex + i * 2, "%02x", rng_seed[i]);
+        g_string_append_printf(gs, "%02x", rng_seed[i]);
     }
+
+    return g_strdup(gs->str);
+}
+
+static void reinitialize_rng_seed(void *opaque)
+{
+    g_autofree char *rng_seed_hex = get_rng_seed_hex();
+
+    strcpy(opaque, rng_seed_hex);
 }
 
 /* Kernel */
@@ -870,8 +879,7 @@ static uint64_t load_kernel(void)
     uint32_t *prom_buf;
     long prom_size;
     int prom_index = 0;
-    uint8_t rng_seed[32];
-    char rng_seed_hex[sizeof(rng_seed) * 2 + 1];
+    g_autofree char *rng_seed_hex = get_rng_seed_hex();
     size_t rng_seed_prom_offset;
 
     kernel_size = load_elf(loaderparams.kernel_filename, NULL,
@@ -946,10 +954,6 @@ static uint64_t load_kernel(void)
     prom_set(prom_buf, prom_index++, "modetty0");
     prom_set(prom_buf, prom_index++, "38400n8r");
 
-    qemu_guest_getrandom_nofail(rng_seed, sizeof(rng_seed));
-    for (size_t i = 0; i < sizeof(rng_seed); ++i) {
-        sprintf(rng_seed_hex + i * 2, "%02x", rng_seed[i]);
-    }
     prom_set(prom_buf, prom_index++, "rngseed");
     rng_seed_prom_offset = prom_index * ENVP_ENTRY_SIZE +
                            sizeof(uint32_t) * ENVP_NB_ENTRIES;
Signature · 1 line
2.41.0
#11 lore raw

PATCH 5/12 system/qtest: Replace sprintf() by g_string_append_printf()

In reply to Philippe Mathieu-Daudé

sprintf() is deprecated on Darwin since macOS 13.0 / XCode 14.1, resulting in painful developper experience.

Replace sprintf() by GString API uses in order to avoid:

[120/169] Compiling C object libcommon.fa.p/system_qtest.c.o system/qtest.c:623:13: warning: 'sprintf' is deprecated:
This function is provided for compatibility reasons only. Due to security concerns inherent in the design of sprintf(3), it is highly recommended that you use snprintf(3) instead. [-Wdeprecated-declarations]
sprintf(&enc[i * 2], "%02x", data[i]);
^
1 warning generated.

---
 system/qtest.c | 8 +++-----
 1 file changed, 3 insertions(+), 5 deletions(-)
system/qtest.c +3 -5
index 6da58b3874..22bf1a33dc 100644
@@ -601,9 +601,9 @@ static void qtest_process_command(CharBackend *chr, gchar **words)
         qtest_send_prefix(chr);
         qtest_sendf(chr, "OK 0x%016" PRIx64 "\n", value);
     } else if (strcmp(words[0], "read") == 0) {
+        g_autoptr(GString) enc = g_string_new("");
         uint64_t addr, len, i;
         uint8_t *data;
-        char *enc;
         int ret;
 
         g_assert(words[1] && words[2]);
@@ -618,16 +618,14 @@ static void qtest_process_command(CharBackend *chr, gchar **words)
         address_space_read(first_cpu->as, addr, MEMTXATTRS_UNSPECIFIED, data,
                            len);
 
-        enc = g_malloc(2 * len + 1);
         for (i = 0; i < len; i++) {
-            sprintf(&enc[i * 2], "%02x", data[i]);
+            g_string_append_printf(enc, "%02x", data[i]);
         }
 
         qtest_send_prefix(chr);
-        qtest_sendf(chr, "OK 0x%s\n", enc);
+        qtest_sendf(chr, "OK 0x%s\n", enc->str);
 
         g_free(data);
-        g_free(enc);
     } else if (strcmp(words[0], "b64read") == 0) {
         uint64_t addr, len;
         uint8_t *data;
Signature · 1 line
2.41.0
Reviewed-by on v1 5/12
#12 lore raw

Re: [PATCH 05/12] system/qtest: Replace sprintf() by g_string_append_printf()

Quoted 15 lines · Philippe Mathieu-Daudé

sprintf() is deprecated on Darwin since macOS 13.0 / XCode 14.1, resulting in painful developper experience.

Replace sprintf() by GString API uses in order to avoid:

[120/169] Compiling C object libcommon.fa.p/system_qtest.c.o system/qtest.c:623:13: warning: 'sprintf' is deprecated:
This function is provided for compatibility reasons only. Due to security concerns inherent in the design of sprintf(3), it is highly recommended that you use snprintf(3) instead. [-Wdeprecated-declarations]
sprintf(&enc[i * 2], "%02x", data[i]);
^
1 warning generated.

Quoted 4 lines
---
  system/qtest.c | 8 +++-----
  1 file changed, 3 insertions(+), 5 deletions(-)
#13 lore raw

PATCH 6/12 util/hexdump: Rename @offset argument in qemu_hexdump_line()

In reply to Philippe Mathieu-Daudé

@offset argument is more descriptive than @b.

Inverse @bufptr <-> @offset arguments order.

Document qemu_hexdump_line().

---
 include/qemu/cutils.h  | 11 +++++++++--
 hw/virtio/vhost-vdpa.c |  8 ++++----
 util/hexdump.c         | 16 ++++++++--------
 3 files changed, 21 insertions(+), 14 deletions(-)
include/qemu/cutils.h +9 -2
index 92c927a6a3..70ca4b876b 100644
@@ -252,12 +252,19 @@ static inline const char *yes_no(bool b)
  */
 int parse_debug_env(const char *name, int max, int initial);
 
-/*
+/**
+ * qemu_hexdump_line:
+ * @line: Buffer to be filled by the hexadecimal/ASCII dump
+ * @bufptr: Buffer to dump
+ * @offset: Offset within @bufptr to start the dump
+ * @len: Length of the bytes do dump
+ * @ascii: Replace non-ASCII characters by the dot symbol
+ *
  * Hexdump a line of a byte buffer into a hexadecimal/ASCII buffer
  */
 #define QEMU_HEXDUMP_LINE_BYTES 16 /* Number of bytes to dump */
 #define QEMU_HEXDUMP_LINE_LEN 75   /* Number of characters in line */
-void qemu_hexdump_line(char *line, unsigned int b, const void *bufptr,
+void qemu_hexdump_line(char *line, const void *bufptr, unsigned offset,
                        unsigned int len, bool ascii);
 
 /*
hw/virtio/vhost-vdpa.c +4 -4
index e827b9175f..cf7cfa3f16 100644
@@ -941,12 +941,12 @@ static int vhost_vdpa_set_config_call(struct vhost_dev *dev,
 static void vhost_vdpa_dump_config(struct vhost_dev *dev, const uint8_t *config,
                                    uint32_t config_len)
 {
-    int b, len;
+    int ofs, len;
     char line[QEMU_HEXDUMP_LINE_LEN];
 
-    for (b = 0; b < config_len; b += 16) {
-        len = config_len - b;
-        qemu_hexdump_line(line, b, config, len, false);
+    for (ofs = 0; ofs < config_len; ofs += 16) {
+        len = config_len - ofs;
+        qemu_hexdump_line(line, config, ofs, len, false);
         trace_vhost_vdpa_dump_config(dev, line);
     }
 }
util/hexdump.c +8 -8
index 9921114b3c..469083d8c0 100644
@@ -16,7 +16,7 @@
 #include "qemu/osdep.h"
 #include "qemu/cutils.h"
 
-void qemu_hexdump_line(char *line, unsigned int b, const void *bufptr,
+void qemu_hexdump_line(char *line, const void *bufptr, unsigned offset,
                        unsigned int len, bool ascii)
 {
     const char *buf = bufptr;
@@ -26,13 +26,13 @@ void qemu_hexdump_line(char *line, unsigned int b, const void *bufptr,
         len = QEMU_HEXDUMP_LINE_BYTES;
     }
 
-    line += snprintf(line, 6, "%04x:", b);
+    line += snprintf(line, 6, "%04x:", offset);
     for (i = 0; i < QEMU_HEXDUMP_LINE_BYTES; i++) {
         if ((i % 4) == 0) {
             *line++ = ' ';
         }
         if (i < len) {
-            line += sprintf(line, " %02x", (unsigned char)buf[b + i]);
+            line += sprintf(line, " %02x", (unsigned char)buf[offset + i]);
         } else {
             line += sprintf(line, "   ");
         }
@@ -40,7 +40,7 @@ void qemu_hexdump_line(char *line, unsigned int b, const void *bufptr,
     if (ascii) {
         *line++ = ' ';
         for (i = 0; i < len; i++) {
-            c = buf[b + i];
+            c = buf[offset + i];
             if (c < ' ' || c > '~') {
                 c = '.';
             }
@@ -53,12 +53,12 @@ void qemu_hexdump_line(char *line, unsigned int b, const void *bufptr,
 void qemu_hexdump(FILE *fp, const char *prefix,
                   const void *bufptr, size_t size)
 {
-    unsigned int b, len;
+    unsigned int ofs, len;
     char line[QEMU_HEXDUMP_LINE_LEN];
 
-    for (b = 0; b < size; b += QEMU_HEXDUMP_LINE_BYTES) {
-        len = size - b;
-        qemu_hexdump_line(line, b, bufptr, len, true);
+    for (ofs = 0; ofs < size; ofs += QEMU_HEXDUMP_LINE_BYTES) {
+        len = size - ofs;
+        qemu_hexdump_line(line, bufptr, ofs, len, true);
         fprintf(fp, "%s: %s\n", prefix, line);
     }
 
Signature · 1 line
2.41.0
#14 lore raw

PATCH 7/12 util/hexdump: Have qemu_hexdump_line() return heap allocated buffer

In reply to Philippe Mathieu-Daudé
---
 include/qemu/cutils.h  | 10 +++++++---
 hw/virtio/vhost-vdpa.c |  5 +++--
 util/hexdump.c         | 12 ++++++++----
 3 files changed, 18 insertions(+), 9 deletions(-)
include/qemu/cutils.h +7 -3
index 70ca4b876b..e8d6b86098 100644
@@ -254,18 +254,22 @@ int parse_debug_env(const char *name, int max, int initial);
 
 /**
  * qemu_hexdump_line:
- * @line: Buffer to be filled by the hexadecimal/ASCII dump
  * @bufptr: Buffer to dump
  * @offset: Offset within @bufptr to start the dump
  * @len: Length of the bytes do dump
  * @ascii: Replace non-ASCII characters by the dot symbol
  *
  * Hexdump a line of a byte buffer into a hexadecimal/ASCII buffer
+ *
+ * The caller must use g_free() to free the returned data when it is
+ * no longer required.
+ *
+ * Returns: Hexadecimal/ASCII dump
  */
 #define QEMU_HEXDUMP_LINE_BYTES 16 /* Number of bytes to dump */
 #define QEMU_HEXDUMP_LINE_LEN 75   /* Number of characters in line */
-void qemu_hexdump_line(char *line, const void *bufptr, unsigned offset,
-                       unsigned int len, bool ascii);
+char *qemu_hexdump_line(const void *bufptr, unsigned offset,
+                        unsigned int len, bool ascii);
 
 /*
  * Hexdump a buffer to a file. An optional string prefix is added to every line
hw/virtio/vhost-vdpa.c +3 -2
index cf7cfa3f16..e61af86d9d 100644
@@ -942,12 +942,13 @@ static void vhost_vdpa_dump_config(struct vhost_dev *dev, const uint8_t *config,
                                    uint32_t config_len)
 {
     int ofs, len;
-    char line[QEMU_HEXDUMP_LINE_LEN];
+    char *line;
 
     for (ofs = 0; ofs < config_len; ofs += 16) {
         len = config_len - ofs;
-        qemu_hexdump_line(line, config, ofs, len, false);
+        line = qemu_hexdump_line(config, ofs, len, false);
         trace_vhost_vdpa_dump_config(dev, line);
+        g_free(line);
     }
 }
 
util/hexdump.c +8 -4
index 469083d8c0..b6f70e93bb 100644
@@ -16,9 +16,10 @@
 #include "qemu/osdep.h"
 #include "qemu/cutils.h"
 
-void qemu_hexdump_line(char *line, const void *bufptr, unsigned offset,
-                       unsigned int len, bool ascii)
+char *qemu_hexdump_line(const void *bufptr, unsigned offset,
+                        unsigned int len, bool ascii)
 {
+    char linebuf[QEMU_HEXDUMP_LINE_BYTES], *line = linebuf;
     const char *buf = bufptr;
     int i, c;
 
@@ -48,18 +49,21 @@ void qemu_hexdump_line(char *line, const void *bufptr, unsigned offset,
         }
     }
     *line = '\0';
+
+    return g_strdup(linebuf);
 }
 
 void qemu_hexdump(FILE *fp, const char *prefix,
                   const void *bufptr, size_t size)
 {
     unsigned int ofs, len;
-    char line[QEMU_HEXDUMP_LINE_LEN];
+    char *line;
 
     for (ofs = 0; ofs < size; ofs += QEMU_HEXDUMP_LINE_BYTES) {
         len = size - ofs;
-        qemu_hexdump_line(line, bufptr, ofs, len, true);
+        line = qemu_hexdump_line(bufptr, ofs, len, true);
         fprintf(fp, "%s: %s\n", prefix, line);
+        g_free(line);
     }
 
 }
Signature · 1 line
2.41.0
#15 lore raw

PATCH 8/12 util/hexdump: Replace sprintf() by g_string_append_printf()

In reply to Philippe Mathieu-Daudé

sprintf() is deprecated on Darwin since macOS 13.0 / XCode 14.1, resulting in painful developper experience.

Replace sprintf() by GString API in order to avoid:

[426/1310] Compiling C object libqemuutil.a.p/util_hexdump.c.o util/hexdump.c:35:21: warning: 'sprintf' is deprecated:
This function is provided for compatibility reasons only. Due to security concerns inherent in the design of sprintf(3), it is highly recommended that you use snprintf(3) instead. [-Wdeprecated-declarations]
line += sprintf(line, " %02x", (unsigned char)buf[b + i]);
^
util/hexdump.c:37:21: warning: 'sprintf' is deprecated:

            line += sprintf(line, "   ");
                    ^

2 warnings generated.

---
 util/hexdump.c | 17 ++++++++---------
 1 file changed, 8 insertions(+), 9 deletions(-)
util/hexdump.c +8 -9
index b6f70e93bb..2ec1171de3 100644
@@ -19,7 +19,7 @@
 char *qemu_hexdump_line(const void *bufptr, unsigned offset,
                         unsigned int len, bool ascii)
 {
-    char linebuf[QEMU_HEXDUMP_LINE_BYTES], *line = linebuf;
+    g_autoptr(GString) gs = g_string_sized_new(QEMU_HEXDUMP_LINE_BYTES);
     const char *buf = bufptr;
     int i, c;
 
@@ -27,30 +27,29 @@ char *qemu_hexdump_line(const void *bufptr, unsigned offset,
         len = QEMU_HEXDUMP_LINE_BYTES;
     }
 
-    line += snprintf(line, 6, "%04x:", offset);
+    g_string_append_printf(gs, "%04x:", offset);
     for (i = 0; i < QEMU_HEXDUMP_LINE_BYTES; i++) {
         if ((i % 4) == 0) {
-            *line++ = ' ';
+            g_string_append_c(gs, ' ');
         }
         if (i < len) {
-            line += sprintf(line, " %02x", (unsigned char)buf[offset + i]);
+            g_string_append_printf(gs, " %02x", (unsigned char)buf[offset + i]);
         } else {
-            line += sprintf(line, "   ");
+            g_string_append(gs, "   ");
         }
     }
     if (ascii) {
-        *line++ = ' ';
+        g_string_append_c(gs, ' ');
         for (i = 0; i < len; i++) {
             c = buf[offset + i];
             if (c < ' ' || c > '~') {
                 c = '.';
             }
-            *line++ = c;
+            g_string_append_c(gs, c);
         }
     }
-    *line = '\0';
 
-    return g_strdup(linebuf);
+    return g_strdup(gs->str);
 }
 
 void qemu_hexdump(FILE *fp, const char *prefix,
Signature · 1 line
2.41.0
#16 lore raw

PATCH 9/12 hw/scsi/scsi-disk: Use qemu_hexdump_line() to avoid sprintf()

In reply to Philippe Mathieu-Daudé

sprintf() is deprecated on Darwin since macOS 13.0 / XCode 14.1, resulting in painful developper experience.

Use qemu_hexdump_line() to avoid sprintf() calls, silencing:

[105/169] Compiling C object libcommon.fa.p/hw_scsi_scsi-disk.c.o hw/scsi/scsi-disk.c:2659:14: warning: 'sprintf' is deprecated:
This function is provided for compatibility reasons only. Due to security concerns inherent in the design of sprintf(3), it is highly recommended that you use snprintf(3) instead. [-Wdeprecated-declarations]
p += sprintf(p, " 0x%02x", buf[i]);
^

---
 hw/scsi/scsi-disk.c | 8 ++------
 1 file changed, 2 insertions(+), 6 deletions(-)
hw/scsi/scsi-disk.c +2 -6
index 4bd7af9d0c..4f914df5c2 100644
@@ -2648,16 +2648,12 @@ static const SCSIReqOps *const scsi_disk_reqops_dispatch[256] = {
 
 static void scsi_disk_new_request_dump(uint32_t lun, uint32_t tag, uint8_t *buf)
 {
-    int i;
     int len = scsi_cdb_length(buf);
-    char *line_buffer, *p;
+    char *line_buffer;
 
     assert(len > 0 && len <= 16);
-    line_buffer = g_malloc(len * 5 + 1);
 
-    for (i = 0, p = line_buffer; i < len; i++) {
-        p += sprintf(p, " 0x%02x", buf[i]);
-    }
+    line_buffer = qemu_hexdump_line(buf, 0, len, false);
     trace_scsi_disk_new_request(lun, tag, line_buffer);
 
     g_free(line_buffer);
Signature · 1 line
2.41.0
#17 lore raw

PATCH 10/12 hw/ide/atapi: Use qemu_hexdump_line() to avoid sprintf()

In reply to Philippe Mathieu-Daudé

sprintf() is deprecated on Darwin since macOS 13.0 / XCode 14.1, resulting in painful developper experience.

Use qemu_hexdump_line() to avoid sprintf() calls, silencing:

[1367/1604] Compiling C object libcommon.fa.p/backends_tpm_tpm_util.c.o backends/tpm/tpm_util.c:355:18: warning: 'sprintf' is deprecated:
This function is provided for compatibility reasons only. Due to security concerns inherent in the design of sprintf(3), it is highly recommended that you use snprintf(3) instead. [-Wdeprecated-declarations]
p += sprintf(p, "\n");
^

---
 hw/ide/atapi.c | 8 ++------
 1 file changed, 2 insertions(+), 6 deletions(-)
hw/ide/atapi.c +2 -6
index 73ec373184..27b6aa59fd 100644
@@ -24,6 +24,7 @@
  */
 
 #include "qemu/osdep.h"
+#include "qemu/cutils.h"
 #include "hw/scsi/scsi.h"
 #include "sysemu/block-backend.h"
 #include "scsi/constants.h"
@@ -1309,12 +1310,7 @@ void ide_atapi_cmd(IDEState *s)
     trace_ide_atapi_cmd(s, s->io_buffer[0]);
 
     if (trace_event_get_state_backends(TRACE_IDE_ATAPI_CMD_PACKET)) {
-        /* Each pretty-printed byte needs two bytes and a space; */
-        char *ppacket = g_malloc(ATAPI_PACKET_SIZE * 3 + 1);
-        int i;
-        for (i = 0; i < ATAPI_PACKET_SIZE; i++) {
-            sprintf(ppacket + (i * 3), "%02x ", buf[i]);
-        }
+        char *ppacket = qemu_hexdump_line(buf, 0, ATAPI_PACKET_SIZE, false);
         trace_ide_atapi_cmd_packet(s, s->lcyl | (s->hcyl << 8), ppacket);
         g_free(ppacket);
     }
Signature · 1 line
2.41.0
#18 lore raw

PATCH 11/12 hw/dma/pl330: Use qemu_hexdump_line() to avoid sprintf()

In reply to Philippe Mathieu-Daudé

sprintf() is deprecated on Darwin since macOS 13.0 / XCode 14.1, resulting in painful developper experience.

Use qemu_hexdump_line() to avoid sprintf() calls, silencing:

[5/8] Compiling C object libcommon.fa.p/hw_dma_pl330.c.o hw/dma/pl330.c:333:13: warning: 'sprintf' is deprecated:
This function is provided for compatibility reasons only. Due to security concerns inherent in the design of sprintf(3), it is highly recommended that you use snprintf(3) instead. [-Wdeprecated-declarations]
sprintf(tmpbuf + strlen(tmpbuf), " %02x", buf[b + i]); ^

---
 hw/dma/pl330.c | 12 +++---------
 1 file changed, 3 insertions(+), 9 deletions(-)
hw/dma/pl330.c +3 -9
index 70a502d245..0435378b7e 100644
@@ -15,6 +15,7 @@
  */
 
 #include "qemu/osdep.h"
+#include "qemu/cutils.h"
 #include "hw/irq.h"
 #include "hw/qdev-properties.h"
 #include "hw/sysbus.h"
@@ -317,21 +318,14 @@ typedef struct PL330InsnDesc {
 
 static void pl330_hexdump(uint8_t *buf, size_t size)
 {
-    unsigned int b, i, len;
-    char tmpbuf[80];
+    unsigned int b, len;
 
     for (b = 0; b < size; b += 16) {
         len = size - b;
         if (len > 16) {
             len = 16;
         }
-        tmpbuf[0] = '\0';
-        for (i = 0; i < len; i++) {
-            if ((i % 4) == 0) {
-                strcat(tmpbuf, " ");
-            }
-            sprintf(tmpbuf + strlen(tmpbuf), " %02x", buf[b + i]);
-        }
+        g_autofree char *tmpbuf = qemu_hexdump_line(buf, b, len, false);
         trace_pl330_hexdump(b, tmpbuf);
     }
 }
Signature · 1 line
2.41.0
#19 lore raw

PATCH 12/12 backends/tpm: Use qemu_hexdump_line() to avoid sprintf()

In reply to Philippe Mathieu-Daudé

sprintf() is deprecated on Darwin since macOS 13.0 / XCode 14.1, resulting in painful developper experience.

Use qemu_hexdump_line() to avoid sprintf() calls, silencing:

backends/tpm/tpm_util.c:357:14: warning: 'sprintf' is deprecated:
This function is provided for compatibility reasons only. Due to security concerns inherent in the design of sprintf(3), it is highly recommended that you use snprintf(3) instead. [-Wdeprecated-declarations]
p += sprintf(p, "%.2X ", buffer[i]);
^

---
 backends/tpm/tpm_util.c | 24 ++++++++----------------
 1 file changed, 8 insertions(+), 16 deletions(-)
backends/tpm/tpm_util.c +8 -16
index 1856589c3b..0747af2d1c 100644
@@ -21,6 +21,7 @@
 
 #include "qemu/osdep.h"
 #include "qemu/error-report.h"
+#include "qemu/cutils.h"
 #include "qapi/error.h"
 #include "qapi/visitor.h"
 #include "tpm_int.h"
@@ -336,27 +337,18 @@ void tpm_sized_buffer_reset(TPMSizedBuffer *tsb)
 void tpm_util_show_buffer(const unsigned char *buffer,
                           size_t buffer_size, const char *string)
 {
-    size_t len, i;
-    char *line_buffer, *p;
+    size_t len;
+    char *line, *lineup;
 
     if (!trace_event_get_state_backends(TRACE_TPM_UTIL_SHOW_BUFFER)) {
         return;
     }
     len = MIN(tpm_cmd_get_size(buffer), buffer_size);
 
-    /*
-     * allocate enough room for 3 chars per buffer entry plus a
-     * newline after every 16 chars and a final null terminator.
-     */
-    line_buffer = g_malloc(len * 3 + (len / 16) + 1);
+    line = qemu_hexdump_line(buffer, 0, len, false);
+    lineup = g_ascii_strup(line, -1);
+    trace_tpm_util_show_buffer(string, len, lineup);
 
-    for (i = 0, p = line_buffer; i < len; i++) {
-        if (i && !(i % 16)) {
-            p += sprintf(p, "\n");
-        }
-        p += sprintf(p, "%.2X ", buffer[i]);
-    }
-    trace_tpm_util_show_buffer(string, len, line_buffer);
-
-    g_free(line_buffer);
+    g_free(line);
+    g_free(lineup);
 }
Signature · 1 line
2.41.0
Reviewed-by on v1 12/12
#20 lore raw

Re: [PATCH 12/12] backends/tpm: Use qemu_hexdump_line() to avoid sprintf()

Quoted 5 lines · Philippe Mathieu-Daudé

sprintf() is deprecated on Darwin since macOS 13.0 / XCode 14.1, resulting in painful developper experience.

Use qemu_hexdump_line() to avoid sprintf() calls, silencing:

Quoted 8 lines

backends/tpm/tpm_util.c:357:14: warning: 'sprintf' is deprecated:
This function is provided for compatibility reasons only. Due to security concerns inherent in the design of sprintf(3), it is highly recommended that you use snprintf(3) instead. [-Wdeprecated-declarations]
p += sprintf(p, "%.2X ", buffer[i]);
^ >

Quoted 51 lines
---
  backends/tpm/tpm_util.c | 24 ++++++++----------------
  1 file changed, 8 insertions(+), 16 deletions(-)
backends/tpm/tpm_util.c +8 -16
index 1856589c3b..0747af2d1c 100644
@@ -21,6 +21,7 @@
 
  #include "qemu/osdep.h"
  #include "qemu/error-report.h"
+#include "qemu/cutils.h"
  #include "qapi/error.h"
  #include "qapi/visitor.h"
  #include "tpm_int.h"
@@ -336,27 +337,18 @@ void tpm_sized_buffer_reset(TPMSizedBuffer *tsb)
  void tpm_util_show_buffer(const unsigned char *buffer,
                            size_t buffer_size, const char *string)
  {
-    size_t len, i;
-    char *line_buffer, *p;
+    size_t len;
+    char *line, *lineup;
 
      if (!trace_event_get_state_backends(TRACE_TPM_UTIL_SHOW_BUFFER)) {
          return;
      }
      len = MIN(tpm_cmd_get_size(buffer), buffer_size);
 
-    /*
-     * allocate enough room for 3 chars per buffer entry plus a
-     * newline after every 16 chars and a final null terminator.
-     */
-    line_buffer = g_malloc(len * 3 + (len / 16) + 1);
+    line = qemu_hexdump_line(buffer, 0, len, false);
+    lineup = g_ascii_strup(line, -1);
+    trace_tpm_util_show_buffer(string, len, lineup);
 
-    for (i = 0, p = line_buffer; i < len; i++) {
-        if (i && !(i % 16)) {
-            p += sprintf(p, "\n");
-        }
-        p += sprintf(p, "%.2X ", buffer[i]);
-    }
-    trace_tpm_util_show_buffer(string, len, line_buffer);
-
-    g_free(line_buffer);
+    g_free(line);
+    g_free(lineup);
  }
#21 lore raw
In reply to Philippe Mathieu-Daudé
Quoted 4 lines · Philippe Mathieu-Daudé

Hi,

sprintf() is deprecated on Darwin since macOS 13.0 / XCode 14.1, resulting in painful developper experience.

Is snprintf also deprecated?
It might be easier to convert some of these fixed buffer cases that way, if allowed.

r~

#22 lore raw
Quoted 8 lines · Richard Henderson
Quoted 4 lines · Philippe Mathieu-Daudé

Hi,

sprintf() is deprecated on Darwin since macOS 13.0 / XCode 14.1, resulting in painful developper experience.

Is snprintf also deprecated?
It might be easier to convert some of these fixed buffer cases that way, if allowed.

I had the same thought as some of these might also have performance implications (although most of them are in rarely called places).

Regards,
BALATON Zoltan

#23 lore raw
Quoted 11 lines · BALATON Zoltan
Quoted 8 lines · Richard Henderson
Quoted 4 lines · Philippe Mathieu-Daudé

Hi,

sprintf() is deprecated on Darwin since macOS 13.0 / XCode 14.1, resulting in painful developper experience.

Is snprintf also deprecated?
It might be easier to convert some of these fixed buffer cases that way, if allowed.

I had the same thought as some of these might also have performance implications (although most of them are in rarely called places).

I thought GLib/GString was recommended for formatting (IIRC some previous discussion with Alex / Daniel), so I switched to this API for style, rather than thinking of performance. Anyway, I'll respin using sprintf() when the buffer size maths are already done.

Quoted 3 lines

Regards,
BALATON Zoltan

#24 lore raw
Quoted 12 lines · Philippe Mathieu-Daudé
Quoted 11 lines · BALATON Zoltan
Quoted 9 lines · Richard Henderson
Quoted 4 lines · Philippe Mathieu-Daudé

Hi,

sprintf() is deprecated on Darwin since macOS 13.0 / XCode 14.1, resulting in painful developper experience.

Is snprintf also deprecated?
It might be easier to convert some of these fixed buffer cases that way, if allowed.

Quoted 7 lines
Quoted 2 lines

I had the same thought as some of these might also have performance implications (although most of them are in rarely called places).

I thought GLib/GString was recommended for formatting (IIRC some previous discussion with Alex / Daniel), so I switched to this API for style, rather than thinking of performance. Anyway, I'll respin using sprintf() when the buffer size maths are already done.

There are places in QEMU where the strings end up living in a fixed size struct fields, and those would be candidates for sticking with snprint().

For stack allocated string buffers, it is preferrable to switch to g_autofree + g_strdup_printf(), unless there's a compelling performance reason to avoid allocation in a hot path IMHO.

With regards,
Daniel

Signature · 3 lines
|: https://berrange.com      -o-    https://www.flickr.com/photos/dberrange :|
|: https://libvirt.org         -o-            https://fstop138.berrange.com :|
|: https://entangle-photo.org    -o-    https://www.instagram.com/dberrange :|