Skip to content
Merged
Show file tree
Hide file tree
Changes from 7 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion scripts/build/deps/webkit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
* for local mode. Override via `--webkit-version=<hash>` to test a branch.
* From https://github.com/oven-sh/WebKit releases.
*/
export const WEBKIT_VERSION = "1817c3c37f5dfc004a33dafac9f6adcf1a9641a4";
export const WEBKIT_VERSION = "c4ddc0cf5255ec9cc209e6369292739b78e3ca80";

/**
* WebKit (JavaScriptCore) — the JS engine.
Expand Down
11 changes: 11 additions & 0 deletions src/bun_core/string/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,11 @@ unsafe extern "C" {
len: usize,
hash: u32,
) -> String;
fn BunString__createStaticExternalUTF16WithHash(
units: *const u16,
len: usize,
hash: u32,
) -> String;
fn BunString__createExternal(
bytes: *const u8,
len: usize,
Expand Down Expand Up @@ -377,6 +382,12 @@ impl String {
// ptr/len without copying or freeing.
unsafe { BunString__createStaticExternal(units.as_ptr().cast::<u8>(), units.len(), false) }
}
/// [`Self::create_static_external_utf16`] for units whose `WTF::StringImpl::hash()` is already known.
pub fn create_static_external_utf16_with_hash(units: &[u16], hash: u32) -> Self {
debug_assert!(!units.is_empty());
// SAFETY: as above; `hash` is StringImpl::hash() of `units`.
unsafe { BunString__createStaticExternalUTF16WithHash(units.as_ptr(), units.len(), hash) }
}
/// Formats `args` into a WTF-backed string; an argument-free ASCII
/// literal is returned as `static_` without copying.
pub fn create_format(args: core::fmt::Arguments<'_>) -> Self {
Expand Down
161 changes: 134 additions & 27 deletions src/bundler/analyze_transpiled_module.rs
Original file line number Diff line number Diff line change
Expand Up @@ -123,15 +123,45 @@
/// `body` / `table` are lifetime-erased: they point either into the
/// executable's mapped section (`'static`) or into `owned`, which lives as long
/// as `self`.
pub struct ModuleInfoDeserialized {

Check warning on line 126 in src/bundler/analyze_transpiled_module.rs

View workflow job for this annotation

GitHub Actions / mordant

`_owned` always has the same value for a given `table`, in all 2 places `analyze_transpiled_module::ModuleInfoDeserialized` is built. It is a stored copy of something `table` decides
body: Body<'static>,
table: ModuleInfoStringTable<'static>,
table: ModuleInfoStrings<'static>,
pub flags: Flags,
/// Backing storage for `body`/`table`: `None` when they live in the
/// executable's mapped section — the ids then index the shared string
/// table and identifiers come from the VM-wide slots
/// (`Bun__VM__sharedModuleInfoIdentifiers`) rather than a per-record array.
owned: Option<Box<[u8]>>,
/// executable's mapped section.
_owned: Option<Box<[u8]>>,
}

/// Where a record's names come from: a self-contained record carries its own
/// strings (`WTF::StringImpl` bodies the runtime atomizes); a record inside an
/// executable indexes the slot table every module of the executable shares,
/// resolved by JSC as the bytecode's own string slots are.
#[derive(Clone, Copy)]
pub enum ModuleInfoStrings<'a> {
Owned(ModuleInfoStringTable<'a>),
Shared(ModuleInfoSlotTable<'a>),
}
/// One name of a record, as the runtime resolves it.
pub enum ModuleInfoString<'a> {
/// `is_8bit` Latin-1 bytes, else little-endian UTF-16 (not necessarily aligned).
Chars { chars: &'a [u8], is_8bit: bool },
/// `EncoderStringTable::slotFor`.
Slot(u32),
}
impl<'a> ModuleInfoStrings<'a> {
pub fn count(&self) -> u32 {
match self {
Self::Owned(t) => t.count,
Self::Shared(t) => t.count(),
}
}
/// String `id`, or `None` if out of bounds (corrupt input).
pub fn get(&self, id: u32) -> Option<ModuleInfoString<'a>> {
match self {
Self::Owned(t) => t.get(id),
Self::Shared(t) => t.get(id).map(ModuleInfoString::Slot),
}
}
}

/// The body split into its regions; every count has been bounds-checked
Expand Down Expand Up @@ -222,31 +252,26 @@
&self.body
}
#[inline]
pub fn table(&self) -> &ModuleInfoStringTable<'_> {
&self.table
}
#[inline]
pub fn ids(&self) -> IdCursor<'_> {
IdCursor {
rem: self.body.ids,
width: self.body.id_width as usize,
count: self.table.count,
count: self.table.count(),
}
}
/// Whether the ids index the executable's shared string table (and so
/// the VM-wide identifier slots).
/// Whether the ids index the executable's shared slot table (and so the
/// VM-wide identifier slots).
#[inline]
pub fn shared(&self) -> bool {
self.owned.is_none()
matches!(self.table, ModuleInfoStrings::Shared(_))
}
/// Ids below this are strings; the rest are sentinels.
#[inline]
pub fn strings_count(&self) -> usize {
self.table.count as usize
self.table.count() as usize
}
/// The WTF-8 bytes of string `id`, or `None` if out of bounds (corrupt input).
#[inline]
pub fn string(&self, id: u32) -> Option<&[u8]> {
pub fn string(&self, id: u32) -> Option<ModuleInfoString<'_>> {
self.table.get(id)
}

Expand All @@ -272,9 +297,9 @@
let (flags, body) = Body::parse(&bytes[table.byte_len..])?;
Ok(Box::new(ModuleInfoDeserialized {
body,
table,
table: ModuleInfoStrings::Owned(table),
flags,
owned: Some(owned),
_owned: Some(owned),
}))
}

Expand All @@ -284,19 +309,19 @@
Self::create(source).ok()
}

/// A body inside the executable whose ids index the string table the
/// A body inside the executable whose ids index the slot table the
/// executable shares between all its modules (`StandaloneModuleGraph`).
/// Nothing is copied.
pub fn create_with_table(
table: &ModuleInfoStringTable<'static>,
table: &ModuleInfoSlotTable<'static>,
body: &'static [u8],
) -> Option<Box<ModuleInfoDeserialized>> {
let (flags, body) = Body::parse(body).ok()?;
Some(Box::new(ModuleInfoDeserialized {
body,
table: *table,
table: ModuleInfoStrings::Shared(*table),
flags,
owned: None,
_owned: None,
}))
}
}
Expand Down Expand Up @@ -332,9 +357,8 @@
}
}

/// Borrowed view over a serialized
/// `bun_js_printer::analyze_transpiled_module::ModuleInfoStringTable`
/// (layout documented there).
/// Borrowed view over a self-contained record's string table
/// (`bun_js_printer::serialize_string_table`).
#[derive(Clone, Copy)]
pub struct ModuleInfoStringTable<'a> {
count: u32,
Expand Down Expand Up @@ -392,9 +416,92 @@
Some([start, end - start])
}
#[inline]
pub fn get(&self, id: u32) -> Option<&'a [u8]> {
pub fn get(&self, id: u32) -> Option<ModuleInfoString<'a>> {
let [offset, len] = self.range(id)?;
Some(&self.buf[offset as usize..(offset + len) as usize])
let record = &self.buf[offset as usize..(offset + len) as usize];
match *record {
[1, ref chars @ ..] => Some(ModuleInfoString::Chars {
chars,
is_8bit: true,
}),
[0, ref chars @ ..] if chars.len() % 2 == 0 => Some(ModuleInfoString::Chars {
chars,
is_8bit: false,
}),
_ => None,
}
}
}

/// The executable's module-info string table: `u32 count` then one `u32`
/// slot per string, each resolved by `JSC__IdentifierArray__setFromSlot`
/// exactly as the bytecode cache resolves its own string slots — up to three
/// Latin-1 characters inline (tag 1), an ordinal into the executable's
/// bytecode string table (tag 2), or the empty string (tag 3). Built by
/// `ModuleInfoSlotTableBuilder`.
#[derive(Clone, Copy)]
pub struct ModuleInfoSlotTable<'a> {
slots: &'a [u8],
}
impl<'a> ModuleInfoSlotTable<'a> {
pub fn parse(bytes: &'a [u8]) -> Result<Self, ModuleInfoError> {
if bytes.is_empty() {
return Ok(Self { slots: &[] });
}
let mut r = Reader { rem: bytes };
let count = r.u32()? as usize;
let slots = r.bytes(count.checked_mul(4).ok_or(ModuleInfoError::BadModuleInfo)?)?;
Ok(Self { slots })
}
#[inline]
pub fn count(&self) -> u32 {
(self.slots.len() / 4) as u32
}
#[inline]
pub fn get(&self, id: u32) -> Option<u32> {
let at = (id as usize).checked_mul(4)?;
let bytes = self.slots.get(at..at + 4)?;
Some(u32::from_le_bytes(bytes.try_into().unwrap()))
}
}

/// Interns every module's strings during a `--compile` link and serializes
/// the `ModuleInfoSlotTable` their bodies index.
#[derive(Default)]
pub struct ModuleInfoSlotTableBuilder {
ids: bun_collections::HashMap<Box<[u8]>, u32>,
slots: Vec<u32>,
}
impl ModuleInfoSlotTableBuilder {
/// Interns every string of `mi`; the result maps its local ids to table ids.
pub fn intern_all(&mut self, mi: &ModuleInfo, slot_for: impl Fn(&[u8]) -> u32) -> Vec<u32> {
let (strings_buf, strings_lens) = mi.strings();
let mut ids = Vec::with_capacity(strings_lens.len());
let mut offset = 0usize;
for &len in strings_lens {
let s = &strings_buf[offset..offset + len as usize];
offset += len as usize;
if let Some(&id) = self.ids.get(s) {
ids.push(id);
continue;
}
let id = u32::try_from(self.slots.len()).expect("int cast");
self.slots.push(slot_for(s));
self.ids.insert(s.into(), id);
ids.push(id);
}
ids
}
pub fn count(&self) -> u32 {
self.slots.len() as u32
}
pub fn serialize(&self) -> Vec<u8> {
let mut out = Vec::with_capacity(4 + self.slots.len() * 4);
out.extend_from_slice(&self.count().to_le_bytes());
for slot in &self.slots {
out.extend_from_slice(&slot.to_le_bytes());
}
out
}
}

Expand Down
9 changes: 9 additions & 0 deletions src/bundler/bundle_v2.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1440,6 +1440,11 @@ pub mod bv2_impl {
safe fn __bun_jsc_encoder_string_table_take(
table: core::ptr::NonNull<EncoderStringTable>,
) -> Box<[u8]>;
/// The runtime-resolvable slot for one module-info string (`EncoderStringTable::slot_for_wtf8`).
safe fn __bun_jsc_encoder_string_table_slot(
table: core::ptr::NonNull<EncoderStringTable>,
wtf8: &[u8],
) -> u32;
}

unsafe extern "Rust" {
Expand Down Expand Up @@ -1510,6 +1515,10 @@ pub mod bv2_impl {
pub(crate) fn take(mut self) -> Box<[u8]> {
__bun_jsc_encoder_string_table_take(self.0.take().expect("taken once"))
}
#[inline]
pub(crate) fn slot(&self, wtf8: &[u8]) -> u32 {
__bun_jsc_encoder_string_table_slot(self.0.expect("not yet taken"), wtf8)
}
}

impl Drop for EncoderStringTableHandle {
Expand Down
19 changes: 9 additions & 10 deletions src/bundler/linker_context/generateChunksInParallel.rs
Original file line number Diff line number Diff line change
Expand Up @@ -502,9 +502,14 @@ pub(crate) fn generate_chunks_in_parallel<const IS_DEV_SERVER: bool>(
// cross-chunk import specifiers. During printing, cross-chunk imports use
// unique_key placeholders as paths. Now that final paths are known, replace
// those placeholders with the resolved paths and serialize.
let mut module_info_strings =
bun_js_printer::analyze_transpiled_module::ModuleInfoStringTable::default();
let external_string_table = (c.options.generate_bytecode_cache
&& c.options.compile_mode.is_executable())
.then(crate::bundle_v2::dispatch::EncoderStringTableHandle::new);
let mut module_info_strings = analyze_transpiled_module::ModuleInfoSlotTableBuilder::default();
if c.options.generates_module_info() {
let external_string_table = external_string_table
.as_ref()
.expect("module_info is only generated for --compile --bytecode");
// Build map from unique_key -> final resolved path
// SAFETY: c points to LinkerContext which is the `linker` field of BundleV2.
let b: &mut BundleV2 =
Expand Down Expand Up @@ -578,7 +583,7 @@ pub(crate) fn generate_chunks_in_parallel<const IS_DEV_SERVER: bool>(
js.module_info = None;
continue;
}
table_ids.push(module_info_strings.intern_all(mi));
table_ids.push(module_info_strings.intern_all(mi, |s| external_string_table.slot(s)));
}
let mut table_ids = table_ids.iter();
for chunk in chunks.iter_mut() {
Expand Down Expand Up @@ -617,9 +622,6 @@ pub(crate) fn generate_chunks_in_parallel<const IS_DEV_SERVER: bool>(
let resolver = c.resolver.expect("resolver set in load()");
let root_path: &[u8] = &resolver.opts.output_dir;
let is_standalone = c.options.compile_mode.is_standalone_html();
let external_string_table = (c.options.generate_bytecode_cache
&& c.options.compile_mode.is_executable())
.then(crate::bundle_v2::dispatch::EncoderStringTableHandle::new);
let more_than_one_output = !is_standalone
&& (c.parse_graph().additional_output_files.len() > 0
|| c.options.generate_bytecode_cache
Expand Down Expand Up @@ -1358,10 +1360,7 @@ pub(crate) fn generate_chunks_in_parallel<const IS_DEV_SERVER: bool>(
);
}
if c.options.generates_module_info() {
let mut bytes = Vec::new();
module_info_strings
.serialize(&mut bytes)
.expect("Vec<u8> write");
let bytes = module_info_strings.serialize();
debug!(
"module_info string table: {} strings, {} bytes",
module_info_strings.count(),
Expand Down
Loading
Loading