Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

bpo-30039: Don't run signal handlers while resuming a yield from stack #1081

Merged
merged 4 commits into from
May 17, 2017

Conversation

njsmith
Copy link
Contributor

@njsmith njsmith commented Apr 11, 2017

If we have a chain of generators/coroutines that are 'yield from'ing
each other, then resuming the stack works like:

  • call send() on the outermost generator
  • this enters _PyEval_EvalFrameDefault, which re-executes the
    YIELD_FROM opcode
  • which calls send() on the next generator
  • which enters _PyEval_EvalFrameDefault, which re-executes the
    YIELD_FROM opcode
  • ...etc.

However, every time we enter _PyEval_EvalFrameDefault, the first thing
we do is to check for pending signals, and if there are any then we
run the signal handler. And if it raises an exception, then we
immediately propagate that exception instead of starting to execute
bytecode. This means that e.g. a SIGINT at the wrong moment can "break
the chain" – it can be raised in the middle of our yield from chain,
with the bottom part of the stack abandoned for the garbage collector.

The fix is pretty simple: there's already a special case in
_PyEval_EvalFrameEx where it skips running signal handlers if the next
opcode is SETUP_FINALLY. (I don't see how this accomplishes anything
useful, but that's another story.) If we extend this check to also
skip running signal handlers when the next opcode is YIELD_FROM, then
that closes the hole – now the exception can only be raised at the
innermost stack frame.

This shouldn't have any performance implications, because the opcode
check happens inside the "slow path" after we've already determined
that there's a pending signal or something similar for us to process;
the vast majority of the time this isn't true and the new check
doesn't run at all.

The included test fails before this patch, but passes afterwards.

@mention-bot
Copy link

@njsmith, thanks for your PR! By analyzing the history of the files in this pull request, we identified @benjaminp, @tim-one and @serhiy-storchaka to be potential reviewers.

@njsmith
Copy link
Contributor Author

njsmith commented Apr 11, 2017

CC @1st1

AFAIK this should be good to go except for missing a NEWS entry (and fingers crossed on the CI bots...). I didn't do that because it's, y'know, a mess for conflicts and I'm not sure what the current status of that discussion is.

@1st1
Copy link
Member

1st1 commented Apr 20, 2017

LGTM.

(for those few interested in why this is needed you can read Nathaniel's insightful blog post here: https://vorpus.org/blog/control-c-handling-in-python-and-trio/#twisted, in addition to the issue/PR)

@1st1 1st1 self-requested a review April 20, 2017 19:59
Python/ceval.c Outdated
@@ -1064,9 +1064,11 @@ _PyEval_EvalFrameDefault(PyFrameObject *f, int throwflag)
Py_MakePendingCalls() above. */

if (_Py_atomic_load_relaxed(&eval_breaker)) {
if (_Py_OPCODE(*next_instr) == SETUP_FINALLY) {
if (_Py_OPCODE(*next_instr) == SETUP_FINALLY
|| _Py_OPCODE(*next_instr) == YIELD_FROM) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

One nit: I think || should be on line 1067.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

PEP 8 switched to recommending binary operators go on the second line a few months ago (because Knuth says so, among other reasons). Was it decided that PEP 7 should stick with the old way, or...? (I mean I don't care either way, if you want then I'm happy to switch it when I get back to a real keyboard.)

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What if the function had some variable it creates before it calls yield from on it?

like for example:

# snip
    def generator1(self):
        something = None
        return (yield from self.generator2())

# snip

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@AraHaan: I don't think I understand... Can you elaborate on what you're worried about? The bug we're trying to fix here is that while the yield from is running, KeyboardInterrupt should only be raised inside generator2, not generator1.

I guess there is a small annoyance that if a KeyboardInterrupt arrives at just the wrong moment we could get a spurious "coroutine was not awaited" warning, but even I can't get too worked up about that...

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@njsmith Can you fix the || operator per my last comment? Also, maybe you can expand the "when re-entering a 'yield from'" piece by explaining that generator/coroutine frames are paused at the opcode, and a therefore we might have a chain of frames all waiting on their YIELD_FROM opcode and we don't want to break that chain with an interrupt.

Copy link
Member

@vstinner vstinner left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The change must be documented in Misc/NEWS. IMHO it deserves to be mentionned in Doc/whatsnew/3.7.rst as well.

_testcapi = support.import_module('_testcapi')


class SignalAndYieldFromTest(unittest.TestCase):
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please add a reference to the bpo in a comment.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe add also a short description of the purpose of this complex test?

if (!PyArg_ParseTuple(args, "O!", &PyGen_Type, &gen))
return NULL;

/* To test what happens if a signal arrives just as we're in the process
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please add a reference to the bpo in a comment.

Python/ceval.c Outdated
@@ -1064,9 +1064,11 @@ _PyEval_EvalFrameDefault(PyFrameObject *f, int throwflag)
Py_MakePendingCalls() above. */

if (_Py_atomic_load_relaxed(&eval_breaker)) {
if (_Py_OPCODE(*next_instr) == SETUP_FINALLY) {
if (_Py_OPCODE(*next_instr) == SETUP_FINALLY
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe store _Py_OPCODE () result in a local variable to ensure that it's only computed once?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think -O2 will do that in this case, no?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, any compiler will trivially handle this, so I'd rather keep the more straightforward code.

gcc and clang both produce identical code for the local variable and no-local-variable code on -O1 and higher: https://godbolt.org/g/AJY9Zi

If we have a chain of generators/coroutines that are 'yield from'ing
each other, then resuming the stack works like:

- call send() on the outermost generator
- this enters _PyEval_EvalFrameDefault, which re-executes the
  YIELD_FROM opcode
- which calls send() on the next generator
- which enters _PyEval_EvalFrameDefault, which re-executes the
  YIELD_FROM opcode
- ...etc.

However, every time we enter _PyEval_EvalFrameDefault, the first thing
we do is to check for pending signals, and if there are any then we
run the signal handler. And if it raises an exception, then we
immediately propagate that exception *instead* of starting to execute
bytecode. This means that e.g. a SIGINT at the wrong moment can "break
the chain" – it can be raised in the middle of our yield from chain,
with the bottom part of the stack abandoned for the garbage collector.

The fix is pretty simple: there's already a special case in
_PyEval_EvalFrameEx where it skips running signal handlers if the next
opcode is SETUP_FINALLY. (I don't see how this accomplishes anything
useful, but that's another story.) If we extend this check to also
skip running signal handlers when the next opcode is YIELD_FROM, then
that closes the hole – now the exception can only be raised at the
innermost stack frame.

This shouldn't have any performance implications, because the opcode
check happens inside the "slow path" after we've already determined
that there's a pending signal or something similar for us to process;
the vast majority of the time this isn't true and the new check
doesn't run at all.

The included test fails before this patch, but passes afterwards.
@njsmith njsmith force-pushed the no-signal-handlers-during-yield-from branch from d9065a6 to 7126cc1 Compare April 23, 2017 01:12
@njsmith
Copy link
Contributor Author

njsmith commented Apr 23, 2017

I've made all the requested changes and added a NEWS entry. I didn't adds a whats-new entry because I couldn't figure out where to put it :-).

@Mariatta
Copy link
Member

🤔 I think it can go under Other Language Changes.
@1st1 @Haypo Any opinion of where in What's New this should go?

@serhiy-storchaka
Copy link
Member

If this is a bug fix no What's New entry is needed.

@njsmith
Copy link
Contributor Author

njsmith commented Apr 24, 2017

It is a bugfix, and should probably be backported to all supported 3.x branches. My preference would be to put it in and let the whats-new editors figure out how/whether to mention it later.

@1st1
Copy link
Member

1st1 commented Apr 24, 2017

I'm ok with classifying this as a bugfix. It's totally safe to backport it to 3.6 and 3.5.

@1st1
Copy link
Member

1st1 commented Apr 24, 2017

I can commit this myself later.

@vstinner
Copy link
Member

If this is a bug fix no What's New entry is needed.

I agree. I will follow @1st1 opinion on how to apply this change and how to backport it or not.

I agree that the change on ceval.c seems safe.

@1st1 1st1 dismissed vstinner’s stale review May 17, 2017 18:14

The PR has been updated with the NEWS entry

@1st1 1st1 merged commit ab4413a into python:master May 17, 2017
1st1 pushed a commit that referenced this pull request May 17, 2017
…m stack (GH-1081)

If we have a chain of generators/coroutines that are 'yield from'ing
each other, then resuming the stack works like:

- call send() on the outermost generator
- this enters _PyEval_EvalFrameDefault, which re-executes the
  YIELD_FROM opcode
- which calls send() on the next generator
- which enters _PyEval_EvalFrameDefault, which re-executes the
  YIELD_FROM opcode
- ...etc.

However, every time we enter _PyEval_EvalFrameDefault, the first thing
we do is to check for pending signals, and if there are any then we
run the signal handler. And if it raises an exception, then we
immediately propagate that exception *instead* of starting to execute
bytecode. This means that e.g. a SIGINT at the wrong moment can "break
the chain" – it can be raised in the middle of our yield from chain,
with the bottom part of the stack abandoned for the garbage collector.

The fix is pretty simple: there's already a special case in
_PyEval_EvalFrameEx where it skips running signal handlers if the next
opcode is SETUP_FINALLY. (I don't see how this accomplishes anything
useful, but that's another story.) If we extend this check to also
skip running signal handlers when the next opcode is YIELD_FROM, then
that closes the hole – now the exception can only be raised at the
innermost stack frame.

This shouldn't have any performance implications, because the opcode
check happens inside the "slow path" after we've already determined
that there's a pending signal or something similar for us to process;
the vast majority of the time this isn't true and the new check
doesn't run at all..
(cherry picked from commit ab4413a)
1st1 pushed a commit that referenced this pull request Jun 9, 2017
…m stack (GH-1081)

If we have a chain of generators/coroutines that are 'yield from'ing
each other, then resuming the stack works like:

- call send() on the outermost generator
- this enters _PyEval_EvalFrameDefault, which re-executes the
  YIELD_FROM opcode
- which calls send() on the next generator
- which enters _PyEval_EvalFrameDefault, which re-executes the
  YIELD_FROM opcode
- ...etc.

However, every time we enter _PyEval_EvalFrameDefault, the first thing
we do is to check for pending signals, and if there are any then we
run the signal handler. And if it raises an exception, then we
immediately propagate that exception *instead* of starting to execute
bytecode. This means that e.g. a SIGINT at the wrong moment can "break
the chain" – it can be raised in the middle of our yield from chain,
with the bottom part of the stack abandoned for the garbage collector.

The fix is pretty simple: there's already a special case in
_PyEval_EvalFrameEx where it skips running signal handlers if the next
opcode is SETUP_FINALLY. (I don't see how this accomplishes anything
useful, but that's another story.) If we extend this check to also
skip running signal handlers when the next opcode is YIELD_FROM, then
that closes the hole – now the exception can only be raised at the
innermost stack frame.

This shouldn't have any performance implications, because the opcode
check happens inside the "slow path" after we've already determined
that there's a pending signal or something similar for us to process;
the vast majority of the time this isn't true and the new check
doesn't run at all..
(cherry picked from commit ab4413a)
1st1 added a commit that referenced this pull request Jun 9, 2017
…m stack (GH-1081) (#1640)

If we have a chain of generators/coroutines that are 'yield from'ing
each other, then resuming the stack works like:

- call send() on the outermost generator
- this enters _PyEval_EvalFrameDefault, which re-executes the
  YIELD_FROM opcode
- which calls send() on the next generator
- which enters _PyEval_EvalFrameDefault, which re-executes the
  YIELD_FROM opcode
- ...etc.

However, every time we enter _PyEval_EvalFrameDefault, the first thing
we do is to check for pending signals, and if there are any then we
run the signal handler. And if it raises an exception, then we
immediately propagate that exception *instead* of starting to execute
bytecode. This means that e.g. a SIGINT at the wrong moment can "break
the chain" – it can be raised in the middle of our yield from chain,
with the bottom part of the stack abandoned for the garbage collector.

The fix is pretty simple: there's already a special case in
_PyEval_EvalFrameEx where it skips running signal handlers if the next
opcode is SETUP_FINALLY. (I don't see how this accomplishes anything
useful, but that's another story.) If we extend this check to also
skip running signal handlers when the next opcode is YIELD_FROM, then
that closes the hole – now the exception can only be raised at the
innermost stack frame.

This shouldn't have any performance implications, because the opcode
check happens inside the "slow path" after we've already determined
that there's a pending signal or something similar for us to process;
the vast majority of the time this isn't true and the new check
doesn't run at all..
(cherry picked from commit ab4413a)
ma8ma added a commit to ma8ma/cpython that referenced this pull request Jun 13, 2017
Resolve conflcts:
ab4413a bpo-30039: Don't run signal handlers while resuming a yield from stack (python#1081)
Copy link
Contributor

@isaiah isaiah left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not sure how to handle this, should I create a bug on bpo instead?

@@ -9,6 +9,35 @@

from test import support

_testcapi = support.import_module('_testcapi')
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This broke the specs on other implementation, which don't have a _testcapi module.
It should always be guarded by try: except ImportError and skip the spec with the unittest.skipIf decorator.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please open a new bug. It seems like there are other bugs, like test_float.py:

    @support.requires_IEEE_754
    def test_serialized_float_rounding(self):
        from _testcapi import FLT_MAX
        ...

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, a new bug is the way to go. And possibly the developers guide should be updated to say whatever the policy is? (What other implementations are you thinking of? I'm a little wary about just skipping tests – this issue this test is checking for can easily exist on other implementations too...)

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, I'll create a new bug.

@njsmith I'm working on a java implementation which is based on jython. Your concern is valid, the issue might exist as well in other implementations, that's why I didn't suggest @support.cpython_only, but since the helper method from the _testcapi is also new, it should still be guarded by skipIf, or else the whole test crashes.

Copy link
Contributor

@isaiah isaiah Dec 20, 2017

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@vstinner just checked the one you posted, it works fine, because it's guarded by @support.requires_IEEE_754, and test.support is implemented in python.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

9 participants