程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> C++入門知識 >> Name Mangling in C++

Name Mangling in C++

編輯:C++入門知識

摘要:詳細介紹了C++中的Name Mangling的原理和gcc中對應的實現,通過程序代碼和nm c++filt等工具來驗證這些原理。對於詳細了解程序的鏈接過程有一定的幫助。
Name Mangling概述
大型程序是通過多個模塊構建而成,模塊之間的關系由makefile來描述。對於由C++語言編制的大型程序而言,也是符合這個規則。
程序的構建過程一般為:各個源文件分別編譯,形成目標文件。多個目標文件通過鏈接器形成最終的可執行程序。顯然,從某種程度上說,編譯器的輸出是鏈接器的輸入,鏈接器要對編譯器的輸出做二次加工。從通信的角度看,這兩個程序需要一定的協議來規范符號的組織格式。這就是Name Mangling產生的根本原因。
C++的語言特性比C豐富的多,C++支持的函數重載功能是需要Name Mangling技術的最直接的例子。對於重載的函數,不能僅依靠函數名稱來區分不同的函數,因為C++中重載函數的區分是建立在以下規則上的:
函數名字不同 || 參數數量不同||某個參數的類型不同
那麼區分函數的時候,應該充分考慮參數數量和參數類型這兩種語義信息,這樣才能為卻分不同的函數保證充分性。
當然,C++還有很多其他的地方需要Name Mangling,如namespace, class, template等等。
總的來說,Name Mangling就是一種規范編譯器和鏈接器之間用於通信的符號表表示方法的協議,其目的在於按照程序的語言規范,使符號具備足夠多的語義信息以保證鏈接過程准確無誤的進行。
簡單的實驗
Name Mangling會帶了一個很常見的負面效應,就是C語言的程序調用C++的程序時,會比較棘手。因為C語言中的Name Mangling很簡單,不如C++中這麼復雜。下面的代碼用於演示這兩種不同點:
 
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. {
14.         return (x2-x1) * (y2-y1);
15. }
16.  
17. int elipse_area(int a,int b)
18. 
19. {
20.         return 3.14 * a * b;
21. }
22.  
23. int main(int argc,char *argv[])
24. 
25. {
26.         int x1 = 10, x2 = 20, y1 = 30, y2 = 40;
27.         int a = 3,b=4;
28.         int result1 = rect_area(x1,x2,y1,y2);
29.         int result2 = elipse_area(a,b);
30.         return 0;
31. }
 
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
從上面的輸出結果上,可以看到使用gcc編譯後對應的符號表中,幾乎沒有對函數做任何修飾。接下來使用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++編譯器對符號的改編比較復雜。所以,如果一個由C語言編譯的目標文件中調用了C++中實現的函數,肯定會出錯的,因為符號不匹配。
簡單對_Z9rect_areaiiii做個介紹:
l C++語言中規定 :以下劃線並緊挨著大寫字母開頭或者以兩個下劃線開頭的標識符都是C++語言中保留的標示符。所以_Z9rect_areaiiii是保留的標識符,g++編譯的目標文件中的符號使用_Z開頭(C99標准)。
l 接下來的部分和網絡協議很類似。9表示接下來的要表示的一個字符串對象的長度(現在知道為什麼不讓用數字作為標識符的開頭了吧?)所以rect_area這九個字符就作為函數的名稱被識別出來了。
l 接下來的每個小寫字母表示參數的類型,i表示int類型。小寫字母的數量表示函數的參數列表中參數的數量。
l 所以,在符號中集成了用於區分不同重載函數的足夠的語義信息。
如果要在C語言中調用C++中的函數該怎麼做?這時候可以使用C++的關鍵字extern “C”。對應代碼如下:
 
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. {
19.         return (x2-x1) * (y2-y1);
20. }
21.  
22. int elipse_area(int a,int b)
23. 
24. {
25.         return (int)(3.14 * a * b);
26. }
27.  
28. #ifdef __cplusplus
29. 
30. }
31. #endif
32.  
33. int main(int argc,char *argv[])
34. 
35. {
36.         int x1 = 10, x2 = 20, y1 = 30, y2 = 40;
37.         int a = 3,b=4;
38.         int result1 = rect_area(x1,x2,y1,y2);
39.         int result2 = elipse_area(a,b);
40.         return 0;
41. }
下面是使用gcc編譯的結果:
 
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”關鍵字之後,符號按照C語言的格式來組織了。
事實上,C標准庫中使用了大量的extern “C”關鍵字,因為C標准庫也是可以用C++編譯器編譯的,但是要確保編譯之後仍然保持C的接口而不是C++的接口(因為是C標准庫),所以需要使用extern “C”關鍵字。
下面是一個簡單的例子:
 
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. {
12.         puts("hello world.\n");
13.         return 0;
14. }
搜索一下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”可以使用{}的形式將其作用域內的函數全部聲明為C語言可調用的接口形式。
標准
不同編譯器使用不同的方式進行name mangling, 你可能會問為什麼不將C++的 name mangling標准化,這樣就能實現各個編譯器之間的互操作了。事實上,在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."
“編譯器由於內部實現的不同而不同,內部實現包括對象在內存中的布局,繼承的實現,虛函數調用處理等等。所以如果將name mangling標准化了,不錯,你的程序確實能夠鏈接成功,但是運行肯定要崩的。恰恰是因為這個原因,ARM鼓勵為同一平台提供的不同編譯器應該使用不同的name mangling方式。這樣在編譯的時候,不兼容的庫就會被檢測到,而不至於鏈接時雖然通過了,但是運行時崩潰了。”
顯然,這是基於“運行時崩潰比鏈接時失敗的代價更大”這個原則而考慮的。
GCC的name 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++編譯器方案不同,所以一種編譯器生成的目標文件並不能被另外一種編譯器生成的目標文件使用。
以下為內置的編碼類型:
 
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. {
16.         return 0;
17. }
18. int main(int argc,char * argv[])
19. 
20. {
21.         char * test="test";
22.         int intNum = 10;
23.         double dou = 10.012;
24.         string str="str";
25.         float f = 1.2;
26.         test_func(intNum,test,dou,str,f);
27.         return 0;
28. }
 
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
加粗的那行就是函數test_func經過name mangling之後的結果,其中:
l Ri,表示對整型變量的引用
l PKc:表示const char *指針
l Ss:目前還沒有找到原因。先留著~
l f:表示浮點型
name demangling
C++的name mangling技術一般使得函數變得面目全非,而很多情況下我們在查看這些符號的時候並不需要看到這些函數name mangling之後的效果,而是想看看是否定義了某個函數,或者是否引用了某個函數,這對於我們調試程序是非常有幫助的。
所以需要一種方法從name mangling之後的符號變換為name mangling之前的符號,這個過程稱之為name demangling.事實上有很多工具提供這些功能,最常用的就是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(int, int)
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符號,使用選項-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(int, int)
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的時候了,還有一個特別重要的接口函數就是__cxa_demangle(),此函數的原型為:
 
1. namespace abi {
2. extern "C" char* __cxa_demangle (const char* mangled_name,
3. 
4. char* buf,
5. size_t* n,
6. int* status);
7. }
用於將mangled_name所指向的mangled進行demangle並將結果存放在buf中,n為buf的大小。status存放函數執行的結果,返回值為0表示執行成功。
下面是使用這個接口函數進行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. {
19.         const char * mangled_string = "_Z9test_funcRiPKcdSsf";
20. 
21.         char buffer[100];
22.         int status;
23.         size_t n=100;
24.         __cxa_demangle(mangled_string,buffer,&n,&status);
25. 
26.         cout<<buffer<<endl;
27.         cout<<status<<endl;
28.         return 0;
29. }
測試結果:
 
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. 
7. 0
name mangling與黑客
l 使用demangling可以破解動態鏈接庫中的沒有公開的API
l 編寫名稱為name mangling接口函數,打開重復符號的編譯開關,可以替換原來函數中鏈接函數的指向,從而改變程序的運行結果。

 


摘自 相信並熱愛著http://hipercomer.blog.51cto.com/4415661/855223

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved