Skip to content

Byte-swapped packed struct fields are not swapped when read inside an array index (segfault in compilation) #622

Open

Description

@alpaylan

With -fpacked-structs (or -fall), a byte-swapped field read inside an array index is used without the byte swap:

#include <stdio.h>
struct __packed__(4, 0, 1) S { int w; };   /* fields stored byte-swapped */
int a[4] = {100, 200, 300, 400};
struct S s;
int main(void) {
  s.w = 2;
  printf("s.w = %d, a[s.w] = %d\n", s.w, a[s.w]);   /* expected: s.w = 2, a[s.w] = 300 */
  return 0;
}
$ ccomp -fpacked-structs t.c && ./a.out
Segmentation fault
$ ccomp -fpacked-structs -interp t.c
Stuck state: in function main, expression
  printf(<ptr __stringlit_1>, 2, <loc a+134217728>)
ERROR: Undefined behavior

gcc gives the expected result for the same layout, written with gcc's attributes:

struct __attribute__((packed, scalar_storage_order("big-endian"))) S { int w; };
$ gcc -O0 g.c && ./a.out        # gcc 15.2.0; same with -O2
s.w = 2, a[s.w] = 300

Tested on master (2685140) and v3.18.

Found by differential testing with Ephyra: generated C programs, CompCert
against gcc.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions