aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorKaz Kylheku <kaz@kylheku.com>2024-10-06 13:27:10 -0700
committerKaz Kylheku <kaz@kylheku.com>2024-10-06 13:27:10 -0700
commit3e53a79ea9825172f8a5ccc019af088c5a1e0994 (patch)
tree90263b1b369c3910f90451d9f5269592d5d672fd
parent8534e9e277723a48cff9f791253a856506e72aa1 (diff)
downloadpw-3e53a79ea9825172f8a5ccc019af088c5a1e0994.tar.gz
pw-3e53a79ea9825172f8a5ccc019af088c5a1e0994.tar.bz2
pw-3e53a79ea9825172f8a5ccc019af088c5a1e0994.zip
bugfix: memory corruption due to sizeof (dstr)
This was reportd by Jeremy Brubaker along with a working patch. I reworked it to a shorter fix. Jeremy is using GCC 13.3.1, Evidently, the sizeof a struct which has a flexible array member is not the same as the offsetof that member, which we are relying on. I have to research more into this because ISO C seems to require them to be the same. * pw.c (dstr_of, dsgrow): use offsetof (struct dsr, str) rather than sizeof (dstr) when displacing the string pointer back to the header, and when allocating the space.
-rw-r--r--pw.c5
1 files changed, 3 insertions, 2 deletions
diff --git a/pw.c b/pw.c
index 29b4cb5..a2ddff0 100644
--- a/pw.c
+++ b/pw.c
@@ -26,6 +26,7 @@
// POSSIBILITY OF SUCH DAMAGE.
#include <assert.h>
+#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
@@ -130,7 +131,7 @@ typedef struct dstr {
char str[];
} dstr;
-#define dstr_of(str) ((dstr *) ((str) - sizeof (dstr)))
+#define dstr_of(s) ((dstr *) ((s) - offsetof (struct dstr, str)))
static char *pw_name;
static int poll_interval = 1000;
@@ -203,7 +204,7 @@ static char *dsgrow(char *str, size_t len)
{
dstr *ds = str ? dstr_of(str) : 0;
int flags = str ? ds->flags : 0;
- size_t size = sizeof *ds + len + 1;
+ size_t size = offsetof(struct dstr, str) + len + 1;
assert (ds == 0 || ds->refs == 1);