nova_vm 1.0.0

Nova Virtual Machine
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.

//! ## [25.1 ArrayBuffer Objects](https://tc39.es/ecma262/#sec-arraybuffer-objects)

mod abstract_operations;
mod data;

use std::collections::hash_map::Entry;

pub(crate) use abstract_operations::*;
pub(crate) use data::*;

#[cfg(feature = "shared-array-buffer")]
use super::shared_array_buffer::SharedArrayBuffer;
#[cfg(feature = "shared-array-buffer")]
use crate::ecmascript::types::SHARED_ARRAY_BUFFER_DISCRIMINANT;
use crate::{
    ecmascript::{
        Agent, JsResult, ProtoIntrinsics,
        types::{
            ARRAY_BUFFER_DISCRIMINANT, InternalMethods, InternalSlots, Object, OrdinaryObject,
            Value, Viewable, copy_data_block_bytes, create_byte_data_block,
        },
    },
    engine::{Bindable, HeapRootData, NoGcScope, bindable_handle},
    heap::{
        ArenaAccess, ArenaAccessMut, BaseIndex, CompactionLists, CreateHeapData, Heap,
        HeapIndexHandle, HeapMarkAndSweep, HeapSweepWeakReference, WorkQueues, arena_vec_access,
    },
};

use ecmascript_atomics::Ordering;

