Template:Short description Template:About Template:Multiple issues

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.

ExamplesEdit

Template:How-to

CEdit

Although name mangling is not generally required or used by languages that do not support function overloading, like C and classic Pascal, they use it in some cases to provide added information about a function. For example, compilers targeted at Microsoft Windows platforms support a variety of calling conventions, which determine the manner in which parameters are sent to subroutines and results are returned. Because the different calling conventions are incompatible with one another, compilers mangle symbols with codes detailing which convention should be used to call the specific routine.

The mangling scheme for Windows was established by Microsoft and has been informally followed by other compilers including Digital Mars, Borland, and GNU Compiler Collection (GCC) when compiling code for the Windows platforms. The scheme even applies to other languages, such as Pascal, D, Delphi, Fortran, and C#. This allows subroutines written in those languages to call, or be called by, extant Windows libraries using a calling convention different from their default.

When compiling the following C examples: <syntaxhighlight lang="c"> int _cdecl f (int x) { return 0; } int _stdcall g (int y) { return 0; } int _fastcall h (int z) { return 0; } </syntaxhighlight>

32-bit compilers emit, respectively:

_f
_g@4
@h@4

In the <syntaxhighlight lang="text" class="" style="" inline="1">stdcall</syntaxhighlight> and <syntaxhighlight lang="text" class="" style="" inline="1">fastcall</syntaxhighlight> mangling schemes, the function is encoded as _Template:Var@Template:Var and @Template:Var@Template:Var respectively, where Template:Var 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 <syntaxhighlight lang="text" class="" style="" inline="1">cdecl</syntaxhighlight>, 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:

<syntaxhighlight lang="fortran"> SUBROUTINE f() !DEC$ ATTRIBUTES C, ALIAS:'_f' :: f END SUBROUTINE </syntaxhighlight>

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 BIND option:

<syntaxhighlight lang="fortran"> SUBROUTINE f() BIND(C,NAME="f") END SUBROUTINE </syntaxhighlight>

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.

C++Edit

Template:Anchor C++ compilers are the most widespread users of name mangling. The first C++ compilers were implemented as translators to C source code, which would then be compiled by a C compiler to object code; because of this, symbol names had to conform to C identifier rules. Even later, with the emergence of compilers that produced machine code or assembly directly, the system's linker generally did not support C++ symbols, and mangling was still required.

The C++ language does not define a standard decoration scheme, so each compiler uses its own. C++ also has complex language features, such as classes, templates, namespaces, and operator overloading, that alter the meaning of specific symbols based on context or usage. Meta-data about these features can be disambiguated by mangling (decorating) the name of a symbol. Because the name-mangling systems for such features are not standardized across compilers, few linkers can link object code that was produced by different compilers.

Simple exampleEdit

A single C++ translation unit might define two functions named <syntaxhighlight lang="text" class="" style="" inline="1">f()</syntaxhighlight>:

<syntaxhighlight lang="cpp"> int f () { return 1; } int f (int) { return 0; } void g () { int i = f(), j = f(0); } </syntaxhighlight>

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:

<syntaxhighlight lang="cpp"> int __f_v () { return 1; } int __f_i (int) { return 0; } void __g_v () { int i = __f_v(), j = __f_i(0); } </syntaxhighlight>

Even though its name is unique, <syntaxhighlight lang="text" class="" style="" inline="1">g()</syntaxhighlight> is still mangled: name mangling applies to all C++ symbols (except for those in an <syntaxhighlight lang="cpp" inline>extern "C"{}</syntaxhighlight> block).

Complex exampleEdit

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:

<syntaxhighlight lang="cpp"> namespace wikipedia {

  class article 
  {
  public:
     std::string format ();  // = _ZN9wikipedia7article6formatEv
     bool print_to (std::ostream&);  // = _ZN9wikipedia7article8print_toERSo
     class wikilink 
     {
     public:
        wikilink (std::string const& name);  // = _ZN9wikipedia7article8wikilinkC1ERKSs
     };
  };

} </syntaxhighlight>

