Microsoft MVP성태의 닷넷 이야기
Linux: 76. Linux - C++ (getaddrinfo 등을 담고 있는) libnss 정적 링크 [링크 복사], [링크+제목 복사],
조회: 7567
글쓴 사람
정성태 (seongtaejeong at gmail.com)
홈페이지
첨부 파일
 
(연관된 글이 2개 있습니다.)
(시리즈 글이 4개 있습니다.)
Linux: 5. Linux 응용 프로그램의 (C++) so 의존성 줄이기(ReleaseMinDependency)
; https://www.sysnet.pe.kr/2/0/11845

개발 환경 구성: 698. Golang - GLIBC 의존을 없애는 정적 빌드 방법
; https://www.sysnet.pe.kr/2/0/13490

Linux: 64. Linux 응용 프로그램의 (C++) so 의존성 줄이기(ReleaseMinDependency) - 두 번째 이야기
; https://www.sysnet.pe.kr/2/0/13494

Linux: 76. Linux - C++ (getaddrinfo 등을 담고 있는) libnss 정적 링크
; https://www.sysnet.pe.kr/2/0/13679




Linux - C++ (getaddrinfo 등을 담고 있는) libnss 정적 링크

지난 글에 따라,

C# - AOT StaticExecutable 정적 링킹 시 빌드 오류
; https://www.sysnet.pe.kr/2/0/13669#form_23

간단하게 다음과 같은 재현 코드를 C/C++로 만들고,

#include <netdb.h>

int main()
{
    struct addrinfo* results;
    int rc = getaddrinfo("localhost", "80", nullptr, &results);
    freeaddrinfo(results);

    return 0;
}

정적 빌드하면 예상했던 (바로 그) 경고가 발생합니다.

$ gcc -static main.cpp -o test
/usr/bin/ld: /tmp/cch4VuOp.o: in function `main':
main.cpp:(.text+0x36): warning: Using 'getaddrinfo' in statically linked applications requires at runtime the shared libraries from the glibc version used for linking

비록 정적 링크는 되었지만,

$ file test
test: ELF 64-bit LSB executable, x86-64, version 1 (GNU/Linux), statically linked, BuildID[sha1]=ab0170b30cef878d7c87817e9b5b80ffed367a31, for GNU/Linux 3.2.0, not stripped

(예를 들어) 위의 빌드를 Ubuntu 18.04에서 수행한 경우, 바이너리 결과물은 20.04까지는 잘 실행이 되지만, 22.04에서 실행하면 예외가 발생합니다.

$ ./test
Segmentation fault




컴파일 시 나온 경고에 따르면 실행 시 공유 라이브러리가 필요하다고 하는데요, 실제로 gdb를 이용해 "Segmentation fault"가 발생한 상황에서 libnss_files 라이브러리가 로딩된 것을 확인할 수 있습니다.

$ gdb ./test
GNU gdb (Ubuntu 12.1-0ubuntu1~22.04.2) 12.1
...[생략]...
Type "apropos word" to search for commands related to "word"...
Reading symbols from ./test...
(No debugging symbols found in ./test)

(gdb) run
Starting program: /app/ConsoleApp1/ConsoleApplication1/test
warning: File "/usr/lib/x86_64-linux-gnu/libthread_db.so.1" auto-loading has been declined by your `auto-load safe-path' set to "$debugdir:$datadir/auto-load".
...[생략]...

Program received signal SIGSEGV, Segmentation fault.
0x00007ffff7f17d24 in __GI___nss_readline (poffset=<optimized out>, len=<optimized out>, buf=<optimized out>, fp=<optimized out>) at ../include/ctype.h:41
41      ../include/ctype.h: No such file or directory.

