Skip to content

Commit 600b2b3

Browse files
authored
Release Yoga ownership of children an unowned node shares with its clone
Summary: **The Bug** Showing a subtree hidden with `<Activity mode="hidden">` again can abort debug builds with `Attempt to mutate a sealed object`. Release builds have no assertion, so the same layout pass silently changes shadow nodes that the committed tree still uses. **The Cause** React keeps the instance of a hidden host component, commits a `display: none` clone of it that shares its children, and appends the instance (or a clone of it) again when the subtree is shown. Since react/yoga#2055, zeroing out a `display: none` subtree no longer clones children that are already zeroed out, so the committed tree can share children that the kept instance owns. The instance itself is unowned, so appending it adopts it in place, and its layout treats the shared children as its own. **The Fix** Cloning an unowned `YogaLayoutableShadowNode` points the owner of the children it owns at the detached-owner sentinel, through `updateYogaChildrenOwnersIfNeeded`, which now takes the Yoga node to update. Whichever node lays those children out next (the kept instance or any clone of it) clones them first through the Yoga clone callback. The kept instance's stale layout cache is already handled by comparing each new child's layout results in `updateYogaChildren`. react/yoga#2055's optimization stays in place. Changelog: [General][Fixed] - Fix showing a subtree hidden with `<Activity>` laying out shadow nodes in place that the committed tree still uses, which crashed debug builds Reviewed By: lenaic Differential Revision: D132556429 Pull Request resolved: #60082
1 parent 6a695d8 commit 600b2b3

4 files changed

Lines changed: 270 additions & 5 deletions

File tree

‎packages/react-native/ReactCommon/react/renderer/components/view/YogaLayoutableShadowNode.cpp‎

