<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html lang="en-us">
<HEAD>
<meta http-equiv="Content-Type" content="text/html;charset=US-ASCII" >
<TITLE>N2481: Minimal Support for Garbage Collection and Reachability-Based Leak Detection</title>
<BODY>
<table summary="This table provides identifying information for this document.">
	<tr>
		<th>Doc. No.:</th>
		<td>WG21/N2481<br>
		J16/07-351</td>
	</tr>
	<tr>
		<th>Date:</th>
		<td>2007-12-09</td>
	</tr>
	<tr>
		<th>Reply to:</th>
		<td>Hans-J. Boehm</td>
		<td>Mike Spertus</td>
	</tr>
	<tr>
		<th>Phone:</th>
		<td>+1-650-857-3406</td>
		<td></td>
	</tr>
	<tr>
		<th>Email:</th>
		<td><a href="mailto:Hans.Boehm@hp.com">Hans.Boehm@hp.com</a></td>
		<td><a href="mailto:mike_spertus@symantec.com">mike_spertus@symantec.com</a></td>
	</tr>
</table>
<H1>N2481: Minimal Support for Garbage Collection and Reachability-Based Leak Detection</h1>
This is a proposal to implement the "Kona garbage
collection compromise", i.e. motion SP1 in
<A HREF="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2452.html">
N2452</a> and
<A HREF="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2453.html">
N2453</a>.
It borrows a few small pieces from the preceding garbage collection
proposals, e.g.
<A HREF="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2310.pdf">
N2310</a>.
<P>
Its purpose is to support both garbage collected implementations and
reachability-based leak detectors.  This is done by giving undefined
behavior to programs that "hide a pointer"
by, for example, xor-ing it with another value, and then later turn it
back into an ordinary pointer and dereference it.  Such programs
may currently produce incorrect results with conservative garbage collectors,
since an object referenced only by such a "hidden pointer"
may be prematurely collected.  For the same reason, reachability-based
leak detectors may erroneously report that such programs leak
memory.
<P>
Note that for programs using the <TT>quick_exit()</tt>
facility
(<A HREF="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2440.htm">
N2440</a>, voted into the working paper at the Kona meeting),
reachability-based leak detectors are arguably the only viable form
of leak detection.
<P>
For a more general discussion,
and the reasons to support transparent garbage collection, please see
<A HREF="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2310.pdf">
N2310</a>.
<H2>Core Language Wording</h2>
Add something along these lines, possibly as 3.7.3.3:
<BLOCKQUOTE class=inserted>
3.7.3.3 Safely derived Pointers
<P>
[Note: Objects allocated by allocation functions must be properly referenced
through chains of pointers until they are dereferenced or deallocated.
The following makes this requirement precise.
This allows, but does not require, implementations to reclaim unreferenced
objects. -- end note.]
<P>
A <EM>traceable pointer location</em> is one of the following:
<UL>
<LI> An object of pointer type.
<LI> An object of an integral type at least as large as <TT>intptr_t</tt>
<LI> A sequence of characters in an array of characters, whose size
and alignment matches that of a pointer type.
</ul>
<P>
A pointer value contained in a traceable pointer location is a
<EM>reconstituted pointer</em> if it was computed by:
<UL>
<LI>Copying from other than a traceable
pointer location,
<LI>Performing arithmetic or bit-wise operations on integer arguments,
<LI>Copying a reconstituted pointer,
<LI>Arithmetic operations on a reconstituted pointer,
<LI>Taking the address of an object obtained
by dereferencing a reconstituted pointer, or
<LI>Reading it from a file.
</ul>
A pointer value that is not a reconstituted pointer is called
a <EM>safely derived</em> pointer.
<P>
[Note: Whether or not a pointer value is safely derived is a property
of how it was computed, and usually not of its actual representation.
In particular, two pointers may be equal, and one of them may be
safely derived, while the other is reconstituted. --end note]
<P>
A pointer to storage obtained from an allocation function
shall be dereferenced or passed to a deallocation function
only if it was either safely derived,
or the referenced object
was previously <EM>declared reachable</em>
(see [library:declare_reachable]).
</blockquote>
<H3>Observations and issues:</h3>
<OL>
<LI> I'm sure this is nowhere near standardese.
<LI> This is really an inductive definition on the chain of operations used to
compute a pointer value.
<LI> It is unclear where we should allow pointers to be stored.  We tentatively
went with a fairly lax interpretation of what the current standard allows.
We do need to allow copies in char arrays, and pointers in intptr_t
variables.  Whether we should allow them in other sufficiently large integer
variables is up to debate.
<LI> Although this is very similar in spirit to N2310, The N2310 rules based
on reachability had a fundamental problem, which is corrected here.  Consider
<PRE>
T *p = new ...;
intptr_t x = reinterpret_cast&lt;intptr_t&gt;(p) ^ 0x555;
a:
T *q = reinterpret_cast&lt;T *&gt;(x ^ 0x555);
T y = *q;
</pre>
The newly allocated object <EM>N</em> referenced by <TT>p</tt> is always reachable by
the N2310 definition.  But at the label <TT>a</tt>, <TT>p</tt>
is dead, and is quite likely to no longer be visible to the garbage collector,
since the register containing <TT>p</tt> may well have been reused, possibly
to hold <TT>x</tt>.  This means that if a garbage collection occurs at point
<TT>a</tt>, <EM>N</em> may not appear to be reachable, and thus may be collected
anyway.
<LI> We could probably get closer to the N2310 definitions
if we allowed reconstituted pointers to be dereferenced if a
safely derived pointer to the same object is stored in a non-stack
location.  That seems worth considering.  It would technically
eliminate the need for <TT>declare_reachable()</tt>, since it
could be implemented by the user.  It would outlaw some kinds
of dead global dead variable and dead field elimination in
garbage-collected implementations.
These are probably rarely practical for C++ in any case.
<LI> Similar issues apply to <TT>declare_reachable</tt> calls.
The only safe way to ensure that a pointer is always visible to the
collector is to require that the argument to <TT>declare_reachable</tt>
was safely derived.  Thus a pointer to the object is guaranteed to
be visible before the call, and the collector treats the object
as being reachable after the call. 

</ol>


<H2>Library Wording</h2>
Add somewhere near the introduction:
<BLOCKQUOTE class=inserted>
Objects constructed by the standard library
that may hold a user-supplied pointer value, or an integer
of type intptr_t, shall store them in a traceable pointer
location (see 3.7.3.3).  [Note:
Other libraries are strongly encouraged to do the same, since not doing so
may result in accidental use of reconstituted pointers.  Libraries
that store pointers outside the user's address space should make it
appear that they are stored and retrieved from a traceable pointer
location. --end note]
</blockquote>
<P>
Add, possibly between 20.6.7 and 20.6.8:
<BLOCKQUOTE class=inserted>
<P>
<pre><samp>
void declare_reachable( void* <var>p</var> ) throw(std::bad_alloc)
</samp></pre>
<dl>
<dt><i>Effects:</i>
</dt><dd>
The argument
is subsequently declared reachable (see 3.7.3.3).
Reconstituted pointers to the same object may be dereferenced while
the object is declared reachable.
</dd>
<dt><i>Throws:</i>
</dt><dd>
May throw <samp>std::bad_alloc</samp> if the system cannot
allocate additional memory
that may be required to track objects declared reachable.
</dd>
<dt><i>Requires:</i>
</dt><dd>
The argument <samp><var>p</var></samp> shall be a safely derived
non-null pointer.
</dd>
</dl>

<P>
<pre><samp>
template < typename T >
T* undeclare_reachable( T* <var>p</var> ) throw()
</samp></pre>
<dl>
<dt><i>Returns:</i>
</dt><dd>
A safely derived copy of <samp><var>p</var></samp>.  The result will
compare equal to <samp>p</samp>.
</dd>
<dt><i>Effects:</i>
</dt><dd>
Once the number of calls to
<samp>undeclare_reachable(<var>p</var>)</samp> equals
the number of calls to <samp>undeclare_reachable(<var>p</var>)</samp>,
the argument is no longer declared reachable (see [above section]).
When this happens,
reconstituted pointers to the object referenced by <samp><var>p</var></samp>
may not be subsequently dereferenced.  [Note: Since the returned pointer
is safely derived, it may be used to access the referenced object, even
if previously no safely derived pointer existed. -- end note]
</dd>
<dt><i>Requires:</i>
</dt><dd>
The object referenced by <samp><var>p</var></samp> shall have been
previously declared reachable,
and shall be live from the time of the call until the last
<samp>undeclare_reachable(<var>p</var>)</samp> call on the
object.
</dd>
</dl>
<P>
[Note: It is expected that calls to
<samp>declare_reachable(<var>p</var>)</samp> will consume
a small amount of memory until the matching call to
<samp>undeclare_reachable(<var>p</var>)</samp> is encountered.
In addition, the referenced object cannot be deallocated
during this period, and garbage collecting implementations will not be
able to collect the object while it is declared reachable.
Long running programs should arrange that calls are matched. -- end note.]
<P>
<pre><samp>
void declare_no_pointers( char* <var>p</var>, size_t n ) throw()
</samp></pre>
<dl>
<dt><i>Effects:</i>
</dt><dd>
The <samp><var>n</var></samp> bytes starting at <samp><var>p</var></samp>
no longer contain traceable pointer locations, independent of their type.
Hence pointers located there may no longer be dereferenced.  [Note:
This may be used to inform a garbage collector or leak detector that
this region of memory need not be traced.]
</dd>
<dt><i>Throws:</i>
</dt><dd>
Throws no exceptions.  [Note: Under some conditions implementations may need to
allocate memory.  However the request can be ignored if memory allocation fails.
-- end note]
</dd>
<dt><i>Requires:</i>
</dt><dd>
No bytes in the specified range may have been previously registered
with <samp>declare_no_pointers()</samp>.  If the specified range
is in an allocated object, then it must be entirely within a
single allocated object.  The object must be live until the
corresponding <samp>undeclare_no_pointers()</samp> call.
[Note: In a garbage-collecting implementation, the fact that
a region in an object is registered with <samp>declare_no_pointers()</samp>
should not prevent the object from being collected. --end note]
</dd>
</dl>
<P>
<pre><samp>
void undeclare_no_pointers( char* <var>p</var>, size_t n ) throw()
</samp></pre>
<dl>
<dt><i>Effects:</i>
</dt><dd>
Prepares an object containing a range registered with
<samp>declare_no_pointers()</samp> for destruction.  It must be called
before the lifetime of the object ends.  It has no other effect.
It does not recreate any traceable pointer locations in the object.
</dd>
<dt><i>Requires:</i>
</dt><dd>
The same range must previously have been passed
to <samp>declare_no_pointers()</samp>.
</dd>
</dl>
</blockquote>
<P>
Add to 20.6.8, between paragraphs 4 and 5:
<BLOCKQUOTE class=inserted>
Storage allocated directly with <samp>malloc()</samp>, <samp>calloc()</samp>, or
<samp>realloc()</samp> is implicitly declared reachable (see 3.7.3.3)
on allocation, ceases to be declared reachable on deallocation, and may
not cease to be declared reachable as the result of an
<samp>undeclare_reachable()</samp> call.
[Note: This allows existing C libraries to remain unaffected by restrictions
on reconstituted pointers, at the expense of providing far fewer garbage
collection and leak detection options for <samp>malloc()</samp>-allocated
objects.  It also allows <samp>malloc()</samp> to be implemented with a separate
allocation arena, bypassing the normal <samp>declare_reachable()</samp>
implementation.  The above functions should never intentionally be used as a
replacement for <samp>declare_reachable()</samp>, and newly written code
is strongly encouraged to treat memory allocated with these functions as
though it were allocated with <samp>operator new</samp>.  --end note]
</blockquote>

<H3>Observations and issues:</h3>
<OL>
<LI> Currently <TT>undeclare_reachable</tt> is a template, while
<TT>declare_reachable</tt> operates on a <TT>void *</tt>.  This is
intentional, since only the former returns a pointer.  Having the
latter return a pointer is far less useful, and doesn't quite
fit the name, though it may still be the right option.
<LI> It is unclear whether null pointers, and pointers to memory not
allocated with one of the system memory allocators should be allowed.
Disallowing the former seems benign, and simplifies matters a bit in
this formulation.  Disallowing the latter causes problems for clients
who don't know where the memory came from.
<LI> By a similar argument,there are reasons to believe that
<TT>declare_reachable</tt> and <TT>undeclare_reachable</tt> should
nest properly.  A client that is passed one and wants to put it
on an xor-ed list may not know whether the caller has already
done so.  In this formulation, it's safe to do so again.
The implementation would presumably just maintain a 
<LI> It is almost certainly safe to dereference a reconstituted pointer
if the object will be correctly declared reachable later.  This is
probably too confusing and useless to guarantee.
<LI> There is some argument that <TT>declare_reachable</tt> /
<TT>undeclare_reachable</tt> should be replaced by an RAII mechanism.
But the simple version would fail to cover many use cases,
e.g. an object declared reachable while a pointer to it
resides in an xor-list container.
This is designed to be a minimalist proposal, so we leave the RAII
version to the programmer for now.
<LI> The current <TT>no_pointers</tt> is consistent with the
usual STL conventions.  But we probably want to preserve the
possibility of invoking this on a single integer field that
is not part of an array.  And there is probably not a standard-conforming
way to compute the "one past the end" pointer for that case.
<LI> Ideally <TT>declare_no_pointers</tt> should be invocable even
on parts of stack allocated variables.  That does complicate the
implementation.  Even initially, a garbage-collected implementation will
have to recognize this case, even if just to ignore it.  We concluded that,
since a garbage collector will need to know about stack locations anyway,
this is not an undue burden, though it may involve some cost. 
<LI> It is not clear whether <TT>declare_no_pointers</tt>
needs an inverse operation, or whether that should be implicit at the
end of the object lifetime.  Hans prefers the latter, but is not sure how
to implement it if we allow stack-allocated objects to be used.
We would need a dynamic check on function return, which
seems highly undesirable.
<LI> One of the authors is not enthusiastic about the special treatment of
<samp>malloc()</samp> allocated memory.
It clearly handicaps garbage collectors or
leak detectors, in that such objects cannot be any more reliably
collected than they can now, and leaks involving such objects cannot
be reliably identified. On the other hand, we expect that it will
make straightforward implementations of garbage collection and leak
detection of objects allocated using operator new (which is the
normative C++ model implied by the standard) far more reliable with
existing libraries. Furthermore, this is probably the only thing we
can do in good conscience without an endorsement from the C committee
for changing the semantics of malloc-allocated memory.
<LI> Sean Parent suggests adding operator new overloads that effectively
perform a <samp>declare_no_pointers()</samp> call on the entire resulting
objects.  Aside from convenience, this has the added benefit that it may
be significantly cheaper to implement than the two separate calls, since
the object can be placed appropriately.  However, it is clearly less general
than the separate calls, since it cannot be applied to statically allocated
storage, stack allocated storage, or a piece of a heap-allocated object.
The authors strongly approve of this addition.  However, it superficially
makes the interface much wider than what had been discussed earlier, since
it involves many new function overloads.  Hence we look for guidance from LWG
before adding these.
</ol>
</body>
</html>