/// ## [25.1 ArrayBuffer Objects](https://tc39.es/ecma262/#sec-arraybuffer-objects)
///
/// _ArrayBuffer_ objects are byte buffers that can be allocated and accessed
/// from JavaScript code. An [`ArrayBuffer`] cannot be shared between threads.
/// For shareable memory, see [`SharedArrayBuffer`] objects.
///
/// [`ArrayBuffer`]: ArrayBuffer
/// [`SharedArrayBuffer`]: crate::ecmascript::SharedArrayBuffer
#[derive(Debug, Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Hash)]
#[repr(transparent)]
pub struct ArrayBuffer<'a>(BaseIndex<'a, ArrayBufferHeapData<'static>>);
array_buffer_handle!(ArrayBuffer);
arena_vec_access!(ArrayBuffer, 'a, ArrayBufferHeapData, array_buffers);

impl<'ab> ArrayBuffer<'ab> {
    /// Allocate a new ArrayBuffer with the given byte length.
    pub fn new<'gc>(
        agent: &mut Agent,
        byte_length: usize,
        gc: NoGcScope<'gc, '_>,
    ) -> JsResult<'gc, ArrayBuffer<'gc>> {
        let data_block = create_byte_data_block(agent, byte_length as u64, gc)?;
        let block = data_block;
        Ok(agent
            .heap
            .create(ArrayBufferHeapData::new_fixed_length(block))
            .bind(gc))
    }

    /// Returns `true` if this ArrayBuffer is detached.
    #[inline]
    pub fn is_detached(self, agent: &Agent) -> bool {
        self.get(agent).is_detached()
    }

    /// Returns `true` if this ArrayBuffer has the
    /// \[\[ArrayBufferMaxByteLength]] slot.
    #[inline]
    pub fn is_resizable(self, agent: &Agent) -> bool {
        self.get(agent).is_resizable()
    }

    /// Returns the \[\[ArrayBufferByteLength]] value.
    #[inline]
    pub fn byte_length(self, agent: &Agent) -> usize {
        self.get(agent).byte_length()
    }

    /// Returns the \[\[ArrayBufferMaxByteLength]] value or the
    /// \[\[ArrayBufferByteLength]] value if this ArrayBuffer is not resizable.
    #[inline]
    pub fn max_byte_length(self, agent: &Agent) -> usize {
        self.get(agent).max_byte_length()
    }

    #[inline]
    pub(crate) fn get_detach_key(self, agent: &Agent) -> Option<DetachKey> {
        agent.heap.array_buffer_detach_keys.get(&self).copied()
    }

    /// Set the detach key of an ArrayBuffer if not yet set.
    ///
    /// Attempting to override an already-set key is ignored.
    #[inline]
    pub fn set_detach_key(self, agent: &mut Agent, key: DetachKey) {
        match agent.heap.array_buffer_detach_keys.entry(self.unbind()) {
            Entry::Occupied(_) => {
                // Ignore already-set key.
            }
            Entry::Vacant(e) => {
                // Set the key.
                e.insert(key);
                agent.heap.alloc_counter += core::mem::size_of::<(ArrayBuffer, DetachKey)>();
            }
        }
    }

    /// Detach the ArrayBuffer.
    pub fn detach<'a>(
        self,
        agent: &mut Agent,
        key: Option<DetachKey>,
        gc: NoGcScope<'a, '_>,
    ) -> JsResult<'a, ()> {
        detach_array_buffer(agent, self, key, gc)
    }

    /// Resize a Resizable ArrayBuffer.
    ///
    /// `new_byte_length` must be a safe integer.
    pub(crate) fn resize(self, agent: &mut Agent, new_byte_length: usize) {
        self.get_mut(agent).resize(new_byte_length);
    }

    /// Get temporary access to an ArrayBuffer's backing data block as a slice
    /// of bytes. The access can only be held while all JavaScript is paused.
    ///
    /// ## Safety
    ///
    /// The function itself has no safety implications, but the caller should
    /// keep in mind that if JavaScript is called into the contents of the
    /// ArrayBuffer may be rewritten or reallocated.
    #[inline]
    pub fn as_slice(self, agent: &'ab Agent) -> &'ab [u8] {
        self.get(agent).get_data_block()
    }

    /// Get temporary exclusive access to an ArrayBuffer's backing data block
    /// as a slice of bytes. The access can only be held while all JavaScript
    /// is paused.
    ///
    /// ## Safety
    ///
    /// The function itself has no safety implications, but the caller should
    /// keep in mind that if JavaScript is called into the contents of the
    /// ArrayBuffer may be rewritten or reallocated.
    #[inline]
    pub fn as_mut_slice(self, agent: &'ab mut Agent) -> &'ab mut [u8] {
        self.get_mut(agent).buffer.get_data_block_mut()
    }

    /// Create a T slice from an ArrayBuffer and byte offset and length values.
    ///
    /// This method should be used when looping over items of a TypedArray.
    pub(crate) fn as_viewable_slice<T: Viewable>(
        self,
        agent: &'ab Agent,
        byte_offset: usize,
        byte_length: Option<usize>,
    ) -> &'ab [T] {
        let byte_slice = self.as_slice(agent);
        let byte_limit = byte_length.map(|byte_length| byte_offset.saturating_add(byte_length));
        if byte_limit.unwrap_or(byte_offset) > byte_slice.len() {
            return &[];
        }
        let byte_slice = if let Some(byte_limit) = byte_limit {
            &byte_slice[byte_offset..byte_limit]
        } else {
            &byte_slice[byte_offset..]
        };
        // SAFETY: All bytes in byte_slice are initialized, and all bitwise
        // combinations of T are valid values. Alignment of T's is
        // guaranteed by align_to_mut itself.
        let (head, slice, _) = unsafe { byte_slice.align_to::<T>() };
        if !head.is_empty() {
            panic!("ArrayBuffer is not properly aligned for T");
        }
        slice
    }

    /// Create a T slice from an ArrayBuffer and byte offset and length values.
    ///
    /// This method should be used when looping over items of a TypedArray.
    pub(crate) fn as_mut_viewable_slice<T: Viewable>(
        self,
        agent: &'ab mut Agent,
        byte_offset: usize,
        byte_length: Option<usize>,
    ) -> &'ab mut [T] {
        let byte_slice = self.as_mut_slice(agent);
        let byte_limit = byte_length.map(|byte_length| byte_offset.saturating_add(byte_length));
        if byte_limit.unwrap_or(byte_offset) > byte_slice.len() {
            return &mut [];
        }
        let byte_slice = if let Some(byte_limit) = byte_limit {
            &mut byte_slice[byte_offset..byte_limit]
        } else {
            &mut byte_slice[byte_offset..]
        };
        // SAFETY: All bytes in byte_slice are initialized, and all bitwise
        // combinations of T are valid values. Alignment of T's is
        // guaranteed by align_to_mut itself.
        let (head, slice, _) = unsafe { byte_slice.align_to_mut::<T>() };
        if !head.is_empty() {
            panic!("ArrayBuffer is not properly aligned for T");
        }
        slice
    }

    /// Copy data from `source` ArrayBuffer to this ArrayBuffer.
    ///
    /// `self` and `source` must be different ArrayBuffers.
    pub(crate) fn copy_array_buffer_data(
        self,
        agent: &mut Agent,
        source: ArrayBuffer,
        first: usize,
        count: usize,
    ) {
        debug_assert_ne!(self, source);
        let array_buffers = &mut *agent.heap.array_buffers;
        let (source_data, target_data) = if self.get_index() > source.get_index() {
            let (before, after) = array_buffers.split_at_mut(self.get_index());
            (&before[source.get_index()], &mut after[0])
        } else {
            let (before, after) = array_buffers.split_at_mut(source.get_index());
            (&after[0], &mut before[self.get_index()])
        };
        let source_data = source_data.buffer.get_data_block();
        let target_data = target_data.buffer.get_data_block_mut();
        copy_data_block_bytes(target_data, 0, source_data, first, count);
    }
}

