nix-community / nix-user-chroot

Install & Run nix without root permissions [maintainer=@Mic92]
MIT License
281 stars 25 forks source link

Building program with nix-shell #49

Closed pachiras closed 3 years ago

pachiras commented 3 years ago

Hello,

Thank you for sharing the great program. But I have a difficulty in building a program with nix-shell.

I wanted to build a program with gcc8. So, here is what I tried:

$ ls
hello.c
$ nix-user-chroot /data/nas1/nix/ bash -l
$ nix-shell -p gcc8Stdenv
bash: warning: setlocale: LC_ALL: cannot change locale (en_US.UTF-8)
bash: warning: setlocale: LC_ALL: cannot change locale (en_US.UTF-8)

[nix-shell:/data/nas1/workspace/test]$ gcc hello.c
/nix/store/kxj6cblcsd1qcbbxlmbswwrn89zcmgd6-bash-4.4-p23/bin/bash: warning: setlocale: LC_ALL: cannot change locale (en_US.UTF-8)
/nix/store/kxj6cblcsd1qcbbxlmbswwrn89zcmgd6-bash-4.4-p23/bin/bash: warning: setlocale: LC_ALL: cannot change locale (en_US.UTF-8)

[nix-shell:/data/nas1/workspace/test]$ ls
a.out  hello.c

[nix-shell:/data/nas1/workspace/test]$ ./a.out
Hello World

[nix-shell:/data/nas1/workspace/test]$ exit
exit
$ ./a.out
Hello World
$ exit
logout
$ ./a.out
-bash: ./a.out: No such file or directory
$ ls -l
total 40
-rwxr-xr-x 1 pachiras analyzer 33792 Jul 15 17:06 a.out
-rw-r--r-- 1 pachtras analyzer    63 Jul 15 17:05 hello.c

Once I get out of the nix-user-chroot environment, I cannot execute the program anymore. What I want to do is just using nix as a developing environment. I would be happy if I could use the program outside of the environment. Is it possible?

Mic92 commented 3 years ago

The issue is that the link-loader embedded into your program (check readelf -a ./a.out| grep /nix) and library paths will have nix store references: /nix/store. I see two possible workarounds for this. In theory you could patchelf afterwards to fix those to point to /data/nas1/nix for its rpath/ld or fix your NIX_CFLAGS_COMPILE, NIX_LDFLAGS to container /data/nas1/nix instead of /nix paths before compiling. However this will break if your libraries have dependencies as their rpath will have nix store references again. The other option would to statically link your program... You might want to look at pkgsStatic for that.

Mic92 commented 3 years ago

There is nothing meaningful I can fix to help with that in nix-user-chroot.

Mic92 commented 3 years ago

Third option: call your program with ldd command and set LD_LIBRARY_PATH according to what the rpath of your program contained before.

pachiras commented 3 years ago

Thank you @Mic92. It became clear why I couldn't run the program. I'll look for solution in pkgsStatic. Thanks, again.