Hi Mark,

Ouch, it looks like the bug here is specifically in kj::Thread::detach().

kj::Thread takes ownership of the functor passed to its constructor.
Meanwhile, kj::Thread's destructor -- assuming detach() hasn't been called
-- waits patiently for the thread to exit before returning. So in the
normal non-detached case, the functor stays alive.

However, in the detached case, the functor can be destroyed while it's
still running.

The fix is probably to pass ownership of the functor directly to the thread
itself, having the thread be responsible for destroying it on exit.

It looks like the network address resolver code will use detach() if you
drop the promise before it is done resolving -- i.e. try to cancel it.
Fortunately that's probably unusual to do in practice.

-Kenton

On Sat, Sep 10, 2016 at 3:31 AM, Mark Grimes <[email protected]> wrote:

> Hi,
> While trying to track down a bug in my own code, I had a memory tracer
> showing use of freed memory here:
>
> https://github.com/sandstorm-io/capnproto/blob/
> cbacb18063db4056a7a4e84b9ba43b9db4731de4/c%2B%2B/src/kj/
> async-io.c%2B%2B#L721
>
> The corruption is on the kj::Strings in the params variable.  I eventually
> figured it out it only happens when the client is destroyed.before the
> address resolves.  I'm pretty sure it's a consequence of the move lambda
> capture trick where a functor is created instead of an actual lambda - the
> main thread destroys the functor holding the moved variables before
> the getaddrinfo thread has a chance to use them.
>
> If you want this fixed then I think the only way is to copy instead of
> moving the strings.  However, it's only triggered in rare cases; and since
> it only happens when everything is shutting down anyway I'm not sure how
> serious it is.  Does anyone think the performance loss of the copy is worth
> the memory correctness?
>
> C++14 generalised captures should also solve this, but I think it'll be a
> while before that's an acceptable minimum requirement.
>
> Thanks,
>
> Mark.
>
> --
> You received this message because you are subscribed to the Google Groups
> "Cap'n Proto" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to [email protected].
> Visit this group at https://groups.google.com/group/capnproto.
>

-- 
You received this message because you are subscribed to the Google Groups 
"Cap'n Proto" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
Visit this group at https://groups.google.com/group/capnproto.

Reply via email to