How to force VC++ name mangling C++Builder? - c++

Is it possible to export a function from a C++Builder DLL with a specific mangled name?
I am trying to build a C++Builder DLL to replace an existing VC++ DLL. The problem is that the application that uses the DLL expects one of the functions to have a specific mangled name.
That is, it expects the function to be called:
"?_FUNCTIONNAME_##YAHPAU_PARAM1_##PAU_PARAM2_###Z"
Of course I can export function from my DLL with a mangled name but CodeGear insists on using its own name mangling scheme.
Is it possible to force C++Builder to:
Use a specific mangled name for a function?
or
Use VC++ name mangling for a specific function?
Note that I only want to change the mangling for a specific function, not all the functions in the DLL.

Name mangling is just one of many aspects of the ABI. And it fact it would be the more easy to standardize. Compilers are using purposefully different name manglings when they are using different ABI in order to prevent linking incompatible objects.
One thing you may try for a given function is to mark it extern "C", then it will use the calling convention of C and the same mangling (commonly no mangling at all or just an initial _). Obviously that won't take care of other issues (handling of exceptions, precise content of vtbls, which registers are used for passing parameters, the precise definition of the standard library, ...)

Use a .def file to specify your own naming for the exported function.

Related

Explicit name mangling (also called name decoration) for all symbols in a library

Is there any way to explicitly do name mangling (also called name decoration) in a library written in c(or cpp).I want all the symbols of my shared library to have their names mangled.
Consider this question:
Two library of different versions in an application
In this if I can explicitly have all their names mangled , I think i can resolve that issue.May be there is some option in gcc compiler itself to do this.
Your question is:
Is there any way to explicitly do name mangling (also called name decoration) in a library written in c(or cpp).I want all the symbols of my shared library to have their names mangled.
However, I suspect that you're using the term name mangling inappropriately. Name mangling has nothing to do with library release version. If you mean to version each object exported in your library, then there are plenty of questions to answer that. Personally, I would use a versioned namespace -- but only because I haven't (yet) been bitten by it. Here's a quick example:
namespace mylibrary {
namespace v1 {
class foo {};
}
using foo = v1::foo;
}
mylibrary::foo f; // mylibrary::v1::foo
...then on a later release...
namespace mylibrary {
namespace v1 {
class foo {};
}
namespace v2 {
class foo;
}
using foo = v2::foo;
}
mylibrary::foo newer_f; // mylibrary::v2::foo
mylibrary::v1::foo older_f;
There are of course many permutations you could have. And there are a lot of caveats, especially if you have templated code or make use of ADL. If you release version 1 of the library with one definition of class foo but then version 2 has a different definition, then the two libraries will not be compatible! That's rather the whole point though.
If however I am incorrect and you truly do want to enforce C++ name mangling in your C++ library (which is odd, because it should be done by default), then the answer is twofold. First, take a look at some related questions:
Why would you use 'extern "C++"'?
"Undefined reference to" error while linking object files
"Undefined reference to" error when linking static C library with C++ code
The reading is related but not causal. The related questions are answering your question in reverse.
Many operating systems are written in C and that is typically why you'd see extern "C" when including system headers. It's also why you sometimes see the linker complaining about missing functions when you try to use things declared in a header whose library was compiled with C instead of C++.
So to go in the other direction (in your direction): in your header file, you can declare your exports to be extern "C++". That tells the compiler to specifically use mangled names when importing or exporting the object.
Using extern "C++" won't by itself be your magic trick. There are some GCC options which control some of the more specific functionality about name mangling. So, secondly, take a look at those. The (external link) to the GCC manual page is here: https://gcc.gnu.org/onlinedocs/gcc/C_002b_002b-Dialect-Options.html
Any option which mentions ABI, such as -fabi, might impact you. "-fabi" flags relate to "Application Binary Interface". You might want to learn more about these terms too. What is an application binary interface has some excellent answers describing what an ABI is and how you can start to reason about them. "-Wabi" will tell GCC to emit warnings when it detects potential ABI conflicts. But, like all things C++, it's not foolproof. I would not be surprised if there are name mangling issues which might not be detected by it. That's particularly true if you ever mix heterogenous compiler vendors or versions.
Importantly: mixing ABIs is likely going to be a big headache. I'd be very concerned about ABI incompatibilities being forced together and causing very difficult-to-debug undefined behaviors!

dlsym Functions inside a class c++ Linux [duplicate]

