e01.org

Name mangling

In compiler construction, name mangling (also called name decoration) is a technique used to solve various problems caused by the need to resolve unique names for programming entities in many modern programming languages. It provides means to encode added information in the name of a function, structure, class or another data type, to pass more semantic information from the compiler to the linker. The need for name mangling arises where a language allows different entities to be named with the same identifier as long as they occupy a different namespace (typically defined by a module, class, or explicit namespace directive) or have different type signatures (such as in function overloading). It is required in these uses because each signature might require different, specialized calling convention in the machine code. Any object code produced by compilers is usually linked with other pieces of object code (produced by the same or another compiler) by a type of program called a...

In compiler construction, name mangling (also called name decoration) is a technique used to solve various problems caused by the need to resolve unique names for programming entities in many modern programming languages. It provides means to encode added information in the name of a function, structure, class or another data type, to pass more semantic information from the compiler to the linker. The need for name mangling arises where a language allows different entities to be named with the same identifier as long as they occupy a different namespace (typically defined by a module, class, or explicit namespace directive) or have different type signatures (such as in function overloading). It is required in these uses because each signature might require different, specialized calling convention in the machine code. Any object code produced by compilers is usually linked with other pieces of object code (produced by the same or another compiler) by a type of program called a linker. The linker needs a great deal of information on each program entity. For example, to correctly link a function it needs its name, the number of arguments and their types, and so on. The simple programming languages of the 1970s, like C, only distinguished subroutines by their name, ignoring other information including parameter and return types. Later languages, like C++, defined stricter requirements for routines to be considered "equal", such as the parameter types, return type, and calling convention of a function. These requirements enable method overloading and detection of some bugs (such as using different definitions of a function when compiling different source code files). These stricter requirements needed to work with extant programming tools and conventions. Thus, added requirements were encoded in the name of the symbol, since that was the only information a traditional linker had about a symbol. int _cdecl f(int x) { return 0; } int _stdcall g(int y) { return 0; } int _fastcall h(int z) { return 0; } 32-bit compilers emit, respectively: _f _g@4 @h@4 In the and mangling schemes, the function is encoded as _ @ and @ @ respectively, where is the number of bytes, in decimal, of the argument(s) in the parameter list (including those passed in registers, for fastcall). In the case of , the function name is merely prefixed by an underscore. The 64-bit convention on Windows (Microsoft C) has no leading underscore. This difference may in some rare cases lead to unresolved externals when porting such code to 64 bits. For example, Fortran code can use "alias" to link against a C method by name as follows: SUBROUTINE f() !DEC$ ATTRIBUTES C, ALIAS:'_f' :: f END SUBROUTINE This will compile and link fine under 32 bits, but generate an unresolved external _f under 64 bits. One workaround for this is not to use "alias" at all (in which the method names typically need to be capitalized in C and Fortran). Another is to use the Fortran 2003 option: SUBROUTINE f() BIND(C,NAME="f") END SUBROUTINE In C, most compilers also mangle static functions and variables (and in C++ functions and variables declared static or put in the anonymous namespace) in translation units using the same mangling rules as for their non-static versions. If functions with the same name (and parameters for C++) are also defined and used in different translation units, it will also mangle to the same name, potentially leading to a clash. However, they will not be equivalent if they are called in their respective translation units. Compilers are usually free to emit arbitrary mangling for these functions, because it is illegal to access these from other translation units directly, so they will never need linking between different object code (linking of them is never needed). To prevent linking conflicts, compilers will use standard mangling, but will use so-called "local" symbols. When linking many such translation units there might be multiple definitions of a function with the same name, but resulting code will only call one or another depending on which translation unit it came from. This is usually done using the relocation mechanism. ====Simple example==== A single C++ translation unit might define two functions named : int f() { return 1; } int f(maybe_unused int x) { return 0; } void g() { int i = f(); int j = f(0); } These are distinct functions, with no relation to each other apart from the name. The C++ compiler will therefore encode the type information in the symbol name, the result being something resembling: int __f_v() { return 1; } int __f_i(maybe_unused int x) { return 0; } void __g_v() { int i = __f_v(); int j = __f_i(0); } Even though its name is unique, is still mangled: name mangling applies to all C++ symbols (except for those in an extern "C" block). extern "C" is used in C++ to grant a symbol "C linkage", disabling name mangling and allowing the calling of these functions from C. ====Complex example==== The mangled symbols in this example, in the comments below the respective identifier name, are those produced by the GNU GCC 3.x compilers, according to the IA-64 (Itanium) ABI: export module wikipedia.structure.Article; import std; using std::ostream; using std::string; using std::string_view; export namespace wikipedia::structure { class Article { public: explicit Article(string_view name); ~Article() = default; nodiscard string format(); // = _ZN9wikipedia8structure7Article6formatEv bool printTo(ostream& os); // = _ZN9wikipedia8structure7article6printToERSo class Wikilink { public: explicit Wikilink(string_view name); // = _ZN9wikipedia8structure7Article6WikilinkC1ERKSs ~Wikilink() = default; }; }; } All mangled symbols begin with (note that an identifier beginning with an underscore followed by a capital letter is a reserved identifier in C, so conflict with user identifiers is avoided); for nested names (including both namespaces and classes), this is followed by , then a series of <length, id> pairs (the length being the length of the next identifier), and finally . For example, becomes: _ZN9wikipedia9structure7Article6formatE For functions, this is then followed by the type information; as function doesn't take any arguments which is equivalent to , this is simply ; hence: _ZN9wikipedia9structure7Article6formatEv For , the standard type (which is a for ) is used, which has the special alias ; a reference to this type is therefore , with the complete name for the function being: _ZN9wikipedia8structure7Article6printToERSo Note that in the Itanium ABI, the return type is omitted for non-template functions, but is encoded for template functions . ====How different compilers mangle the same functions==== There isn't a standardized scheme by which even trivial C++ identifiers are mangled, and consequently different compilers (or even different versions of the same compiler, or the same compiler on different platforms) mangle public symbols in radically different (and thus totally incompatible) ways. Consider how different C++ compilers mangle the same functions: Notes: The Visual Studio and Windows SDK include the program which prints the C-style function prototype for a given mangled name. On Microsoft Windows, the Intel compiler and Clang uses the Visual C++ name mangling for compatibility. (Clang can use the Itanium scheme on Windows when not linking to the Visual C++ Runtime Library.) ====Handling of C symbols when linking from C++==== The job of the common C++ idiom: ifdef __cplusplus extern "C" { endif // symbols here ifdef __cplusplus } endif is to ensure that the symbols within are "unmangled" – that the compiler emits a binary file with their names undecorated, as a C compiler would do. As C language definitions are unmangled, the C++ compiler needs to avoid mangling references to these identifiers. For example, the header usually contains contents resembling: ifdef __cplusplus extern "C" { endif void* memset(void* s, int c, size_t n); char* strcat(char* s1, const char* s2); int strcmp(const char* s1, const char* s2); char* strcpy(char* s1, const char* s2); ifdef __cplusplus } endif Thus, code such as: if (strcmp(argv[1], "-x") == 0) { strcpy(a, argv[2]); } else { memset(a, 0, sizeof(a)); } uses the correct, unmangled and . If the extern "C" had not been used, the (SunPro) C++ compiler would produce code equivalent to: if (__1cGstrcmp6Fpkc1_i_(argv[1], "-x") == 0) { __1cGstrcpy6Fpcpkc_0_(a, argv[2]); } else { __1cGmemset6FpviI_0_(a, 0, sizeof(a)); } Since those symbols do not exist in the C runtime library (e.g. libc), link errors would result. ====Standardized name mangling in C++==== It would seem that standardized name mangling in the C++ language would lead to greater interoperability between compiler implementations. However, such a standardization by itself would not suffice to guarantee C++ compiler interoperability and it might even create a false impression that interoperability is possible and safe when it isn't. Name mangling is only one of several application binary interface (ABI) details that need to be decided and observed by a C++ implementation. Other ABI aspects like exception handling, virtual table layout, structure, and stack frame padding also cause differing C++ implementations to be incompatible. Further, requiring a particular form of mangling would cause issues for systems where implementation limits (e.g., length of symbols) dictate a particular mangling scheme. A standardized requirement for name mangling would also prevent an implementation where mangling was not required at all – for example, a linker that understood the C++ language. The C++ standard therefore does not attempt to standardize name mangling. On the contrary, the Annotated C++ Reference Manual (also known as ARM, , section 7.2.1c) actively encourages the use of different mangling schemes to prevent linking when other aspects of the ABI are incompatible. Nevertheless, as detailed in the section above, on some platforms the full C++ ABI has been standardized, including name mangling. ====Real-world effects of C++ name mangling==== Because C++ symbols are routinely exported from DLL and shared object files, the name mangling scheme is not merely a compiler-internal matter. Different compilers (or different versions of the same compiler, in many cases) produce such binaries under different name decoration schemes, meaning that symbols are frequently unresolved if the compilers used to create the library and the program using it employed different schemes. For example, if a system with multiple C++ compilers installed (e.g., GNU GCC and the OS vendor's compiler) wished to install the Boost C++ Libraries, it would have to be compiled multiple times (once for GCC and once for the vendor compiler). It is good for safety purposes that compilers producing incompatible object codes (codes based on different ABIs, regarding e.g., classes and exceptions) use different name mangling schemes. This guarantees that these incompatibilities are detected at the linking phase, not when executing the software (which could lead to obscure bugs and serious stability issues). For this reason, name decoration is an important aspect of any C++-related ABI. There are instances, particularly in large, complex code bases, where it can be difficult or impractical to map the mangled name emitted within a linker error message back to the particular corresponding token/variable-name in the source. This problem can make identifying the relevant source file(s) very difficult for build or test engineers even if only one compiler and linker are in use. Demanglers (including those within the linker error reporting mechanisms) sometimes help but the mangling mechanism itself may discard critical disambiguating information. ====Demangle via c++filt==== $ c++filt -n _ZNK3MapI10StringName3RefI8GDScriptE10ComparatorIS0_E16DefaultAllocatorE3hasERKS0_ Map , Comparator , DefaultAllocator>::has(StringName const&) const ====Demangle via builtin GCC ABI==== import ; import std; int main(int argc, char* argv[]) { const char* mangledName = "_ZNK3MapI10StringName3RefI8GDScriptE10ComparatorIS0_E16DefaultAllocatorE3hasERKS0_"; int status = -1; char* demangledName = abi::__cxa_demangle(mangledName, nullptr, nullptr, &status); std::println("Demangled: {}", demangledName); std::free(demangledName); return 0; } Output: The C# programming language avoids using name mangling entirely by instead relying on metadata in Common Intermediate Language representation. Unmangled C/C++ symbols (marked with extern "C" ) can be consumed with Platform Invocation Services (P/Invoke) [DllImport] . The D programming language uses name mangling, which mangles differently from C++, and produces generally more human-readable names. Names are mangled unless linking with C (using extern(C) ). It offers a tool "ddemangle" for demangling symbol names. The library offers modules dmd.mangle for mangling extern(D) symbols , and core.demangle for demangling D symbols. module m contains integer function five() five = 5 end function five end module m In this module, the name of the function will be mangled as (e.g., GNU Fortran), (e.g., Intel's ifort), (e.g., Oracle's sun95), etc. Since Fortran does not allow overloading the name of a procedure, but uses generic interface blocks and generic type-bound procedures instead, the mangled names do not need to incorporate clues about the arguments. The Fortran 2003 BIND option causes the compiler to use mangling rules used for another programing language, such as C, as shown above. ====Creating unique names for inner and anonymous classes==== The scope of anonymous classes is confined to their parent class, so the compiler must produce a "qualified" public name for the inner class, to avoid conflict where other classes with the same name (inner or not) exist in the same namespace. Similarly, anonymous classes must have "fake" public names generated for them (as the concept of anonymous classes only exists in the compiler, not the runtime). So, compiling the following Java program: public class Foo { class Bar { public int x; } public void baz() { Object f = new Object() { public String toString() { return "hello"; } }; } } will produce three .class files: foo.class, containing the main (outer) class foo foo$bar.class, containing the named inner class foo.bar foo$1.class, containing the anonymous inner class (local to method foo.baz) All of these class names are valid (as symbols are permitted in the JVM specification) and these names are "safe" for the compiler to generate, as the Java language definition advises not to use symbols in normal java class definitions. Name resolution in Java is further complicated at runtime, as fully qualified names for classes are unique only inside a specific classloader instance. Classloaders are ordered hierarchically and each Thread in the JVM has a so-called context class loader, so in cases where two different classloader instances contain classes with the same name, the system first tries to load the class using the root (or system) classloader and then goes down the hierarchy to the context class loader. ====Java Native Interface==== Java Native Interface, Java's native method support, allows Java language programs to call out to programs written in another language (usually C or C++). There are two name-resolution concerns here, neither of which is implemented in a standardized manner: JVM to native name translation - this seems to be more stable, since Oracle makes its scheme public. Normal C++ name mangling - see above. class Test: def __mangled_name(self) -> None: pass def normal_name(self) -> None: pass if __name == "__main__": t: Test = Test() print([attr for attr in dir(t) if "name" in attr]) # prints: ['_Test__mangled_name', 'normal_name'] ====Turbo Pascal, Delphi==== To avoid name mangling in Pascal, use: exports myFunc name 'myFunc', myProc name 'myProc'; ====Free Pascal==== Free Pascal supports function and operator overloading, thus it also uses name mangling to support these features. On the other hand, Free Pascal is capable of calling symbols defined in external modules created with another language and exporting its own symbols to be called by another language. For further information, consult Chapter 6.2 and 7.1 of Free Pascal Programmer's Guide. + (id) initWithX: (int) number andY: (int) number; + (id) new; With instance methods looking like this: - (id) value; - (id) setValue: (id) new_value; Each of these method declarations have a specific internal representation. When compiled, each method is named according to the following scheme for class methods: _c_Class_name 0 _name 1 _ ... and this for instance methods: _i_Class_name 0 _name 1 _ ... The colons in the Objective-C syntax are translated to underscores. So, the Objective-C class method , if belonging to the class would translate as , and the instance method (belonging to the same class) would translate to . Each of the methods of a class are labeled in this way. However, to look up a method that a class may respond to would be tedious if all methods are represented in this fashion. Each of the methods is assigned a unique symbol (such as an integer). Such a symbol is known as a selector. In Objective-C, one can manage selectors directly – they have a specific type in Objective-C – . During compiling, a table is built that maps the textual representation, such as , to selectors (which are given a type ). Managing selectors is more efficient than manipulating the text representation of a method. Note that a selector only matches a method's name, not the class it belongs to: different classes can have different implementations of a method with the same name. Because of this, implementations of a method are given a specific identifier too, these are known as implementation pointers, and are also given a type, . Message sends are encoded by the compiler as calls to the function, or one of its cousins, where is the receiver of the message, and determines the method to call. Each class has its own table that maps selectors to their implementations – the implementation pointer specifies where in memory the implementation of the method resides. There are separate tables for class and instance methods. Apart from being stored in the to lookup tables, the functions are essentially anonymous. The value for a selector does not vary between classes. This enables polymorphism. The Objective-C runtime maintains information about the argument and return types of methods. However, this information is not part of the name of the method, and can vary from class to class. Since Objective-C does not support namespaces, there is no need for the mangling of class names (that do appear as symbols in generated binaries). ==References== ==External links== Linux Itanium ABI for C++, including name mangling scheme. Macintosh C/C++ ABI Standard Specification c++filt – filter to demangle encoded C++ symbols for GNU/Intel compilers undname – msvc tool to demangle names. demangler.com – An online tool for demangling GCC and MSVC C++ symbols The Objective-C Runtime System – From Apple's The Objective-C Programming Language 1.0 Calling conventions for different C++ compilers by Agner Fog contains detailed description of name mangling schemes for various x86 and x64 C++ compilers (pp. 24–42 in 2011-06-08 version) C++ Name Mangling/Demangling Quite detailed explanation of Visual C++ compiler name mangling scheme PHP UnDecorateSymbolName a php script that demangles Microsoft Visual C's function names. Mixing C and C++ Code Code: [ftp://ftp.iecc.com/pub/linker/] Errata: Name mangling demystified by Fivos Kefallonitis

source: e01 Encyclopedia · licence: CC BY-SA 4.0 · page · source revision

Cite this

"Name mangling". 1791240515. e01 Encyclopedia. CC BY-SA 4.0. https://en.wikipedia.org/w/index.php?oldid=1378749324

JSON record · API collection · BibTeX · RIS · CSL-JSON · citation policy

Save to pass ·