<div dir="ltr"><div class="gmail_extra"><div class="gmail_quote">On 19 April 2014 15:41, Austin Seipp <span dir="ltr"><<a href="mailto:aseipp@pobox.com" target="_blank">aseipp@pobox.com</a>></span> wrote:<br><blockquote class="gmail_quote" style="margin:0px 0px 0px 0.8ex;border-left-width:1px;border-left-color:rgb(204,204,204);border-left-style:solid;padding-left:1ex">

You would think that considering this variable is (p)thread local, we<br>
could just use a __thread variable, or pthread_{get,set}specific to<br>
manage. But on OS X, both of these equate to an absolutely huge<br>
performance loss, upwards of 25%. Which is unacceptable, realistically<br>
speaking, but we've had to deal with it.</blockquote><div><br></div><div>In practice, pthread_getspecific() on x86-64 on Mac OS X is just a very simple assembly routine:</div><div><br></div><div><div>  movq %gs:_PTHREAD_TSD_OFFSET(,%rdi,8),%rax</div>

<div>  ret</div></div><div><br></div><div>For Native Client on Mac x86-64, we check that pthread_getspecific() contains the code above, and we inline the %gs access into NaCl's runtime code (reading the value of _PTHREAD_TSD_OFFSET from pthread_getspecific()'s code).</div>

<div><br></div><div>You can find the code for doing that here:</div><div><a href="https://src.chromium.org/viewvc/native_client/trunk/src/native_client/src/trusted/service_runtime/arch/x86_64/nacl_tls_64.c?revision=11149">https://src.chromium.org/viewvc/native_client/trunk/src/native_client/src/trusted/service_runtime/arch/x86_64/nacl_tls_64.c?revision=11149</a><br>

</div><div><br></div><div>NaCl's reason for doing this is that NaCl needs to be able to read a thread-local variable in a context when there's no stack available for calling pthread_getspecific().  (We could pre-allocate a pool of stacks and then allocate a stack from this pool with an atomic operation, then call pthread_getspecific() on that stack.  But that's a lot more complicated, and slower.)</div>

<div><br></div><div>This will of course break if OS X's implementation of pthread_getspecific() changes (other than to change _PTHREAD_TSD_OFFSET).  Hopefully, if that ever happens, OS X will have already started providing better thread-local variables that can be accessed without calling a function, like what Linux/ELF and Windows provide. :-)</div>

<div><br></div><div>This is hacky, but it should be completely reliable if pthread_getspecific() matches the expected pattern, because it's not like the code for pthread_getspecific() is going to change underneath you.</div>

<div><br></div><div>You could use the same trick, and fall back to calling pthread_getspecific() if the code it contains doesn't match the pattern you expect.</div><div><br></div><div>Cheers,</div><div>Mark</div><div>

<br></div></div></div></div>