溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Name Mangling in C++

發(fā)布時間:2020-06-27 08:35:39 來源:網(wǎng)絡(luò) 閱讀:10614 作者:hipercomer 欄目:移動開發(fā)

 

Name Mangling(C++)
Author: Chaos Lee
Date: 2012/05/06

摘要:詳細(xì)介紹了C++中的Name Mangling的原理和gcc中對應(yīng)的實(shí)現(xiàn),通過程序代碼和nm c++filt等工具來驗(yàn)證這些原理。對于詳細(xì)了解程序的鏈接過程有一定的幫助。

Name Mangling概述

大型程序是通過多個模塊構(gòu)建而成,模塊之間的關(guān)系由makefile來描述。對于由C++語言編制的大型程序而言,也是符合這個規(guī)則。
程序的構(gòu)建過程一般為:各個源文件分別編譯,形成目標(biāo)文件。多個目標(biāo)文件通過鏈接器形成最終的可執(zhí)行程序。顯然,從某種程度上說,編譯器的輸出是鏈接器的輸入,鏈接器要對編譯器的輸出做二次加工。從通信的角度看,這兩個程序需要一定的協(xié)議來規(guī)范符號的組織格式。這就是Name Mangling產(chǎn)生的根本原因。

C++的語言特性比C豐富的多,C++支持的函數(shù)重載功能是需要Name Mangling技術(shù)的最直接的例子。對于重載的函數(shù),不能僅依靠函數(shù)名稱來區(qū)分不同的函數(shù),因?yàn)镃++中重載函數(shù)的區(qū)分是建立在以下規(guī)則上的:

函數(shù)名字不同 || 參數(shù)數(shù)量不同||某個參數(shù)的類型不同
那么區(qū)分函數(shù)的時候,應(yīng)該充分考慮參數(shù)數(shù)量和參數(shù)類型這兩種語義信息,這樣才能為卻分不同的函數(shù)保證充分性。

當(dāng)然,C++還有很多其他的地方需要Name Mangling,如namespace, class, template等等。

總的來說,Name Mangling就是一種規(guī)范編譯器和鏈接器之間用于通信的符號表表示方法的協(xié)議,其目的在于按照程序的語言規(guī)范,使符號具備足夠多的語義信息以保證鏈接過程準(zhǔn)確無誤的進(jìn)行。
簡單的實(shí)驗(yàn)
Name Mangling會帶了一個很常見的負(fù)面效應(yīng),就是C語言的程序調(diào)用C++的程序時,會比較棘手。因?yàn)镃語言中的Name Mangling很簡單,不如C++中這么復(fù)雜。下面的代碼用于演示這兩種不同點(diǎn):
 
  1. /* 
  2. * simple_test.c 
  3. * a demo to show that different name mangling technology in C++ and C 
  4.  
  5. * Author: Chaos Lee 
  6.  
  7. */ 
  8.   
  9. #include<stdio.h> 
  10.   
  11. int rect_area(int x1,int x2,int y1,int y2) 
  12.  
  13.         return (x2-x1) * (y2-y1); 
  14.   
  15. int elipse_area(int a,int b) 
  16.  
  17.         return 3.14 * a * b; 
  18.   
  19. int main(int argc,char *argv[]) 
  20.  
  21.         int x1 = 10, x2 = 20, y1 = 30, y2 = 40; 
  22.         int a = 3,b=4; 
  23.         int result1 = rect_area(x1,x2,y1,y2); 
  24.         int result2 = elipse_area(a,b); 
  25.         return 0; 

 

  1. [lichao@sg01 name_mangling]$ gcc -c simple_test.c 
  2.  
  3. [lichao@sg01 name_mangling]$ nm simple_test.o 
  4.  
  5. 0000000000000027 T elipse_area 
  6.  
  7. 0000000000000051 T main 
  8.  
  9. 0000000000000000 T rect_area 
從上面的輸出結(jié)果上,可以看到使用gcc編譯后對應(yīng)的符號表中,幾乎沒有對函數(shù)做任何修飾。接下來使用g++編譯:
 
  1.  [lichao@sg01 name_mangling]$ nm simple_test.o 
  2. 0000000000000028 T _Z11elipse_areaii 
  3.  
  4. 0000000000000000 T _Z9rect_areaiiii 
  5.  
  6.                  U __gxx_personality_v0 
  7. 0000000000000052 T main 
顯然,g++編譯器對符號的改編比較復(fù)雜。所以,如果一個由C語言編譯的目標(biāo)文件中調(diào)用了C++中實(shí)現(xiàn)的函數(shù),肯定會出錯的,因?yàn)榉柌黄ヅ洹?/div>
簡單對_Z9rect_areaiiii做個介紹:

l C++語言中規(guī)定 :以下劃線并緊挨著大寫字母開頭或者以兩個下劃線開頭的標(biāo)識符都是C++語言中保留的標(biāo)示符。所以_Z9rect_areaiiii是保留的標(biāo)識符,g++編譯的目標(biāo)文件中的符號使用_Z開頭(C99標(biāo)準(zhǔn))。

l 接下來的部分和網(wǎng)絡(luò)協(xié)議很類似。9表示接下來的要表示的一個字符串對象的長度(現(xiàn)在知道為什么不讓用數(shù)字作為標(biāo)識符的開頭了吧?)所以rect_area這九個字符就作為函數(shù)的名稱被識別出來了。
l 接下來的每個小寫字母表示參數(shù)的類型,i表示int類型。小寫字母的數(shù)量表示函數(shù)的參數(shù)列表中參數(shù)的數(shù)量。
l 所以,在符號中集成了用于區(qū)分不同重載函數(shù)的足夠的語義信息。
如果要在C語言中調(diào)用C++中的函數(shù)該怎么做?這時候可以使用C++的關(guān)鍵字extern “C”。對應(yīng)代碼如下:
 
  1. /* 
  2. * simple_test.c 
  3. * a demo to show that different name mangling technology in C++ and C 
  4.  
  5. * Author: Chaos Lee 
  6.  
  7. */ 
  8.   
  9. #include<stdio.h> 
  10.   
  11. #ifdef __cplusplus 
  12.  
  13. extern "C" { 
  14.  
  15. #endif 
  16. int rect_area(int x1,int x2,int y1,int y2) 
  17.  
  18.         return (x2-x1) * (y2-y1); 
  19.   
  20. int elipse_area(int a,int b) 
  21.  
  22.         return (int)(3.14 * a * b); 
  23.   
  24. #ifdef __cplusplus 
  25.  
  26. #endif 
  27.   
  28. int main(int argc,char *argv[]) 
  29.  
  30.         int x1 = 10, x2 = 20, y1 = 30, y2 = 40; 
  31.         int a = 3,b=4; 
  32.         int result1 = rect_area(x1,x2,y1,y2); 
  33.         int result2 = elipse_area(a,b); 
  34.         return 0; 
下面是使用gcc編譯的結(jié)果:

 

  1. [lichao@sg01 name_mangling]$ gcc -c simple_test.c 
  2.  
  3. [lichao@sg01 name_mangling]$ nm simple_test.o 
  4.  
  5. 0000000000000027 T elipse_area 
  6.  
  7. 0000000000000051 T main 
  8.  
  9. 0000000000000000 T rect_area 
在使用g++編譯一次:

 

  1. [lichao@sg01 name_mangling]$ g++ -c simple_test.c 
  2.  
  3. [lichao@sg01 name_mangling]$ nm simple_test.o 
  4.  
  5.                  U __gxx_personality_v0 
  6.  
  7. 0000000000000028 T elipse_area 
  8.  
  9. 0000000000000052 T main 
  10.  
  11. 0000000000000000 T rect_area 
可見,使用extern “C”關(guān)鍵字之后,符號按照C語言的格式來組織了。

事實(shí)上,C標(biāo)準(zhǔn)庫中使用了大量的extern “C”關(guān)鍵字,因?yàn)镃標(biāo)準(zhǔn)庫也是可以用C++編譯器編譯的,但是要確保編譯之后仍然保持C的接口而不是C++的接口(因?yàn)槭荂標(biāo)準(zhǔn)庫),所以需要使用extern “C”關(guān)鍵字。

