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

비밀번호

댓글 작성자
 




1  2  3  4  5  6  7  8  9  10  11  12  [13]  14  15  ...
NoWriterDateCnt.TitleFile(s)
13616정성태5/3/20248612닷넷: 2256. ASP.NET Core 웹 사이트의 HTTP/HTTPS + Dual mode Socket (IPv4/IPv6) 지원 방법파일 다운로드1
13615정성태5/3/20249515닷넷: 2255. C# 배열을 Numpy ndarray 배열과 상호 변환
13614정성태5/2/20249181닷넷: 2254. C# - COM 인터페이스의 상속 시 중복으로 메서드를 선언
13613정성태5/1/20248906닷넷: 2253. C# - Video Capture 장치(Camera) 열거 및 지원 포맷 조회파일 다운로드1
13612정성태4/30/20249178오류 유형: 902. Visual Studio - error MSB3021: Unable to copy file
13611정성태4/29/20248563닷넷: 2252. C# - GUID 타입 전용의 UnmanagedType.LPStruct - 두 번째 이야기파일 다운로드1
13610정성태4/28/20248945닷넷: 2251. C# - 제네릭 인자를 가진 타입을 생성하는 방법 - 두 번째 이야기
13609정성태4/27/20249163닷넷: 2250. PInvoke 호출 시 참조 타입(class)을 마샬링하는 [IN], [OUT] 특성파일 다운로드1
13608정성태4/26/20249498닷넷: 2249. C# - 부모의 필드/프로퍼티에 대해 서로 다른 자식 클래스 간에 Reflection 접근이 동작할까요?파일 다운로드1
13607정성태4/25/20249495닷넷: 2248. C# - 인터페이스 타입의 다중 포인터를 인자로 갖는 C/C++ 함수 연동
13606정성태4/24/20249362닷넷: 2247. C# - tensorflow 연동 (MNIST 예제)파일 다운로드1
13605정성태4/23/202410701닷넷: 2246. C# - Python.NET을 이용한 파이썬 소스코드 연동파일 다운로드1
13604정성태4/22/20248400오류 유형: 901. Visual Studio - Unable to set the next statement. Set next statement cannot be used in '[Exception]' call stack frames.
13603정성태4/21/20249663닷넷: 2245. C# - IronPython을 이용한 파이썬 소스코드 연동파일 다운로드1
13602정성태4/20/20248942닷넷: 2244. C# - PCM 오디오 데이터를 연속(Streaming) 재생 (Windows Multimedia)파일 다운로드1
13601정성태4/19/20249052닷넷: 2243. C# - PCM 사운드 재생(NAudio)파일 다운로드1
13600정성태4/18/20249663닷넷: 2242. C# - 관리 스레드와 비관리 스레드
13599정성태4/17/20249512닷넷: 2241. C# - WAV 파일의 PCM 사운드 재생(Windows Multimedia)파일 다운로드1
13598정성태4/16/202410727닷넷: 2240. C# - WAV 파일 포맷 + LIST 헤더파일 다운로드2
13597정성태4/15/20249105닷넷: 2239. C# - WAV 파일의 PCM 데이터 생성 및 출력파일 다운로드1
13596정성태4/14/20249745닷넷: 2238. C# - WAV 기본 파일 포맷파일 다운로드1
13595정성태4/13/20249894닷넷: 2237. C# - Audio 장치 열기 (Windows Multimedia, NAudio)파일 다운로드1
13594정성태4/12/20249760닷넷: 2236. C# - Audio 장치 열람 (Windows Multimedia, NAudio)파일 다운로드1
13593정성태4/8/20248976닷넷: 2235. MSBuild - AccelerateBuildsInVisualStudio 옵션
13592정성태4/2/202411297C/C++: 165. CLion으로 만든 Rust Win32 DLL을 C#과 연동 [1]
13591정성태4/2/20249420닷넷: 2234. C# - WPF 응용 프로그램에 Blazor App 통합파일 다운로드1
1  2  3  4  5  6  7  8  9  10  11  12  [13]  14  15  ...