(gdb) i shared
From                To                  Syms Read   Shared Object Library
0x00007ffff7fed040  0x00007ffff7fed0f9  Yes         /lib/x86_64-linux-gnu/libnss_files.so.2
0x00007ffff7deb700  0x00007ffff7f7d93d  Yes         /lib/x86_64-linux-gnu/libc.so.6
0x00007ffff7d89090  0x00007ffff7db2315  Yes         /lib/x86_64-linux-gnu/ld-linux-x86-64.so.2

(gdb) bt
#0  0x00007ffff7f17d24 in __GI___nss_readline (poffset=<optimized out>, len=<optimized out>, buf=<optimized out>, fp=<optimized out>) at ../include/ctype.h:41
#1  __GI___nss_readline (fp=fp@entry=0x7ffff7c872a0,
    buf=buf@entry=0x7fffffffd6d0 "# This file was automatically generated by WSL. To stop automatic generation of this file, add the following entry to /etc/wsl.conf:\n", len=len@entry=992, poffset=poffset@entry=0x7fffffffd180) at ./nss/nss_readline.c:26
#2  0x00007ffff7f1b3a0 in internal_getent (stream=stream@entry=0x7ffff7c872a0, result=result@entry=0x7fffffffd220, buffer=buffer@entry=0x7fffffffd6b0 "",
    buflen=buflen@entry=1024, errnop=errnop@entry=0x4e6830, herrnop=herrnop@entry=0x4e6850, af=0) at nss_files/files-XXX.c:124
#3  0x00007ffff7f1c5e9 in __GI__nss_files_gethostbyname4_r (name=0x4b4007 "localhost", pat=0x7fffffffd398, buffer=0x7fffffffd6b0 "", buflen=1024,
    errnop=0x4e6830, herrnop=0x4e6850, ttlp=0x0) at nss_files/files-hosts.c:404
#4  0x0000000000449e5b in gaih_inet.constprop ()
#5  0x000000000044ba79 in getaddrinfo ()
#6  0x0000000000401d4f in main ()

게다가 libnss_files.so.2뿐만 아니라 libc.so.6까지 동적 로딩돼 정적으로 빌드된 C/C++ 라이브러리와의 충돌까지 발생할 수 있는 상황입니다.




결국, glibc에 대한 정적 링킹을 해도 getaddrinfo 등의 함수를 사용하게 되면 저렇게 Linux OS에 탑재된 glibc 버전에 따라 실행이 안 될 수 있습니다. 이것마저도 정적 빌드하려면,

Shared Libraries are Loaded by Custom glibc Compiled with --enable-static-nss
; https://stackoverflow.com/questions/66386087/shared-libraries-are-loaded-by-custom-glibc-compiled-with-enable-static-nss

nss 관련 라이브러리를 정적으로 포함하는 (--enable-static-nss 옵션을 적용해 빌드한) glibc 버전이 필요합니다. 그렇긴 한데, (덧글에 소개가 된) 아래의 글을 보면,

Static Linking Considered Harmful
; https://www.akkadia.org/drepper/no_static_linking.html

저 역시, 과연 리눅스 환경에서 glibc에 대한 정적 빌드를 하는 것이 필요한가...라는 생각이 드는군요. ^^; 아무래도 glibc에 대한 빌드까지는 동적으로 하고 아주 특별한 상황, 예를 들어 busybox 등의 환경에 올릴 제한적인 도구에 대해서만 정적 빌드를 하는 것이 좋을 듯합니다.

실제로 위의 예제 코드를 glibc에 대해 동적 링킹을 하면 22.04에서도 잘 실행이 됩니다. 즉, 실행 환경을 독립적으로 유지하기 위해 정적 링킹을 하려고 애쓴 것보다, 아이러니하게도 오히려 동적 링킹을 하는 것이 더 범용성이 좋아진 것입니다.




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]

[연관 글]






[최초 등록일: ]
[최종 수정일: 8/6/2024]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 




