www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.bugs - [Issue 22331] New: spec is incorrect regarding interfacing C with GC


          Issue ID: 22331
           Summary: spec is incorrect regarding interfacing C with GC and
                    local variables
           Product: D
           Version: D2
          Hardware: All
               URL: https://dlang.org/spec/interfaceToC.html#storage_alloc
                OS: All
            Status: NEW
          Keywords: spec
          Severity: normal
          Priority: P1
         Component: dlang.org
          Assignee: nobody puremagic.com
          Reporter: schveiguy gmail.com

For reference:

https://forum.dlang.org/post/xchnfzvpmxgytqprbosz forum.dlang.org
https://forum.dlang.org/post/siajpj$3p2$1 digitalmars.com

When a local variable is kept in a temporary register, the GC will not see it
after that register is used for something else. This means the object can be

This becomes a problem when you store the pointer outside the GC's view. The
spec currently lists the following as a remedy for such a thing:

 Leaving a pointer to it on the stack (as a parameter or automatic variable),
as the garbage collector will scan the stack.
Typically, one leaves it on the stack by declaring an automatic variable, and assigning it to that pointer. However, if the compiler notices that the variable isn't used later on, it will not actually put even local variables on the stack. This results in the object sometimes being collected seemingly when the local variable is still in scope and should be referencing the block. The spec should be changed to remove this possible remedy, or the remedy should be clarified to outline how exactly to ensure that a variable gets put on the stack. Advanced optimizers are working against this goal by trying to avoid writing registers to memory if it can avoid doing so. This may require changes to the compiler and/or library to provide a good way to ensure the stack is storing the data. If none of that is possible, the remedy should be removed. Other languages that rely on a GC have a mechanism that does this exact operation: https://docs.microsoft.com/en-us/dotnet/api/system.gc.keepalive?view=net-5.0 Go: `runtime.KeepAlive`: https://pkg.go.dev/runtime#KeepAlive In both those examples, the function itself does nothing, it is just an intrinsic to the compiler to note that the lifetime of the object should last until at least that line. --
Sep 22 2021