Unverified Commit 62d9b8e0 authored by Sam Poder's avatar Sam Poder Committed by GitHub

[turbopack] Treat constants with values referencing other values as unsafe (#96190)

Previously this was treated as side-effect free:

```javascript
const box = { a: { b: globalThis } }; box.a.b.x = 1;
```

This was an issue introduced by
https://github.com/vercel/next.js/pull/94294.
parent e6313968
...@@ -315,6 +315,7 @@ fn collect_safe_assignment_constant_ids(program: &Program) -> HashSet<Id> { ...@@ -315,6 +315,7 @@ fn collect_safe_assignment_constant_ids(program: &Program) -> HashSet<Id> {
for d in &decl.decls { for d in &decl.decls {
if let (Pat::Ident(binding), Some(init)) = (&d.name, d.init.as_deref()) if let (Pat::Ident(binding), Some(init)) = (&d.name, d.init.as_deref())
&& is_object_or_array_literal(init) && is_object_or_array_literal(init)
&& is_fresh_value(init)
&& !contains_getters_or_setters(init) && !contains_getters_or_setters(init)
{ {
self.ids.insert(binding.id.to_id()); self.ids.insert(binding.id.to_id());
...@@ -335,11 +336,12 @@ fn collect_safe_assignment_constant_ids(program: &Program) -> HashSet<Id> { ...@@ -335,11 +336,12 @@ fn collect_safe_assignment_constant_ids(program: &Program) -> HashSet<Id> {
// Drop any binding that later has an accessor attached to its object graph // Drop any binding that later has an accessor attached to its object graph
// (e.g. `o.x = { set y(v) {} }`): a subsequent write through that property // (e.g. `o.x = { set y(v) {} }`): a subsequent write through that property
// could invoke the accessor, so the binding is no longer safe to mutate. // could invoke the accessor, so the binding is no longer safe to mutate.
// The same goes for a value the module doesn't own (`o.x = globalThis`).
for_each_top_level_expr(program, |expr| { for_each_top_level_expr(program, |expr| {
if let Expr::Assign(assign) = expr if let Expr::Assign(assign) = expr
&& assign.op == AssignOp::Assign && assign.op == AssignOp::Assign
&& let AssignTarget::Simple(SimpleAssignTarget::Member(member)) = &assign.left && let AssignTarget::Simple(SimpleAssignTarget::Member(member)) = &assign.left
&& contains_getters_or_setters(&assign.right) && (!is_fresh_value(&assign.right) || contains_getters_or_setters(&assign.right))
&& let Some(root) = root_identifier(&member.obj) && let Some(root) = root_identifier(&member.obj)
{ {
ids.remove(&root.to_id()); ids.remove(&root.to_id());
...@@ -349,6 +351,28 @@ fn collect_safe_assignment_constant_ids(program: &Program) -> HashSet<Id> { ...@@ -349,6 +351,28 @@ fn collect_safe_assignment_constant_ids(program: &Program) -> HashSet<Id> {
ids ids
} }
/// Whether `expr` is a primitive or an object created by the expression itself,
/// transitively. `{ g: globalThis }` is not: `box.g.x = 1` writes to the global.
fn is_fresh_value(expr: &Expr) -> bool {
match unparen(expr) {
Expr::Lit(_) | Expr::Tpl(_) | Expr::Fn(_) | Expr::Arrow(_) => true,
Expr::Object(obj) => obj.props.iter().all(|prop| match prop {
PropOrSpread::Prop(prop) => match &**prop {
Prop::KeyValue(kv) => is_fresh_value(&kv.value),
Prop::Method(_) => true,
Prop::Shorthand(_) | Prop::Getter(_) | Prop::Setter(_) | Prop::Assign(_) => false,
},
PropOrSpread::Spread(spread) => is_fresh_value(&spread.expr),
}),
Expr::Array(arr) => arr
.elems
.iter()
.flatten()
.all(|elem| is_fresh_value(&elem.expr)),
_ => false,
}
}
/// Whether `expr`'s object graph contains a getter or setter. An accessor makes /// Whether `expr`'s object graph contains a getter or setter. An accessor makes
/// member access (read *or* write) potentially effectful — e.g. `o.foo = 1` /// member access (read *or* write) potentially effectful — e.g. `o.foo = 1`
/// invokes a `set foo` — so a value carrying one can't be attached to the /// invokes a `set foo` — so a value carrying one can't be attached to the
...@@ -404,7 +428,10 @@ fn for_each_top_level_expr(program: &Program, f: impl FnMut(&Expr)) { ...@@ -404,7 +428,10 @@ fn for_each_top_level_expr(program: &Program, f: impl FnMut(&Expr)) {
/// ///
/// A reassignment to an alias (`module.exports = require('./x')`, /// A reassignment to an alias (`module.exports = require('./x')`,
/// `module.exports = other`) would make later changes to properties on /// `module.exports = other`) would make later changes to properties on
/// `module.exports` have side effects. /// `module.exports` have side effects. A fresh object/array literal is safe,
/// but not one capturing a value the module does not own
/// (`module.exports = { g: globalThis }` is unsafe: a later
/// `module.exports.g.x = 1` mutates the global).
fn module_exports_is_tainted(program: &Program, unresolved_mark: Mark) -> bool { fn module_exports_is_tainted(program: &Program, unresolved_mark: Mark) -> bool {
let mut tainted = false; let mut tainted = false;
for_each_top_level_expr(program, |expr| { for_each_top_level_expr(program, |expr| {
...@@ -412,7 +439,7 @@ fn module_exports_is_tainted(program: &Program, unresolved_mark: Mark) -> bool { ...@@ -412,7 +439,7 @@ fn module_exports_is_tainted(program: &Program, unresolved_mark: Mark) -> bool {
&& assign.op == AssignOp::Assign && assign.op == AssignOp::Assign
&& let AssignTarget::Simple(SimpleAssignTarget::Member(member)) = &assign.left && let AssignTarget::Simple(SimpleAssignTarget::Member(member)) = &assign.left
&& is_module_dot_exports(member, unresolved_mark) && is_module_dot_exports(member, unresolved_mark)
&& !is_object_or_array_literal(&assign.right) && (!is_object_or_array_literal(&assign.right) || !is_fresh_value(&assign.right))
{ {
tainted = true; tainted = true;
} }
...@@ -2740,6 +2767,12 @@ mod tests { ...@@ -2740,6 +2767,12 @@ mod tests {
test_cjs_export_alias_then_write, test_cjs_export_alias_then_write,
"module.exports = other; module.exports.foo = 1;" "module.exports = other; module.exports.foo = 1;"
); );
// A fresh literal capturing a value the module does not own also taints
// it: `module.exports.g.x = 1` mutates the global, not the exports object.
side_effects!(
test_cjs_export_literal_capturing_global_then_write,
"module.exports = { g: globalThis }; module.exports.g.x = 1;"
);
// The reassignment is also detected when hidden inside a top-level // The reassignment is also detected when hidden inside a top-level
// comma-sequence expression rather than a standalone statement. // comma-sequence expression rather than a standalone statement.
side_effects!( side_effects!(
...@@ -2943,5 +2976,58 @@ mod tests { ...@@ -2943,5 +2976,58 @@ mod tests {
test_local_setter_attached_in_conditional, test_local_setter_attached_in_conditional,
"const o = {}; x && (o.a = { set y(v) { sideEffect() } }); o.a.y = 1;" "const o = {}; x && (o.a = { set y(v) { sideEffect() } }); o.a.y = 1;"
); );
side_effects!(
test_literal_capturing_global_nested_mutation,
"const box = { g: globalThis }; box.g.x = 1;"
);
side_effects!(
test_literal_capturing_global_direct_mutation,
"const box = { g: globalThis }; box.g = 1;"
);
side_effects!(
test_literal_capturing_global_deeply_nested_mutation,
"const box = { a: { b: globalThis } }; box.a.b.x = 1;"
);
side_effects!(
test_array_literal_capturing_global_nested_mutation,
"const box = [globalThis]; box[0].x = 1;"
);
side_effects!(
test_literal_capturing_window_mutation,
"const box = { w: window }; box.w.x = 1;"
);
side_effects!(
test_literal_capturing_import_mutation,
"import obj from './obj'; const box = { obj }; box.obj.foo = 1;"
);
side_effects!(
test_literal_capturing_require_result_mutation,
"const box = { dep: require('./dep') }; box.dep.x = 1;"
);
side_effects!(
test_literal_spreading_import_mutation,
"import obj from './obj'; const box = { ...obj }; box.foo.bar = 1;"
);
side_effects!(
test_foreign_value_assigned_then_nested_mutation,
"const box = {}; box.g = globalThis; box.g.x = 1;"
);
side_effects!(
test_foreign_value_assigned_then_direct_mutation,
"const box = {}; box.g = globalThis; box.a = 1;"
);
side_effects!(
test_require_result_assigned_then_direct_mutation,
"const box = {}; box.dep = require('./dep'); box.a = 1;"
);
no_side_effects!(
test_deeply_nested_literal_mutation,
"const box = { a: { b: {} } }; box.a.b.c = 1;"
);
no_side_effects!(
test_nested_literal_assigned_then_mutated,
"const box = {}; box.a = { b: {} }; box.a.b.c = 1;"
);
} }
} }
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment