Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 
(연관된 글이 3개 있습니다.)
(시리즈 글이 3개 있습니다.)
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 응용 프로그램의 (C++) so 의존성 줄이기(ReleaseMinDependency) - 두 번째 이야기

지난번에 쓴 글에서,

Linux 응용 프로그램의 (C++) so 의존성 줄이기(ReleaseMinDependency)
; https://www.sysnet.pe.kr/2/0/11845

glibc에 대한 의존성까지는 제거할 수 없었다고 했는데요, Go 언어에서 된다는 것을 봤으니,

Golang - GLIBC 의존을 없애는 정적 빌드 방법
; https://www.sysnet.pe.kr/2/0/13490

당연히 C/C++에도 있을 거라는 확신이 들었습니다. ^^




간단하게 Visual Studio에서 리눅스 C/C++ 프로젝트를 만들고,

#include <cstdio>

int main()
{
    printf("hello from %s!\n", "testapp");
    return 0;
}

빌드한 다음 ldd로 확인하면,

$ ldd testapp.out
        linux-vdso.so.1 (0x00007ffddd154000)
        libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007f63c8959000)
        /lib64/ld-linux-x86-64.so.2 (0x00007f63c8f4c000)

glibc 의존성이 나왔습니다. "Linux 응용 프로그램의 (C++) so 의존성 줄이기(ReleaseMinDependency)" 글에서, -static-libgcc -static-libstdc++ 옵션을 주면 된다고 했는데, 위의 기본 예제에서는 변함이 없습니다.

대신 "-static"을 주면 glibc 의존성이 없어집니다.

$ ldd testapp.out
        not a dynamic executable

$ file testapp.out
testapp.out: ELF 64-bit LSB executable, x86-64, version 1 (GNU/Linux), statically linked, for GNU/Linux 3.2.0, BuildID[sha1]=ee...[생략]...3f9, with debug_info, not stripped

여기까지는 일단 우리가 원하는 대로 됩니다. ^^




반면에, 프로젝트 설정에서 "Configuration Type"만 "Application (.out)"에서 "Dynamic Library (.so)"로 바꾼 다음 소스코드를 main이 없는 것으로 변경하고,

#include <stdio.h>

void foo(void)
{
    puts("foo");
}

빌드하면 이번엔 링크 단계에서 (이전 상황과 같은) 오류가 발생합니다.

1>Linking objects
1>/usr/bin/ld : error : /usr/lib/gcc/x86_64-linux-gnu/7/crtbeginT.o: relocation R_X86_64_32 against hidden symbol `__TMC_END__' can not be used when making a shared object
1>/usr/bin/ld : error : final link failed: Nonrepresentable section on output
1>collect2 : error : ld returned 1 exit status

처음엔, Visual Studio 측에서 리눅스 빌드와의 연동 과정에 뭔가 복잡한 의존성이 있어 충돌이 나는 거라 생각했는데, 검색을 해보니,

Building a shared library created a static library instead
; https://stackoverflow.com/questions/44429253/building-a-shared-library-created-a-static-library-instead

단순히 gcc로도 재현이 되는 문제였습니다.

$ cat foo.c
#include <stdio.h>

void foo(void)
{
    puts("foo");
}

$ gcc -c foo.c

$ gcc -shared -static -o libfoo.so foo.o
/usr/bin/ld: /usr/lib/gcc/x86_64-linux-gnu/9/crtbeginT.o: relocation R_X86_64_32 against hidden symbol `__TMC_END__' can not be used when making a shared object
collect2: error: ld returned 1 exit status

즉 shared library로 빌드하는 경우, 저런 오류가 발생하는 것입니다. 좀 더 검색해 보면,

Compile a shared object (.so) with static glibc
; https://stackoverflow.com/questions/42764747/compile-a-shared-object-so-with-static-glibc

so인 경우 정적 링킹은 불가능하다고 합니다. 이유를 보면 공유 라이브러리 측에서 정적 링크를 해버리면 서로 다른 버전의 함수들이 사용되므로 예기치 못한 동작을 할 수 있기 때문이라는데요, 어쩌면 윈도우용 Visual C++의 msvcrt dll 충돌 문제와 유사한 것입니다.

그 글의 또 다른 덧글에 보면,

Statically linking glibc also risks running a version of glibc that doesn't match the underlying run-time kernel's system call interface.


라는 의견이 보이는데, 저건 좀 이해가 안 됩니다. 저런 식이라면, shared object가 아닌 executable로 빌드한 경우에도 정적 링크가 된 glibc의 system call 역시 마찬가지로 문제가 되어야 합니다.

또 다른 글을 보면,

Building a shared library created a static library instead
; https://stackoverflow.com/questions/44429253/building-a-shared-library-created-a-static-library-instead

shared object인 경우 반드시 "PIC(위치 독립 코드)"로 이뤄져야 하는데 static 옵션을 적용하는 경우 non-PIC 오브젝트 파일들과 링킹을 시도하기 때문에 가능하지 않다고 합니다.

이래저래 정리해 보면, 결국 달성할 수 없는 목표인 듯합니다. ^^