下面是一個簡單的例子:
 
  1. /* 
  2. * libc_test.c 
  3. * a demo program to show that how the standard C 
  4.  
  5. * library are compiled when encountering a C++ compiler 
  6.  
  7. */ 
  8. #include<stdio.h> 
  9. int main(int argc,char * argv[]) 
  10.  
  11.         puts("hello world.\n"); 
  12.         return 0; 

搜索一下puts,我們并沒有看到extern “C”.奇怪么?

 

  1. [lichao@sg01 name_mangling]$ g++ -E libc_test.c | grep 'puts' 
  2.  
  3. extern int fputs (__const char *__restrict __s, FILE *__restrict __stream); 
  4.  
  5. extern int puts (__const char *__s); 
  6.  
  7. extern int fputs_unlocked (__const char *__restrict __s, 
  8.  
  9.  puts("hello world.\n"); 
搜索一下 extern “C”試下

 

  1. [lichao@sg01 name_mangling]$ g++ -E libc_test.c | grep 'extern "C"' 
  2.  
  3. extern "C" { 
  4.  
  5. extern "C" { 
這是由于extern “C”可以使用{}的形式將其作用域內(nèi)的函數(shù)全部聲明為C語言可調(diào)用的接口形式。
標(biāo)準(zhǔn)

不同編譯器使用不同的方式進(jìn)行name mangling, 你可能會問為什么不將C++的 name mangling標(biāo)準(zhǔn)化,這樣就能實(shí)現(xiàn)各個編譯器之間的互操作了。事實(shí)上,在C++的FAQ列表上有對此問題的回答:

"Compilers differ as to how objects are laid out, how multiple inheritance is implemented, how virtual function calls are handled, and so on, so if the name mangling were made the same, your programs would link against libraries provided from other compilers but then crash when run. For this reason, the ARM (Annotated C++ Reference Manual) encourages compiler writers to make their name mangling different from that of other compilers for the same platform. Incompatible libraries are then detected at link time, rather than at run time."

“編譯器由于內(nèi)部實(shí)現(xiàn)的不同而不同,內(nèi)部實(shí)現(xiàn)包括對象在內(nèi)存中的布局,繼承的實(shí)現(xiàn),虛函數(shù)調(diào)用處理等等。所以如果將name mangling標(biāo)準(zhǔn)化了,不錯,你的程序確實(shí)能夠鏈接成功,但是運(yùn)行肯定要崩的。恰恰是因?yàn)檫@個原因,ARM鼓勵為同一平臺提供的不同編譯器應(yīng)該使用不同的name mangling方式。這樣在編譯的時候,不兼容的庫就會被檢測到,而不至于鏈接時雖然通過了,但是運(yùn)行時崩潰了。”
顯然,這是基于“運(yùn)行時崩潰比鏈接時失敗的代價更大”這個原則而考慮的。
GCCname mangling

GCC采用IA 64的name mangling方案,此方案定義于Intel IA64 standard ABI.在g++的FAQ列表中有以下一段話:
       "GNU C++ does not do name mangling in the same way as other C++ compilers.

This means that object files compiled with one compiler cannot be used with

another”

GNU C++的name mangling方案和其他C++編譯器方案不同,所以一種編譯器生成的目標(biāo)文件并不能被另外一種編譯器生成的目標(biāo)文件使用。

以下為內(nèi)置的編碼類型:

 

  1. Builtin types encoding 
  2.  
  3.   <builtin-type> ::= v  # void 
  4.                  ::= w  # wchar_t 
  5.                  ::= b  # bool 
  6.                  ::= c  # char 
  7.                  ::= a  # signed char 
  8.                  ::= h  # unsigned char 
  9.                  ::= s  # short 
  10.                  ::= t  # unsigned short 
  11.                  ::= i  # int 
  12.                  ::= j  # unsigned int 
  13.                  ::= l  # long 
  14.                  ::= m  # unsigned long 
  15.                  ::= x  # long long, __int64 
  16.                  ::= y  # unsigned long long, __int64 
  17.                  ::= n  # __int128 
  18.                  ::= o  # unsigned __int128 
  19.                  ::= f  # float 
  20.                  ::= d  # double 
  21.                  ::= e  # long double, __float80 
  22.                  ::= g  # __float128 
  23.                  ::= z  # ellipsis 
  24.                  ::= u <source-name>    # vendor extended type 
操作符編碼:

Operator encoding

 
  1. <operator-name> ::= nw # new           
  2.                  ::= na        # new[] 
  3.                  ::= dl        # delete        
  4.                  ::= da        # delete[]      
  5.                  ::= ps        # + (unary) 
  6.                  ::= ng        # - (unary)     
  7.                  ::= ad        # & (unary)     
  8.                  ::= de        # * (unary)     
  9.                  ::= co        # ~             
  10.                  ::= pl        # +             
  11.                  ::= mi        # -   
  12.  
  13.                                   ::= ml        # *             
  14.  
  15.                  ::= dv        # /             
  16.                  ::= rm        # %             
  17.                  ::= an        # &             
  18.                  ::= or        # |             
  19.                  ::= eo        # ^             
  20.                  ::= aS        # =             
  21.                  ::= pL        # +=            
  22.                  ::= mI        # -=            
  23.                  ::= mL        # *=            
  24.                  ::= dV        # /=            
  25.                  ::= rM        # %=            
  26.                  ::= aN        # &=            
  27.                  ::= oR        # |=            
  28.                  ::= eO        # ^=            
  29.                  ::= ls        # <<            
  30.                  ::= rs        # >>            
  31.                  ::= lS        # <<=           
  32.                  ::= rS        # >>=           
  33.                  ::= eq        # ==            
  34.                  ::= ne        # !=            
  35.                  ::= lt        # <             
  36.                  ::= gt        # >             
  37.                  ::= le        # <=            
  38.                  ::= ge        # >=            
  39.                  ::= nt        # !             
  40.                  ::= aa        # &&            
  41.                  ::= oo        # ||            
  42.                  ::= pp        # ++            
  43.                  ::= mm        # --            
  44.                  ::= cm        # ,              
  45.                  ::= pm        # ->*           
  46.                  ::= pt        # ->            
  47.                  ::= cl        # ()            
  48.                  ::= ix        # []            
  49.                  ::= qu        # ?             
  50.                  ::= st        # sizeof (a type) 
  51.                  ::= sz        # sizeof (an expression) 
  52.                  ::= cv <type> # (cast)        
  53.  
  54.                  ::= v <digit> <source-name>   # vendor extended operator 
類型編碼:

 

  1. <type> ::= <CV-qualifiers> <type> 
  2.  
  3.          ::= P <type>   # pointer-to 
  4.          ::= R <type>   # reference-to 
  5.          ::= O <type>     # rvalue reference-to (C++0x) 
  6.          ::= C <type>   # complex pair (C 2000) 
  7.          ::= G <type>   # imaginary (C 2000) 
  8.          ::= U <source-name> <type>     # vendor extended type qualifier 
下面是一段簡單的代碼:
 
  1. /* 
  2. * Author: Chaos Lee 
  3.  
  4. * Description: A simple demo to show how the rules used to mangle functions' names work 
  5.  
  6. * Date:2012/05/06 
  7.  
  8. */ 
  9. #include<iostream> 
  10. #include<string> 
  11. using namespace std; 
  12.  
  13. int test_func(int & tmpInt,const char * ptr,double dou,string str,float f) 
  14.  
  15.         return 0; 
  16. int main(int argc,char * argv[]) 
  17.  
  18.         char * test="test"
  19.         int intNum = 10; 
  20.         double dou = 10.012; 
  21.         string str="str"
  22.         float f = 1.2; 
  23.         test_func(intNum,test,dou,str,f); 
  24.         return 0; 

 

  1. [lichao@sg01 name_mangling]$ g++ -c func.cpp 
  2.  
  3. [lichao@sg01 name_mangling]$ nm func.cpp 
  4.  
  5. nm: func.cpp: File format not recognized 
  6.  
  7. [lichao@sg01 name_mangling]$ nm func.o 
  8.  
  9. 0000000000000060 t _GLOBAL__I__Z9test_funcRiPKcdSsf 
  10.                  U _Unwind_Resume 
  11. 0000000000000022 t _Z41__static_initialization_and_destruction_0ii 
  12.  
  13. 0000000000000000 T _Z9test_funcRiPKcdSsf 
  14.  
  15.                  U _ZNSaIcEC1Ev 
  16.                  U _ZNSaIcED1Ev 
  17.                  U _ZNSsC1EPKcRKSaIcE 
  18.                  U _ZNSsC1ERKSs 
  19.                  U _ZNSsD1Ev 
  20.                  U _ZNSt8ios_base4InitC1Ev 
  21.                  U _ZNSt8ios_base4InitD1Ev 
  22. 0000000000000000 b _ZSt8__ioinit 
  23.  
  24.                  U __cxa_atexit 
  25.                  U __dso_handle 
  26.                  U __gxx_personality_v0 
  27. 0000000000000076 t __tcf_0 
  28.  
  29. 000000000000008e T main 

加粗的那行就是函數(shù)test_func經(jīng)過name mangling之后的結(jié)果,其中:

l Ri,表示對整型變量的引用
l PKc:表示const char *指針
Ss:目前還沒有找到原因。先留著~
l f:表示浮點(diǎn)型
name demangling

C++的name mangling技術(shù)一般使得函數(shù)變得面目全非,而很多情況下我們在查看這些符號的時候并不需要看到這些函數(shù)name mangling之后的效果,而是想看看是否定義了某個函數(shù),或者是否引用了某個函數(shù),這對于我們調(diào)試程序是非常有幫助的。

所以需要一種方法從name mangling之后的符號變換為name mangling之前的符號,這個過程稱之為name demangling.事實(shí)上有很多工具提供這些功能,最常用的就是c++file命令,c++filt命令接受一個name mangling之后的符號作為輸入并輸出demangling之后的符號。例如:

 

  1. [lichao@sg01 name_mangling]$ c++filt _Z9test_funcRiPKcdSsf 
  2.  
  3. test_func(int&, char const*, double, std::basic_string<char, std::char_traits<char>, std::allocator<char> >, float
一般更常用的方法為:

 

  1. [lichao@sg01 name_mangling]$ nm func.o | c++filt 
  2.  
  3. 0000000000000060 t global constructors keyed to _Z9test_funcRiPKcdSsf 
  4.  
  5.                  U _Unwind_Resume 
  6. 0000000000000022 t __static_initialization_and_destruction_0(intint
  7.  
  8. 0000000000000000 T test_func(int&, char const*, double, std::basic_string<char, std::char_traits<char>, std::allocator<char> >, float
  9.  
  10.                  U std::allocator<char>::allocator() 
  11.  
  12.                  U std::allocator<char>::~allocator() 
  13.  
  14.                  U std::basic_string<char, std::char_traits<char>, std::allocator<char> >::basic_string(char const*, std::allocator<char> const&) 
  15.  
  16.                  U std::basic_string<char, std::char_traits<char>, std::allocator<char> >::basic_string(std::basic_string<char, std::char_traits<char>, std::allocator<char> > const&) 
  17.  
  18.                  U std::basic_string<char, std::char_traits<char>, std::allocator<char> >::~basic_string() 
  19.  
  20.                  U std::ios_base::Init::Init() 
  21.                  U std::ios_base::Init::~Init() 
  22. 0000000000000000 b std::__ioinit 
  23.  
  24.                  U __cxa_atexit 
  25.                  U __dso_handle 
  26.                  U __gxx_personality_v0 
  27. 0000000000000076 t __tcf_0 
  28.  
  29. 000000000000008e T main 
另外使用nm命令也可以demangle符號,使用選項(xiàng)-C即可,例如:

 

  1. [lichao@sg01 name_mangling]$ nm -C func.o 
  2.  
  3. 0000000000000060 t global constructors keyed to _Z9test_funcRiPKcdSsf 
  4.  
  5.                  U _Unwind_Resume 
  6. 0000000000000022 t __static_initialization_and_destruction_0(intint
  7.  
  8. 0000000000000000 T test_func(int&, char const*, double, std::string, float
  9.  
  10.                  U std::allocator<char>::allocator() 
  11.  
  12.                  U std::allocator<char>::~allocator() 
  13.  
  14.                  U std::basic_string<char, std::char_traits<char>, std::allocator<char> >::basic_string(char const*, std::allocator<char> const&) 
  15.  
  16.                  U std::basic_string<char, std::char_traits<char>, std::allocator<char> >::basic_string(std::string const&) 
  17.  
  18.                  U std::basic_string<char, std::char_traits<char>, std::allocator<char> >::~basic_string() 
  19.  
  20.                  U std::ios_base::Init::Init() 
  21.                  U std::ios_base::Init::~Init() 
  22. 0000000000000000 b std::__ioinit 
  23.  
  24.                  U __cxa_atexit 
  25.                  U __dso_handle 
  26.                  U __gxx_personality_v0 
  27. 0000000000000076 t __tcf_0 
  28.  
  29. 000000000000008e T main 

又到了Last but not least important的時候了,還有一個特別重要的接口函數(shù)就是__cxa_demangle(),此函數(shù)的原型為:

 
  1. namespace abi { 
  2. extern "C" char* __cxa_demangle (const char* mangled_name, 
  3.  
  4. char* buf, 
  5. size_t* n, 
  6. int* status); 
用于將mangled_name所指向的mangled進(jìn)行demangle并將結(jié)果存放在buf中,n為buf的大小。status存放函數(shù)執(zhí)行的結(jié)果,返回值為0表示執(zhí)行成功。
下面是使用這個接口函數(shù)進(jìn)行demangle的例子:
 
  1. /* 
  2. * Author: Chaos Lee 
  3.  
  4. * Description: Employ __cxa_demangle to demangle a mangling function name. 
  5.  
  6. * Date:2012/05/06 
  7.  
  8. * 
  9. */ 
  10. #include<iostream> 
  11. #include<cxxabi.h> 
  12. using namespace std; 
  13.  
  14. using namespace abi; 
  15.  
  16. int main(int argc,char *argv[]) 
  17.  
  18.         const char * mangled_string = "_Z9test_funcRiPKcdSsf"
  19.  
  20.         char buffer[100]; 
  21.         int status; 
  22.         size_t n=100; 
  23.         __cxa_demangle(mangled_string,buffer,&n,&status); 
  24.  
  25.         cout<<buffer<<endl; 
  26.         cout<<status<<endl; 
  27.         return 0; 
測試結(jié)果:

 

  1. [lichao@sg01 name_mangling]$ g++ cxa_demangle.cpp -o cxa_demangle 
  2.  
  3. [lichao@sg01 name_mangling]$ ./cxa_demangle 
  4.  
  5. test_func(int&, char const*, double, std::string, float
  6.  
name mangling與***
l 使用demangling可以破解動態(tài)鏈接庫中的沒有公開的API

l 編寫名稱為name mangling接口函數(shù),打開重復(fù)符號的編譯開關(guān),可以替換原來函數(shù)中鏈接函數(shù)的指向,從而改變程序的運(yùn)行結(jié)果。

 

 

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI