Skip to content

Commit

Permalink
Fix stack overflow when partially-__init__ Node raises exception. (ap…
Browse files Browse the repository at this point in the history
…ache#7481)

* Fix stack overflow when partially-__init__ Node raises exception.

 * If a Node subclass raises an exception and ctypes is in use before
   __init_handle_by_constructor__ is called (or self.handle is
   otherwise set), a Python stack overflow could result. This is
   because the unset handle slot causes self.handle accesses to
   fallback on the getattr(self, 'handle') method, invoking
   NodeGetAttr.
 * Then I believe this causes an infinite loop.
 * The fix is to make Node.__getattr__ raise AttributeError for all
   attributes in __slots__, then make __del__ tolerant to missing
   self.handle.
 * I don't believe cython is affected because it implements a
   descriptor to access its underlying chandle and that shouldn't be unset.

* black format

* actually use handle instead of self.handle
  • Loading branch information
areusch authored and trevor-m committed Mar 2, 2021
1 parent 108bf66 commit 2e30e2d
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 1 deletion.
7 changes: 6 additions & 1 deletion python/tvm/_ffi/_ctypes/object.py
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,12 @@ class ObjectBase(object):

def __del__(self):
if _LIB is not None:
check_call(_LIB.TVMObjectFree(self.handle))
try:
handle = self.handle
except AttributeError:
return

check_call(_LIB.TVMObjectFree(handle))

def __init_handle_by_constructor__(self, fconstructor, *args):
"""Initialize the handle by calling constructor function.
Expand Down
3 changes: 3 additions & 0 deletions python/tvm/runtime/object.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,9 @@ def __dir__(self):
return sorted([fnames(i) for i in range(size)] + class_names)

def __getattr__(self, name):
if name in self.__slots__:
raise AttributeError(f"{name} is not set")

try:
return _ffi_node_api.NodeGetAttr(self, name)
except AttributeError:
Expand Down

0 comments on commit 2e30e2d

Please sign in to comment.