impl<'a> InternalSlots<'a> for ArrayBuffer<'a> {
    const DEFAULT_PROTOTYPE: ProtoIntrinsics = ProtoIntrinsics::ArrayBuffer;

    #[inline(always)]
    fn get_backing_object(self, agent: &Agent) -> Option<OrdinaryObject<'static>> {
        self.get(agent).object_index.unbind()
    }

    fn set_backing_object(self, agent: &mut Agent, backing_object: OrdinaryObject<'static>) {
        assert!(
            self.get_mut(agent)
                .object_index
                .replace(backing_object.unbind())
                .is_none()
        );
    }
}

impl<'a> InternalMethods<'a> for ArrayBuffer<'a> {}

impl HeapMarkAndSweep for ArrayBuffer<'static> {
    fn mark_values(&self, queues: &mut WorkQueues) {
        queues.array_buffers.push(*self);
    }

    fn sweep_values(&mut self, compactions: &CompactionLists) {
        compactions.array_buffers.shift_index(&mut self.0);
    }
}

impl HeapSweepWeakReference for ArrayBuffer<'static> {
    fn sweep_weak_reference(self, compactions: &CompactionLists) -> Option<Self> {
        compactions.array_buffers.shift_weak_index(self.0).map(Self)
    }
}

impl<'a> CreateHeapData<ArrayBufferHeapData<'a>, ArrayBuffer<'a>> for Heap {
    fn create(&mut self, data: ArrayBufferHeapData<'a>) -> ArrayBuffer<'a> {
        self.array_buffers.push(data.unbind());
        self.alloc_counter += core::mem::size_of::<ArrayBufferHeapData<'static>>();
        ArrayBuffer(BaseIndex::last(&self.array_buffers))
    }
}

/// ## [25.1 ArrayBuffer Objects](https://tc39.es/ecma262/#sec-arraybuffer-objects)
///
/// An [`ArrayBuffer`] or [`SharedArrayBuffer`].
///
/// [`ArrayBuffer`]: crate::ecmascript::ArrayBuffer
/// [`SharedArrayBuffer`]: crate::ecmascript::SharedArrayBuffer
#[derive(Debug, Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Hash)]
#[repr(u8)]
pub enum AnyArrayBuffer<'a> {
    /// ## [25.1 ArrayBuffer Objects](https://tc39.es/ecma262/#sec-arraybuffer-objects)
    ArrayBuffer(ArrayBuffer<'a>) = ARRAY_BUFFER_DISCRIMINANT,
    #[cfg(feature = "shared-array-buffer")]
    /// ## [25.2 SharedArrayBuffer Objects](https://tc39.es/ecma262/#sec-sharedarraybuffer-objects)
    SharedArrayBuffer(SharedArrayBuffer<'a>) = SHARED_ARRAY_BUFFER_DISCRIMINANT,
}
bindable_handle!(AnyArrayBuffer);

impl<'ab> AnyArrayBuffer<'ab> {
    /// Returns true if the ArrayBuffer is a SharedArrayBuffer.
    #[inline(always)]
    pub fn is_shared(self) -> bool {
        match self {
            Self::ArrayBuffer(_) => false,
            #[cfg(feature = "shared-array-buffer")]
            Self::SharedArrayBuffer(_) => true,
        }
    }

    /// Returns true if the ArrayBuffer is detached.
    #[inline(always)]
    pub fn is_detached(self, agent: &Agent) -> bool {
        match self {
            Self::ArrayBuffer(ta) => ta.is_detached(agent),
            #[cfg(feature = "shared-array-buffer")]
            Self::SharedArrayBuffer(_) => false,
        }
    }

    /// Returns true if the ArrayBuffer is resizable or growable.
    #[inline(always)]
    pub fn is_resizable(self, agent: &Agent) -> bool {
        match self {
            Self::ArrayBuffer(ta) => ta.is_resizable(agent),
            #[cfg(feature = "shared-array-buffer")]
            Self::SharedArrayBuffer(sta) => sta.is_growable(agent),
        }
    }

    /// \[\[ArrayBufferByteLength]]
    #[inline(always)]
    pub fn byte_length(self, agent: &Agent, order: Ordering) -> usize {
        #[cfg(not(feature = "shared-array-buffer"))]
        let _ = order;
        match self {
            Self::ArrayBuffer(ta) => ta.byte_length(agent),
            #[cfg(feature = "shared-array-buffer")]
            Self::SharedArrayBuffer(sta) => sta.byte_length(agent, order),
        }
    }

    /// \[\[ArrayBufferMaxByteLength]]
    #[inline(always)]
    pub fn max_byte_length(self, agent: &Agent) -> usize {
        match self {
            Self::ArrayBuffer(ta) => ta.max_byte_length(agent),
            #[cfg(feature = "shared-array-buffer")]
            Self::SharedArrayBuffer(sta) => sta.max_byte_length(agent),
        }
    }
}

impl<'a> From<AnyArrayBuffer<'a>> for Object<'a> {
    #[inline(always)]
    fn from(value: AnyArrayBuffer<'a>) -> Self {
        match value {
            AnyArrayBuffer::ArrayBuffer(dv) => Self::ArrayBuffer(dv),
            #[cfg(feature = "shared-array-buffer")]
            AnyArrayBuffer::SharedArrayBuffer(sdv) => Self::SharedArrayBuffer(sdv),
        }
    }
}

