Delay the construction of a static member object - c++

The project is compiled into a dll to be injected into an executable
The project relies on an API which is initialized at the very beginning in main() like so:
int DLL_main()
{
TheApi::Initialize();
AnObject anObjectInstance;
//..
}
There is an object that is constructed with a class definition similar to this:
class AnObject()
{
AnObject();
~AnObject();
static ApiHelper apiHelperObject; //This object assists in making certain api features easier to use
}
//Inside AnObject.cpp
ApiHelper AnObject::apiHelperObject;
In the constructor of apiHelperObject, there are some API function calls
Upon injection of the dll, nothing happens (no error message as well) however,
when the static keyword is removed from apiHelperObject all works fine
The issue seems to be that the static member is being constructed before the API is initialized
It is not possible to call TheApi::Initialize() in apiHelperObject's constructor because there are multiple different api helper objects, and that would cause TheApi::Initialize() to be called more than once
And so the question is:
What is the best way of initializing the api before the static member object is constructed? Or, what is the best way to delay the construction of the static member?
Preferably, a pointer is not used as the syntax is not especially favored
Thank you

In ordinary standard C++ you can always delay the initialization of a static object by making it local to an accessor function.
Essentially that's a Meyers' singleton:
auto helper_object()
-> ApiHelper&
{
static ApiHelper the_object;
return the_object;
}
Here, in standard C++, the object is initialized the first time execution passes through the declaration.
But the C++ standard does not actively support dynamic libraries, much less DLL injection. So it's difficult to say how this is going to play out. Beware of threading issues.

Related

Purpose of class ExplicitInit in objc runtime source code

I'm studying class ExplicitInit in objc runtime source code. I know that class ExplicitInit is used in static objc::ExplicitInit<StripedMap<SideTable>> SideTablesMap;. But why ExplicitInit is necessary? StripedMap is good enough to store SideTable.
I think the comments for class ExplicitInit in DenseMapExtras.h is the key to understand why ExplicitInit is necessary. But I can't understand the comments because of my poor C++ knowledge.
the comments show below:
// We cannot use a C++ static initializer to initialize certain globals because
// libc calls us before our C++ initializers run. We also don't want a global
// pointer to some globals because of the extra indirection.
//
// ExplicitInit / LazyInit wrap doing it the hard way.
there are three sentences in comments above, but I can't understand them all. Can anybody help me explain them?
And don't forget the first question: why ExplicitInit is necessary? 😀😂
We cannot use a C++ static initializer to initialize certain globals because libc calls us before our C++ initializers run.
There is some deep dyld and Mach-O voodoo that I don't understand when it comes to the Objective-C runtime! This was a fun question to try dig into.
The function _objc_init() (in objc-os.mm) performs:
Bootstrap initialization. Registers our image notifier with dyld.
Called by libSystem BEFORE library initialization time
_objc_init() calls runtime_init(), a portion of which is objc::allocatedClasses.init();. allocatedClasses is declared as static ExplicitInitDenseSet<Class> allocatedClasses; in objc-runtime-new.mm.
So it appears libSystem calls _objc_init() which in turns calls runtime_init() which in turn uses a C++ static variable that hasn't yet been constructed because the library itself hasn't been initialized, hence the need for ExplicitInit.
We also don't want a global pointer to some globals because of the extra indirection.
I don't know why this design wasn't chosen. Perhaps for cache locality?
ExplicitInit / LazyInit wrap doing it the hard way.
The init() methods in these classes use placement new to explicitly initialize the underlying type into the space reserved for it in _storage. This would normally happen automatically during static initialization if the type was instantiated directly. In this case space is reserved for the underlying object so it may be explicitly initialized by calling init() which constructs the object.

How can I call a function or statically initialize an object immediately before main?

In short, I would like a particular piece of static initialization to occur as close to the beginning of main()/DllMain() as possible. It would probably be acceptable for this to be a constructor called last during static initialization.
Since this will almost certainly be a compiler-specific implementation, I'm specifically looking to do this using the visual C++ compiler (VS 2010 and beyond). In the future I will probably need to do this in GCC and Clang, but that's not an immediate concern.
The long story is I have a object in a base library that is statically initialized and creates a thread in its constructor. This thread relies on other statically initialized objects in libraries that we don't control so it causes a race condition in static initialization. If I can pause or avoid creating the thread until all other static initialization is complete this should fix the problem (a simple Sleep(5000) avoids the issue, though that's not exactly a robust solution).
I could explicitly call an initialize function in our main() function, however this isn't ideal as we have 20+ binaries that use this library so every programmer would have to remember to run the initialization in every binary. I would prefer to push this responsibility to the compiler if possible.
The comment of Refugnic Eternium above is correct, and offers one solution.
The best solution is to have a function like this:
BOOL InitMyLib();
All functions in MyLib.dll, and all constructors, should fail until this has been called. That way you can ensure that programmers don't forget to call it.
Create an initializer class and then declare a static instance of it:
class MyInitializer
{
public:
MyInitializer ()
{
doInitStuffHere();
}
};
static MyInitializer myInit;
You can control when the static variable is initialized by using #pragma init_seg. For example, #pragma init_seg(lib).
Use #pragma init_seg to Control Static Construction (KB104248)

