rusty icon indicating copy to clipboard operation
rusty copied to clipboard

Segmentation fault with --pic

Open ghaith opened this issue 2 years ago • 2 comments

With new master branch we are able to build with our code with commenting and without using --pic flag. Output binaries are also running successfully. But if we use --pic flag to build the code, it build successfully but when running the binary we are still getting Segmentation fault while running the code.

Originally posted by @eddkhfjgdkhgkjfbhnfguh in https://github.com/PLC-lang/rusty/discussions/1024#discussioncomment-7659100

ghaith avatar Nov 24 '23 16:11 ghaith

Since I'm a sucker for segfaults, I've briefly looked into this. The symbols seem to be all there (checked nm, objdump and gdb), so I started commenting out POUs until I ended up with the minimal reproducible example for the segfault, which is simply

FUNCTION main : DINT
END_FUNCTION

I've omitted the stdlib during compilation and added debug-information with the -g flag to attempt a backtrace in gdb, but we don't even reach main. Looking at the bt, it looks like something is messing up the stack.

gdb outputs of the MRE: bt

#0  0x00007fdbb6c1a000 in ?? ()
#1  0x0000000000000001 in ?? ()
#2  0x00007fff12ed533e in ?? ()
#3  0x0000000000000000 in ?? ()

info functions

All defined functions:

File target/demo.st:
1:      void main();

Of note here is that main() is being shown as void type when it is declared as i32 but this is also true when compiling without -pic, which runs without segfault so this might just be gdb.

I've also tried setting a breakpoint at main and running gdb to confirm this happens before we even get to main.

#0  0x00007f94d07a0000 in ?? ()
(gdb) break main
Breakpoint 1 at 0x7f94d07a1100: file target/demo.st, line 2.
(gdb) run
Starting program: /home/michael/dev/rusty/segfaulttest 

Program received signal SIGSEGV, Segmentation fault.
0x00007ffff7ffa000 in ?? ()

A workaround for now would be to compile using --ir instead of --pic and then compiling the resulting .ll file with clang file.ll -fPIC. The resulting binary runs without segfaulting.

mhasel avatar Nov 28 '23 12:11 mhasel

Further tests: I tried to compile the object file as pic plc seg.st -o seg.o --linker=clang -c --pic and then compile that file back into a normal application: plc seg.o -o seg --linker=clang and it works without segfault, i think clang is doing the same. Meaning only the object file is affected by the -fPIC flag and not the final binary

ghaith avatar Nov 29 '23 04:11 ghaith