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

비밀번호

댓글 작성자
 




... 91  92  93  94  95  96  97  98  99  100  101  [102]  103  104  105  ...
NoWriterDateCnt.TitleFile(s)
11382정성태12/4/201721855오류 유형: 436. System.Data.SqlClient.SqlException (0x80131904): Connection Timeout Expired 예외 발생 시 "[Pre-Login] initialization=48; handshake=1944;" 값의 의미
11381정성태11/30/201718238.NET Framework: 702. 한글이 포함된 바이트 배열을 나눈 경우 한글이 깨지지 않도록 다시 조합하는 방법(두 번째 이야기)파일 다운로드1
11380정성태11/30/201718286디버깅 기술: 109. windbg - (x64에서의 인자 값 추적을 이용한) Thread.Abort 시 대상이 되는 스레드를 식별하는 방법
11379정성태11/30/201719015오류 유형: 435. System.Web.HttpException - Session state has created a session id, but cannot save it because the response was already flushed by the application.
11378정성태11/29/201720482.NET Framework: 701. 한글이 포함된 바이트 배열을 나눈 경우 한글이 깨지지 않도록 다시 조합하는 방법 [1]파일 다운로드1
11377정성태11/29/201719754.NET Framework: 700. CommonOpenFileDialog 사용 시 사용자가 선택한 파일 목록을 구하는 방법 [3]파일 다운로드1
11376정성태11/28/201724097VS.NET IDE: 123. Visual Studio 편집기의 \r\n (crlf) 개행을 \n으로 폴더 단위로 설정하는 방법
11375정성태11/28/201718920오류 유형: 434. Visual Studio로 ASP.NET 디버깅 중 System.Web.HttpException - Could not load type 오류
11374정성태11/27/201724003사물인터넷: 14. 라즈베리 파이 - (윈도우의 NT 서비스처럼) 부팅 시 시작하는 프로그램 설정 [1]
11373정성태11/27/201722995오류 유형: 433. Raspberry Pi/Windows 다중 플랫폼 지원 컴파일 관련 오류 기록
11372정성태11/25/201726035사물인터넷: 13. 윈도우즈 사용자를 위한 라즈베리 파이 제로 W 모델을 설정하는 방법 [4]
11371정성태11/25/201719669오류 유형: 432. Hyper-V 가상 스위치 생성 시 Failed to connect Ethernet switch port 0x80070002 오류 발생
11370정성태11/25/201719552오류 유형: 431. Hyper-V의 Virtual Switch 생성 시 "External network" 목록에 특정 네트워크 어댑터 항목이 없는 경우
11369정성태11/25/201721676사물인터넷: 12. Raspberry Pi Zero(OTG)를 다른 컴퓨터에 연결해 가상 키보드 및 마우스로 쓰는 방법 (절대 좌표, 상대 좌표, 휠) [1]
11368정성태11/25/201727260.NET Framework: 699. UDP 브로드캐스트 주소 255.255.255.255와 192.168.0.255의 차이점과 이를 고려한 C# UDP 서버/클라이언트 예제 [2]파일 다운로드1
11367정성태11/25/201727323개발 환경 구성: 337. 윈도우 운영체제의 route 명령어 사용법
11366정성태11/25/201718979오류 유형: 430. 이벤트 로그 - Cryptographic Services failed while processing the OnIdentity() call in the System Writer Object.
11365정성태11/25/201721233오류 유형: 429. 이벤트 로그 - User Policy could not be updated successfully
11364정성태11/24/201723126사물인터넷: 11. Raspberry Pi Zero(OTG)를 다른 컴퓨터에 연결해 가상 마우스로 쓰는 방법 (절대 좌표) [2]
11363정성태11/23/201723079사물인터넷: 10. Raspberry Pi Zero(OTG)를 다른 컴퓨터에 연결해 가상 마우스 + 키보드로 쓰는 방법 (두 번째 이야기)
11362정성태11/22/201719636오류 유형: 428. 윈도우 업데이트 KB4048953 - 0x800705b4 [2]
11361정성태11/22/201722417오류 유형: 427. 이벤트 로그 - Filter Manager failed to attach to volume '\Device\HarddiskVolume??' 0xC03A001C
11360정성태11/22/201722225오류 유형: 426. 이벤트 로그 - The kernel power manager has initiated a shutdown transition.
11359정성태11/16/201721698오류 유형: 425. 윈도우 10 Version 1709 (OS Build 16299.64) 업그레이드 시 발생한 문제 2가지
11358정성태11/15/201726471사물인터넷: 9. Visual Studio 2017에서 Raspberry Pi C++ 응용 프로그램 제작 [1]
11357정성태11/15/201726930개발 환경 구성: 336. 윈도우 10 Bash 쉘에서 C++ 컴파일하는 방법
... 91  92  93  94  95  96  97  98  99  100  101  [102]  103  104  105  ...