https://gcc.gnu.org/bugzilla/show_bug.cgi?id=120182

            Bug ID: 120182
           Summary: Incorrect code with -O3
           Product: gcc
           Version: 16.0
            Status: UNCONFIRMED
          Severity: normal
          Priority: P3
         Component: rtl-optimization
          Assignee: unassigned at gcc dot gnu.org
          Reporter: fanghs666 at gmail dot com
  Target Milestone: ---

struct S
{
    struct S *next;
};

#define MAP_PRIVATE 0x02
#define MAP_ANONYMOUS 0x20
#define MAP_FIXED_NOREPLACE 0x100000
#define PROT_READ 0x1
#define PROT_WRITE 0x2
void *mmap(void *addr, unsigned long long length, int prot, int flags, int fd,
long long offset);
void exit(int status);
int printf(const char *format, ...);

static void
allocate(void *addr, unsigned long long size)
{
    void *ptr = mmap((void *)addr, size,
                     PROT_READ | PROT_WRITE,
                     MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED_NOREPLACE,
                     -1, 0);
    if(ptr != addr)
        exit(1);
}

int main (void)
{
    int size = 0x8000;
    char *ptr = (char *)0x288000ull;
    allocate((void *)ptr, size);

    struct S *s1 = (struct S *)ptr;
    struct S *s2 = (struct S *)256;
    for (int i = 0; i < 3; i++)
    {
        for(char *addr = (char *)s1; addr < (char *)s1 + sizeof(*s1); ++addr)
            *addr = 0;

        if(s1->next)
            s1->next = s1->next->next = s2;
        else
            s1->next = s2;
    }
    printf("DONE\n");
    return 0;
}


The expected output is "DONE".

$ gcc-trunk -O3 -fPIE -pie a.c
$ ./a.out
Segmentation fault (core dumped)

The result will be correct if:
1. Use "s1->next = 0;" to clear the memory instead of clearing each byte in a
loop.
2. or s2 <= 255.

Reply via email to