그래도 그나마 다행인 것은 C++의 경우 (닷넷 AOT와는 달리) 빌드된 결과물이 그다지 높은 glibc를 요구하지는 않습니다. 위에서 빌드한 hello world 예제의 경우 2.2.5 버전을 요구하고,

$ objdump -p libtestapp.so
...[생략]...
Version References:
  required from libc.so.6:
    0x09691a75 0x00 02 GLIBC_2.2.5

제가 실제로 만든 C++ 업무 프로그램도 (ldd 2.27 버전의) Ubuntu 18.04에서 빌드하는데 버전 의존성이 2.14가 최고인 것으로 나옵니다.

Version References:
  required from libdl.so.2:
    0x09691a75 0x00 07 GLIBC_2.2.5
  required from ld-linux-x86-64.so.2:
    0x0d696913 0x00 05 GLIBC_2.3
  required from libpthread.so.0:
    0x09691a75 0x00 03 GLIBC_2.2.5
  required from libc.so.6:
    0x06969194 0x00 09 GLIBC_2.14
    0x09691974 0x00 08 GLIBC_2.3.4
    0x0d696914 0x00 06 GLIBC_2.4
    0x0d696913 0x00 04 GLIBC_2.3
    0x09691a75 0x00 02 GLIBC_2.2.5

이게 어느 정도로 낮은 거냐면,,, glibc에 대한 리눅스 배포본을 조사한 글이 있는데,

glibc Versions
; https://gist.github.com/wagenet/35adca1a032cec2999d47b6c40aa45b1

CentOS 6.10에 glibc 버전이 2.12로 사용 중인 것을 제외하고 그 이외의 배포본들은 2.17 이상으로 나오기 때문에 웬만큼 오래된 컴퓨터가 아니고서는 대부분 실행된다고 봐도 무방할 것입니다.

만약 glibc의 높은 버전과 바인딩하고 있다면 어떤 함수들의 사용으로 인한 것인지 알아내는 것도 가능합니다. 실제로 닷넷 AOT 빌드 결과물에 대해 적용해 보면,

$ readelf -Ws ConsoleApp1 | grep 2.32
    44: 0000000000000000     0 FUNC    GLOBAL DEFAULT  UND pthread_getattr_np@GLIBC_2.32 (8)

$ readelf -Ws ConsoleApp1 | grep 2.34
     3: 0000000000000000     0 FUNC    GLOBAL DEFAULT  UND pthread_mutexattr_init@GLIBC_2.34 (4)
    12: 0000000000000000     0 FUNC    GLOBAL DEFAULT  UND pthread_setspecific@GLIBC_2.34 (4)
    28: 0000000000000000     0 FUNC    GLOBAL DEFAULT  UND dladdr@GLIBC_2.34 (4)
    30: 0000000000000000     0 FUNC    GLOBAL DEFAULT  UND pthread_condattr_setclock@GLIBC_2.34 (4)
    46: 0000000000000000     0 FUNC    GLOBAL DEFAULT  UND __libc_start_main@GLIBC_2.34 (4)
    57: 0000000000000000     0 FUNC    GLOBAL DEFAULT  UND pthread_rwlock_rdlock@GLIBC_2.34 (4)
    72: 0000000000000000     0 FUNC    GLOBAL DEFAULT  UND pthread_setname_np@GLIBC_2.34 (4)
    88: 0000000000000000     0 FUNC    GLOBAL DEFAULT  UND pthread_kill@GLIBC_2.34 (4)
    91: 0000000000000000     0 FUNC    GLOBAL DEFAULT  UND pthread_rwlock_unlock@GLIBC_2.34 (4)
   110: 0000000000000000     0 FUNC    GLOBAL DEFAULT  UND pthread_mutexattr_settype@GLIBC_2.34 (4)
   111: 0000000000000000     0 FUNC    GLOBAL DEFAULT  UND pthread_mutexattr_destroy@GLIBC_2.34 (4)
   113: 0000000000000000     0 FUNC    GLOBAL DEFAULT  UND pthread_rwlock_wrlock@GLIBC_2.34 (4)
   120: 0000000000000000     0 FUNC    GLOBAL DEFAULT  UND pthread_key_create@GLIBC_2.34 (4)
   124: 0000000000000000     0 FUNC    GLOBAL DEFAULT  UND pthread_attr_getstack@GLIBC_2.34 (4)
   140: 0000000000000000     0 FUNC    GLOBAL DEFAULT  UND pthread_create@GLIBC_2.34 (4)

대부분 pthraed 관련 함수들인 것을 확인할 수 있습니다. 아쉽게도 닷넷 AOT의 경우 저걸 알았다고 해서 바꿀 수 있는 제어권은 없지만, C/C++의 경우에는 특정 버전의 함수와 바인딩하는 방법들이 제공되는 듯하니,

How can I link to a specific glibc version?
; https://stackoverflow.com/questions/2856438/how-can-i-link-to-a-specific-glibc-version

활용해도 좋을 것입니다.




잠깐 쓸데없을 것 같은 검색 기록을 남겨 보면, 아래의 글에서,

