From 9858e47dfd0d945b750bce7b19716a834f0d78e3 Mon Sep 17 00:00:00 2001 From: Jesse Rosenstock Date: Sun, 21 Jun 2020 21:28:32 +0200 Subject: [PATCH] Pad bit-fields only to the next byte Fixes #1054. Previously, bit-fields followed by another field were aligned to two bytes. Bit-fields ending the struct were (and continue to be) aligned only to a single byte. ``` struct s { unsigned int x : 4; }; struct t { unsigned int x : 4; unsigned int y; }; ``` Before: `sizeof(struct s) == 1`, sizeof(struct t) == 4` After: `sizeof(struct s) == 1` sizeof(struct t) == 3` --- src/cc65/declare.c | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/src/cc65/declare.c b/src/cc65/declare.c index d7940c93b..730406088 100644 --- a/src/cc65/declare.c +++ b/src/cc65/declare.c @@ -772,17 +772,19 @@ static SymEntry* ParseStructDecl (const char* Name) */ if (BitOffs > 0) { if (FieldWidth <= 0 || (BitOffs + FieldWidth) > INT_BITS) { + /* Bits needed to byte-align the next field. */ + unsigned PaddingBitWidth = -BitOffs % CHAR_BITS; /* We need an anonymous name */ AnonName (Ident, "bit-field"); /* Add an anonymous bit-field that aligns to the next - ** storage unit. + ** byte. */ - AddBitField (Ident, StructSize, BitOffs, INT_BITS - BitOffs); + AddBitField (Ident, StructSize, BitOffs, PaddingBitWidth); /* No bits left */ - StructSize += SIZEOF_INT; + StructSize += (BitOffs + PaddingBitWidth) / CHAR_BITS; BitOffs = 0; } }