On 07/08/2023 16:51, Şahin Duran via Gcc wrote:
Dear GCC Developers,
I think I've just discovered a bug/ undefined situation in the compiler.
When I try to call a weakly defined function, compiler successfully
generates the code of calling procedure. However, this calling procedure is
nothing but branching to address 0 which results in segmentation fault. I
am not sure if this is the case for the latest version of GCC but it is for
GCC 4.9.2 and many online compilers. I just thought that maybe including a
rule that generates compilation error when the user defines a weak function
and calls it without actually implementing it. You may find the results in
the attachments.
Kind regards,
I am looking forward to hearing from you about this.
Şahin Duran
If a function might be weak, you need to test that it is defined before
calling it. So this is a bug in your program. You need to write
if (add)
add (31, 31);
Or something like that which checks that the symbol has been defined.
R.
Attachments:
Source Code:
#include <stdio.h>
#include <stdlib.h>
#include "header.h"
__attribute__((weak)) int add(int,int);
int main(int argc, char *argv[]) {
printf("%x",add);
add(31,31);
return 0;
}
terminal result : 0
Disassembly (on a 64bit AMD Machine):
0x0000000000401530 <+0>: push rbp
0x0000000000401531 <+1>: mov rbp,rsp
0x0000000000401534 <+4>: sub rsp,0x20
0x0000000000401538 <+8>: mov DWORD PTR [rbp+0x10],ecx
0x000000000040153b <+11>: mov QWORD PTR [rbp+0x18],rdx
0x000000000040153f <+15>: call 0x402100 <__main>
0x0000000000401544 <+20>: mov rdx,QWORD PTR [rip+0x2ed5] #
0x404420 <.refptr.add>
0x000000000040154b <+27>: lea rcx,[rip+0x2aae] # 0x404000
0x0000000000401552 <+34>: call 0x402b18 <printf>
=> 0x0000000000401557 <+39>: mov edx,0x1f
0x000000000040155c <+44>: mov ecx,0x1f
0x0000000000401561 <+49>: call 0x0
0x0000000000401566 <+54>: mov eax,0x0
0x000000000040156b <+59>: add rsp,0x20
0x000000000040156f <+63>: pop rbp
0x0000000000401570 <+64>: ret