C++ execute function after constructors before main - c++

Question: is there a way to tell GCC to call a function before main() but after all constructors (including __attribute__ ((constructor)) and globally scoped static variables)?
Background: I have a shared library which needs to automatically provide some capability on loading and clean up after itself on exit. The "on loading" functionality is handled by defining a set of functions with __attribute__ ((constructor)). These constructor functions may interact with globally scoped static variables. Some of these constructor functions may further register atexit() handler to take care of the cleanup requirement. The catch is that my exit handler needs to access those static variables. Unfortunately, some of those static variables are declared an inner scopes (e.g. inside functions), which means that their destructors get called before the exit handler. This results in "use after free" type functionality.
The easiest way to demonstrate this problem is with the following code
#include <iostream>
class A
{
public:
A() { std::cout << "A ctor" << std::endl; }
~A() { std::cout << "A dtor" << std::endl; }
void doit() { std::cout << "Exit handler cleanup" << std::endl; }
};
static A a;
static void my_handler()
{
a.doit();
}
__attribute__ ((constructor)) void prepare_exit_handler(void)
{
printf("Foo constructor function\n");
atexit(my_handler);
}
int main()
{
std::cout << "Start of main" << std::endl;
exit(1);
}
When executed, this outputs
Foo constructor function
A ctor
Start of main
A dtor
Exit handler cleanup
The last line of the output shows that a.doit() is executed after a is destructed.
One possibility I considered was to use init_priroty attribute to force the atexit() call to happen after all static variables are instantiated, thus guaranteeing the exit handler will get executed before static variable destructors.
__attribute__ ((constructor)) __attribute__ ((init_priority (65535))) void prepare_exit_handler(void)
However, this causes a compile time error
error: can only use ‘init_priority’ attribute on file-scope definitions of objects of class type
UPDATE 1 - apparently the correct way to specify init priority for constructors is with __attribute__ ((constructor(65535))). However, even the last priority (highest legal number, 65535) appears to be before static constructors are called.
UPDATE 2 - I think I found the magic combination of attributes which works as desired. There is one downfall - it requires explicitly specifying init_priority on all of my static variables. Is there a way around that limitation?
#include <iostream>
class A
{
public:
A() { printf("A ctor\n"); }
~A() { printf("A dtor\n"); }
void doit() { std::cout << "Exit handler cleanup" << std::endl; }
};
static __attribute__ ((init_priority(1001))) A a;
static void my_handler()
{
a.doit();
}
__attribute__ ((constructor(65535))) void prepare_exit_handler(void)
{
printf("Registering atexit\n");
atexit(my_handler);
}
int main()
{
std::cout << "Start of main" << std::endl;
exit(1);
}
which produces
A ctor
Registering atexit
Start of main
Exit handler cleanup
A dtor

Related

Is a global boolean variable reliable during global destruction?

If I have a simple data type as a global variable -- like a boolean flag; specifically, something that doesn't have a destructor -- does that variable remain reliable even during global destruction? Or is that not guaranteed?
For example, would the result for the following code be well-defined?
Flag.h:
void SetFlagState(bool flag);
bool GetFlagState();
Flag.cpp:
#include <Flag.h>
namespace { // local declarations
bool g_flag;
}
void SetFlagState(bool flag)
{
g_flag = flag;
}
bool GetFlagState()
{
return g_flag;
}
Main:
#include <iostream>
#include <Flag.h>
class FlagChecker
{
public:
~FlagChecker()
{
std::cout << "Flag value: " << GetFlagState() << std::endl;
}
};
FlagChecker g_FlagChecker; // global instance; dtor will be called on exit
int main()
{
SetFlagState(true);
}
Yes, this is safe. The lifetime of the storage is the duration of the program. The chief issue during that lifetime is with the moment of initialization (via your g_Flagchecker). As there's no such thing "de-initialization" for built-in types, your g_flag remains valid as long as there's code executing in your process.

How to invoke a C++ function after main() finishes

I am developing a C++ tool that should run transparent to main program. That is: if user simply links the tool to his program the tool will be activated. For that I need to invoke two functions, function a(), before main() gets control and function b() after main() finishes.
I can easily do the first by declaring a global variable in my program and have it initialize by return code of a(). i.e
int v = a() ;
but I cannot find a way to call b() after main() finishes?
Does any one can think of a way to do this?
The tool runs on windows, but I'd rather not use any OS specific calls.
Thank you, George
Use RAII, with a and b called in constructor/destructor.
class MyObj {
MyObj()
{
a();
};
~MyObj()
{
b();
};
};
Then just have an instance of MyObj outside the scope of main()
MyObj obj;
main()
{
...
}
Some things to note.
This is bog-standard C++ and will work on any platform
You can use this without changing ANY existing source code, simply by having your instance of MyObj in a separate compilation unit.
While it will run before and after main(), any other objects constructed outside main will also run at this time. And you have little control of the order
of your object's construction/destruction, among those others.
SOLUTION IN C:
have a look at atexit:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
void bye(void)
{
printf("That was all, folks\n");
}
int main(void)
{
long a;
int i;
a = sysconf(_SC_ATEXIT_MAX);
printf("ATEXIT_MAX = %ld\n", a);
i = atexit(bye);
if (i != 0) {
fprintf(stderr, "cannot set exit function\n");
exit(EXIT_FAILURE);
}
exit(EXIT_SUCCESS);
}
http://linux.die.net/man/3/atexit
this still implies however that you have access to your main and you can add the atexit call. If you have no access to the main and you cannot add this function call I do not think there is any option.
EDIT:
SOLUTION IN C++:
as sudgested there is a c++ equivalent from std. I simply paste in here an example which i copied from the link available just below the code:
#include <iostream>
#include <cstdlib>
void atexit_handler_1()
{
std::cout << "at exit #1\n";
}
void atexit_handler_2()
{
std::cout << "at exit #2\n";
}
int main()
{
const int result_1 = std::atexit(atexit_handler_1);
const int result_2 = std::atexit(atexit_handler_2);
if ((result_1 != 0) or (result_2 != 0)) {
std::cerr << "Registration failed\n";
return EXIT_FAILURE;
}
std::cout << "returning from main\n";
return EXIT_SUCCESS;
}
http://en.cppreference.com/w/cpp/utility/program/atexit
Isn't any global variable constructed before main and destructed afterward? I made a test struct whose constructor is called before main and the destructor afterward.
#include <iostream>
struct Test
{
Test() { std::cout << "Before main..." << std::endl; }
~Test() { std::cout << "After main..." << std::endl; }
};
Test test;
int main()
{
std::cout << "Returning now..." << std::endl;
return 0;
}
If you're happy to stick with a single compiler and non-standard C/C++, then GCC's __attribute__((constructor)) and __attribute__((destructor)) might be of use:
#include <stdio.h>
void __attribute__((constructor)) ctor()
{
printf("Before main()\n");
}
void __attribute__((destructor)) dtor()
{
printf("After main()\n");
}
int main()
{
printf("main()\n");
return 0;
}
Result:
Before main()
main()
After main()
Alternatively to the destructor, you can use atexit() in a similar manner - in C++, you do not need to have access to main() to register atexit there. You can do that as well it in your a() - for example:
void b(void) {
std::cout << "Exiting.\n";
}
int a(void) {
std::cout << "Starting.\n";
atexit(b);
return 0;
}
// global in your module
int i = a();
That being said, I'd also prefer the global C++ class object, which will call the b() stuff in its destructor.

How to catch an error resulting from an invalid memory block being destroyed

The following code makes it so that a destructor is called twice.
#include <iostream>
#include <memory>
#include <exception>
#include <cstdlib>
void myterminate()
{
std::cout << "terminate\n";
abort();
}
class data
{
int a;
public:
data(int a) : a(a) { std::cout << "ctor " << a << "\n"; }
~data() { std::cout << "dtor " << a << "\n"; }
static data failure(int a) { return data(a); }
};
void main()
{
std::set_terminate(myterminate); //terminate is not called
try
{
std::unique_ptr<data> u;
u.reset(&data::failure(1));
std::cout << "no worries\n"; //this prints
//destructor called at try-block end and attempt to destruct an invalid memory block.
}
catch (...)
{
std::cout << "caught\n"; //this can not catch the error
}
std::cout << "end\n"; //program crash, will not be called
}
How would I catch an error like this in production?
On a Release build the program crashes. On a Debug build it the on my system is:
How would I catch an error like this in production?
You cannot. The standard says that invalid memory access has undefined behaviour. There is no standard way to "catch" UB. Catching and terminate handler are for exceptions, which are defined behaviour.
What you could do, is use the debug build in production, and run it with valgrind or similar tool, so that you can at least analyze the error.
"try/catch" such mistakes will not catch, because in this case a great probability of a crash. But a moment of destruction you can try to catch, using signals and more menne dignified exit the program.
Looking away: #include , signal(), sig_atomic_t ...
First as noted in the comments you declare main as void main where the standard only allows two forms in § 3.6.1
An implementation shall not predefine the main function. This function
shall not be overloaded. It shall have a declared return type of type
int, but otherwise its type is implementation-defined. An
implementation shall allow both
(2.1) — a function of () returning int and
(2.2) — a function of (int, pointer to pointer to char) returning int
Secondly you are resetting your unique_ptr to manage a temporary which when unique_ptr gets destroyed at the end of its scope will be deleted which results in undefined behavior. You can't predict/catch errors resulting from undefined behavior.
What you should do (if you really want to use dynamically allocated memory) you can return a pointer to object on the heap:
#include <iostream>
#include <memory>
#include <exception>
#include <cstdlib>
void myterminate()
{
std::cout << "terminate\n";
abort();
}
class data
{
int a;
public:
data(int a) : a(a) { std::cout << "ctor " << a << "\n"; }
~data() { std::cout << "dtor " << a << "\n"; }
static data* failure(int a) { return new data(a); }
};
int main()
{
std::set_terminate(myterminate); //terminate is not called
try
{
std::unique_ptr<data> u;
u.reset(data::failure(1));
std::cout << "no worries\n"; //this prints
//destructor called at try-block end and attempt to destruct an invalid memory block.
}
catch (...)
{
std::cout << "caught\n"; //this can not catch the error
}
std::cout << "end\n"; //program crash, will not be called
}
Online code: http://melpon.org/wandbox/permlink/pdiijgDxBshVOYRu

C++ Static members of a class are initialized after constructor

I have a problem with static members of a class not being initialized before the constructor. Am i doing something wrong? Is it a bug in G++ ?
Any workarounds?
g++ --version : (Ubuntu 4.8.4-2ubuntu1~14.04) 4.8.4
I am also using Eclipse as my IDE, but i just copy the static lib headers to /usr/include/StaticTestLib/InitTest.h and the library to /usr/lib/x86_64-linux-gnu/libStaticTestLib.a
Note this only happens if the object that holds the data is defined before main and the class is in a Static Library.
Static library header (the static library itself is named StaticTestLib):
InitTest.h
#include <iostream>
namespace StaticTestLib {
class notifier_header{
public:
notifier_header(){
std::cout<<"static var init"<<std::endl;
}
};
class InitTest {
public:
static notifier_header _header_notifier;
InitTest();
virtual ~InitTest();
};
}
Static library source file:
InitTest.cpp
#include "InitTest.h"
namespace StaticTestLib {
notifier_header InitTest::_header_notifier;
class notifier_cpp{
public:
notifier_cpp(){
std::cout<<"code before constructor"<<std::endl;
}
}_notifier_in_cpp;
InitTest::InitTest() {
std::cout<<"constructor"<<std::endl;
}
InitTest::~InitTest() {
std::cout<<"destructor"<<std::endl;
}
}
This program:
StaticTest.cpp
#include <iostream>
#include <StaticTestLib/InitTest.h>
StaticTestLib::InitTest test;
int main() {
std::cout << "program main" << std::endl;
std::cout << "program end" << std::endl;
return 0;
}
… outputs:
constructor
static var init
code before constructor
program main
program end
destructor
But this program:
#include <iostream>
#include <StaticTestLib/InitTest.h>
int main() {
std::cout << "program main" << std::endl;
StaticTestLib::InitTest test;
std::cout << "program end" << std::endl;
return 0;
}
… outputs:
static var init
code before constructor
program main
contructor
program end
destructor
My guess is that this is related to the order of static objects initialisation in different compilation units being undefined.
The second code snippet where you create a test object in your main is easy to explain. Static initialisation will always happen before any code is executed, so by the time you enter main, your notifier_header object is definitely created.
Now, when you create your test before main, you have two static objects. notifier_header object does not depend on your InitTest: it is scoped within that class, but it is stored in static memory. You seem to reference the notifier_header in your InitTest.cpp, which is a different compilation unit to main. A compiler is free to do static allocations in any order for those two units, provided that there is no interdependencies.
If your constructor depended on notifier_header, you could use it as a singleton. Create a function that returns an instance of a static object (headerInstance in the example below), and upon its call, the object will be created:
#include <iostream>
namespace StaticTestLib {
class notifier_header{
public:
notifier_header(){
std::cout<<"static var init"<<std::endl;
}
};
class InitTest {
public:
InitTest();
virtual ~InitTest();
notifier_header& headerInstance();
};
}
Static library source file (InitTest.cpp)
#include "InitTest.h"
namespace StaticTestLib {
class notifier_cpp{
public:
notifier_cpp(){
std::cout<<"code before constructor"<<std::endl;
}
}_notifier_in_cpp;
InitTest::InitTest() {
headerInstance();
std::cout<<"constructor"<<std::endl;
}
InitTest::~InitTest() {
std::cout<<"destructor"<<std::endl;
}
notifier_header& InitTest::headerInstance() {
static notifier_header _header_notifier; // will only be constructed once
return _header_notifier;
}
}
The output I get:
static var init
constructor
code before constructor
program main
program end
destructor

