I know why GCC doesn\'t re-order members of a structure by default, but I seldom write code that relies on the order of the structure, so is there some way I can flag my str
As a side note, the Linux kernel implements a gcc plugin to introduce an attibute named randomize_layout. The goal is to use it in the definition of the structures to make the compiler randomize the order of the fields. Linux kernel uses it for the sake of security to counter attacks that need to know the layout of structures. For example the cred structure is defined as follow in include/linux/cred.h:
struct cred {
atomic_t usage;
#ifdef CONFIG_DEBUG_CREDENTIALS
atomic_t subscribers; /* number of processes subscribed */
void *put_addr;
[...]
struct user_struct *user; /* real user ID subscription */
struct user_namespace *user_ns; /* user_ns the caps and keyrings are relative to. */
struct group_info *group_info; /* supplementary groups for euid/fsgid */
/* RCU deletion */
union {
int non_rcu; /* Can we skip RCU deletion? */
struct rcu_head rcu; /* RCU deletion hook */
};
} __randomize_layout;
The __randomize_layout tag is defined in include/linux/compiler-gcc.h of the Linux source tree as:
#define __randomize_layout __attribute__((randomize_layout))