Skip to contentSkip to conversation

xenpmd.c: use dynamic allocation

PATCH In review Manuel Bouyer 2 participants 4 messages Jan 30, 2021 – Feb 1, 2021

lore
Share & tools
lore
#0 lore raw

PATCH v3 1/2 xenpmd.c: use dynamic allocation

On NetBSD, d_name is larger than 256, so file_name[284] may not be large enough (and gcc emits a format-truncation error).
Use asprintf() instead of snprintf() on a static on-stack buffer.

---
 tools/xenpmd/xenpmd.c | 8 ++++----
 1 file changed, 4 insertions(+), 4 deletions(-)
tools/xenpmd/xenpmd.c +4 -4
index 12b82cf43e..e432aad856 100644
@@ -101,7 +101,7 @@ FILE *get_next_battery_file(DIR *battery_dir,
 {
     FILE *file = 0;
     struct dirent *dir_entries;
-    char file_name[284];
+    char *file_name;
     int ret;
     
     do 
@@ -112,16 +112,16 @@ FILE *get_next_battery_file(DIR *battery_dir,
         if ( strlen(dir_entries->d_name) < 4 )
             continue;
         if ( battery_info_type == BIF ) 
-            ret = snprintf(file_name, sizeof(file_name), BATTERY_INFO_FILE_PATH,
+            ret = asprintf(&file_name, BATTERY_INFO_FILE_PATH,
                      dir_entries->d_name);
         else 
-            ret = snprintf(file_name, sizeof(file_name), BATTERY_STATE_FILE_PATH,
+            ret = asprintf(&file_name, BATTERY_STATE_FILE_PATH,
                      dir_entries->d_name);
         /* This should not happen but is needed to pass gcc checks */
         if (ret < 0)
             continue;
-        file_name[sizeof(file_name) - 1] = '\0';
         file = fopen(file_name, "r");
+	free(file_name);
     } while ( !file );
 
     return file;
Signature · 1 line
2.29.2
#1 lore raw

PATCH v3 2/2 define GNU_SOURCE for asprintf()

#define _GNU_SOURCE to get for asprintf() prototype on Linux. Harmless on NetBSD.

---
 tools/xenpmd/xenpmd.c | 1 +
 1 file changed, 1 insertion(+)
tools/xenpmd/xenpmd.c +1 -0
index e432aad856..8e783181e1 100644
@@ -32,6 +32,7 @@
  * passed to the guest when appropriate battery ports are read/written to.
  */
 
+#define _GNU_SOURCE         /* for asprintf() */
 #include <stdio.h>
 #include <stdarg.h>
 #include <string.h>
Signature · 1 line
2.29.2
#2 lore raw

Re: [PATCH v3 2/2] define GNU_SOURCE for asprintf()

Manuel Bouyer writes ("[PATCH v3 2/2] define GNU_SOURCE for asprintf()"):

Quoted 2 lines

#define _GNU_SOURCE to get for asprintf() prototype on Linux. Harmless on NetBSD.

This needs to be folded into the previous patch so I will do so.

Ian.

#3 lore raw
In reply to Manuel Bouyer

Manuel Bouyer writes ("[PATCH v3 1/2] xenpmd.c: use dynamic allocation"):

Quoted 6 lines

On NetBSD, d_name is larger than 256, so file_name[284] may not be large enough (and gcc emits a format-truncation error).
Use asprintf() instead of snprintf() on a static on-stack buffer.

I consider this a bugfix, so

I think Roger's ack got dropped, so I have added it back.#

Ian.