Microsoft MVP성태의 닷넷 이야기
Linux: 76. Linux - C++ (getaddrinfo 등을 담고 있는) libnss 정적 링크 [링크 복사], [링크+제목 복사],
조회: 7131
글쓴 사람
정성태 (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

비밀번호

댓글 작성자
 




... 106  107  108  109  110  [111]  112  113  114  115  116  117  118  119  120  ...
NoWriterDateCnt.TitleFile(s)
11149정성태2/21/201723013오류 유형: 378. A 64-bit test cannot run in a 32-bit process. Specify platform as X64 to force test run in X64 mode on X64 machine.
11148정성태2/20/201721961.NET Framework: 644. AppDomain에 대한 단위 테스트 시 알아야 할 사항
11147정성태2/19/201721200오류 유형: 377. Windows 10에서 Fake 어셈블리를 생성하는 경우 빌드 시 The type or namespace name '...' does not exist in the namespace 컴파일 오류 발생
11146정성태2/19/201719855오류 유형: 376. Error VSP1033: The file '...' does not contain a recognized executable image. [2]
11145정성태2/16/201721336.NET Framework: 643. 작업자 프로세스(w3wp.exe)가 재시작되는 시점을 알 수 있는 방법 - 두 번째 이야기 [4]파일 다운로드1
11144정성태2/6/201724676.NET Framework: 642. C# 개발자를 위한 Win32 DLL export 함수의 호출 규약 (부록 1) - CallingConvention.StdCall, CallingConvention.Cdecl에 상관없이 왜 호출이 잘 될까요?파일 다운로드1
11143정성태2/5/201722088.NET Framework: 641. [Out] 형식의 int * 인자를 가진 함수에 대한 P/Invoke 호출 방법파일 다운로드1
11142정성태2/5/201730084.NET Framework: 640. 닷넷 - 배열 크기의 한계 [2]파일 다운로드1
11141정성태1/31/201724366.NET Framework: 639. C# 개발자를 위한 Win32 DLL export 함수의 호출 규약 (4) - CLR JIT 컴파일러의 P/Invoke 호출 규약 [1]파일 다운로드1
11140정성태1/27/201720127.NET Framework: 638. RSAParameters와 RSA파일 다운로드1
11139정성태1/22/201722807.NET Framework: 637. C# 개발자를 위한 Win32 DLL export 함수의 호출 규약 (3) - x64 환경의 __fastcall과 Name mangling [1]파일 다운로드1
11138정성태1/20/201721069VS.NET IDE: 113. 프로젝트 생성 시부터 "Enable the Visual Studio hosting process" 옵션을 끄는 방법 - 두 번째 이야기 [3]
11137정성태1/20/201719787Windows: 135. AD에 참여한 컴퓨터로 RDP 연결 시 배경 화면을 못 바꾸는 정책
11136정성태1/20/201718990오류 유형: 375. Hyper-V 내에 구성한 Active Directory 환경의 시간 구성 방법 - 두 번째 이야기
11135정성태1/20/201719974Windows: 134. Windows Server 2016의 작업 표시줄에 있는 시계가 사라졌다면? [1]
11134정성태1/20/201727399.NET Framework: 636. System.Threading.Timer를 이용해 타이머 작업을 할 때 유의할 점 [5]파일 다운로드1
11133정성태1/20/201723508.NET Framework: 635. C# 개발자를 위한 Win32 DLL export 함수의 호출 규약 (2) - x86 환경의 __fastcall [1]파일 다운로드1
11132정성태1/19/201734993.NET Framework: 634. C# 개발자를 위한 Win32 DLL export 함수의 호출 규약 (1) - x86 환경에서의 __cdecl, __stdcall에 대한 Name mangling [1]파일 다운로드1
11131정성태1/13/201723942.NET Framework: 633. C# - IL 코드 분석을 위한 팁 [2]
11130정성태1/11/201724436.NET Framework: 632. x86 실행 환경에서 SECURITY_ATTRIBUTES 구조체를 CreateEvent에 전달할 때 예외 발생파일 다운로드1
11129정성태1/11/201728826.NET Framework: 631. async/await에 대한 "There Is No Thread" 글의 부가 설명 [9]파일 다운로드1
11128정성태1/9/201723279.NET Framework: 630. C# - Interlocked.CompareExchange 사용 예제 [3]파일 다운로드1
11127정성태1/8/201722794기타: 63. (개발자를 위한) Visual Studio의 "with MSDN" 라이선스 설명
11126정성태1/7/201727536기타: 62. Edge 웹 브라우저의 즐겨찾기(Favorites)를 편집/백업/복원하는 방법 [1]파일 다운로드1
11125정성태1/7/201724367개발 환경 구성: 310. IIS - appcmd.exe를 이용해 특정 페이지에 클라이언트 측 인증서를 제출하도록 설정하는 방법
11124정성태1/4/201727815개발 환경 구성: 309. 3년짜리 유효 기간을 제공하는 StartSSL [2]
... 106  107  108  109  110  [111]  112  113  114  115  116  117  118  119  120  ...