-
-
Notifications
You must be signed in to change notification settings - Fork 8.2k
py/runtime: Avoid crash on calling members of uninitialized native type. #9997
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
Closed
Closed
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,31 @@ | ||
""" | ||
categories: Core,Classes | ||
description: When inheriting native types, calling a method in ``__init__(self, ...)`` before ``super().__init__()`` raises an ``AttributeError`` (or segfaults if ``MICROPY_BUILTIN_METHOD_CHECK_SELF_ARG`` is not enabled). | ||
cause: MicroPython does not have separate ``__new__`` and ``__init__`` methods in native types. | ||
workaround: Call ``super().__init__()`` first. | ||
""" | ||
|
||
|
||
class L1(list): | ||
def __init__(self, a): | ||
self.append(a) | ||
|
||
|
||
try: | ||
L1(1) | ||
print("OK") | ||
except AttributeError: | ||
print("AttributeError") | ||
|
||
|
||
class L2(list): | ||
def __init__(self, a): | ||
super().__init__() | ||
self.append(a) | ||
|
||
|
||
try: | ||
L2(1) | ||
print("OK") | ||
except AttributeError: | ||
print("AttributeError") |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,3 +1,9 @@ | ||
<Timer> | ||
True | ||
True | ||
AdvancedTimer() | ||
AdvancedTimer() # created 0 seconds ago | ||
0 | ||
123 | ||
True | ||
TypeError |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -12,5 +12,6 @@ | |
d = dir(cexample) | ||
d.index("add_ints") | ||
d.index("Timer") | ||
d.index("AdvancedTimer") | ||
|
||
print(cexample.add_ints(1, 3)) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,38 @@ | ||
# test subclassing custom native class | ||
|
||
try: | ||
from cexample import AdvancedTimer | ||
except ImportError: | ||
print("SKIP") | ||
raise SystemExit | ||
|
||
|
||
class SubTimer(AdvancedTimer): | ||
def __init__(self): | ||
|
||
# At this point, self does not yet represent a AdvancedTimer instance. | ||
print(self) | ||
|
||
# So lookups via type.attr handler will fail. | ||
try: | ||
self.seconds | ||
except AttributeError: | ||
print("AttributeError") | ||
|
||
# Also applies to builtin methods. | ||
try: | ||
self.time() | ||
except AttributeError: | ||
print("AttributeError") | ||
|
||
# Initialize base class. | ||
super().__init__(self) | ||
|
||
# Now you can access methods and attributes normally. | ||
self.time() | ||
print(self.seconds) | ||
self.seconds = 123 | ||
print(self.seconds) | ||
|
||
|
||
watch = SubTimer() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,5 @@ | ||
<function> | ||
AttributeError | ||
AttributeError | ||
0 | ||
123 |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
It might be possible to just fix it and make it work like CPython (as much as that's possible without having both
__new__
and__init__
in MicroPython) by doing this:That will call
__init__
automatically and reload the newly-created native instance.Then I wouldn't wrap it in
MICROPY_BUILTIN_METHOD_CHECK_SELF_ARG
, just do it unconditionally.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
(if you do this, please don't remove the C example module or tests, they are good!)
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Wouldn't that segfault (null dereference)? I started digging based on your suggestion. Perhaps did you mean something like this? This seems to work, with no AttributeError required, so closer to CPython indeed.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Yep, that's right!
(We had a fairly long discussion around this today and wrapped up the conclusion a bit quickly :) )
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Thanks for the instant feedback. While updating the tests, I noticed this would cause
make_new
to be called twice:There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The behavior is still a bit odd (and different from CPython). Take this slightly more elaborate class, which takes a parameter to
__init__
:I suppose I would OK with that (anything that doesn't segfault is fine), but I just wanted to make sure. We can add an updated CPython difference.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
We discussed exactly this scenario... It makes sense to me that this should fail, but I agree that the error message is confusing because it looks like
info()
is missing theport
argument.What's the CPython behaviour that you'd expect here? (I'm struggling to think of an example where this could come up with a built-in type. It is different to the behaviour of a non-native base of course)
Note there's another CPython diff here which is that if you don't explicitly call
super().__init__
and you have a native base, then by default we pass the derived type's__init__
args to the native base. (CPython only does this when the base istuple
andfrozenset
, perhaps others).There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I think MiroPython's
make_new
is really the equivalent of__new__
without__init__
in CPython. This is why immutable types liketuple
have the different behavior as above - since they are immutable, all of the "init" has to be done in__new__
. So I don't think we should be callingmake_new
more than once, otherwise it forces all implementations to have to be aware of which call it is (if first call treat as__new__
, otherwise treat as__init__
) or risk leaking resources or other unexpected behaviors (e.g. ifmake_new
opens a file descriptor, then is called again, that file descriptor has to be closed, otherwise it is leaked with no way to close it later).There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Could we implement something like this?
self
is accessed in an__init__
overload of a native type andsuper.__init__()
was not called yet, then callmake_new
with the args of the overload.super().__init__()
is called aftermake_new
was called because of the condition above, raise an exception.super.__init__()
is called before something triggered the call tomake_new
, then callmake_new
with the args fromsuper.__init__()
.make_new
before the__init__
overload returns, callmake_new
with the args from the overload.The recommendation in the MicroPython docs should be to call
super().__init__()
as the first line of any__init__
overload of a native type (or at least before usingself
). But at least in other cases, it might work as expected or at least not segfault.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
That proposal just above does seem to cover all points raised here.
But it makes things complicated: implementation, documentation, behaviour, and what the user needs to learn and understand.
I think the simplest thing is to just prevent the crash if trying to access super before its initialised, and the user can initialise the native type it early if needed. That's much easier to understand.
(Also I don't even know how we would implement the first bullet point above, the part where the native make_new was called with the args of the overload, because those args are not available at that point in the runtime.)