From 0c2ef02e0662a245eb8c48a1e58cefae7f5d1c7e Mon Sep 17 00:00:00 2001 From: jedel1043 Date: Thu, 30 Jun 2022 08:32:47 -0500 Subject: [PATCH] Statically check that `COMMON_STRINGS` cannot cause overflows --- Cargo.lock | 1 + boa_interner/Cargo.toml | 1 + boa_interner/src/lib.rs | 6 +++-- boa_interner/src/sym.rs | 51 ++++++++++++++++++++++------------------- 4 files changed, 34 insertions(+), 25 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 0040aa61079..f35ada14544 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -136,6 +136,7 @@ dependencies = [ "phf", "rustc-hash", "serde", + "static_assertions", ] [[package]] diff --git a/boa_interner/Cargo.toml b/boa_interner/Cargo.toml index 68b362b1e4e..95f27c5810c 100644 --- a/boa_interner/Cargo.toml +++ b/boa_interner/Cargo.toml @@ -14,3 +14,4 @@ license = "Unlicense/MIT" serde = { version = "1.0.137", features = ["derive"], optional = true } phf = { version = "0.10.1", features = ["macros"] } rustc-hash = "1.1.0" +static_assertions = "1.1.0" diff --git a/boa_interner/src/lib.rs b/boa_interner/src/lib.rs index 984a4538fac..94e1bddb3c9 100644 --- a/boa_interner/src/lib.rs +++ b/boa_interner/src/lib.rs @@ -70,6 +70,8 @@ rustdoc::missing_doc_code_examples )] +extern crate static_assertions as sa; + mod fixed_string; mod interned_str; mod sym; @@ -263,8 +265,8 @@ impl Interner { COMMON_STRINGS.get_index(string).map(|idx| // SAFETY: `idx >= 0`, since it's an `usize`, and `idx + 1 > 0`. // In this case, we don't need to worry about overflows - // because `COMMON_STRINGS` would need to be of considerable - // size to cause an overflow, even on machines with `usize = u32`. + // because we have a static assertion in place checking that + // `COMMON_STRINGS.len() < usize::MAX`. unsafe { Sym::new_unchecked(idx + 1) }) diff --git a/boa_interner/src/sym.rs b/boa_interner/src/sym.rs index 51000e80600..60f147c707e 100644 --- a/boa_interner/src/sym.rs +++ b/boa_interner/src/sym.rs @@ -117,27 +117,32 @@ impl Sym { /// /// `COMMON_STRINGS` and the constants defined in [`Sym`] must always /// be in sync. -pub(super) static COMMON_STRINGS: phf::OrderedSet<&'static str> = phf::phf_ordered_set! { - "", - "arguments", - "await", - "yield", - "eval", - "default", - "null", - "RegExp", - "get", - "set", - "
", - "raw", - "static", - "prototype", - "constructor", - "implements", - "interface", - "let", - "package", - "private", - "protected", - "public", +pub(super) static COMMON_STRINGS: phf::OrderedSet<&'static str> = { + const COMMON_STRINGS: phf::OrderedSet<&'static str> = phf::phf_ordered_set! { + "", + "arguments", + "await", + "yield", + "eval", + "default", + "null", + "RegExp", + "get", + "set", + "
", + "raw", + "static", + "prototype", + "constructor", + "implements", + "interface", + "let", + "package", + "private", + "protected", + "public", + }; + // A `COMMON_STRINGS` of size `usize::MAX` would cause an overflow on our `Interner` + sa::const_assert!(COMMON_STRINGS.len() < usize::MAX); + COMMON_STRINGS };