Wednesday, April 6, 2022

[SOLVED] How to use -fPIC and -fPIE GCC options correctly

Issue

I have a directory structure like this

dir1
    one.c
    two.c
dir2
    three_main.c
    four.c

I need to create a shared library libdir1.so out of all c files in dir1
and an executable my_exe out of all c files in dir2 along with the libdir1.so

I am creating the .so and the executable in two steps.

.so step1:    gcc -c -fPIC -g -O2 -pthread -o one.o one.c
              gcc -c -fPIC -g -O2 -pthread -o two.o two.c
.so step2:    gcc -shared -g -O2 -pthread -o libdir1.so one.o two.o


exe step1:    gcc -c -fPIE -o three_main.o three_main.c
              gcc -c -fPIE -o four.o four.c
exe step2:    gcc -Wall -g -L -ldir1 -o my_exe three_main.o four.o

Now my questions are....

  1. Should I use -fPIC and -fPIE in step1 or step2 or in both?
  2. Can I use -fPIE in step2 in creating the .so file?
  3. Can I use -fPIC in step1 in creating the executable?
  4. How can I use RELRO compiler option in creating both .so and executable?

Thanks


Solution

Should I use -fPIC and -fPIE in step1 or step2 or in both?

No. The way you currently build the .so and the binary is correct / optimal.

Can I use -fPIE in step2 in creating the .so file?

You could, but you shouldn't: -fPIE is a compile-time option, and you are only linking in step2. If you pass -fPIE to the link, it will be ignored.

Can I use -fPIC in step1 in creating the executable?

You could, but this will create sub-optimal code in the executable.

How can I use RELRO compiler option in creating both .so and executable?

Add -Wl,-z,relro.

should I be using -z,now along with -Wl,-z,relro to be effective?

Yes: for maximum hardening, you should. -Wl,-z,relro without -z,now is not ineffective, but it is less effective. Details.

can I use relro for both binary and .so?

Yes.



Answered By - Employed Russian
Answer Checked By - Dawn Plyler (WPSolving Volunteer)