Call a function before static member allocation

I am using a 3rd party API that overrides the memory management functions found in the C Runtime libraries. In order for everything to work properly, I must make a call to initialize the API before any memory allocations take place.
The project I am working on uses a static Factory object that is dynamically initialized before any of the code in the main file is executed.
How can I ensure that the API will be initialized before the static Factory object?
The C++ standard library runs into the same problem: it has to ensure that cin, cout, etc. are initialized before any code, including constructors for static objects, uses them. The trick that was invented for handling this situation can also solve yours. In a header file that gets included first in every translation unit (well, every translation unit that has static objects with dynamic initializers):
class init_library {
public:
init_library() { if (counter++ == 0) initilaize_the_library(); }
private:
static int counter;
};
static init_library i_library;
and in one translation unit you have to provide a definition of init_library::counter.
This will put a static object of type init_library in every translation unit that pulls in the header. Its initialization will happen before any other initialization in that same translation unit (because its #include directive came first -- don't forget that!), and the first time that one of these objects gets initialized, it will call the code to initialize the library. (Note that this code is not thread-safe; making it thread-safe is straightforward)
This is known as the "nifty counter trick".
You should move your static factory objects initilization to a static function and call that function after initializing 3rd party lib as a first thing in main.

Calling QPluginLoader::staticInstances from the constructor of a class instantiated as a static local crashes

I have a singleton class for the purpose of loading Qt plugins instantiated as a static local:
LibraryManager* LibraryManager::instance()
{
static LibraryManager manager;
return &manager;
}
I'm getting "__cxa_guard_acquire(): initializer for function local static variable called enclosing function" in the console whenever QPluginLoader::staticInstances() is hit in the constructor of LibraryManager. What does this mean exactly, and how can I fix this?
According to this source, you have somehow managed to recurse back to the same function local in the same thread. Isn't your library manager a plugin itself, by chance? :)
I don't know what it means, but my gut feeling is that an oldschool singleton could fix it. That is having a pointer to instance as class member initialized to null and do a lazy check in instance() call. I understand that it requires implementing a static release method and finding a proper place to call it. But it would bypass the function local, which is what your error message complains about.
This was just a brain error.
My plugin class was inheriting from the class actually used by library clients (which calls into manager, which instantiates plugins, whose constructors call manager... you can see where that leads), when it should have inherited from a different class that only calls manager from member functions (not its constructor).
tl;dr I typed the wrong class name, but didn't think I did so I dismissed that part of the code as possibly containing the issue.

Static initialization in C++

Hi, all!
I'm developing winForm app on visual C++ (managed code).
This app link native static library which contain block of code with static variable initialization:
Cls.h
class Cls
{
public:
static Cls* getInstance();
private:
static Cls _instance;
protected:
Cls(void);
};
Cls.cpp
#include "StdAfx.h"
#include "Cls.h"
Cls::Cls(void)
{
}
Cls Cls::_instance;
Cls* Cls::getInstance()
{
return &_instance;
}
I can link those library successfully, but when I try to use getInstance() method I get a run-time error before invoke main function of my app.
It's a third party library, so I cannot rebuild it or redefine Cls class on any other way.
App project uses /clr, entry point defined as main.
I tired to search a solution. I found that I must change entry point, but I don't know what value would be correct.
Please, help!
You're encountering the notorious "static initialisation order fiasco". When static objects are defined in two translation units, it's unspecified which is initialised first; so, if the constructor of one refers to the other, you could end up accessing it before it is initialised. The only guarantee is that they will all be initialised before main begins.
The best solution is to avoid static objects. In particular, the Singleton anti-pattern that you are using is rather tricky to get right in C++, and is generally more trouble than it's worth.
If you really want to do this, then you can work around the fiasco by defining the static object inside a function:
Cls* Cls::getInstance()
{
static Cls _instance;
return &_instance;
}
This has the disadvantage that it introduces a "destruction order fiasco" (where it might not be safe to access from the destructor of another static object), and that it might not be thread-safe in some compilers (although it should be in any that claims C++11 compliance). If construction is thread-safe, then there will be a (small) runtime cost for each access, which might be a problem if you have extreme performance issues.
UPDATE: I've just noticed that you say that this evil class is outside your control and can't be changed. In that case, your options are:
Get rid of this library and use something less insane, or
Be careful not to access any of its static data until main has begun; in particular, follow my advice above and avoid any static objects of your own.