Skip to content

Discrepancy in debugging information for the value pointed to by the global pointer variable "shared_ptr" in binaries compiled with optimization levels "-O0", "-O1", "-O2", and "-O3" #107144

@edumoot

Description

@edumoot

The value obtained by dereferencing the global pointer shared_ptr is inconsistent at line 38. It shows 1 in binaries compiled with "-O0" and "-O1", but displays 1139366573 in binaries compiled with "-O2" and "-O3". Godblot Link

We can reproduce this issue in LLVM versions 18.1.8, 17.0.6, and 16.0.3 :

clang -g -O3 -o 402_O3.out 402.c
clang -g -O2 -o 402_O2.out 402.c
clang -g -O1 -o 402_O1.out 402.c
clang -g -O0 -o 402_O0.out 402.c

(lldb) file 402_O3.out
(lldb) b 38
(lldb) r
[...]

(lldb) p *shared_ptr
(int) 1139366573


(lldb) file 402_O1.out
(lldb) b 38
(lldb) r
[...]

(lldb) p *shared_ptr
(int) 1


cat 402.c

struct S0 {
   volatile int f0;
   unsigned short f1;
};

union U3 {
   struct S0 f0;
   signed f1 ;
};

static unsigned global_flag = 1U;
static int global_var = 0x43E95AAD;
static int *const global_ptr = &global_var;
static volatile union U3 global_union = {{-1, 0x2079}};
static int helper_var = 0xCAAAA389;
static int main_var = 0x1340892D;
static int *const main_ptr = &main_var;
static int *const volatile shared_ptr = &global_var;

static unsigned execute_main(void);
static int *execute_func(unsigned long long param);
static unsigned helper_func(int *ptr1, int val, int *ptr2);

static unsigned execute_main(void) {
    int *local_ptr = &global_var;
    int **double_ptr = &local_ptr;

    *local_ptr &= global_flag;
    *shared_ptr = (*main_ptr ^= (execute_func(global_var) != main_ptr));
    return **double_ptr;
}

static int *execute_func(unsigned long long param) {
    long long temp_val = 0;
    int *result_ptr = &global_var;
    int *update_ptr = &helper_var;

    *update_ptr |= ((param < param) >= (global_union, helper_func(&global_var, (*result_ptr = (0xA7 + temp_val)), result_ptr)));
    return result_ptr;
}

static unsigned helper_func(int *ptr1, int val, int *ptr2) {
    int temp_var = -9;
    unsigned short temp_flag = 65535U;
    temp_flag++;
    return global_union.f0.f0;
}

int main(void) {
    execute_main();
    return 0;
}

GDB also demonstrates the same issue.

(gdb) file 402_O3.out
(gdb) b 38
(gdb) r
[...]
(gdb) p *shared_ptr
$5 = 1139366573


(gdb) file 402_O1.out
(gdb) b 38
(gdb) r
[...]
(gdb) p *shared_ptr
$4 = 1


$ gdb --version
GNU gdb (Ubuntu 15.0.50.20240403-0ubuntu1) 15.0.50.20240403-git

Metadata

Metadata

Assignees

No one assigned

    Labels

    debuginfollvm:optimizationsquestionA question, not bug report. Check out https://llvm.org/docs/GettingInvolved.html instead!

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions