toStringz lifetime

Ali Çehreli acehreli at yahoo.com
Mon Nov 9 01:58:02 UTC 2020


On 10/25/20 3:19 AM, rikki cattermole wrote:
> On 25/10/2020 11:03 PM, Ali Çehreli wrote:
>> Does the GC see that local variable 'name' that is on the C side? What 
>> I don't know is whether the GC is aware only of the stack frames of D 
>> functions or the entire thread, which would include the C caller's 
>> 'name'.
> 
> The thread stack frame that is registered with the D GC will know about 
> the D side and may know about the C side.
> 
> It depends on what the C side is doing.
> 
> If the C side went ahead and made a new stack frame via a fiber... it 
> won't know about it. But even if it did, the D stack frame is still 
> alive and pinning that bit of memory.
> 
> Ultimately, if the C side puts that pointer some place like a global or 
> send it to another thread, there are no guarantees that things will play 
> out well.

Sorry to bring this up again but I want to understand this fully before 
I say something wrong during my DConf presentation. :)

The D code is a library. The actual program is e.g. written in C. When 
the D library is loaded into the program, the following function is 
executed and the D GC is initialized:

pragma (crt_constructor)
extern(C) int initialize() {
   return rt_init();
}

Does the D GC know the complete function call stack of the C program all 
the way up from 'main'? Is there the concept of "bottom of the stack" or 
does the D GC can only know the value of the stack pointer at the time 
rt_init() was called. If the latter, then I think a toStringz string may 
not be alive in a C function.

Imagine the C program dlopens our library from inside a function called 
from main. Then the program calls one of our library functions from 
another function in main:

// C program
int main() {
   initializeDlibrary();  // This does dlopen()
   useDlibrary();    // This receives a string returned from
                     // toStringZ and uses that string.
}

So, the question is, does D GC only know initializeDlibrary's stack 
frame up because it was initialized there?

I know threads complicate matters and they need to be attached to the GC 
with core.thread.osthread.thread_attachThis but I am not there yet. :) I 
want to understand the basic single thread stack pointer issue first.

Thank you,
Ali



More information about the Digitalmars-d-learn mailing list