Priority settings for static variables and __attribute__((destructor))

Hello all:

I am helping to debug a Mach-o dylib program written by C++ and there are some codes like this:

class Resource ; // global static variable

attribute((destructor))
void shutdown()
{
Resource->Check();
}

When dylib unloaded, the static variable Resource will be unloaded first then clang will call shutdown() with a crash. I tried GCC style attribute((destructor(100))) to set the priority but it seems that clang cannot recongnised this.

Is there anyway I can precisely constrol the order of static variables deconstruction and attributed destructor functions in clang. My environment is Mac OS X 10.7.5, Xcode 4.6 with clang-425.0.24 x86_64-aple-darwin11.4.2

Many thanks.

Huaxia

Hello

When dylib unloaded, the static variable Resource will be unloaded first
then clang will call shutdown() with a crash. I tried GCC style
__attribute__((destructor(100))) to set the priority but it seems that clang
cannot recongnised this.

It does recognize this, but on darwin constructor / destructor
priorities works only inside single module.

Is there anyway I can precisely constrol the order of static variables
deconstruction and attributed destructor functions in clang. My environment
is Mac OS X 10.7.5, Xcode 4.6 with clang-425.0.24 x86_64-aple-darwin11.4.2

If I remember correctly, on darwin the order of ctors / dtors is
induced by link order. Though, in general you cannot rely on this :slight_smile:

Well, this would be a weak point since Apple recommend
__attribute__((destructor)) as a module finalizer.

From:

https://developer.apple.com/library/mac/#documentation/macosx/Conceptual/BPFrameworks/Tasks/InitializingFrameworks.html#//apple_ref/doc/uid/20002259-BDEIDDJG

"Module initializers are the preferred way to initialize a framework. A
module initializer is a static function that takes no arguments and returns
no value. It is declared using the constructor compiler attribute as shown
in Listing 1. "

Does this mean that the module ctor/dtor are unable to safely use any
existing static variables?

Thanks.

Huaxia

Well, this would be a weak point since Apple recommend
__attribute__((destructor)) as a module finalizer.

And this is perfectly fine. As I said, 'constructor' and 'destructor'
attributes are recognized and work w/o any problems.

You cannot rely on priorities scattered across different modules.

Does this mean that the module ctor/dtor are unable to safely use any
existing static variables?

Static variables of which type? The example you mentioned seems to be
written in C. In C there are no constructors / destructors (in C++
sense), so you're fine here.

In C++ case you need to use init_priority attribute. And again, you
can rely on the order of constructor / destructor execution only
inside single module (on darwin).