[PATCH] tst-setcontext2: avoid bug from compiler optimization

Chris Metcalf cmetcalf@mellanox.com
Wed Jan 25 21:27:00 GMT 2017


On 1/25/2017 1:05 PM, Torvald Riegel wrote:
> On Wed, 2017-01-25 at 12:23 -0500, Chris Metcalf wrote:
>> On 1/25/2017 6:23 AM, Torvald Riegel wrote:
>>> I agree with Florian that the compiler needs to be made aware that
>>> getcontext can return twice, or something to that effect.  This would
>>> tell it that it has to reason about the lifetimes of variables
>>> differently.
>> The problem is that "returns_twice" doesn't offer the semantics we want.
> There are similarities to setjmp/longjmp, I think.
>
>  From C11 7.13.2.1:
> All accessible objects have values, and all other components of the
> abstract machine have state, as of the time the longjmp function was
> called, except that the values of objects of automatic storage duration
> that are local to the function containing the invocation of the
> corresponding setjmp macro that do not have volatile-qualified type
> and have been changed between the setjmp invocation and longjmp call are
> indeterminate.
>
> oldctx is modified between the getcontext (like setjmp) and effective
> longjmp part of swapcontext.

Yes, there are certainly similarities.  Note that swapcontext also acts like
getcontext as a returns_twice function.

>> It ensures that register-allocated variables are handled properly, i.e.
>> everything is saved to the stack frame prior to calling the function.  But
>> here the issue is that the stack frame itself isn't being set up in a way that
>> actually works.  And in practice, tagging getcontext and swapcontext with
>> attribute((returns_twice)) does not fix the bug.  (It does seem like doing so
>> isn't a bad idea, but it is beyond the scope of fixing this one test bug.)
>>
>> Another way to fix the problem is to make the context variables function static,
>> which should forbid the compiler from doing anything funky with them.
>> (Although do_test itself is static, it is called from main, and the compiler
>> has to assume main could get called again and expect to find the updated
>> context variables still updated, so it can't trickily ignore the static modifier
>> or anything like that, I think.)
> I think that we need the returns_twice attribute, but we also shouldn't
> put oldctx on the stack (unless it's marked volatile).

I'm not sure we need or want the returns_twice attribute, given that
gcc already has special code for recognizing setjmp, vfork, etc. Currently
glibc does not use the returns_twice attribute anywhere in its source tree.
If getcontext or swapcontext is missing from gcc (and I don't know that
it is) then presumably it's a gcc bug.

-- 
Chris Metcalf, Mellanox Technologies
http://www.mellanox.com



More information about the Libc-alpha mailing list