Lines changed: 14 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -123,11 +123,20 @@ YogaLayoutableShadowNode::YogaLayoutableShadowNode(
123123
&static_cast<const YogaLayoutableShadowNode&>(sourceShadowNode)
124124
.yogaConfig_;
125125

126+
// An unowned source can be appended and laid out again after this clone is
127+
// committed (React does this when it shows a hidden subtree again), so it
128+
// must not keep owning the children it now shares with this clone.
129+
auto& sourceYogaNode =
130+
static_cast<const YogaLayoutableShadowNode&>(sourceShadowNode).yogaNode_;
131+
if (YGNodeGetOwner(&sourceYogaNode) == nullptr) {
132+
updateYogaChildrenOwnersIfNeeded(sourceYogaNode);
133+
}
134+
126135
YGNodeSetContext(&yogaNode_, this);
127136
yogaNode_.setOwner(nullptr);
128137
YGNodeSetConfig(
129138
&yogaNode_, &initializeYogaConfig(yogaConfig_, previousConfig));
130-
updateYogaChildrenOwnersIfNeeded();
139+
updateYogaChildrenOwnersIfNeeded(yogaNode_);
131140

132141
// We do not need to reconfigure this subtree before the next layout pass if
133142
// the previous node with the same props and children has already been
@@ -332,16 +341,17 @@ bool YogaLayoutableShadowNode::shouldNewRevisionDirtyMeasurement(
332341
//
333342
// No-op in the common case: right after a clone, children's owner
334343
// pointers still reference the source node, not us.
335-
void YogaLayoutableShadowNode::updateYogaChildrenOwnersIfNeeded() {
344+
/*static*/ void YogaLayoutableShadowNode::updateYogaChildrenOwnersIfNeeded(
345+
yoga::Node& yogaNode) {
336346
// Magic constant intentionally recognisable in debuggers when the address
337347
// pops up. `reinterpret_cast` is not constexpr, so this is a runtime-
338348
// initialised function-local static.
339349
// NOLINTBEGIN(cppcoreguidelines-pro-type-reinterpret-cast)
340350
static auto* const kDetachedYogaNodeOwnerSentinel =
341351
reinterpret_cast<yoga::Node*>(0xBADC0FFEE0DDF000ULL);
342352
// NOLINTEND(cppcoreguidelines-pro-type-reinterpret-cast)
343-
for (auto& childYogaNode : yogaNode_.getChildren()) {
344-
if (YGNodeGetOwner(childYogaNode) == &yogaNode_) {
353+
for (auto& childYogaNode : yogaNode.getChildren()) {
354+
if (YGNodeGetOwner(childYogaNode) == &yogaNode) {
345355
childYogaNode->setOwner(kDetachedYogaNodeOwnerSentinel);
346356
}
347357
}

‎packages/react-native/ReactCommon/react/renderer/components/view/YogaLayoutableShadowNode.h‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -110,7 +110,11 @@ class YogaLayoutableShadowNode : public LayoutableShadowNode {
110110
mutable yoga::Node yogaNode_;
111111

112112
private:
113-
void updateYogaChildrenOwnersIfNeeded();
113+
/*
114+
* Points the owner of every child that `yogaNode` owns at a sentinel, so
115+
* that whichever node lays the child out next clones it first.
116+
*/
117+
static void updateYogaChildrenOwnersIfNeeded(yoga::Node &yogaNode);
114118

115119
/*
116120
* Return true if child's yogaNode's owner is this->yogaNode_. Otherwise
Lines changed: 190 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,190 @@
1+
/*
2+
* Copyright (c) Meta Platforms, Inc. and affiliates.
3+
*
4+
* This source code is licensed under the MIT license found in the
5+
* LICENSE file in the root directory of this source tree.
6+
*/
7+
8+
#include <memory>
9+
#include <vector>
10+
11+
#include <gtest/gtest.h>
12+
13+
#include <react/renderer/components/root/RootComponentDescriptor.h>
14+
#include <react/renderer/components/view/ViewComponentDescriptor.h>
15+
#include <react/renderer/element/ComponentBuilder.h>
16+
#include <react/renderer/element/Element.h>
17+
#include <react/renderer/element/testUtils.h>
18+
19+
namespace facebook::react {
20+
21+
namespace {
22+
23+
std::shared_ptr<const ViewProps> sizedProps(float width, float height) {
24+
auto props = std::make_shared<ViewProps>();
25+
props->yogaStyle.setDimension(
26+
yoga::Dimension::Width, yoga::StyleSizeLength::points(width));
27+
props->yogaStyle.setDimension(
28+
yoga::Dimension::Height, yoga::StyleSizeLength::points(height));
29+
return props;
30+
}
31+
32+
std::shared_ptr<const ViewProps> displayNoneProps() {
33+
auto props = std::make_shared<ViewProps>();
34+
props->yogaStyle.setDisplay(yoga::Display::None);
35+
return props;
36+
}
37+
38+
std::shared_ptr<ShadowNode> cloneWithChild(
39+
const ShadowNode& shadowNode,
40+
const std::shared_ptr<const ShadowNode>& child) {
41+
auto children =
42+
std::make_shared<const std::vector<std::shared_ptr<const ShadowNode>>>(
43+
std::vector<std::shared_ptr<const ShadowNode>>{child});
44+
return shadowNode.clone(
45+
ShadowNodeFragment{
46+
.props = ShadowNodeFragment::propsPlaceholder(),
47+
.children = children});
48+
}
49+
50+
std::shared_ptr<ShadowNode> cloneHidden(const ShadowNode& shadowNode) {
51+
return shadowNode.clone(ShadowNodeFragment{.props = displayNoneProps()});
52+
}
53+
54+
std::shared_ptr<RootShadowNode> commit(
55+
const std::shared_ptr<ShadowNode>& root) {
56+
auto rootShadowNode = std::static_pointer_cast<RootShadowNode>(root);
57+
rootShadowNode->layoutIfNeeded();
58+
rootShadowNode->sealRecursive();
59+
return rootShadowNode;
60+
}
61+
62+
Size frameSize(const std::shared_ptr<const ShadowNode>& shadowNode) {
63+
return static_cast<const LayoutableShadowNode&>(*shadowNode)
64+
.getLayoutMetrics()
65+
.frame.size;
66+
}
67+
68+
std::vector<LayoutMetrics> subtreeLayoutMetrics(const ShadowNode& shadowNode) {
69+
std::vector<LayoutMetrics> metrics{
70+
static_cast<const LayoutableShadowNode&>(shadowNode).getLayoutMetrics()};
71+
for (const auto& child : shadowNode.getChildren()) {
72+
auto childMetrics = subtreeLayoutMetrics(*child);
73+
metrics.insert(metrics.end(), childMetrics.begin(), childMetrics.end());
74+
}
75+
return metrics;
76+
}
77+
78+
} // namespace
79+
80+
// React keeps the instance of a hidden subtree, commits a `display: none`
81+
// clone of it that shares its children, and appends the instance (or a clone
82+
// of it) again when the subtree is shown. The parameter is the size of the
83+
// instance's child: a zero-sized child keeps its frame when it is zeroed out.
84+
class RevealHiddenInstanceTest : public ::testing::TestWithParam<float> {
85+
protected:
86+
RevealHiddenInstanceTest() {
87+
std::shared_ptr<RootShadowNode> rootShadowNode;
88+
std::shared_ptr<ViewShadowNode> instance;
89+
90+
// clang-format off
91+
auto element =
92+
Element<RootShadowNode>()
93+
.reference(rootShadowNode)
94+
.tag(1)
95+
.props([] {
96+
auto props = std::make_shared<RootProps>();
97+
props->layoutConstraints = LayoutConstraints{
98+
.minimumSize = {.width = 0, .height = 0},
99+
.maximumSize = {.width = 200, .height = 200}};
100+
return props;
101+
})
102+
.children({
103+
Element<ViewShadowNode>()
104+
.reference(instance)
105+
.tag(2)
106+
.props([] { return sizedProps(100, 100); })
107+
.children({
108+
Element<ViewShadowNode>()
109+
.tag(3)
110+
.props([size = GetParam()] { return sizedProps(size, size); })
111+
.children({
112+
Element<ViewShadowNode>()
113+
.tag(4)
114+
.props([] { return sizedProps(10, 10); })
115+
})
116+
})
117+
});
118+
// clang-format on
119+
120+
builder_.build(element);
121+
commit(rootShadowNode);
122+
123+
auto hiddenRoot =
124+
commit(cloneWithChild(*rootShadowNode, cloneHidden(*instance)));
125+
126+
// An update while hidden starts from the child as laid out in the hidden
127+
// tree, so the new instance owns a child that is already zeroed out.
128+
const auto& zeroedOutChild =
129+
hiddenRoot->getChildren().front()->getChildren().front();
130+
hiddenChild_ = zeroedOutChild->clone(ShadowNodeFragment{});
131+
instance_ = cloneWithChild(*instance, hiddenChild_);
132+
133+
hiddenRoot_ = commit(cloneWithChild(*hiddenRoot, cloneHidden(*instance_)));
134+
}
135+
136+
void expectShownWithoutChangingHiddenTree(
137+
const std::shared_ptr<const ShadowNode>& shownInstance) {
138+
ASSERT_EQ(
139+
hiddenRoot_->getChildren().front()->getChildren().front(),
140+
hiddenChild_);
141+
const auto hiddenTreeLayoutMetrics = subtreeLayoutMetrics(*hiddenRoot_);
142+
143+
auto shownRoot = std::static_pointer_cast<RootShadowNode>(
144+
cloneWithChild(*hiddenRoot_, shownInstance));
145+
shownRoot->layoutIfNeeded();
146+
147+
const auto& instance = shownRoot->getChildren().front();
148+
const auto& child = instance->getChildren().front();
149+
EXPECT_NE(child, hiddenChild_);
150+
const std::vector<Size> expectedSizes{
151+
{.width = 100, .height = 100},
152+
{.width = GetParam(), .height = GetParam()},
153+
{.width = 10, .height = 10}};
154+
EXPECT_EQ(
155+
(std::vector<Size>{
156+
frameSize(instance),
157+
frameSize(child),
158+
frameSize(child->getChildren().front())}),
159+
expectedSizes);
160+
EXPECT_EQ(subtreeLayoutMetrics(*hiddenRoot_), hiddenTreeLayoutMetrics);
161+
}
162+
163+
ComponentBuilder builder_{simpleComponentBuilder()};
164+
std::shared_ptr<RootShadowNode> hiddenRoot_;
165+
std::shared_ptr<const ShadowNode> instance_;
166+
std::shared_ptr<const ShadowNode> hiddenChild_;
167+
};
168+
169+
TEST_P(RevealHiddenInstanceTest, showingInstance) {
170+
expectShownWithoutChangingHiddenTree(instance_);
171+
}
172+
173+
TEST_P(RevealHiddenInstanceTest, showingCloneOfInstance) {
174+
expectShownWithoutChangingHiddenTree(instance_->clone(ShadowNodeFragment{}));
175+
}
176+
177+
TEST_P(RevealHiddenInstanceTest, showingCloneOfInstanceWithNewNonLayoutProp) {
178+
auto props = std::make_shared<ViewProps>(
179+
static_cast<const ViewProps&>(*instance_->getProps()));
180+
props->backgroundColor = blackColor();
181+
expectShownWithoutChangingHiddenTree(
182+
instance_->clone(ShadowNodeFragment{.props = props}));
183+
}
184+
185+
INSTANTIATE_TEST_SUITE_P(
186+
ChildSizes,
187+
RevealHiddenInstanceTest,
188+
::testing::Values(50.0f, 0.0f));
189+
190+
} // namespace facebook::react
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
/**
2+
* Copyright (c) Meta Platforms, Inc. and affiliates.
3+
*
4+
* This source code is licensed under the MIT license found in the
5+
* LICENSE file in the root directory of this source tree.
6+
*
7+
* @flow strict-local
8+
* @format
9+
*/
10+
11+
import '@react-native/fantom/src/setUpDefaultReactNativeEnvironment';
12+
13+
import type {HostInstance} from 'react-native';
14+
15+
import * as Fantom from '@react-native/fantom';
16+
import nullthrows from 'nullthrows';
17+
import * as React from 'react';
18+
import {Activity, createRef} from 'react';
19+
import {View} from 'react-native';
20+
21+
describe('<Activity>', () => {
22+
it('lays out a subtree shown again after it was updated while hidden', () => {
23+
const root = Fantom.createRoot();
24+
const childRef = createRef<HostInstance>();
25+
const grandchildRef = createRef<HostInstance>();
26+
const siblingRef = createRef<HostInstance>();
27+
28+
function render(mode: 'visible' | 'hidden', siblingWidth: number) {
29+
Fantom.runTask(() => {
30+
root.render(
31+
<Activity mode={mode}>
32+
<View style={{width: 100, height: 100}}>
33+
<View ref={childRef} style={{width: 50, height: 50}}>
34+
<View ref={grandchildRef} style={{width: 10, height: 10}} />
35+
</View>
36+
<View
37+
ref={siblingRef}
38+
style={{width: siblingWidth, height: 10}}
39+
/>
40+
</View>
41+
</Activity>,
42+
);
43+
});
44+
}
45+
46+
render('visible', 20);
47+
render('hidden', 20);
48+
// Updating the sibling while hidden appends the unchanged child as it was
49+
// laid out (zeroed out) in the hidden tree.
50+
render('hidden', 30);
51+
render('visible', 30);
52+
53+
const sizeOf = (ref: {current: HostInstance | null}) => {
54+
const rect = nullthrows(ref.current).getBoundingClientRect();
55+
return [rect.width, rect.height];
56+
};
57+
expect(sizeOf(childRef)).toEqual([50, 50]);
58+
expect(sizeOf(grandchildRef)).toEqual([10, 10]);
59+
expect(sizeOf(siblingRef)).toEqual([30, 10]);
60+
});
61+
});

0 commit comments

Comments
 (0)