Skip site navigation (1)Skip section navigation (2)
Date:      Sun, 10 Oct 2004 22:21:20 -0500
From:      Dan Nelson <dnelson@allantgroup.com>
To:        "Li, Qing" <qing.li@bluecoat.com>
Cc:        freebsd-hackers@freebsd.org
Subject:   Re: Bit field definition ?
Message-ID:  <20041011032120.GA10108@dan.emsphone.com>
In-Reply-To: <00CDF9AA240E204FA6E923BD35BC643606BF695A@bcs-mail.internal.cacheflow.com>
References:  <00CDF9AA240E204FA6E923BD35BC643606BF695A@bcs-mail.internal.cacheflow.com>

next in thread | previous in thread | raw e-mail | index | archive | help
In the last episode (Oct 10), Li, Qing said:
> > In the last episode (Oct 08), Li, Qing said:
> > > 	The bit fields "th_x2" and "th_off" in "struct tcphdr", even
> > > 	though defined as "u_int", actually occupies 1 byte.
> > 
> >     u_int   th_x2:4,        /* (unused) */
> >         th_off:4;       /* data offset */
> > 
> > The :4 after each variable means 4 bits long, so both fields
> > together take up 8 bits = 1 byte.  That's the whole purpose of
> > bitfields :)
> 	
> 	D'oh
> 
> 	I didn't ask the right question.
> 
> 	It seems u_int specifies the packing and alignment size
> 	for the bit fields, is that correct ?

I don't think so.  C99 only allows bitfields to be of type Bool, signed
_int, or unsigned int, so that seems to prevent the use of
char/short/int/long to dictate padding or alignment.  There must be
something in the FreeBSD ABI that says structs must be padded so they
are 4-byte aligned, even if none of the members require it. Try putting
your 4 structs into a program and compiling them with gcc -Wpadding:

> 	struct {
>           u_int a:4,   
>                 b:4;
> 	};               is 4 bytes in size.
a.c:7: warning: padding struct size to alignment boundary

> 	struct {
>          u_int a:4,
>                b:4;
>          short c;
>       };               is 4 bytes in size.
a.c:13: warning: padding struct to align 'c'
(1 byte of padding added just before c)

>       struct {
>          u_int a:4,
>                b:4;
>          short c;
>          u_char d;
>       };               is 8 bytes in size;
a.c:19: warning: padding struct to align 'c' 
(1 byte padding just before c, and 3 bytes just after d).  I think it
should have printed a "padding struct size to alignment boundary"
warning also, since if it didn't, the padding after d would have been 1
byte, and struct would have been 6 bytes total.
 
>       But
> 
>       struct {
>          u_int a:4,
>                b:4;
>          u_char d;
>          short c;
>       };               is 4 bytes in size;
> 
a.c:21: warning: padding struct size to alignment boundary

This last warning I don't understand, since 1+1+2 is 4 all by itself. 
No padding is needed or used.

-- 
	Dan Nelson
	dnelson@allantgroup.com



Want to link to this message? Use this URL: <https://mail-archive.FreeBSD.org/cgi/mid.cgi?20041011032120.GA10108>