www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.bugs - [Issue 1957] New: 'new' may return same memory to two threads

reply d-bugmail puremagic.com writes:

           Summary: 'new' may return same memory to two threads
           Product: D
           Version: 1.028
          Platform: PC
        OS/Version: All
            Status: NEW
          Severity: normal
          Priority: P2
         Component: Phobos
        AssignedTo: bugzilla digitalmars.com
        ReportedBy: fvbommel wxs.nl

As I posted at
Hmm, reading the relevant parts of the GC code just now, something occurred to
me. Some background first:
If allocation triggers an actual collection it checks thread_needLock() again,
and locks for the duration of the collection if there's only one thread. The
comment explains this is done because finalizers may start new threads.

However, the lock is then released *before* using the newly-collected heap to
perform the actual allocation. That makes me wonder what happens if the first
thing such a new thread does is allocating some memory...

In other words:
1) The only thread starts an allocation, determining the lock is not needed.
2) There's no space to allocate, and the GC prepares for a collection.
3) The GC notices the number of threads is 1, and acquires the lock, and starts
performing the collection.
4) A finalizer starts a new thread, which attempts to allocate and blocks on
the GC lock held by the collector.
5) The original thread finishes the collection and *releases the lock*.
6) It then determines what memory location to return from 'new'.
7) Thread switch, the second thread acquires the GC lock (which is no longer
held by the first thread) and starts its own allocation activities. Since the
original thread didn't yet mark its chosen memory as allocated, the second
thread picks the same memory and marks it as allocated.
8) Thread switch, the first thread finishes its allocation by marking the
memory as allocated. (even though it already was marked by the second thread)
9) Both threads start using the same piece of memory as if they have the only
reference to it (which should be true from either perspective, since it was
just returned from 'new').
10) *KABOOM*

It'll probably be hard to force this bug to actually manifest itself[1], given
that there's probably only a window of a few opcodes for the thread switch in
step (7) above to occur and cause the symptom described.

[1]: Well, short of modifying the GC to force a thread switch between (6) and

Mar 28 2008
parent d-bugmail puremagic.com writes:

Martin Nowak <code dawg.eu> changed:

           What    |Removed                     |Added
                 CC|                            |code dawg.eu

--- Comment #1 from Martin Nowak <code dawg.eu> 2013-11-01 00:02:46 PDT ---
Is this still relevant?

Configure issuemail: http://d.puremagic.com/issues/userprefs.cgi?tab=email
------- You are receiving this mail because: -------
Nov 01 2013