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

비밀번호

댓글 작성자
 




... 76  77  78  79  80  81  82  83  [84]  85  86  87  88  89  90  ...
NoWriterDateCnt.TitleFile(s)
11835정성태3/5/201921705.NET Framework: 810. C# 8.0의 Index/Range 연산자를 .NET Framework에서 사용하는 방법 및 비동기 스트림의 컴파일 방법 [3]파일 다운로드1
11834정성태3/4/201920549개발 환경 구성: 432. Visual Studio 없이 최신 C# (8.0) 컴파일러를 사용하는 방법
11833정성태3/4/201921046개발 환경 구성: 431. Visual Studio 2019 - CMake를 이용한 공유/실행(so/out) 리눅스 프로젝트 설정파일 다운로드1
11832정성태3/4/201916984오류 유형: 524. Visual Studio CMake - rsync: connection unexpectedly closed
11831정성태3/4/201916791오류 유형: 523. Visual Studio 2019 - 새 창으로 뜬 윈도우를 닫을 때 비정상 종료
11830정성태2/26/201916490오류 유형: 522. 이벤트 로그 - Error opening event log file State. Log will not be processed. Return code from OpenEventLog is 87.
11829정성태2/26/201918234개발 환경 구성: 430. 마이크로소프트의 CoreCLR 프로파일러 예제 빌드 방법 - 리눅스 환경 [1]
11828정성태2/26/201926117개발 환경 구성: 429. Component Services 관리자의 RuntimeBroker 설정이 2개 있는 경우 [8]
11827정성태2/26/201919046오류 유형: 521. Visual Studio - Could not start the 'rsync' command on the remote host, please install it using your system package manager.
11826정성태2/26/201919239오류 유형: 520. 우분투에 .NET Core SDK 설치 시 패키지 의존성 오류
11825정성태2/25/201924439개발 환경 구성: 428. Visual Studio 2019 - CMake를 이용한 리눅스 빌드 환경 설정 [1]
11824정성태2/25/201918870오류 유형: 519. The SNMP Service encountered an error while accessing the registry key SYSTEM\CurrentControlSet\Services\SNMP\Parameters\TrapConfiguration. [1]
11823정성태2/21/201920612오류 유형: 518. IIS 관리 콘솔이 뜨지 않는 문제
11822정성태2/20/201918901오류 유형: 517. docker에 설치한 MongoDB 서버로 연결이 안 되는 경우
11821정성태2/20/201919669오류 유형: 516. Visual Studio 2019 - This extension uses deprecated APIs and is at risk of not functioning in a future VS update. [1]
11820정성태2/20/201922723오류 유형: 515. 윈도우 10 1809 업데이트 후 "User Profiles Service" 1534 경고 발생
11819정성태2/20/201922018Windows: 158. 컴퓨터와 사용자의 SID(security identifier) 확인 방법
11818정성태2/20/201920050VS.NET IDE: 131. Visual Studio 2019 Preview의 닷넷 프로젝트 빌드가 20초 이상 걸리는 경우 [2]
11817정성태2/17/201916435오류 유형: 514. WinDbg Preview 실행 오류 - Error : DbgX.dll : WindowsDebugger.WindowsDebuggerException: Could not load dbgeng.dll
11816정성태2/17/201919834Windows: 157. 윈도우 스토어 앱(Microsoft Store App)을 명령행에서 직접 실행하는 방법
11815정성태2/14/201918086오류 유형: 513. Visual Studio 2019 - VSIX 설치 시 "The extension cannot be installed to this product due to prerequisites that cannot be resolved." 오류 발생
11814정성태2/12/201916930오류 유형: 512. VM(가상 머신)의 NT 서비스들이 자동 시작되지 않는 문제
11813정성태2/12/201918308.NET Framework: 809. C# - ("Save File Dialog" 등의) 대화 창에 확장 속성을 보이는 방법
11812정성태2/11/201915602오류 유형: 511. Windows Server 2003 VM 부팅 후 로그인 시점에 0xC0000005 BSOD 발생
11811정성태2/11/201920760오류 유형: 510. 서버 운영체제에 NVIDIA GeForce Experience 실행 시 wlanapi.dll 누락 문제
11810정성태2/11/201918484.NET Framework: 808. .NET Profiler - GAC 모듈에서 GAC 비-등록 모듈을 참조하는 경우의 문제
... 76  77  78  79  80  81  82  83  [84]  85  86  87  88  89  90  ...