0
0
Fork 0
mirror of https://github.com/denoland/deno.git synced 2025-03-03 09:31:22 -05:00

refactor: remove core/libdeno.rs (#3611)

This commit is contained in:
Bartek Iwańczuk 2020-01-06 20:07:35 +01:00 committed by GitHub
parent 29df272133
commit 8bf383710f
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
8 changed files with 645 additions and 766 deletions

View file

@ -1,22 +1,226 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
#![allow(mutable_transmutes)]
#![allow(clippy::transmute_ptr_to_ptr)]
use crate::isolate::DenoBuf;
use crate::isolate::Isolate;
use crate::libdeno::deno_buf;
use crate::libdeno::script_origin;
use crate::libdeno::PinnedBuf;
use crate::isolate::PinnedBuf;
use crate::isolate::ResolveContext;
use rusty_v8 as v8;
use v8::InIsolate;
use libc::c_char;
use libc::c_void;
use std::convert::TryFrom;
use std::ffi::CString;
use std::option::Option;
lazy_static! {
pub static ref EXTERNAL_REFERENCES: v8::ExternalReferences =
v8::ExternalReferences::new(&[
v8::ExternalReference { function: print },
v8::ExternalReference { function: recv },
v8::ExternalReference { function: send },
v8::ExternalReference {
function: eval_context
},
v8::ExternalReference {
function: error_to_json
},
v8::ExternalReference {
getter: shared_getter
},
v8::ExternalReference {
message: message_callback
},
v8::ExternalReference {
function: queue_microtask
},
]);
}
pub fn script_origin<'a>(
s: &mut impl v8::ToLocal<'a>,
resource_name: v8::Local<'a, v8::String>,
) -> v8::ScriptOrigin<'a> {
let resource_line_offset = v8::Integer::new(s, 0);
let resource_column_offset = v8::Integer::new(s, 0);
let resource_is_shared_cross_origin = v8::Boolean::new(s, false);
let script_id = v8::Integer::new(s, 123);
let source_map_url = v8::String::new(s, "source_map_url").unwrap();
let resource_is_opaque = v8::Boolean::new(s, true);
let is_wasm = v8::Boolean::new(s, false);
let is_module = v8::Boolean::new(s, false);
v8::ScriptOrigin::new(
resource_name.into(),
resource_line_offset,
resource_column_offset,
resource_is_shared_cross_origin,
script_id,
source_map_url.into(),
resource_is_opaque,
is_wasm,
is_module,
)
}
pub fn module_origin<'a>(
s: &mut impl v8::ToLocal<'a>,
resource_name: v8::Local<'a, v8::String>,
) -> v8::ScriptOrigin<'a> {
let resource_line_offset = v8::Integer::new(s, 0);
let resource_column_offset = v8::Integer::new(s, 0);
let resource_is_shared_cross_origin = v8::Boolean::new(s, false);
let script_id = v8::Integer::new(s, 123);
let source_map_url = v8::String::new(s, "source_map_url").unwrap();
let resource_is_opaque = v8::Boolean::new(s, true);
let is_wasm = v8::Boolean::new(s, false);
let is_module = v8::Boolean::new(s, true);
v8::ScriptOrigin::new(
resource_name.into(),
resource_line_offset,
resource_column_offset,
resource_is_shared_cross_origin,
script_id,
source_map_url.into(),
resource_is_opaque,
is_wasm,
is_module,
)
}
pub fn initialize_context<'a>(
scope: &mut impl v8::ToLocal<'a>,
mut context: v8::Local<v8::Context>,
) {
context.enter();
let global = context.global(scope);
let deno_val = v8::Object::new(scope);
global.set(
context,
v8::String::new(scope, "Deno").unwrap().into(),
deno_val.into(),
);
let mut core_val = v8::Object::new(scope);
deno_val.set(
context,
v8::String::new(scope, "core").unwrap().into(),
core_val.into(),
);
let mut print_tmpl = v8::FunctionTemplate::new(scope, print);
let print_val = print_tmpl.get_function(scope, context).unwrap();
core_val.set(
context,
v8::String::new(scope, "print").unwrap().into(),
print_val.into(),
);
let mut recv_tmpl = v8::FunctionTemplate::new(scope, recv);
let recv_val = recv_tmpl.get_function(scope, context).unwrap();
core_val.set(
context,
v8::String::new(scope, "recv").unwrap().into(),
recv_val.into(),
);
let mut send_tmpl = v8::FunctionTemplate::new(scope, send);
let send_val = send_tmpl.get_function(scope, context).unwrap();
core_val.set(
context,
v8::String::new(scope, "send").unwrap().into(),
send_val.into(),
);
let mut eval_context_tmpl = v8::FunctionTemplate::new(scope, eval_context);
let eval_context_val =
eval_context_tmpl.get_function(scope, context).unwrap();
core_val.set(
context,
v8::String::new(scope, "evalContext").unwrap().into(),
eval_context_val.into(),
);
let mut error_to_json_tmpl = v8::FunctionTemplate::new(scope, error_to_json);
let error_to_json_val =
error_to_json_tmpl.get_function(scope, context).unwrap();
core_val.set(
context,
v8::String::new(scope, "errorToJSON").unwrap().into(),
error_to_json_val.into(),
);
core_val.set_accessor(
context,
v8::String::new(scope, "shared").unwrap().into(),
shared_getter,
);
// Direct bindings on `window`.
let mut queue_microtask_tmpl =
v8::FunctionTemplate::new(scope, queue_microtask);
let queue_microtask_val =
queue_microtask_tmpl.get_function(scope, context).unwrap();
global.set(
context,
v8::String::new(scope, "queueMicrotask").unwrap().into(),
queue_microtask_val.into(),
);
context.exit();
}
pub unsafe fn buf_to_uint8array<'sc>(
scope: &mut impl v8::ToLocal<'sc>,
buf: DenoBuf,
) -> v8::Local<'sc, v8::Uint8Array> {
if buf.data_ptr.is_null() {
let ab = v8::ArrayBuffer::new(scope, 0);
return v8::Uint8Array::new(ab, 0, 0).expect("Failed to create UintArray8");
}
/*
// To avoid excessively allocating new ArrayBuffers, we try to reuse a single
// global ArrayBuffer. The caveat is that users must extract data from it
// before the next tick. We only do this for ArrayBuffers less than 1024
// bytes.
v8::Local<v8::ArrayBuffer> ab;
void* data;
if (buf.data_len > GLOBAL_IMPORT_BUF_SIZE) {
// Simple case. We allocate a new ArrayBuffer for this.
ab = v8::ArrayBuffer::New(d->isolate_, buf.data_len);
data = ab->GetBackingStore()->Data();
} else {
// Fast case. We reuse the global ArrayBuffer.
if (d->global_import_buf_.IsEmpty()) {
// Lazily initialize it.
DCHECK_NULL(d->global_import_buf_ptr_);
ab = v8::ArrayBuffer::New(d->isolate_, GLOBAL_IMPORT_BUF_SIZE);
d->global_import_buf_.Reset(d->isolate_, ab);
d->global_import_buf_ptr_ = ab->GetBackingStore()->Data();
} else {
DCHECK(d->global_import_buf_ptr_);
ab = d->global_import_buf_.Get(d->isolate_);
}
data = d->global_import_buf_ptr_;
}
memcpy(data, buf.data_ptr, buf.data_len);
auto view = v8::Uint8Array::New(ab, 0, buf.data_len);
return view;
*/
// TODO(bartlomieju): for now skipping part with `global_import_buf_`
// and always creating new buffer
let ab = v8::ArrayBuffer::new(scope, buf.data_len);
let mut backing_store = ab.get_backing_store();
let data = backing_store.data();
let data: *mut u8 = data as *mut libc::c_void as *mut u8;
std::ptr::copy_nonoverlapping(buf.data_ptr, data, buf.data_len);
v8::Uint8Array::new(ab, 0, buf.data_len).expect("Failed to create UintArray8")
}
pub extern "C" fn host_import_module_dynamically_callback(
context: v8::Local<v8::Context>,
referrer: v8::Local<v8::ScriptOrModule>,
@ -52,10 +256,10 @@ pub extern "C" fn host_import_module_dynamically_callback(
let mut resolver_handle = v8::Global::new();
resolver_handle.set(scope, resolver);
let import_id = deno_isolate.next_dyn_import_id_;
deno_isolate.next_dyn_import_id_ += 1;
let import_id = deno_isolate.next_dyn_import_id;
deno_isolate.next_dyn_import_id += 1;
deno_isolate
.dyn_import_map_
.dyn_import_map
.insert(import_id, resolver_handle);
deno_isolate.dyn_import_cb(&specifier_str, &referrer_name_str, import_id);
@ -104,8 +308,8 @@ pub extern "C" fn message_callback(
let mut locker = v8::Locker::new(isolate);
let mut hs = v8::HandleScope::new(&mut locker);
let scope = hs.enter();
assert!(!deno_isolate.context_.is_empty());
let context = deno_isolate.context_.get(scope).unwrap();
assert!(!deno_isolate.global_context.is_empty());
let context = deno_isolate.global_context.get(scope).unwrap();
// TerminateExecution was called
if isolate.is_execution_terminating() {
@ -115,7 +319,7 @@ pub extern "C" fn message_callback(
}
let json_str = deno_isolate.encode_message_as_json(scope, context, message);
deno_isolate.last_exception_ = Some(json_str);
deno_isolate.last_exception = Some(json_str);
}
pub extern "C" fn promise_reject_callback(msg: v8::PromiseRejectMessage) {
@ -125,10 +329,10 @@ pub extern "C" fn promise_reject_callback(msg: v8::PromiseRejectMessage) {
let deno_isolate: &mut Isolate =
unsafe { &mut *(isolate.get_data(0) as *mut Isolate) };
let mut locker = v8::Locker::new(isolate);
assert!(!deno_isolate.context_.is_empty());
assert!(!deno_isolate.global_context.is_empty());
let mut hs = v8::HandleScope::new(&mut locker);
let scope = hs.enter();
let mut context = deno_isolate.context_.get(scope).unwrap();
let mut context = deno_isolate.global_context.get(scope).unwrap();
context.enter();
let promise = msg.get_promise();
@ -140,12 +344,12 @@ pub extern "C" fn promise_reject_callback(msg: v8::PromiseRejectMessage) {
let mut error_global = v8::Global::<v8::Value>::new();
error_global.set(scope, error);
deno_isolate
.pending_promise_map_
.pending_promise_map
.insert(promise_id, error_global);
}
v8::PromiseRejectEvent::PromiseHandlerAddedAfterReject => {
if let Some(mut handle) =
deno_isolate.pending_promise_map_.remove(&promise_id)
deno_isolate.pending_promise_map.remove(&promise_id)
{
handle.reset(scope);
}
@ -160,6 +364,8 @@ pub extern "C" fn promise_reject_callback(msg: v8::PromiseRejectMessage) {
}
pub extern "C" fn print(info: &v8::FunctionCallbackInfo) {
#[allow(mutable_transmutes)]
#[allow(clippy::transmute_ptr_to_ptr)]
let info: &mut v8::FunctionCallbackInfo =
unsafe { std::mem::transmute(info) };
@ -205,7 +411,7 @@ pub extern "C" fn recv(info: &v8::FunctionCallbackInfo) {
let mut hs = v8::HandleScope::new(&mut locker);
let scope = hs.enter();
if !deno_isolate.recv_.is_empty() {
if !deno_isolate.js_recv_cb.is_empty() {
let msg = v8::String::new(scope, "Deno.core.recv already called.").unwrap();
isolate.throw_exception(msg.into());
return;
@ -213,7 +419,7 @@ pub extern "C" fn recv(info: &v8::FunctionCallbackInfo) {
let recv_fn =
v8::Local::<v8::Function>::try_from(info.get_argument(0)).unwrap();
deno_isolate.recv_.set(scope, recv_fn);
deno_isolate.js_recv_cb.set(scope, recv_fn);
}
pub extern "C" fn send(info: &v8::FunctionCallbackInfo) {
@ -227,7 +433,7 @@ pub extern "C" fn send(info: &v8::FunctionCallbackInfo) {
let isolate = scope.isolate();
let deno_isolate: &mut Isolate =
unsafe { &mut *(isolate.get_data(0) as *mut Isolate) };
assert!(!deno_isolate.context_.is_empty());
assert!(!deno_isolate.global_context.is_empty());
let op_id = v8::Local::<v8::Uint32>::try_from(info.get_argument(0))
.unwrap()
@ -240,28 +446,25 @@ pub extern "C" fn send(info: &v8::FunctionCallbackInfo) {
let backing_store_ptr = backing_store.data() as *mut _ as *mut u8;
let view_ptr = unsafe { backing_store_ptr.add(view.byte_offset()) };
let view_len = view.byte_length();
unsafe { deno_buf::from_raw_parts(view_ptr, view_len) }
unsafe { DenoBuf::from_raw_parts(view_ptr, view_len) }
})
.unwrap_or_else(|_| deno_buf::empty());
.unwrap_or_else(|_| DenoBuf::empty());
let zero_copy: Option<PinnedBuf> =
v8::Local::<v8::ArrayBufferView>::try_from(info.get_argument(2))
.map(PinnedBuf::new)
.ok();
// TODO: what's the point of this again?
// DCHECK_NULL(d->current_args_);
// d->current_args_ = &args;
assert!(deno_isolate.current_args_.is_null());
deno_isolate.current_args_ = info;
assert!(deno_isolate.current_send_cb_info.is_null());
deno_isolate.current_send_cb_info = info;
deno_isolate.pre_dispatch(op_id, control, zero_copy);
if deno_isolate.current_args_.is_null() {
// This indicates that deno_repond() was called already.
if deno_isolate.current_send_cb_info.is_null() {
// This indicates that respond() was called already.
} else {
// Asynchronous.
deno_isolate.current_args_ = std::ptr::null();
deno_isolate.current_send_cb_info = std::ptr::null();
}
}
@ -279,8 +482,8 @@ pub extern "C" fn eval_context(info: &v8::FunctionCallbackInfo) {
let isolate = scope.isolate();
let deno_isolate: &mut Isolate =
unsafe { &mut *(isolate.get_data(0) as *mut Isolate) };
assert!(!deno_isolate.context_.is_empty());
let context = deno_isolate.context_.get(scope).unwrap();
assert!(!deno_isolate.global_context.is_empty());
let context = deno_isolate.global_context.get(scope).unwrap();
let source = match v8::Local::<v8::String>::try_from(arg0) {
Ok(s) => s,
@ -414,10 +617,10 @@ pub extern "C" fn error_to_json(info: &v8::FunctionCallbackInfo) {
let deno_isolate: &mut Isolate =
unsafe { &mut *(isolate.get_data(0) as *mut Isolate) };
let mut locker = v8::Locker::new(&isolate);
assert!(!deno_isolate.context_.is_empty());
assert!(!deno_isolate.global_context.is_empty());
let mut hs = v8::HandleScope::new(&mut locker);
let scope = hs.enter();
let context = deno_isolate.context_.get(scope).unwrap();
let context = deno_isolate.global_context.get(scope).unwrap();
// </Boilerplate>
let exception = info.get_argument(0);
let json_string =
@ -465,27 +668,27 @@ pub extern "C" fn shared_getter(
let deno_isolate: &mut Isolate =
unsafe { &mut *(isolate.get_data(0) as *mut Isolate) };
if deno_isolate.shared_.data_ptr.is_null() {
if deno_isolate.shared_buf.data_ptr.is_null() {
return;
}
// Lazily initialize the persistent external ArrayBuffer.
if deno_isolate.shared_ab_.is_empty() {
if deno_isolate.shared_ab.is_empty() {
#[allow(mutable_transmutes)]
#[allow(clippy::transmute_ptr_to_ptr)]
let data_ptr: *mut u8 =
unsafe { std::mem::transmute(deno_isolate.shared_.data_ptr) };
unsafe { std::mem::transmute(deno_isolate.shared_buf.data_ptr) };
let ab = unsafe {
v8::SharedArrayBuffer::new_DEPRECATED(
scope,
data_ptr as *mut c_void,
deno_isolate.shared_.data_len,
deno_isolate.shared_buf.data_len,
)
};
deno_isolate.shared_ab_.set(scope, ab);
deno_isolate.shared_ab.set(scope, ab);
}
let shared_ab = deno_isolate.shared_ab_.get(scope).unwrap();
let shared_ab = deno_isolate.shared_ab.get(scope).unwrap();
scope.escape(shared_ab)
};
@ -521,12 +724,9 @@ pub fn module_resolve_callback(
let req_str = req.to_rust_string_lossy(scope);
if req_str == specifier_str {
let resolve_cb = deno_isolate.resolve_cb_.unwrap();
let c_str = CString::new(req_str.to_string()).unwrap();
let c_req_str: *const c_char = c_str.as_ptr() as *const c_char;
let id = unsafe {
resolve_cb(deno_isolate.resolve_context_, c_req_str, referrer_id)
};
let ResolveContext { resolve_fn } =
unsafe { ResolveContext::from_raw_ptr(deno_isolate.resolve_context) };
let id = resolve_fn(&req_str, referrer_id);
let maybe_info = deno_isolate.get_module_info(id);
if maybe_info.is_none() {

File diff suppressed because it is too large Load diff

View file

@ -16,7 +16,6 @@ mod bindings;
mod flags;
mod isolate;
mod js_errors;
mod libdeno;
mod module_specifier;
mod modules;
mod ops;
@ -30,9 +29,6 @@ pub use crate::any_error::*;
pub use crate::flags::v8_set_flags;
pub use crate::isolate::*;
pub use crate::js_errors::*;
pub use crate::libdeno::deno_mod;
pub use crate::libdeno::OpId;
pub use crate::libdeno::PinnedBuf;
pub use crate::module_specifier::*;
pub use crate::modules::*;
pub use crate::ops::*;

View file

@ -1,449 +0,0 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
#![allow(mutable_transmutes)]
#![allow(clippy::transmute_ptr_to_ptr)]
use crate::bindings;
use rusty_v8 as v8;
use libc::c_char;
use libc::c_void;
use std::convert::From;
use std::marker::PhantomData;
use std::ops::{Deref, DerefMut};
use std::ptr::null;
use std::ptr::NonNull;
use std::slice;
pub type OpId = u32;
pub struct ModuleInfo {
pub main: bool,
pub name: String,
pub handle: v8::Global<v8::Module>,
pub import_specifiers: Vec<String>,
}
pub fn script_origin<'a>(
s: &mut impl v8::ToLocal<'a>,
resource_name: v8::Local<'a, v8::String>,
) -> v8::ScriptOrigin<'a> {
let resource_line_offset = v8::Integer::new(s, 0);
let resource_column_offset = v8::Integer::new(s, 0);
let resource_is_shared_cross_origin = v8::Boolean::new(s, false);
let script_id = v8::Integer::new(s, 123);
let source_map_url = v8::String::new(s, "source_map_url").unwrap();
let resource_is_opaque = v8::Boolean::new(s, true);
let is_wasm = v8::Boolean::new(s, false);
let is_module = v8::Boolean::new(s, false);
v8::ScriptOrigin::new(
resource_name.into(),
resource_line_offset,
resource_column_offset,
resource_is_shared_cross_origin,
script_id,
source_map_url.into(),
resource_is_opaque,
is_wasm,
is_module,
)
}
pub fn module_origin<'a>(
s: &mut impl v8::ToLocal<'a>,
resource_name: v8::Local<'a, v8::String>,
) -> v8::ScriptOrigin<'a> {
let resource_line_offset = v8::Integer::new(s, 0);
let resource_column_offset = v8::Integer::new(s, 0);
let resource_is_shared_cross_origin = v8::Boolean::new(s, false);
let script_id = v8::Integer::new(s, 123);
let source_map_url = v8::String::new(s, "source_map_url").unwrap();
let resource_is_opaque = v8::Boolean::new(s, true);
let is_wasm = v8::Boolean::new(s, false);
let is_module = v8::Boolean::new(s, true);
v8::ScriptOrigin::new(
resource_name.into(),
resource_line_offset,
resource_column_offset,
resource_is_shared_cross_origin,
script_id,
source_map_url.into(),
resource_is_opaque,
is_wasm,
is_module,
)
}
/// This type represents a borrowed slice.
#[repr(C)]
pub struct deno_buf {
pub data_ptr: *const u8,
pub data_len: usize,
}
/// `deno_buf` can not clone, and there is no interior mutability.
/// This type satisfies Send bound.
unsafe impl Send for deno_buf {}
impl deno_buf {
#[inline]
pub fn empty() -> Self {
Self {
data_ptr: null(),
data_len: 0,
}
}
#[inline]
pub unsafe fn from_raw_parts(ptr: *const u8, len: usize) -> Self {
Self {
data_ptr: ptr,
data_len: len,
}
}
}
/// Converts Rust &Buf to libdeno `deno_buf`.
impl<'a> From<&'a [u8]> for deno_buf {
#[inline]
fn from(x: &'a [u8]) -> Self {
Self {
data_ptr: x.as_ref().as_ptr(),
data_len: x.len(),
}
}
}
impl<'a> From<&'a mut [u8]> for deno_buf {
#[inline]
fn from(x: &'a mut [u8]) -> Self {
Self {
data_ptr: x.as_ref().as_ptr(),
data_len: x.len(),
}
}
}
impl Deref for deno_buf {
type Target = [u8];
#[inline]
fn deref(&self) -> &[u8] {
unsafe { std::slice::from_raw_parts(self.data_ptr, self.data_len) }
}
}
impl AsRef<[u8]> for deno_buf {
#[inline]
fn as_ref(&self) -> &[u8] {
&*self
}
}
/// A PinnedBuf encapsulates a slice that's been borrowed from a JavaScript
/// ArrayBuffer object. JavaScript objects can normally be garbage collected,
/// but the existence of a PinnedBuf inhibits this until it is dropped. It
/// behaves much like an Arc<[u8]>, although a PinnedBuf currently can't be
/// cloned.
#[allow(unused)]
pub struct PinnedBuf {
data_ptr: NonNull<u8>,
data_len: usize,
backing_store: v8::SharedRef<v8::BackingStore>,
}
unsafe impl Send for PinnedBuf {}
impl PinnedBuf {
pub fn new(view: v8::Local<v8::ArrayBufferView>) -> Self {
let mut backing_store = view.buffer().unwrap().get_backing_store();
let backing_store_ptr = backing_store.data() as *mut _ as *mut u8;
let view_ptr = unsafe { backing_store_ptr.add(view.byte_offset()) };
let view_len = view.byte_length();
Self {
data_ptr: NonNull::new(view_ptr).unwrap(),
data_len: view_len,
backing_store,
}
}
}
impl Deref for PinnedBuf {
type Target = [u8];
fn deref(&self) -> &[u8] {
unsafe { slice::from_raw_parts(self.data_ptr.as_ptr(), self.data_len) }
}
}
impl DerefMut for PinnedBuf {
fn deref_mut(&mut self) -> &mut [u8] {
unsafe { slice::from_raw_parts_mut(self.data_ptr.as_ptr(), self.data_len) }
}
}
impl AsRef<[u8]> for PinnedBuf {
fn as_ref(&self) -> &[u8] {
&*self
}
}
impl AsMut<[u8]> for PinnedBuf {
fn as_mut(&mut self) -> &mut [u8] {
&mut *self
}
}
#[repr(C)]
#[allow(unused)]
pub struct deno_snapshot<'a> {
pub data_ptr: *const u8,
pub data_len: usize,
_marker: PhantomData<&'a [u8]>,
}
/// `deno_snapshot` can not clone, and there is no interior mutability.
/// This type satisfies Send bound.
unsafe impl Send for deno_snapshot<'_> {}
// TODO(ry) Snapshot1 and Snapshot2 are not very good names and need to be
// reconsidered. The entire snapshotting interface is still under construction.
/// The type returned from deno_snapshot_new. Needs to be dropped.
pub type Snapshot1 = v8::OwnedStartupData;
#[allow(non_camel_case_types)]
pub type deno_mod = i32;
#[allow(non_camel_case_types)]
pub type deno_dyn_import_id = i32;
#[allow(non_camel_case_types)]
pub type deno_resolve_cb = unsafe extern "C" fn(
resolve_context: *mut c_void,
specifier: *const c_char,
referrer: deno_mod,
) -> deno_mod;
pub enum SnapshotConfig {
Borrowed(v8::StartupData<'static>),
Owned(v8::OwnedStartupData),
}
impl From<&'static [u8]> for SnapshotConfig {
fn from(sd: &'static [u8]) -> Self {
Self::Borrowed(v8::StartupData::new(sd))
}
}
impl From<v8::OwnedStartupData> for SnapshotConfig {
fn from(sd: v8::OwnedStartupData) -> Self {
Self::Owned(sd)
}
}
impl Deref for SnapshotConfig {
type Target = v8::StartupData<'static>;
fn deref(&self) -> &Self::Target {
match self {
Self::Borrowed(sd) => sd,
Self::Owned(sd) => &*sd,
}
}
}
pub unsafe fn deno_init() {
let platform = v8::platform::new_default_platform();
v8::V8::initialize_platform(platform);
v8::V8::initialize();
// TODO(ry) This makes WASM compile synchronously. Eventually we should
// remove this to make it work asynchronously too. But that requires getting
// PumpMessageLoop and RunMicrotasks setup correctly.
// See https://github.com/denoland/deno/issues/2544
let argv = vec![
"".to_string(),
"--no-wasm-async-compilation".to_string(),
"--harmony-top-level-await".to_string(),
];
v8::V8::set_flags_from_command_line(argv);
}
lazy_static! {
pub static ref EXTERNAL_REFERENCES: v8::ExternalReferences =
v8::ExternalReferences::new(&[
v8::ExternalReference {
function: bindings::print
},
v8::ExternalReference {
function: bindings::recv
},
v8::ExternalReference {
function: bindings::send
},
v8::ExternalReference {
function: bindings::eval_context
},
v8::ExternalReference {
function: bindings::error_to_json
},
v8::ExternalReference {
getter: bindings::shared_getter
},
v8::ExternalReference {
message: bindings::message_callback
},
v8::ExternalReference {
function: bindings::queue_microtask
},
]);
}
pub fn initialize_context<'a>(
scope: &mut impl v8::ToLocal<'a>,
mut context: v8::Local<v8::Context>,
) {
context.enter();
let global = context.global(scope);
let deno_val = v8::Object::new(scope);
global.set(
context,
v8::String::new(scope, "Deno").unwrap().into(),
deno_val.into(),
);
let mut core_val = v8::Object::new(scope);
deno_val.set(
context,
v8::String::new(scope, "core").unwrap().into(),
core_val.into(),
);
let mut print_tmpl = v8::FunctionTemplate::new(scope, bindings::print);
let print_val = print_tmpl.get_function(scope, context).unwrap();
core_val.set(
context,
v8::String::new(scope, "print").unwrap().into(),
print_val.into(),
);
let mut recv_tmpl = v8::FunctionTemplate::new(scope, bindings::recv);
let recv_val = recv_tmpl.get_function(scope, context).unwrap();
core_val.set(
context,
v8::String::new(scope, "recv").unwrap().into(),
recv_val.into(),
);
let mut send_tmpl = v8::FunctionTemplate::new(scope, bindings::send);
let send_val = send_tmpl.get_function(scope, context).unwrap();
core_val.set(
context,
v8::String::new(scope, "send").unwrap().into(),
send_val.into(),
);
let mut eval_context_tmpl =
v8::FunctionTemplate::new(scope, bindings::eval_context);
let eval_context_val =
eval_context_tmpl.get_function(scope, context).unwrap();
core_val.set(
context,
v8::String::new(scope, "evalContext").unwrap().into(),
eval_context_val.into(),
);
let mut error_to_json_tmpl =
v8::FunctionTemplate::new(scope, bindings::error_to_json);
let error_to_json_val =
error_to_json_tmpl.get_function(scope, context).unwrap();
core_val.set(
context,
v8::String::new(scope, "errorToJSON").unwrap().into(),
error_to_json_val.into(),
);
core_val.set_accessor(
context,
v8::String::new(scope, "shared").unwrap().into(),
bindings::shared_getter,
);
// Direct bindings on `window`.
let mut queue_microtask_tmpl =
v8::FunctionTemplate::new(scope, bindings::queue_microtask);
let queue_microtask_val =
queue_microtask_tmpl.get_function(scope, context).unwrap();
global.set(
context,
v8::String::new(scope, "queueMicrotask").unwrap().into(),
queue_microtask_val.into(),
);
context.exit();
}
pub unsafe fn deno_import_buf<'sc>(
scope: &mut impl v8::ToLocal<'sc>,
buf: deno_buf,
) -> v8::Local<'sc, v8::Uint8Array> {
/*
if (buf.data_ptr == nullptr) {
return v8::Local<v8::Uint8Array>();
}
*/
if buf.data_ptr.is_null() {
let ab = v8::ArrayBuffer::new(scope, 0);
return v8::Uint8Array::new(ab, 0, 0).expect("Failed to create UintArray8");
}
/*
// To avoid excessively allocating new ArrayBuffers, we try to reuse a single
// global ArrayBuffer. The caveat is that users must extract data from it
// before the next tick. We only do this for ArrayBuffers less than 1024
// bytes.
v8::Local<v8::ArrayBuffer> ab;
void* data;
if (buf.data_len > GLOBAL_IMPORT_BUF_SIZE) {
// Simple case. We allocate a new ArrayBuffer for this.
ab = v8::ArrayBuffer::New(d->isolate_, buf.data_len);
data = ab->GetBackingStore()->Data();
} else {
// Fast case. We reuse the global ArrayBuffer.
if (d->global_import_buf_.IsEmpty()) {
// Lazily initialize it.
DCHECK_NULL(d->global_import_buf_ptr_);
ab = v8::ArrayBuffer::New(d->isolate_, GLOBAL_IMPORT_BUF_SIZE);
d->global_import_buf_.Reset(d->isolate_, ab);
d->global_import_buf_ptr_ = ab->GetBackingStore()->Data();
} else {
DCHECK(d->global_import_buf_ptr_);
ab = d->global_import_buf_.Get(d->isolate_);
}
data = d->global_import_buf_ptr_;
}
memcpy(data, buf.data_ptr, buf.data_len);
auto view = v8::Uint8Array::New(ab, 0, buf.data_len);
return view;
*/
// TODO(bartlomieju): for now skipping part with `global_import_buf_`
// and always creating new buffer
let ab = v8::ArrayBuffer::new(scope, buf.data_len);
let mut backing_store = ab.get_backing_store();
let data = backing_store.data();
let data: *mut u8 = data as *mut libc::c_void as *mut u8;
std::ptr::copy_nonoverlapping(buf.data_ptr, data, buf.data_len);
v8::Uint8Array::new(ab, 0, buf.data_len).expect("Failed to create UintArray8")
}
/*
#[allow(dead_code)]
pub unsafe fn deno_snapshot_delete(s: &mut deno_snapshot) {
todo!()
}
*/

View file

@ -7,12 +7,12 @@
// synchronously. The isolate.rs module should never depend on this module.
use crate::any_error::ErrBox;
use crate::isolate::DynImportId;
use crate::isolate::ImportStream;
use crate::isolate::Isolate;
use crate::isolate::ModuleId;
use crate::isolate::RecursiveLoadEvent as Event;
use crate::isolate::SourceCodeInfo;
use crate::libdeno::deno_dyn_import_id;
use crate::libdeno::deno_mod;
use crate::module_specifier::ModuleSpecifier;
use futures::future::FutureExt;
use futures::stream::FuturesUnordered;
@ -55,7 +55,7 @@ pub trait Loader: Send + Sync {
#[derive(Debug, Eq, PartialEq)]
enum Kind {
Main,
DynamicImport(deno_dyn_import_id),
DynamicImport(DynImportId),
}
#[derive(Debug, Eq, PartialEq)]
@ -63,8 +63,8 @@ enum State {
ResolveMain(String, Option<String>), // specifier, maybe code
ResolveImport(String, String), // specifier, referrer
LoadingRoot,
LoadingImports(deno_mod),
Instantiated(deno_mod),
LoadingImports(ModuleId),
Instantiated(ModuleId),
}
/// This future is used to implement parallel async module loading without
@ -93,7 +93,7 @@ impl<L: Loader + Unpin> RecursiveLoad<L> {
}
pub fn dynamic_import(
id: deno_dyn_import_id,
id: DynImportId,
specifier: &str,
referrer: &str,
loader: L,
@ -104,7 +104,7 @@ impl<L: Loader + Unpin> RecursiveLoad<L> {
Self::new(kind, state, loader, modules)
}
pub fn dyn_import_id(&self) -> Option<deno_dyn_import_id> {
pub fn dyn_import_id(&self) -> Option<DynImportId> {
match self.kind {
Kind::Main => None,
Kind::DynamicImport(id) => Some(id),
@ -165,7 +165,7 @@ impl<L: Loader + Unpin> RecursiveLoad<L> {
&mut self,
specifier: &str,
referrer: &str,
parent_id: deno_mod,
parent_id: ModuleId,
) -> Result<(), ErrBox> {
let referrer_specifier = ModuleSpecifier::resolve_url(referrer)
.expect("Referrer should be a valid specifier");
@ -199,7 +199,7 @@ impl<L: Loader + Unpin> RecursiveLoad<L> {
pub fn get_future(
self,
isolate: Arc<Mutex<Box<Isolate>>>,
) -> impl Future<Output = Result<deno_mod, ErrBox>> {
) -> impl Future<Output = Result<ModuleId, ErrBox>> {
async move {
let mut load = self;
loop {
@ -287,7 +287,7 @@ impl<L: Loader + Unpin> ImportStream for RecursiveLoad<L> {
};
let mut resolve_cb =
|specifier: &str, referrer_id: deno_mod| -> deno_mod {
|specifier: &str, referrer_id: ModuleId| -> ModuleId {
let modules = self.modules.lock().unwrap();
let referrer = modules.get_name(referrer_id).unwrap();
match self.loader.resolve(
@ -376,7 +376,7 @@ enum SymbolicModule {
/// the same underlying module (particularly due to redirects).
Alias(String),
/// This module associates with a V8 module by id.
Mod(deno_mod),
Mod(ModuleId),
}
#[derive(Default)]
@ -395,7 +395,7 @@ impl ModuleNameMap {
/// Get the id of a module.
/// If this module is internally represented as an alias,
/// follow the alias chain to get the final module id.
pub fn get(&self, name: &str) -> Option<deno_mod> {
pub fn get(&self, name: &str) -> Option<ModuleId> {
let mut mod_name = name;
loop {
let cond = self.inner.get(mod_name);
@ -414,7 +414,7 @@ impl ModuleNameMap {
}
/// Insert a name assocated module id.
pub fn insert(&mut self, name: String, id: deno_mod) {
pub fn insert(&mut self, name: String, id: ModuleId) {
self.inner.insert(name, SymbolicModule::Mod(id));
}
@ -436,7 +436,7 @@ impl ModuleNameMap {
/// A collection of JS modules.
#[derive(Default)]
pub struct Modules {
info: HashMap<deno_mod, ModuleInfo>,
info: HashMap<ModuleId, ModuleInfo>,
by_name: ModuleNameMap,
}
@ -448,11 +448,11 @@ impl Modules {
}
}
pub fn get_id(&self, name: &str) -> Option<deno_mod> {
pub fn get_id(&self, name: &str) -> Option<ModuleId> {
self.by_name.get(name)
}
pub fn get_children(&self, id: deno_mod) -> Option<&Vec<String>> {
pub fn get_children(&self, id: ModuleId) -> Option<&Vec<String>> {
self.info.get(&id).map(|i| &i.children)
}
@ -460,7 +460,7 @@ impl Modules {
self.get_id(name).and_then(|id| self.get_children(id))
}
pub fn get_name(&self, id: deno_mod) -> Option<&String> {
pub fn get_name(&self, id: ModuleId) -> Option<&String> {
self.info.get(&id).map(|i| &i.name)
}
@ -468,7 +468,7 @@ impl Modules {
self.by_name.get(name).is_some()
}
pub fn add_child(&mut self, parent_id: deno_mod, child_name: &str) -> bool {
pub fn add_child(&mut self, parent_id: ModuleId, child_name: &str) -> bool {
self
.info
.get_mut(&parent_id)
@ -480,7 +480,7 @@ impl Modules {
.is_some()
}
pub fn register(&mut self, id: deno_mod, name: &str) {
pub fn register(&mut self, id: ModuleId, name: &str) {
let name = String::from(name);
debug!("register_complete {}", name);

View file

@ -1,5 +1,4 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
pub use crate::libdeno::OpId;
use crate::PinnedBuf;
use futures::Future;
use std::collections::HashMap;
@ -7,6 +6,8 @@ use std::pin::Pin;
use std::sync::Arc;
use std::sync::RwLock;
pub type OpId = u32;
pub type Buf = Box<[u8]>;
pub type OpAsyncFuture<E> =

View file

@ -1,4 +1,4 @@
use crate::libdeno::PinnedBuf;
use crate::isolate::PinnedBuf;
use crate::ops::CoreOp;
pub type PluginInitFn = fn(context: &mut dyn PluginInitContext);

View file

@ -16,8 +16,8 @@ SharedQueue Binary Layout
+---------------------------------------------------------------+
*/
use crate::libdeno::deno_buf;
use crate::libdeno::OpId;
use crate::isolate::DenoBuf;
use crate::ops::OpId;
const MAX_RECORDS: usize = 100;
/// Total number of records added.
@ -47,10 +47,10 @@ impl SharedQueue {
q
}
pub fn as_deno_buf(&self) -> deno_buf {
pub fn as_deno_buf(&self) -> DenoBuf {
let ptr = self.bytes.as_ptr();
let len = self.bytes.len();
unsafe { deno_buf::from_raw_parts(ptr, len) }
unsafe { DenoBuf::from_raw_parts(ptr, len) }
}
fn reset(&mut self) {