... 16  17  18  19  20  [21]  22  23  24  25  26  27  28  29  30  ...
NoWriterDateCnt.TitleFile(s)
13450정성태11/21/202311303닷넷: 2164. C# - Octokit을 이용한 GitHub Issue 검색파일 다운로드1
13449정성태11/21/202311840개발 환경 구성: 688. Azure OpenAI 서비스 신청 방법
13448정성태11/20/202311127닷넷: 2163. .NET 8 - Dynamic PGO를 결합한 성능 향상파일 다운로드1
13447정성태11/16/202311778닷넷: 2162. ASP.NET Core 웹 사이트의 SSL 설정을 코드로 하는 방법
13446정성태11/16/202312161닷넷: 2161. .NET Conf 2023 - Day 1 Blazor 개요 정리
13445정성태11/15/202313150Linux: 62. 리눅스/WSL에서 CA 인증서를 저장하는 방법
13444정성태11/15/202312274닷넷: 2160. C# 12 - Experimental 특성 지원
13443정성태11/14/202311532개발 환경 구성: 687. OpenSSL로 생성한 사용자 인증서를 ASP.NET Core 웹 사이트에 적용하는 방법
13442정성태11/13/202311011개발 환경 구성: 686. 비주얼 스튜디오로 실행한 ASP.NET Core 사이트를 WSL 2 인스턴스에서 https로 접속하는 방법
13441정성태11/12/202311903닷넷: 2159. C# - ASP.NET Core 프로젝트에서 서버 Socket을 직접 생성하는 방법파일 다운로드1
13440정성태11/11/202310510Windows: 253. 소켓 Listen 시 방화벽의 Public/Private 제어 기능이 비활성화된 경우
13439정성태11/10/202312367닷넷: 2158. C# - 소켓 포트를 미리 시스템에 등록/예약해 사용하는 방법(Port Exclusion Ranges)파일 다운로드1
13438정성태11/9/202312575닷넷: 2157. C# - WinRT 기능을 이용해 윈도우에서 실행 중인 Media App 제어
13437정성태11/8/202312792닷넷: 2156. .NET 7 이상의 콘솔 프로그램을 (dockerfile 없이) 로컬 docker에 배포하는 방법
13436정성태11/7/202312920닷넷: 2155. C# - .NET 8 런타임부터 (Reflection 없이) 특성을 이용해 public이 아닌 멤버 호출 가능
13435정성태11/6/202311502닷넷: 2154. C# - 네이티브 자원을 포함한 관리 개체(예: 스레드)의 GC 정리
13434정성태11/1/202312135스크립트: 62. 파이썬 - class의 정적 함수를 동적으로 교체
13433정성태11/1/202310628스크립트: 61. 파이썬 - 함수 오버로딩 미지원
13432정성태10/31/202311737오류 유형: 878. 탐색기의 WSL 디렉터리 접근 시 "Attempt to access invalid address." 오류 발생
13431정성태10/31/202312073스크립트: 60. 파이썬 - 비동기 FastAPI 앱을 gunicorn으로 호스팅
13430정성태10/30/202312549닷넷: 2153. C# - 사용자가 빌드한 ICU dll 파일을 사용하는 방법
13429정성태10/27/202312550닷넷: 2152. Win32 Interop - C/C++ DLL로부터 이중 포인터 버퍼를 C#으로 받는 예제파일 다운로드1
13428정성태10/25/202312863닷넷: 2151. C# 12 - ref readonly 매개변수
13427정성태10/18/202311557닷넷: 2150. C# 12 - 정적 문맥에서 인스턴스 멤버에 대한 nameof 접근 허용(Allow nameof to always access instance members from static context)
13426정성태10/13/202312428스크립트: 59. 파이썬 - 비동기 호출 함수(run_until_complete, run_in_executor, create_task, run_in_threadpool)
13425정성태10/11/202312712닷넷: 2149. C# - PLinq의 Partitioner<T>를 이용한 사용자 정의 분할파일 다운로드1
... 16  17  18  19  20  [21]  22  23  24  25  26  27  28  29  30  ...