C++ Initialization of static function pointer array

I want to create a static function pointer array, so I can jump to a certain function regarding a received index. Like an index jumper.
So imagine a class like this:
Class A
{
private:
static void 1stFunction();
static void 2ndFunction();
static void(*functionPointer[20])(void);
};
Then I would like that functionPointer to get the value of the 1stFunction and 2ndFunction, and maybe even more.
So, how do I initialize it?
As far as I know, when a static member is declared, you can use it even before an instance is created. So I though, lets initialize that function pointer, so later I can call it like this
functionPointer[receivedIndex]();
So i tried to initilize it like this, in the same .h file
void (*A::functionPointer[])(void) =
{
A::1stFunction,
A::2ndFunction,
};
But the compiler gives me redifinition, it says it's already created.
So, pretty sure I'm missing something. I don't know though, if it is syntax or simply it is not possible to do it this way.
I know that function pointers to class's member functions are different than normal function pointers... But this is a static function, so I believe it doesn't belong to an instance and therefore it should work with normal function pointers.
Any help would be appreciated.
Thanks
The following would be a working example that probably achieves what you need.
You need C++11 for the initializer list.
It is a good practice to initialize the static member in the cpp file, as you don't want to have a definition of the static member everytime the header is included (this can lead to linking issues).
You can call callf with the desired index and have the corresponding function called, based on the initialization of the function pointer array.
The output of the program would be:
I am 2ndFunction
Header file
class A
{
private:
static void Function1();
static void Function2();
static void(*functionPointer[20])();
public:
static void callf(int index);
};
Implementation
#include <iostream>
#include "ex.h"
void(*A::functionPointer[20])() {
A::Function1,
A::Function2
};
void A::Function1() {
std::cout << "I am 1stFunction" << std::endl;
}
void A::Function2() {
std::cout << "I am 2ndFunction" << std::endl;
}
void A::callf(int index) {
A::functionPointer[index]();
}
int main(int argc, char const *argv[]) {
A::callf(1);
return 0;
}
Here you have a more modern C++ approach (C++14 needed)
I would advise you to explore lambda functions if you are not restricted to C++03.
#include <iostream>
#include <functional>
#include <vector>
class A {
public:
using f_type = std::function<void(void)>;
f_type f1 = []() { std::cout << "f0" << std::endl;};
f_type f2 = []() { std::cout << "f1" << std::endl;};
static void f3() { std::cout << "f3" << std::endl; }
std::vector<f_type> functions{f1, f2, f3};
};
int main() {
A a;
a.functions[0]();
a.functions[1]();
//adding custom lambda
a.functions.emplace_back([](){ std::cout << "custom f" << std::endl;});
a.functions[2]();
return 0;
}
you can add both functions and lambdas to your container.