All mangled symbols begin with <syntaxhighlight lang="text" class="" style="" inline="1">_Z</syntaxhighlight> (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 <syntaxhighlight lang="text" class="" style="" inline="1">N</syntaxhighlight>, then a series of <length, id> pairs (the length being the length of the next identifier), and finally <syntaxhighlight lang="text" class="" style="" inline="1">E</syntaxhighlight>. For example, <syntaxhighlight lang="text" class="" style="" inline="1">wikipedia::article::format</syntaxhighlight> becomes:

_ZN9wikipedia7article6formatE

For functions, this is then followed by the type information; as <syntaxhighlight lang="text" class="" style="" inline="1">format()</syntaxhighlight> is a <syntaxhighlight lang="text" class="" style="" inline="1">void</syntaxhighlight> function, this is simply <syntaxhighlight lang="text" class="" style="" inline="1">v</syntaxhighlight>; hence:

_ZN9wikipedia7article6formatEv

For <syntaxhighlight lang="text" class="" style="" inline="1">print_to</syntaxhighlight>, the standard type <syntaxhighlight lang="text" class="" style="" inline="1">std::ostream</syntaxhighlight> (which is a Template:Mono for <syntaxhighlight lang="text" class="" style="" inline="1">std::basic_ostream<char, std::char_traits<char> ></syntaxhighlight>) is used, which has the special alias <syntaxhighlight lang="text" class="" style="" inline="1">So</syntaxhighlight>; a reference to this type is therefore <syntaxhighlight lang="text" class="" style="" inline="1">RSo</syntaxhighlight>, with the complete name for the function being:

_ZN9wikipedia7article8print_toERSo

How different compilers mangle the same functionsEdit

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:

Compiler Template:Codett Template:Codett Template:Codett
Intel C++ 8.0 for Linux Template:Codett Template:Codett Template:Codett
HP aC++ A.05.55 IA-64
IAR EWARM C++
GCC 3.x and higher
Clang 1.x and higher<ref>Template:Citation</ref>
GCC 2.9.x Template:Codett Template:Codett Template:Codett
HP aC++ A.03.45 PA-RISC
Microsoft Visual C++ v6-v10 (mangling details) Template:Codett Template:Codett Template:Codett
Digital Mars C++
Borland C++ v3.1 Template:Codett Template:Codett Template:Codett
OpenVMS C++ v6.5 (ARM mode) Template:Codett Template:Codett Template:Codett
OpenVMS C++ v6.5 (ANSI mode) Template:Codett Template:Codett
OpenVMS C++ X7.1 IA-64 Template:Codett Template:Codett Template:Codett
SunPro CC Template:Codett Template:Codett Template:Codett
Tru64 C++ v6.5 (ARM mode) Template:Codett Template:Codett Template:Codett
Tru64 C++ v6.5 (ANSI mode) Template:Codett Template:Codett Template:Codett
Watcom C++ 10.6 Template:Codett Template:Codett Template:Codett

Notes:

  • The Compaq C++ compiler on OpenVMS VAX and Alpha (but not IA-64) and Tru64 UNIX has two name mangling schemes. The original, pre-standard scheme is known as the ARM model, and is based on the name mangling described in the C++ Annotated Reference Manual (ARM). With the advent of new features in standard C++, particularly templates, the ARM scheme became more and more unsuitable – it could not encode certain function types, or produced identically mangled names for different functions. It was therefore replaced by the newer American National Standards Institute (ANSI) model, which supported all ANSI template features, but was not backward compatible.
  • On IA-64, a standard application binary interface (ABI) exists (see external links), which defines (among other things) a standard name-mangling scheme, and which is used by all the IA-64 compilers. GNU GCC 3.x has further adopted the name mangling scheme defined in this standard for use on other, non-Intel platforms.
  • The Visual Studio and Windows SDK include the program <syntaxhighlight lang="text" class="" style="" inline="1">undname</syntaxhighlight> which prints the C-style function prototype for a given mangled name.
  • On Microsoft Windows, the Intel compiler<ref>{{#invoke:citation/CS1|citation

|CitationClass=web }}</ref> and Clang<ref>{{#invoke:citation/CS1|citation |CitationClass=web }}</ref> uses the Visual C++ name mangling for compatibility.

Handling of C symbols when linking from C++Edit

The job of the common C++ idiom:

<syntaxhighlight lang="cpp">

  1. ifdef __cplusplus

extern "C" {

  1. endif
   /* ... */
  1. ifdef __cplusplus

}

  1. endif

</syntaxhighlight>

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 standard strings library, <syntaxhighlight lang="text" class="" style="" inline="1"><string.h></syntaxhighlight>, usually contains something resembling:

<syntaxhighlight lang="cpp">

  1. ifdef __cplusplus

extern "C" {

  1. endif

void *memset (void *, int, size_t); char *strcat (char *, const char *); int strcmp (const char *, const char *); char *strcpy (char *, const char *);

  1. ifdef __cplusplus

}

  1. endif

</syntaxhighlight>

Thus, code such as:

<syntaxhighlight lang="cpp"> if (strcmp(argv[1], "-x") == 0)

   strcpy(a, argv[2]);

else

   memset (a, 0, sizeof(a));

</syntaxhighlight>

uses the correct, unmangled <syntaxhighlight lang="text" class="" style="" inline="1">strcmp</syntaxhighlight> and <syntaxhighlight lang="text" class="" style="" inline="1">memset</syntaxhighlight>. If the <syntaxhighlight lang="text" class="" style="" inline="1">extern "C"</syntaxhighlight> had not been used, the (SunPro) C++ compiler would produce code equivalent to:

<syntaxhighlight lang="cpp"> if (__1cGstrcmp6Fpkc1_i_(argv[1], "-x") == 0)

   __1cGstrcpy6Fpcpkc_0_(a, argv[2]);

else

   __1cGmemset6FpviI_0_ (a, 0, sizeof(a));

</syntaxhighlight>

Since those symbols do not exist in the C runtime library (e.g. libc), link errors would result.


Standardized name mangling in C++Edit

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, Template:ISBN, 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<ref>{{#invoke:citation/CS1|citation |CitationClass=web }}</ref> the full C++ ABI has been standardized, including name mangling.

Real-world effects of C++ name manglingEdit

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++filtEdit

<syntaxhighlight lang="console"> $ c++filt -n _ZNK3MapI10StringName3RefI8GDScriptE10ComparatorIS0_E16DefaultAllocatorE3hasERKS0_ Map<StringName, Ref<GDScript>, Comparator<StringName>, DefaultAllocator>::has(StringName const&) const </syntaxhighlight>

Demangle via builtin GCC ABIEdit

<syntaxhighlight lang="cpp">

  1. include <stdio.h>
  2. include <stdlib.h>
  3. include <cxxabi.h>

int main() { const char *mangled_name = "_ZNK3MapI10StringName3RefI8GDScriptE10ComparatorIS0_E16DefaultAllocatorE3hasERKS0_"; int status = -1; char *demangled_name = abi::__cxa_demangle(mangled_name, NULL, NULL, &status); printf("Demangled: %s\n", demangled_name); free(demangled_name); return 0; } </syntaxhighlight>

Output:

Template:Codett

JavaEdit

In Java, the signature of a method or a class contains its name and the types of its method arguments and return value, where applicable. The format of signatures is documented, as the language, compiler, and .class file format were all designed together (and had object-orientation and universal interoperability in mind from the start).

Creating unique names for inner and anonymous classesEdit

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:

<syntaxhighlight lang="java"> public class foo {

   class bar {
       public int x;
   }
   public void zark () {
       Object f = new Object () {
           public String toString() {
               return "hello";
           }
       };
   }

} </syntaxhighlight>

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.zark)

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 InterfaceEdit

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.<ref>{{#invoke:citation/CS1|citation

|CitationClass=web }}</ref>

  • Normal C++ name mangling - see above.

PythonEdit

In Python, mangling is used for class attributes that one does not want subclasses to use<ref>{{#invoke:citation/CS1|citation |CitationClass=web }}</ref> which are designated as such by giving them a name with two or more leading underscores and no more than one trailing underscore. For example, <syntaxhighlight lang="text" class="" style="" inline="1">__thing</syntaxhighlight> will be mangled, as will <syntaxhighlight lang="text" class="" style="" inline="1">___thing</syntaxhighlight> and <syntaxhighlight lang="text" class="" style="" inline="1">__thing_</syntaxhighlight>, but <syntaxhighlight lang="text" class="" style="" inline="1">__thing__</syntaxhighlight> and <syntaxhighlight lang="text" class="" style="" inline="1">__thing___</syntaxhighlight> will not. Python's runtime does not restrict access to such attributes, the mangling only prevents name collisions if a derived class defines an attribute with the same name.

On encountering name mangled attributes, Python transforms these names by prepending a single underscore and the name of the enclosing class, for example:

<syntaxhighlight lang="pycon"> >>> class Test: ... def __mangled_name(self): ... pass ... def normal_name(self): ... pass >>> t = Test() >>> [attr for attr in dir(t) if "name" in attr] ['_Test__mangled_name', 'normal_name'] </syntaxhighlight>

PascalEdit

Turbo Pascal, DelphiEdit

To avoid name mangling in Pascal, use:

<syntaxhighlight lang="pascal"> exports

 myFunc name 'myFunc',
 myProc name 'myProc';

</syntaxhighlight>

Free PascalEdit

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.

FortranEdit

Name mangling is also necessary in Fortran compilers, originally because the language is case insensitive. Further mangling requirements were imposed later in the evolution of the language because of the addition of modules and other features in the Fortran 90 standard. The case mangling, especially, is a common issue that must be dealt with to call Fortran libraries, such as LAPACK, from other languages, such as C.

Because of the case insensitivity, the name of a subroutine or function <syntaxhighlight lang="text" class="" style="" inline="1">FOO</syntaxhighlight> must be converted to a standardized case and format by the compiler so that it will be linked in the same way regardless of case. Different compilers have implemented this in various ways, and no standardization has occurred. The AIX and HP-UX Fortran compilers convert all identifiers to lower case <syntaxhighlight lang="text" class="" style="" inline="1">foo</syntaxhighlight>, while the Cray and Unicos Fortran compilers converted identifiers to all upper case <syntaxhighlight lang="text" class="" style="" inline="1">FOO</syntaxhighlight>. The GNU g77 compiler converts identifiers to lower case plus an underscore <syntaxhighlight lang="text" class="" style="" inline="1">foo_</syntaxhighlight>, except that identifiers already containing an underscore <syntaxhighlight lang="text" class="" style="" inline="1">FOO_BAR</syntaxhighlight> have two underscores appended <syntaxhighlight lang="text" class="" style="" inline="1">foo_bar__</syntaxhighlight>, following a convention established by f2c. Many other compilers, including Silicon Graphics's (SGI) IRIX compilers, GNU Fortran, and Intel's Fortran compiler (except on Microsoft Windows), convert all identifiers to lower case plus an underscore (<syntaxhighlight lang="text" class="" style="" inline="1">foo_</syntaxhighlight> and <syntaxhighlight lang="text" class="" style="" inline="1">foo_bar_</syntaxhighlight>, respectively). On Microsoft Windows, the Intel Fortran compiler defaults to uppercase without an underscore.<ref>{{#invoke:citation/CS1|citation |CitationClass=web }}</ref>

Identifiers in Fortran 90 modules must be further mangled, because the same procedure name may occur in different modules. Since the Fortran 2003 Standard requires that module procedure names not conflict with other external symbols,<ref>{{#invoke:citation/CS1|citation |CitationClass=web }}</ref> compilers tend to use the module name and the procedure name, with a distinct marker in between. For example:

<syntaxhighlight lang="fortran"> module m contains

  integer function five()
     five = 5
  end function five

end module m </syntaxhighlight>

In this module, the name of the function will be mangled as <syntaxhighlight lang="text" class="" style="" inline="1">__m_MOD_five</syntaxhighlight> (e.g., GNU Fortran), <syntaxhighlight lang="text" class="" style="" inline="1">m_MP_five_</syntaxhighlight> (e.g., Intel's ifort), <syntaxhighlight lang="text" class="" style="" inline="1">m.five_</syntaxhighlight> (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 overrides any name mangling done by the compiler, as shown above.

RustEdit

Template:Expand section Function names are mangled by default in Rust. However, this can be disabled by the <syntaxhighlight lang="text" class="" style="" inline="1">#[no_mangle]</syntaxhighlight> function attribute. This attribute can be used to export functions to C, C++, or Objective-C.<ref>{{#invoke:citation/CS1|citation |CitationClass=web }}</ref> Further, along with the <syntaxhighlight lang="text" class="" style="" inline="1">#[start]</syntaxhighlight> function attribute or the <syntaxhighlight lang="text" class="" style="" inline="1">#[no_main]</syntaxhighlight> crate attribute, it allows the user to define a C-style entry point for the program.<ref>{{#invoke:citation/CS1|citation |CitationClass=web }}</ref>

Rust has used many versions of symbol mangling schemes that can be selected at compile time with an <syntaxhighlight lang="text" class="" style="" inline="1">-Z symbol-mangling-version</syntaxhighlight> option. The following manglers are defined:

  • <syntaxhighlight lang="text" class="" style="" inline="1">legacy</syntaxhighlight> A C++ style mangling based on the Itanium IA-64 C++ ABI. Symbols begin with <syntaxhighlight lang="text" class="" style="" inline="1">_ZN</syntaxhighlight>, and filename hashes are used for disambiguation. Used since Rust 1.9.<ref>{{#invoke:citation/CS1|citation

|CitationClass=web }}</ref>

  • <syntaxhighlight lang="text" class="" style="" inline="1">v0</syntaxhighlight> An improved version of the legacy scheme, with changes for Rust. Symbols begin with <syntaxhighlight lang="text" class="" style="" inline="1">_R</syntaxhighlight>. Polymorphism can be encoded. Functions don't have return types encoded (Rust does not have overloading). Unicode names use modified punycode. Compression (backreference) use byte-based addressing. Used since Rust 1.37.<ref>{{#invoke:citation/CS1|citation

|CitationClass=web }}</ref>

Examples are provided in the Rust <syntaxhighlight lang="text" class="" style="" inline="1">symbol-names</syntaxhighlight> tests.<ref>{{#invoke:citation/CS1|citation |CitationClass=web }}</ref>

Objective-CEdit

Essentially two forms of method exist in Objective-C, the class ("static") method, and the instance method. A method declaration in Objective-C is of the following form:

+ (return-type) name0:parameter0 name1:parameter1 ...
– (return-type) name0:parameter0 name1:parameter1 ...

Class methods are signified by +, instance methods use -. A typical class method declaration may then look like:

<syntaxhighlight lang="objc"> + (id) initWithX: (int) number andY: (int) number; + (id) new; </syntaxhighlight>

With instance methods looking like this:

<syntaxhighlight lang="objc"> - (id) value; - (id) setValue: (id) new_value; </syntaxhighlight>

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_name0_name1_ ...

and this for instance methods:

_i_Class_name0_name1_ ...

The colons in the Objective-C syntax are translated to underscores. So, the Objective-C class method <syntaxhighlight lang="objc" class="" style="" inline="1">+ (id) initWithX: (int) number andY: (int) number;</syntaxhighlight>, if belonging to the <syntaxhighlight lang="text" class="" style="" inline="1">Point</syntaxhighlight> class would translate as <syntaxhighlight lang="text" class="" style="" inline="1">_c_Point_initWithX_andY_</syntaxhighlight>, and the instance method (belonging to the same class) <syntaxhighlight lang="objc" class="" style="" inline="1">- (id) value;</syntaxhighlight> would translate to <syntaxhighlight lang="text" class="" style="" inline="1">_i_Point_value</syntaxhighlight>.

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 – <syntaxhighlight lang="text" class="" style="" inline="1">SEL</syntaxhighlight>.

During compiling, a table is built that maps the textual representation, such as <syntaxhighlight lang="text" class="" style="" inline="1">_i_Point_value</syntaxhighlight>, to selectors (which are given a type <syntaxhighlight lang="text" class="" style="" inline="1">SEL</syntaxhighlight>). 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, <syntaxhighlight lang="text" class="" style="" inline="1">IMP</syntaxhighlight>.

Message sends are encoded by the compiler as calls to the <syntaxhighlight lang="objc" class="" style="" inline="1">id objc_msgSend (id receiver, SEL selector, ...)</syntaxhighlight> function, or one of its cousins, where <syntaxhighlight lang="text" class="" style="" inline="1">receiver</syntaxhighlight> is the receiver of the message, and <syntaxhighlight lang="text" class="" style="" inline="1">SEL</syntaxhighlight> 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 <syntaxhighlight lang="text" class="" style="" inline="1">SEL</syntaxhighlight> to <syntaxhighlight lang="text" class="" style="" inline="1">IMP</syntaxhighlight> lookup tables, the functions are essentially anonymous.

The <syntaxhighlight lang="text" class="" style="" inline="1">SEL</syntaxhighlight> 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).

SwiftEdit

Swift keeps metadata about functions (and more) in the mangled symbols referring to them. This metadata includes the function's name, attributes, module name, parameter types, return type, and more. For example:

The mangled name for a method <syntaxhighlight lang="text" class="" style="" inline="1">func calculate(x: int) -> int</syntaxhighlight> of a <syntaxhighlight lang="text" class="" style="" inline="1">MyClass</syntaxhighlight> class in module <syntaxhighlight lang="text" class="" style="" inline="1">test</syntaxhighlight> is <syntaxhighlight lang="text" class="" style="" inline="1">_TFC4test7MyClass9calculatefS0_FT1xSi_Si</syntaxhighlight>, for 2014 Swift. The components and their meanings are as follows:<ref>{{#invoke:citation/CS1|citation |CitationClass=web }}</ref>

  • <syntaxhighlight lang="text" class="" style="" inline="1">_T</syntaxhighlight>: The prefix for all Swift symbols. Everything will start with this.
  • <syntaxhighlight lang="text" class="" style="" inline="1">F</syntaxhighlight>: Non-curried function.
  • <syntaxhighlight lang="text" class="" style="" inline="1">C</syntaxhighlight>: Function of a class, i.e. a method
  • <syntaxhighlight lang="text" class="" style="" inline="1">4test</syntaxhighlight>: Module name, prefixed with its length.
  • <syntaxhighlight lang="text" class="" style="" inline="1">7MyClass</syntaxhighlight>: Name of class the function belongs to, prefixed with its length.
  • <syntaxhighlight lang="text" class="" style="" inline="1">9calculate</syntaxhighlight>: Function name, prefixed with its length.
  • <syntaxhighlight lang="text" class="" style="" inline="1">f</syntaxhighlight>: The function attribute. In this case ‘f’, which means a normal function.
  • <syntaxhighlight lang="text" class="" style="" inline="1">S0</syntaxhighlight>: Designates the type of the first parameter (namely the class instance) as the first in the type stack (here <syntaxhighlight lang="text" class="" style="" inline="1">MyClass</syntaxhighlight> is not nested and thus has index 0).
  • <syntaxhighlight lang="text" class="" style="" inline="1">_FT</syntaxhighlight>: This begins the type list for the parameter tuple of the function.
  • <syntaxhighlight lang="text" class="" style="" inline="1">1x</syntaxhighlight>: External name of first parameter of the function.
  • <syntaxhighlight lang="text" class="" style="" inline="1">Si</syntaxhighlight>: Indicates builtin Swift type Swift.Int for the first parameter.
  • <syntaxhighlight lang="text" class="" style="" inline="1">_Si</syntaxhighlight>: The return type: again Swift.Int.

Mangling for versions since Swift 4.0 is documented officially. It retains some similarity to Itanium.<ref>{{#invoke:citation/CS1|citation |CitationClass=web }}</ref>

See alsoEdit

ReferencesEdit

Template:Reflist

External linksEdit

Template:Application binary interface