What are Linker Symbols __TMC_END__ and __TMC_LIST__ for?
; https://stackoverflow.com/questions/17605794/what-are-linker-symbols-tmc-end-and-tmc-list-for

TMC는 tm_clone_table을 의미한다고 하면서 아래의 소스코드를 제시합니다.

gcc/libgcc/crtstuff.c
; https://github.com/gcc-mirror/gcc/blob/master/libgcc/crtstuff.c

crtstuff.c 파일은 빌드되면 crtend.o로 바뀌고 그것이 gcc 빌드 도중 collect2를 실행할 때 인자로 넘겨진다고 합니다.

/usr/lib/gcc/x86_64-linux-gnu/9/collect2 -plugin ...[생략]... --end-group /usr/lib/gcc/x86_64-linux-gnu/9/crtend.o /usr/lib/gcc/x86_64-linux-gnu/9/../../../x86_64-linux-gnu/crtn.o


실제로 crtend.o에 정의된 심벌을 보면,

$ nm /usr/lib/gcc/x86_64-linux-gnu/9/crtend.o
0000000000000000 r __FRAME_END__
0000000000000000 D __TMC_END__

"__TMC_END__"가 있군요. ^^





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

[연관 글]






[최초 등록일: ]
[최종 수정일: 1/15/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)
13512정성태1/4/20242168개발 환경 구성: 701. IIS - w3wp.exe 프로세스의 ASP.NET 런타임을 항상 Warmup 모드로 유지하는 preload Enabled 설정
13511정성태1/4/20242189닷넷: 2193. C# - ASP.NET Web Application + OpenAPI(Swashbuckle) 스펙 제공
13510정성태1/3/20242117닷넷: 2192. C# - 특정 실행 파일이 있는지 확인하는 방법 (Linux)
13509정성태1/3/20242167오류 유형: 887. .NET Core 2 이하의 프로젝트에서 System.Runtime.CompilerServices.Unsafe doesn't support netcoreapp2.0.
13508정성태1/3/20242210오류 유형: 886. ORA-28000: the account is locked
13507정성태1/2/20242850닷넷: 2191. C# - IPGlobalProperties를 이용해 netstat처럼 사용 중인 Socket 목록 구하는 방법파일 다운로드1
13506정성태12/29/20232428닷넷: 2190. C# - 닷넷 코어/5+에서 달라지는 System.Text.Encoding 지원
13505정성태12/27/20232966닷넷: 2189. C# - WebSocket 클라이언트를 닷넷으로 구현하는 예제 (System.Net.WebSockets)파일 다운로드1
13504정성태12/27/20232553닷넷: 2188. C# - ASP.NET Core SignalR로 구현하는 채팅 서비스 예제파일 다운로드1
13503정성태12/27/20232426Linux: 67. WSL 환경 + mlocate(locate) 도구의 /mnt 디렉터리 검색 문제
13502정성태12/26/20232540닷넷: 2187. C# - 다른 프로세스의 환경변수 읽는 예제파일 다운로드1
13501정성태12/25/20232315개발 환경 구성: 700. WSL + uwsgi - IPv6로 바인딩하는 방법
13500정성태12/24/20232401디버깅 기술: 194. Windbg - x64 가상 주소를 물리 주소로 변환
13498정성태12/23/20233078닷넷: 2186. 한국투자증권 KIS Developers OpenAPI의 C# 래퍼 버전 - eFriendOpenAPI NuGet 패키지
13497정성태12/22/20232477오류 유형: 885. Visual Studiio - error : Could not connect to the remote system. Please verify your connection settings, and that your machine is on the network and reachable.
13496정성태12/21/20232466Linux: 66. 리눅스 - 실행 중인 프로세스 내부의 환경변수 설정을 구하는 방법 (gdb)
13495정성태12/20/20232410Linux: 65. clang++로 공유 라이브러리의 -static 옵션 빌드가 가능할까요?
13494정성태12/20/20232571Linux: 64. Linux 응용 프로그램의 (C++) so 의존성 줄이기(ReleaseMinDependency) - 두 번째 이야기
13493정성태12/19/20232680닷넷: 2185. C# - object를 QueryString으로 직렬화하는 방법
13492정성태12/19/20232363개발 환경 구성: 699. WSL에 nopCommerce 예제 구성
13491정성태12/19/20232266Linux: 63. 리눅스 - 다중 그룹 또는 사용자를 리소스에 권한 부여
13490정성태12/19/20232395개발 환경 구성: 698. Golang - GLIBC 의존을 없애는 정적 빌드 방법
13489정성태12/19/20232174개발 환경 구성: 697. GoLand에서 ldflags 지정 방법
13488정성태12/18/20232106오류 유형: 884. HTTP 500.0 - 명령행에서 실행한 ASP.NET Core 응용 프로그램을 실행하는 방법
13487정성태12/16/20232409개발 환경 구성: 696. C# - 리눅스용 AOT 빌드를 docker에서 수행 [1]
13486정성태12/15/20232223개발 환경 구성: 695. Nuget config 파일에 값 설정/삭제 방법
1  2  3  4  [5]  6  7  8  9  10  11  12  13  14  15  ...