From e4cd83ec59fb697b3c00dbca30895d66e70d4df6 Mon Sep 17 00:00:00 2001 From: James Chen Date: Mon, 22 Aug 2022 09:54:42 +0800 Subject: [PATCH] Fix potential crash in Node::isChildOf (#12493) --- cocos/core/scene-graph/node.jsb.ts | 12 +++++++----- native/cocos/core/scene-graph/Node.cpp | 6 ++++++ 2 files changed, 13 insertions(+), 5 deletions(-) diff --git a/cocos/core/scene-graph/node.jsb.ts b/cocos/core/scene-graph/node.jsb.ts index 2422b35d8a..29fdeffdce 100644 --- a/cocos/core/scene-graph/node.jsb.ts +++ b/cocos/core/scene-graph/node.jsb.ts @@ -1063,11 +1063,11 @@ Object.defineProperty(nodeProto, '_parent', { configurable: true, enumerable: true, get () { - return this._parentInternal; + this._parentRef = this._parentInternal; + return this._parentRef; }, set (v) { - // jsb.registerNativeRef(v, this); // Root JSB object to avoid child node being garbage collected - this._parentInternal = v; + this._parentRef = this._parentInternal = v; }, }); @@ -1075,10 +1075,11 @@ Object.defineProperty(nodeProto, 'parent', { configurable: true, enumerable: true, get () { - return this.getParent(); + this._parentRef = this.getParent(); + return this._parentRef; }, set (v) { - // jsb.registerNativeRef(v, this); // Root JSB object to avoid child node being garbage collected + this._parentRef = v; this.setParent(v); }, }); @@ -1263,6 +1264,7 @@ nodeProto._instantiate = function (cloned: Node, isSyncedNode: boolean) { // nodeProto._ctor = function (name?: string) { this.__nativeRefs = {}; + this._parentRef = null; this.__jsb_ref_id = undefined; this._iN$t = null; this.__editorExtras__ = { editorOnly: true }; diff --git a/native/cocos/core/scene-graph/Node.cpp b/native/cocos/core/scene-graph/Node.cpp index b47be302bc..5e2ee153ff 100644 --- a/native/cocos/core/scene-graph/Node.cpp +++ b/native/cocos/core/scene-graph/Node.cpp @@ -89,6 +89,12 @@ Node::Node(const ccstd::string &name) { Node::~Node() { CC_SAFE_DELETE(_eventProcessor); + if (!_children.empty()) { + // Reset children's _parent to nullptr to avoid dangerous pointer + for (const auto &child : _children) { + child->_parent = nullptr; + } + } } void Node::onBatchCreated(bool dontChildPrefab) {