I am trying to learn and understand name mangling in C++. Here are some questions:
(1) From devx
When a global function is overloaded, the generated mangled name for each overloaded version is unique. Name mangling is also applied to variables. Thus, a local variable and a global variable with the same user-given name still get distinct mangled names.
Are there other examples that are using name mangling, besides overloading functions and same-name global and local variables ?
(2) From Wiki
The need arises where the language allows different entities to be named with the same identifier as long as they occupy a different namespace (where a namespace is typically defined by a module, class, or explicit namespace directive).
I don't quite understand why name mangling is only applied to the cases when the identifiers belong to different namespaces, since overloading functions can be in the same namespace and same-name global and local variables can also be in the same space. How to understand this?
Do variables with same name but in different scopes also use name mangling?
(3) Does C have name mangling? If it does not, how can it deal with the case when some global and local variables have the same name? C does not have overloading functions, right?
Thanks and regards!
C does not do name mangling, though it does pre-pend an underscore to function names, so the printf(3) is actually _printf in the libc object.
In C++ the story is different. The history of it is that originally Stroustrup created "C with classes" or cfront, a compiler that would translate early C++ to C. Then rest of the tools - C compiler and linker would we used to produce object code. This implied that C++ names had to be translated to C names somehow. This is exactly what name mangling does. It provides a unique name for each class member and global/namespace function and variable, so namespace and class names (for resolution) and argument types (for overloading) are somehow included in the final linker names.
This is very easy to see with tools like nm(1) - compile your C++ source and look at the generated symbols. The following is on OSX with GCC:
namespace zoom
{
void boom( const std::string& s )
{
throw std::runtime_error( s );
}
}
~$ nm a.out | grep boom
0000000100001873 T __ZN4zoom4boomERKSs
In both C and C++ local (automatic) variables produce no symbols, but live in registers or on stack.
Edit:
Local variables do not have names in resulting object file for mere reason that linker does not need to know about them. So no name, no mangling. Everything else (that linker has to look at) is name-mangled in C++.
Mangling is simply how the compiler keeps the linker happy.
In C, you can't have two functions with the same name, no matter what. So that's what the linker was written to assume: unique names. (You can have static functions in different compilation units, because their names aren't of interest to the linker.)
In C++, you can have two functions with the same name as long as they have different parameter types. So C++ combines the function name with the types in some way. That way the linker sees them as having different names.
The exact manner of mangling is not significant to the programmer, only the compiler, and in fact every compiler does it differently. All that matters is that every function with the same base name is somehow made unique for the linker.
You can see now that adding namespaces and templates to the mix keeps extending the principle.
Technically, it's "decorating". It sounds less crude but also mangling sort of implies that CreditInterest might get rearranged into IntCrederestit whereas what actually happens is more like _CreditInterest#4 which is, fair to say, "decorated" more than mangled. That said, I call it mangling too :-) but you'll find more technical info and examples if you search for "C++ name decoration".
Are there other examples that are using name mangling, besides overloading functions and same-name global and local variables?
C++ mangles all symbols, always. It's just easier for the compiler. Typically the mangling encodes something about the parameter list or types as these are the most common causes of mangling being needed.
C does not mangle. Scoping is used to control access to local and global variables of the same name.
Source:http://sickprogrammersarea.blogspot.in/2014/03/technical-interview-questions-on-c_6.html
Name mangling is the process used by C++ compilers give each function in your program a unique name. In C++, generally programs have at-least a few functions with the same name. Thus name mangling can be considered as an important aspect in C++.
Example:
Commonly, member names are uniquely generated by concatenating the name of the member with that of the class e.g. given the declaration:
class Class1
{
public:
int val;
...
};
val becomes something like:
// a possible member name mangling
val__11Class1
agner has more information on what is a name mangling and how it is done in different compilers.
Name mangling (also called name decoration) is a method used by C++
compilers to add additional information to the names of functions and
objects in object files. This information is used by linkers when a
function or object defined in one module is referenced from another
module. Name mangling serves the following purposes:
Make it possible for linkers to distinguish between different versions of overloaded functions.
Make it possible for linkers to check that objects and functions are declared in exactly the same way in all modules.
Make it possible for linkers to give complete information about the type of unresolved references in error messages.
Name mangling was invented to fulfill purpose 1. The other purposes
are secondary benefits not fully supported by all compilers. The
minimum information that must be supplied for a function is the name
of the function and the types of all its parameters as well as any
class or namespace qualifiers. Possible additional information
includes the return type, calling convention, etc. All this
information is coded into a single ASCII text string which looks
cryptic to the human observer. The linker does not have to know what
this code means in order to fulfill purpose 1 and 2. It only needs to
check if strings are identical.

Calling C++ function from C without using extern "C"

Is it possible to call a function in a C++ DLL from C code?
The function is not declared extern "C".
An ugly platform dependent hack that only works with Visual Studio is fine.
Calling conventions should not be a major issue, but how do I deal with name mangling.?
For instance with Visual Studio, a C++ function with signature void f() has the mangled name ?f##YAXXZ and that is not a legal C identifier.
(You don't need to tell me that I should declare the C++ function as extern "C".
I already know that. But I'm in a situation where I cannot change the C++ code.)
Wrap the offenging function in another C++ function, and declare it with extern "C". No need to create a special DLL for it, just include one C++ file in your project.
To make your compiler to statically link a function with a different exported name may be tricky. But you can always load the DLL with LoadLibrary and then use GetProcAddress.
You could investigate
LoadLibrary("path to dll");
to load the DLL and
GetProcAddress("?f##YAXXZ");
to grab a function pointer to the externally declared function.
I do not see any clean solution besides creating an additional dll written in C++ and exposing all interfaces via extern "C".
You could compile your C code using the same C++ compiler they used, then your C functions will be mangled using the same mechanism and everything will link seamlessly, and no-one will notice any difference.
If you must use a different compiler, then you'll have to manually load the dll using LoadLibrary and each function using GetProcAddress.

stdcall name mangling using extern c and dllexport vs module definitions (msvc++)

I was trying to export a simple test function for a dll to work with an application (fyi: mIRC) that specifies the calling convention as:
int __stdcall test_func(HWND mWnd, HWND aWnd, char *data, char *parms, BOOL show, BOOL nopause)
Now, to call this from the application, I'd be using test_func but I have noticed due to name mangling it is not as simple as I'd thought.
Through similar topics here I have come to the understanding that using extern "C" in combination with __declspec(dllexport) is an equivelant (somewhat) method of removing mangling to module definitions (.def). However, when using the extern/dllexport method my function (as an example) is always _test_func#numbers whereas the .def removed all mangling as required for use with the application i needed to export to.
Could someone please explain why this is? I'm just curious about the two methods. Thanks!
extern "C" has nothing to do with stdcall: it only declares that C++ name mangling (aka type-safe linkage; inclusion of type information in symbol name) is disable. You need to use it independent of whether you use C calling convention or stdcall calling convention.
In stdcall calling convention, the callee removes the parameters from the stack. To make that safe, the exported name contains the number of bytes that the callee will remove from the stack.
If the application you are exporting to requires that no #number suffix is added to the name, it probably means that it expects C calling convention. So you should stop declaring the function as __stdcall. When you the declare it as declspec(dllexport), you should get an undecorated name in the DLL.
In the DEF file, you can call the function whatever you want; no additional checking is performed.
dllexport/import are designed to be loaded back by themselves, not an old C library using GetProcAddress. The mangling you have seen is what all Microsoft compilers have done for a long time for __stdcall functions. Most likely, your target either expects a __cdecl function, not __stdcall, but if not, you will need to use a .def file to specifically un-mangle the name.

Is C++ name mangling (decoration) deterministic?

I hope to LoadLibrary on an unmanaged C++ DLL with managed code, and then call GetProcAddress on extern functions which have been mangled. My question is are the mangled names you get from a C++ compiler deterministic? That is: Will the name always by converted to the same mangled name, if the original's signature hasn't changed?
It isn't specified by the standard, and has certainly changed between versions of the same compiler in my experience, though it has to be deterministic over some fixed set of circumstances, because otherwise there would be no way to link two separately compiled modules.
If you're using GetProcAddress, it would be far cleaner to export the functions as extern "C" so their names are not mangled.
It's compiler specific, as others have said. However, you can find details in a document by Agner Fog...
http://www.agner.org/optimize/#manuals
See item 5 on that page.
Also, these days, there are libraries which can handle mangling and demangling for common compilers for you. For Visual C++, the starting point would be the dbghelp and imagehlp libraries.
http://msdn.microsoft.com/en-us/library/ms679292%28v=VS.85%29.aspx
http://msdn.microsoft.com/en-us/library/ms680321%28v=VS.85%29.aspx
Name mangeling is handled differently by every compiler (maybe or not-there is no standard). If you use pure C functions in your C++ code, you can use the extern "C" to supress name mangeling for the C functions so the compiler is able to find them.