impl<'a> From<AnyArrayBuffer<'a>> for Value<'a> {
    #[inline(always)]
    fn from(value: AnyArrayBuffer<'a>) -> Self {
        match value {
            AnyArrayBuffer::ArrayBuffer(dv) => Self::ArrayBuffer(dv),
            #[cfg(feature = "shared-array-buffer")]
            AnyArrayBuffer::SharedArrayBuffer(sdv) => Self::SharedArrayBuffer(sdv),
        }
    }
}

impl<'a> From<AnyArrayBuffer<'a>> for HeapRootData {
    #[inline(always)]
    fn from(value: AnyArrayBuffer<'a>) -> Self {
        match value {
            AnyArrayBuffer::ArrayBuffer(dv) => Self::from(dv),
            #[cfg(feature = "shared-array-buffer")]
            AnyArrayBuffer::SharedArrayBuffer(sdv) => Self::from(sdv),
        }
    }
}

impl<'a> TryFrom<Object<'a>> for AnyArrayBuffer<'a> {
    type Error = ();

    fn try_from(value: Object<'a>) -> Result<Self, Self::Error> {
        match value {
            Object::ArrayBuffer(ab) => Ok(Self::ArrayBuffer(ab)),
            #[cfg(feature = "shared-array-buffer")]
            Object::SharedArrayBuffer(sab) => Ok(Self::SharedArrayBuffer(sab)),
            _ => Err(()),
        }
    }
}

impl<'a> TryFrom<Value<'a>> for AnyArrayBuffer<'a> {
    type Error = ();

    fn try_from(value: Value<'a>) -> Result<Self, Self::Error> {
        match value {
            Value::ArrayBuffer(ab) => Ok(Self::ArrayBuffer(ab)),
            #[cfg(feature = "shared-array-buffer")]
            Value::SharedArrayBuffer(sab) => Ok(Self::SharedArrayBuffer(sab)),
            _ => Err(()),
        }
    }
}

impl TryFrom<HeapRootData> for AnyArrayBuffer<'_> {
    type Error = ();

    #[inline]
    fn try_from(value: HeapRootData) -> Result<Self, Self::Error> {
        match value {
            HeapRootData::ArrayBuffer(dv) => Ok(AnyArrayBuffer::ArrayBuffer(dv)),
            #[cfg(feature = "shared-array-buffer")]
            HeapRootData::SharedArrayBuffer(sdv) => Ok(AnyArrayBuffer::SharedArrayBuffer(sdv)),
            _ => Err(()),
        }
    }
}

macro_rules! array_buffer_handle {
    ($name: ident) => {
        crate::ecmascript::types::object_handle!($name);

        impl<'a> From<$name<'a>> for crate::ecmascript::builtins::array_buffer::AnyArrayBuffer<'a> {
            fn from(value: $name<'a>) -> Self {
                Self::$name(value)
            }
        }

        impl<'a> TryFrom<crate::ecmascript::builtins::array_buffer::AnyArrayBuffer<'a>>
            for $name<'a>
        {
            type Error = ();

            fn try_from(
                value: crate::ecmascript::builtins::array_buffer::AnyArrayBuffer<'a>,
            ) -> Result<Self, Self::Error> {
                match value {
                    crate::ecmascript::builtins::array_buffer::AnyArrayBuffer::$name(data) => {
                        Ok(data)
                    }
                    _ => Err(()),
                }
            }
        }
    };
}
pub(crate) use array_buffer_handle;