Skip to content

Truly independent web browser

LibJS: Uninitialize a block's lexical locals each time it is entered

Shannon Boothc0ba43d9b530
diff --git a/Libraries/LibJS/Rust/src/bytecode/codegen.rs b/Libraries/LibJS/Rust/src/bytecode/codegen.rs
index a087e847a02..fc772549b1c 100644
--- a/Libraries/LibJS/Rust/src/bytecode/codegen.rs
+++ b/Libraries/LibJS/Rust/src/bytecode/codegen.rs
@@ -2966,6 +2966,7 @@ fn generate_block_statement(
// environment and its only child is a for-loop variant, skip
// generate_scope_children and generate the child directly to avoid
// emitting a redundant completion Mov.
+ emit_tdz_reset_of_declared_locals(generator, scope.children.iter());
let result = if !did_create_env && scope.children.len() == 1 && is_for_loop(&scope.children[0]) {
generate_statement(&scope.children[0], generator, preferred_dst)
} else {
@@ -2978,6 +2979,74 @@ fn generate_block_statement(
result
}
+/// Empty the locals that a scope declares lexically where the scope starts, so that entering it again (as a loop does)
+/// starts them uninitialized. The generator drops the store for a local that no TDZ check reads.
+fn emit_tdz_reset_of_declared_locals<'a>(generator: &mut Generator, statements: impl Iterator<Item = &'a Statement>) {
+ let arena = generator.arena.clone();
+ let mut locals = Vec::new();
+ for statement in statements {
+ collect_lexically_declared_locals(statement, &arena, &mut locals);
+ }
+ for index in locals {
+ generator.emit_tdz_reset(index);
+ }
+}
+
+/// Collect the locals that a statement directly in a scope declares lexically, including in a loop head.
+fn collect_lexically_declared_locals(statement: &Statement, arena: &AstArena, locals: &mut Vec<u32>) {
+ if let Some((declarations, _)) = lexical_declarators(statement) {
+ for declaration in declarations {
+ match &declaration.target {
+ VariableDeclaratorTarget::Identifier(id) => collect_local(*id, arena, locals),
+ VariableDeclaratorTarget::BindingPattern(pattern) => {
+ collect_pattern_locals(pattern, arena, locals);
+ }
+ }
+ }
+ return;
+ }
+ match &statement.inner {
+ StatementKind::ClassDeclaration(data) => {
+ if let Some(id) = data.name {
+ collect_local(id, arena, locals);
+ }
+ }
+ StatementKind::For(data) => {
+ if let Some(ForInit::Declaration(declaration)) = &data.init {
+ collect_lexically_declared_locals(declaration, arena, locals);
+ }
+ }
+ StatementKind::ForInOf(data) => {
+ if let ForInOfLhs::Declaration(declaration) = &data.lhs {
+ collect_lexically_declared_locals(declaration, arena, locals);
+ }
+ }
+ _ => {}
+ }
+}
+
+fn collect_pattern_locals(pattern: &BindingPattern, arena: &AstArena, locals: &mut Vec<u32>) {
+ for entry in &pattern.entries {
+ match &entry.alias {
+ Some(BindingEntryAlias::Identifier(id)) => collect_local(*id, arena, locals),
+ Some(BindingEntryAlias::BindingPattern(sub_pattern)) => collect_pattern_locals(sub_pattern, arena, locals),
+ Some(BindingEntryAlias::MemberExpression(_)) => {}
+ None => {
+ if let Some(BindingEntryName::Identifier(id)) = &entry.name {
+ collect_local(*id, arena, locals);
+ }
+ }
+ }
+ }
+}
+
+fn collect_local(id: IdentifierId, arena: &AstArena, locals: &mut Vec<u32>) {
+ let identifier = &arena.identifiers[id];
+ if identifier.is_local() && identifier.local_type == Some(LocalType::Variable) {
+ locals.push(identifier.local_index);
+ }
+}
+
/// How the resources of a scope are disposed of, if the scope has `using` or `await using` declarations.
#[derive(Clone, Copy, PartialEq, Eq)]
enum DisposalKind {
@@ -5196,6 +5265,8 @@ fn emit_tdz_check_if_needed(generator: &mut Generator, id: crate::ast::Identifie
if ident.local_type == Some(LocalType::Argument) {
let empty = generator.add_constant_empty();
generator.emit_mov(&local, &empty);
+ } else {
+ generator.mark_local_tdz_checked(local_index);
}
generator.emit(Instruction::ThrowIfTDZ { src: local.operand() });
}
@@ -5963,6 +6034,13 @@ fn generate_switch_statement(
}
let initialized_locals_at_entry = generator.initialized_locals.clone();
+ let arena = generator.arena.clone();
+ emit_tdz_reset_of_declared_locals(
+ generator,
+ data.cases
+ .iter()
+ .flat_map(|case| arena.scopes[case.scope].children.iter()),
+ );
// Create first test block and jump to it.
let first_test_block = generator.make_block();
diff --git a/Libraries/LibJS/Rust/src/bytecode/generator.rs b/Libraries/LibJS/Rust/src/bytecode/generator.rs
index 5ae403a1871..695a318b0c2 100644
--- a/Libraries/LibJS/Rust/src/bytecode/generator.rs
+++ b/Libraries/LibJS/Rust/src/bytecode/generator.rs
@@ -399,6 +399,9 @@ pub struct Generator {
pub argument_variable_names: Vec<ak::Utf16FlyString>,
pub initialized_locals: Vec<bool>,
pub initialized_arguments: Vec<bool>,
+ /// Lexically declared locals with a TDZ check, for which the store that empties them where their scope starts is
+ /// kept.
+ pub tdz_checked_locals: Vec<bool>,
/// When set, function/class expressions will use this as their `.name`.
/// Set by assignment/declaration codegen, consumed by function expression codegen.
@@ -583,6 +586,7 @@ impl Generator {
argument_variable_names: Vec::new(),
initialized_locals: Vec::new(),
initialized_arguments: Vec::new(),
+ tdz_checked_locals: Vec::new(),
pending_lhs_name: None,
current_source_start: Position {
line: 0,
@@ -948,6 +952,41 @@ impl Generator {
// --- Instruction emission ---
+ /// Emit the store that empties a lexically declared local where a scope declaring it starts. Until the code is
+ /// assembled, it is a move of the local to itself, which nothing else emits (see resolve_tdz_resets).
+ pub fn emit_tdz_reset(&mut self, index: u32) {
+ let local = Operand::local(index);
+ self.emit(Instruction::Mov { dst: local, src: local });
+ }
+
+ /// Make each TDZ reset of a local that a TDZ check reads store the empty value, and remove the others, which a
+ /// local only read once it is initialized does not need.
+ fn resolve_tdz_resets(&mut self) {
+ let mut empty = None;
+ for block_index in 0..self.basic_blocks.len() {
+ let mut instructions = core::mem::take(&mut self.basic_blocks[block_index].instructions);
+ instructions.retain_mut(|(instruction, _, _)| {
+ let Instruction::Mov { dst, src } = instruction else {
+ return true;
+ };
+ if dst.operand_type() != OperandType::Local || dst != src {
+ return true;
+ }
+ if !self
+ .tdz_checked_locals
+ .get(dst.index() as usize)
+ .copied()
+ .unwrap_or(false)
+ {
+ return false;
+ }
+ *src = *empty.get_or_insert_with(|| self.add_constant_empty().operand());
+ true
+ });
+ self.basic_blocks[block_index].instructions = instructions;
+ }
+ }
+
/// Emit an instruction to the current basic block.
pub fn emit(&mut self, instruction: Instruction) {
if self.is_current_block_terminated() {
@@ -1904,6 +1943,14 @@ impl Generator {
.is_some_and(|v| v.is_lexically_declared)
}
+ pub fn mark_local_tdz_checked(&mut self, index: u32) {
+ let index = index as usize;
+ if index >= self.tdz_checked_locals.len() {
+ self.tdz_checked_locals.resize(index + 1, false);
+ }
+ self.tdz_checked_locals[index] = true;
+ }
+
pub fn mark_local_initialized(&mut self, index: u32) {
let index = index as usize;
if index >= self.initialized_locals.len() {
@@ -2001,6 +2048,8 @@ impl Generator {
}
}
+ self.resolve_tdz_resets();
+
// If any block is unterminated, ensure the undefined constant exists
// for the assembly-time End(undefined) fallthrough. This must happen
// before computing number_of_constants so operand rewriting accounts
diff --git a/Tests/LibJS/Runtime/loops/tdz-on-each-iteration.js b/Tests/LibJS/Runtime/loops/tdz-on-each-iteration.js
new file mode 100644
index 00000000000..8e106c0866e
--- /dev/null
+++ b/Tests/LibJS/Runtime/loops/tdz-on-each-iteration.js
@@ -0,0 +1,117 @@
+describe("a lexical binding is uninitialized again on each iteration", () => {
+ test("let in a loop body", () => {
+ function loop() {
+ const results = [];
+ for (let i = 0; i < 2; i++) {
+ try {
+ results.push(value);
+ } catch (error) {
+ results.push(error.name);
+ }
+ let value = i;
+ }
+ return results;
+ }
+
+ expect(loop()).toEqual(["ReferenceError", "ReferenceError"]);
+ });
+
+ test("typeof in a loop body", () => {
+ function loop() {
+ const results = [];
+ let i = 0;
+ while (i < 2) {
+ try {
+ results.push(typeof value);
+ } catch (error) {
+ results.push(error.name);
+ }
+ const value = i++;
+ }
+ return results;
+ }
+
+ expect(loop()).toEqual(["ReferenceError", "ReferenceError"]);
+ });
+
+ test("class declaration in a loop body", () => {
+ function loop() {
+ const results = [];
+ for (let i = 0; i < 2; i++) {
+ try {
+ results.push(typeof C);
+ } catch (error) {
+ results.push(error.name);
+ }
+ class C {}
+ }
+ return results;
+ }
+
+ expect(loop()).toEqual(["ReferenceError", "ReferenceError"]);
+ });
+
+ test("initializer that throws after starting to build its value", () => {
+ function loop() {
+ const results = [];
+ for (let i = 0; i < 2; i++) {
+ try {
+ try {
+ results.push(value);
+ } catch (error) {
+ results.push(error.name);
+ }
+ let value = [
+ i,
+ ...(() => {
+ throw new Error();
+ })(),
+ ];
+ } catch {}
+ }
+ return results;
+ }
+
+ expect(loop()).toEqual(["ReferenceError", "ReferenceError"]);
+ });
+
+ test("switch case entered after an earlier iteration declared the binding", () => {
+ function loop() {
+ const results = [];
+ for (let i = 0; i < 2; i++) {
+ switch (i) {
+ case 0:
+ let value = i;
+ break;
+ case 1:
+ try {
+ results.push(value);
+ } catch (error) {
+ results.push(error.name);
+ }
+ }
+ }
+ return results;
+ }
+
+ expect(loop()).toEqual(["ReferenceError"]);
+ });
+
+ test("for-of head binding read by its own expression", () => {
+ function loop() {
+ const results = [];
+ for (let i = 0; i < 2; i++) {
+ try {
+ for (let value of i === 0 ? [i] : [value]) {
+ results.push(value);
+ }
+ } catch (error) {
+ results.push(error.name);
+ }
+ }
+ return results;
+ }
+
+ expect(loop()).toEqual([0, "ReferenceError"]);
+ });
+});