Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement Startup Snapshot #3041

Draft
wants to merge 4 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all 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
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -36,3 +36,6 @@ chrome_profiler.json
# e2e test
playwright-report
test-results

# Binary snapshot file
snapshot.bin
7 changes: 7 additions & 0 deletions boa_cli/src/debug/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ mod object;
mod optimizer;
mod realm;
mod shape;
mod snapshot;

fn create_boa_object(context: &mut Context<'_>) -> JsObject {
let function_module = function::create_object(context);
Expand All @@ -19,6 +20,7 @@ fn create_boa_object(context: &mut Context<'_>) -> JsObject {
let gc_module = gc::create_object(context);
let realm_module = realm::create_object(context);
let limits_module = limits::create_object(context);
let snapshot_module = snapshot::create_object(context);

ObjectInitializer::new(context)
.property(
Expand Down Expand Up @@ -56,6 +58,11 @@ fn create_boa_object(context: &mut Context<'_>) -> JsObject {
limits_module,
Attribute::WRITABLE | Attribute::NON_ENUMERABLE | Attribute::CONFIGURABLE,
)
.property(
"snapshot",
snapshot_module,
Attribute::WRITABLE | Attribute::NON_ENUMERABLE | Attribute::CONFIGURABLE,
)
.build()
}

Expand Down
59 changes: 59 additions & 0 deletions boa_cli/src/debug/snapshot.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
use std::{
fs::{File, OpenOptions},
io::{Read, Write},
};

use boa_engine::{
object::ObjectInitializer,
snapshot::{Snapshot, SnapshotSerializer},
Context, JsNativeError, JsObject, JsResult, JsValue, NativeFunction,
};

const SNAPSHOT_PATH: &str = "./snapshot.bin";

fn get_file_as_byte_vec(filename: &str) -> Vec<u8> {
let mut f = File::open(&filename).expect("no file found");
let metadata = std::fs::metadata(&filename).expect("unable to read metadata");
let mut buffer = vec![0; metadata.len() as usize];
f.read(&mut buffer).expect("buffer overflow");

buffer
}

fn create(_: &JsValue, _: &[JsValue], context: &mut Context<'_>) -> JsResult<JsValue> {
let Ok(mut file) = OpenOptions::new().write(true).create(true).open(SNAPSHOT_PATH) else {
return Err(JsNativeError::error().with_message("could not create snapshot.bin file").into());
};

let serializer = SnapshotSerializer::new();

let snapshot = serializer.serialize(context).unwrap();

file.write_all(snapshot.bytes()).unwrap();
file.flush().unwrap();

Ok(JsValue::undefined())
}

fn load(_: &JsValue, _: &[JsValue], context: &mut Context<'_>) -> JsResult<JsValue> {
// let Ok(mut file) = OpenOptions::new().read(true).open(SNAPSHOT_PATH) else {
// return Err(JsNativeError::error().with_message("could not open snapshot.bin file").into());
// };

let bytes = get_file_as_byte_vec(SNAPSHOT_PATH);

let snapshot = Snapshot::new(bytes);

let deser_context = snapshot.deserialize().unwrap();

*context = deser_context;

Ok(JsValue::undefined())
}

pub(super) fn create_object(context: &mut Context<'_>) -> JsObject {
ObjectInitializer::new(context)
.function(NativeFunction::from_fn_ptr(create), "create", 0)
.function(NativeFunction::from_fn_ptr(load), "load", 1)
.build()
}
75 changes: 54 additions & 21 deletions boa_cli/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@ use boa_engine::{
optimizer::OptimizerOptions,
property::Attribute,
script::Script,
snapshot::Snapshot,
vm::flowgraph::{Direction, Graph},
Context, JsError, JsNativeError, JsResult, Source,
};
Expand All @@ -81,7 +82,13 @@ use colored::Colorize;
use debug::init_boa_debug_object;
use rustyline::{config::Config, error::ReadlineError, EditMode, Editor};
use std::{
cell::RefCell, collections::VecDeque, eprintln, fs::read, fs::OpenOptions, io, path::PathBuf,
cell::RefCell,
collections::VecDeque,
eprintln,
fs::OpenOptions,
fs::{read, File},
io::{self, Read},
path::{Path, PathBuf},
println,
};

Expand Down Expand Up @@ -168,6 +175,9 @@ struct Opt {
/// Root path from where the module resolver will try to load the modules.
#[arg(long, short = 'r', default_value_os_t = PathBuf::from("."), requires = "mod")]
root: PathBuf,

#[arg(long)]
snapshot: Option<PathBuf>,
}

impl Opt {
Expand Down Expand Up @@ -363,37 +373,60 @@ fn evaluate_files(
Ok(())
}

fn get_file_as_byte_vec(filename: &Path) -> Vec<u8> {
let mut f = File::open(&filename).expect("no file found");
let metadata = std::fs::metadata(&filename).expect("unable to read metadata");
let mut buffer = vec![0; metadata.len() as usize];
f.read(&mut buffer).expect("buffer overflow");

buffer
}

fn main() -> Result<(), io::Error> {
let args = Opt::parse();

let queue: &dyn JobQueue = &Jobs::default();
let loader = &SimpleModuleLoader::new(&args.root)
.map_err(|e| io::Error::new(io::ErrorKind::Other, e.to_string()))?;

let queue: &dyn JobQueue = &Jobs::default();
let dyn_loader: &dyn ModuleLoader = loader;
let mut context = ContextBuilder::new()
.job_queue(queue)
.module_loader(dyn_loader)
.build()
.expect("cannot fail with default global object");

// Strict mode
context.strict(args.strict);
let mut context = if let Some(path) = &args.snapshot {
let bytes = get_file_as_byte_vec(&path);

// Add `console`.
add_runtime(&mut context);
let snapshot = Snapshot::new(bytes);

// Trace Output
context.set_trace(args.trace);
let deser_context = snapshot.deserialize().unwrap();

if args.debug_object {
init_boa_debug_object(&mut context);
}
deser_context
} else {
let mut context = ContextBuilder::new()
.job_queue(queue)
.module_loader(dyn_loader)
.build()
.expect("cannot fail with default global object");

// Strict mode
context.strict(args.strict);

// Add `console`.
add_runtime(&mut context);

// Trace Output
context.set_trace(args.trace);

// Configure optimizer options
let mut optimizer_options = OptimizerOptions::empty();
optimizer_options.set(OptimizerOptions::STATISTICS, args.optimizer_statistics);
optimizer_options.set(OptimizerOptions::OPTIMIZE_ALL, args.optimize);
context.set_optimizer_options(optimizer_options);
if args.debug_object {
init_boa_debug_object(&mut context);
}

// Configure optimizer options
let mut optimizer_options = OptimizerOptions::empty();
optimizer_options.set(OptimizerOptions::STATISTICS, args.optimizer_statistics);
optimizer_options.set(OptimizerOptions::OPTIMIZE_ALL, args.optimize);
context.set_optimizer_options(optimizer_options);

context
};

if args.files.is_empty() {
let config = Config::builder()
Expand Down
23 changes: 23 additions & 0 deletions boa_engine/src/builtins/iterable/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,29 @@ pub struct IteratorPrototypes {
segment: JsObject,
}

impl crate::snapshot::Serialize for IteratorPrototypes {
fn serialize(
&self,
s: &mut crate::snapshot::SnapshotSerializer,
) -> Result<(), crate::snapshot::SnapshotError> {
self.iterator.serialize(s)?;
self.async_iterator.serialize(s)?;
self.async_from_sync_iterator.serialize(s)?;
self.array.serialize(s)?;
self.set.serialize(s)?;
self.string.serialize(s)?;
self.regexp_string.serialize(s)?;
self.map.serialize(s)?;
self.for_in.serialize(s)?;
#[cfg(feature = "intl")]
{
self.segment.serialize(s)?;
}

Ok(())
}
}

impl IteratorPrototypes {
/// Returns the `ArrayIteratorPrototype` object.
#[inline]
Expand Down
21 changes: 21 additions & 0 deletions boa_engine/src/builtins/uri/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,27 @@ pub struct UriFunctions {
encode_uri_component: JsFunction,
}

impl crate::snapshot::Serialize for UriFunctions {
fn serialize(
&self,
s: &mut crate::snapshot::SnapshotSerializer,
) -> Result<(), crate::snapshot::SnapshotError> {
self.decode_uri.serialize(s)?;
self.decode_uri_component.serialize(s)?;
self.encode_uri.serialize(s)?;
self.encode_uri_component.serialize(s)?;
Ok(())
}
}

impl crate::snapshot::Deserialize for UriFunctions {
fn deserialize(
_d: &mut crate::snapshot::SnapshotDeserializer<'_>,
) -> crate::snapshot::SnapshotResult<Self> {
todo!()
}
}

impl Default for UriFunctions {
fn default() -> Self {
Self {
Expand Down
Loading