builtins-arraybuffer.cc 12.2 KB
Newer Older
1 2 3 4
// Copyright 2016 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

5
#include "src/builtins/builtins-utils-inl.h"
6 7 8
#include "src/builtins/builtins.h"
#include "src/conversions.h"
#include "src/counters.h"
9
#include "src/maybe-handles-inl.h"
10
#include "src/objects-inl.h"
11
#include "src/objects/js-array-buffer-inl.h"
12 13 14 15

namespace v8 {
namespace internal {

16 17
#define CHECK_SHARED(expected, name, method)                                \
  if (name->is_shared() != expected) {                                      \
18 19 20 21 22 23 24
    THROW_NEW_ERROR_RETURN_FAILURE(                                         \
        isolate,                                                            \
        NewTypeError(MessageTemplate::kIncompatibleMethodReceiver,          \
                     isolate->factory()->NewStringFromAsciiChecked(method), \
                     name));                                                \
  }

25
// -----------------------------------------------------------------------------
26
// ES#sec-arraybuffer-objects
27

28 29 30 31 32
namespace {

Object* ConstructBuffer(Isolate* isolate, Handle<JSFunction> target,
                        Handle<JSReceiver> new_target, Handle<Object> length,
                        bool initialize) {
33
  Handle<JSObject> result;
34 35 36
  ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
      isolate, result,
      JSObject::New(target, new_target, Handle<AllocationSite>::null()));
37
  size_t byte_length;
38 39
  if (!TryNumberToSize(*length, &byte_length) ||
      byte_length > JSArrayBuffer::kMaxByteLength) {
40
    JSArrayBuffer::SetupAsEmpty(Handle<JSArrayBuffer>::cast(result), isolate);
41 42 43 44 45 46 47 48
    THROW_NEW_ERROR_RETURN_FAILURE(
        isolate, NewRangeError(MessageTemplate::kInvalidArrayBufferLength));
  }
  SharedFlag shared_flag =
      (*target == target->native_context()->array_buffer_fun())
          ? SharedFlag::kNotShared
          : SharedFlag::kShared;
  if (!JSArrayBuffer::SetupAllocatingData(Handle<JSArrayBuffer>::cast(result),
49
                                          isolate, byte_length, initialize,
50 51 52 53 54 55 56
                                          shared_flag)) {
    THROW_NEW_ERROR_RETURN_FAILURE(
        isolate, NewRangeError(MessageTemplate::kArrayBufferAllocationFailed));
  }
  return *result;
}

57 58
}  // namespace

59 60
// ES #sec-arraybuffer-constructor
BUILTIN(ArrayBufferConstructor) {
61 62 63 64
  HandleScope scope(isolate);
  Handle<JSFunction> target = args.target();
  DCHECK(*target == target->native_context()->array_buffer_fun() ||
         *target == target->native_context()->shared_array_buffer_fun());
65
  if (args.new_target()->IsUndefined(isolate)) {  // [[Call]]
66
    THROW_NEW_ERROR_RETURN_FAILURE(
67
        isolate, NewTypeError(MessageTemplate::kConstructorNotFunction,
68
                              handle(target->shared()->Name(), isolate)));
69 70 71 72
  }
  // [[Construct]]
  Handle<JSReceiver> new_target = Handle<JSReceiver>::cast(args.new_target());
  Handle<Object> length = args.atOrUndefined(isolate, 1);
73

74 75 76 77 78 79
  Handle<Object> number_length;
  ASSIGN_RETURN_FAILURE_ON_EXCEPTION(isolate, number_length,
                                     Object::ToInteger(isolate, length));
  if (number_length->Number() < 0.0) {
    THROW_NEW_ERROR_RETURN_FAILURE(
        isolate, NewRangeError(MessageTemplate::kInvalidArrayBufferLength));
80
    }
81

82
    return ConstructBuffer(isolate, target, new_target, number_length, true);
83 84 85 86 87 88 89
}

// This is a helper to construct an ArrayBuffer with uinitialized memory.
// This means the caller must ensure the buffer is totally initialized in
// all cases, or we will expose uinitialized memory to user code.
BUILTIN(ArrayBufferConstructor_DoNotInitialize) {
  HandleScope scope(isolate);
90 91
  Handle<JSFunction> target(isolate->native_context()->array_buffer_fun(),
                            isolate);
92 93 94 95
  Handle<Object> length = args.atOrUndefined(isolate, 1);
  return ConstructBuffer(isolate, target, target, length, false);
}

96 97
// ES6 section 24.1.4.1 get ArrayBuffer.prototype.byteLength
BUILTIN(ArrayBufferPrototypeGetByteLength) {
98
  const char* const kMethodName = "get ArrayBuffer.prototype.byteLength";
99
  HandleScope scope(isolate);
100
  CHECK_RECEIVER(JSArrayBuffer, array_buffer, kMethodName);
101
  CHECK_SHARED(false, array_buffer, kMethodName);
102 103
  // TODO(franzih): According to the ES6 spec, we should throw a TypeError
  // here if the JSArrayBuffer is detached.
104
  return *isolate->factory()->NewNumberFromSize(array_buffer->byte_length());
105 106
}

107 108 109 110 111 112 113
// ES7 sharedmem 6.3.4.1 get SharedArrayBuffer.prototype.byteLength
BUILTIN(SharedArrayBufferPrototypeGetByteLength) {
  const char* const kMethodName = "get SharedArrayBuffer.prototype.byteLength";
  HandleScope scope(isolate);
  CHECK_RECEIVER(JSArrayBuffer, array_buffer,
                 "get SharedArrayBuffer.prototype.byteLength");
  CHECK_SHARED(true, array_buffer, kMethodName);
114
  return *isolate->factory()->NewNumberFromSize(array_buffer->byte_length());
115 116
}

117 118 119 120
// ES6 section 24.1.3.1 ArrayBuffer.isView ( arg )
BUILTIN(ArrayBufferIsView) {
  SealHandleScope shs(isolate);
  DCHECK_EQ(2, args.length());
121
  ObjectPtr arg = args[1];
122 123 124
  return isolate->heap()->ToBoolean(arg->IsJSArrayBufferView());
}

125 126
static Object* SliceHelper(BuiltinArguments args, Isolate* isolate,
                           const char* kMethodName, bool is_shared) {
127 128 129 130
  HandleScope scope(isolate);
  Handle<Object> start = args.at(1);
  Handle<Object> end = args.atOrUndefined(isolate, 2);

131 132 133
  // * If Type(O) is not Object, throw a TypeError exception.
  // * If O does not have an [[ArrayBufferData]] internal slot, throw a
  //   TypeError exception.
134
  CHECK_RECEIVER(JSArrayBuffer, array_buffer, kMethodName);
135 136 137
  // * [AB] If IsSharedArrayBuffer(O) is true, throw a TypeError exception.
  // * [SAB] If IsSharedArrayBuffer(O) is false, throw a TypeError exception.
  CHECK_SHARED(is_shared, array_buffer, kMethodName);
138

139
  // * [AB] If IsDetachedBuffer(buffer) is true, throw a TypeError exception.
140
  if (!is_shared && array_buffer->was_detached()) {
141 142 143 144 145 146
    THROW_NEW_ERROR_RETURN_FAILURE(
        isolate, NewTypeError(MessageTemplate::kDetachedOperation,
                              isolate->factory()->NewStringFromAsciiChecked(
                                  kMethodName)));
  }

147 148
  // * [AB] Let len be O.[[ArrayBufferByteLength]].
  // * [SAB] Let len be O.[[ArrayBufferByteLength]].
149
  double const len = array_buffer->byte_length();
150

151
  // * Let relativeStart be ? ToInteger(start).
152 153 154 155
  Handle<Object> relative_start;
  ASSIGN_RETURN_FAILURE_ON_EXCEPTION(isolate, relative_start,
                                     Object::ToInteger(isolate, start));

156 157
  // * If relativeStart < 0, let first be max((len + relativeStart), 0); else
  //   let first be min(relativeStart, len).
158 159 160 161 162
  double const first = (relative_start->Number() < 0)
                           ? Max(len + relative_start->Number(), 0.0)
                           : Min(relative_start->Number(), len);
  Handle<Object> first_obj = isolate->factory()->NewNumber(first);

163 164
  // * If end is undefined, let relativeEnd be len; else let relativeEnd be ?
  //   ToInteger(end).
165 166 167 168 169 170 171 172 173 174
  double relative_end;
  if (end->IsUndefined(isolate)) {
    relative_end = len;
  } else {
    Handle<Object> relative_end_obj;
    ASSIGN_RETURN_FAILURE_ON_EXCEPTION(isolate, relative_end_obj,
                                       Object::ToInteger(isolate, end));
    relative_end = relative_end_obj->Number();
  }

175 176
  // * If relativeEnd < 0, let final be max((len + relativeEnd), 0); else let
  //   final be min(relativeEnd, len).
177 178 179
  double const final_ = (relative_end < 0) ? Max(len + relative_end, 0.0)
                                           : Min(relative_end, len);

180
  // * Let newLen be max(final-first, 0).
181 182 183
  double const new_len = Max(final_ - first, 0.0);
  Handle<Object> new_len_obj = isolate->factory()->NewNumber(new_len);

184 185 186 187 188
  // * [AB] Let ctor be ? SpeciesConstructor(O, %ArrayBuffer%).
  // * [SAB] Let ctor be ? SpeciesConstructor(O, %SharedArrayBuffer%).
  Handle<JSFunction> constructor_fun = is_shared
                                           ? isolate->shared_array_buffer_fun()
                                           : isolate->array_buffer_fun();
189 190 191 192
  Handle<Object> ctor;
  ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
      isolate, ctor,
      Object::SpeciesConstructor(
193
          isolate, Handle<JSReceiver>::cast(args.receiver()), constructor_fun));
194

195
  // * Let new be ? Construct(ctor, newLen).
196 197 198 199 200 201 202 203 204
  Handle<JSReceiver> new_;
  {
    const int argc = 1;

    ScopedVector<Handle<Object>> argv(argc);
    argv[0] = new_len_obj;

    Handle<Object> new_obj;
    ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
205
        isolate, new_obj, Execution::New(isolate, ctor, argc, argv.start()));
206 207 208 209

    new_ = Handle<JSReceiver>::cast(new_obj);
  }

210 211
  // * If new does not have an [[ArrayBufferData]] internal slot, throw a
  //   TypeError exception.
212 213 214 215 216 217 218 219
  if (!new_->IsJSArrayBuffer()) {
    THROW_NEW_ERROR_RETURN_FAILURE(
        isolate,
        NewTypeError(MessageTemplate::kIncompatibleMethodReceiver,
                     isolate->factory()->NewStringFromAsciiChecked(kMethodName),
                     new_));
  }

220 221
  // * [AB] If IsSharedArrayBuffer(new) is true, throw a TypeError exception.
  // * [SAB] If IsSharedArrayBuffer(new) is false, throw a TypeError exception.
222
  Handle<JSArrayBuffer> new_array_buffer = Handle<JSArrayBuffer>::cast(new_);
223
  CHECK_SHARED(is_shared, new_array_buffer, kMethodName);
224

225
  // * [AB] If IsDetachedBuffer(new) is true, throw a TypeError exception.
226
  if (!is_shared && new_array_buffer->was_detached()) {
227 228 229 230 231 232
    THROW_NEW_ERROR_RETURN_FAILURE(
        isolate, NewTypeError(MessageTemplate::kDetachedOperation,
                              isolate->factory()->NewStringFromAsciiChecked(
                                  kMethodName)));
  }

233 234
  // * [AB] If SameValue(new, O) is true, throw a TypeError exception.
  if (!is_shared && new_->SameValue(*args.receiver())) {
235 236 237 238
    THROW_NEW_ERROR_RETURN_FAILURE(
        isolate, NewTypeError(MessageTemplate::kArrayBufferSpeciesThis));
  }

239 240 241 242 243 244 245 246 247
  // * [SAB] If new.[[ArrayBufferData]] and O.[[ArrayBufferData]] are the same
  //         Shared Data Block values, throw a TypeError exception.
  if (is_shared &&
      new_array_buffer->backing_store() == array_buffer->backing_store()) {
    THROW_NEW_ERROR_RETURN_FAILURE(
        isolate, NewTypeError(MessageTemplate::kSharedArrayBufferSpeciesThis));
  }

  // * If new.[[ArrayBufferByteLength]] < newLen, throw a TypeError exception.
248
  if (new_array_buffer->byte_length() < new_len) {
249
    THROW_NEW_ERROR_RETURN_FAILURE(
250 251 252
        isolate,
        NewTypeError(is_shared ? MessageTemplate::kSharedArrayBufferTooShort
                               : MessageTemplate::kArrayBufferTooShort));
253 254
  }

255 256
  // * [AB] NOTE: Side-effects of the above steps may have detached O.
  // * [AB] If IsDetachedBuffer(O) is true, throw a TypeError exception.
257
  if (!is_shared && array_buffer->was_detached()) {
258 259 260 261 262 263
    THROW_NEW_ERROR_RETURN_FAILURE(
        isolate, NewTypeError(MessageTemplate::kDetachedOperation,
                              isolate->factory()->NewStringFromAsciiChecked(
                                  kMethodName)));
  }

264 265 266
  // * Let fromBuf be O.[[ArrayBufferData]].
  // * Let toBuf be new.[[ArrayBufferData]].
  // * Perform CopyDataBlockBytes(toBuf, 0, fromBuf, first, newLen).
267 268 269
  size_t first_size = 0, new_len_size = 0;
  CHECK(TryNumberToSize(*first_obj, &first_size));
  CHECK(TryNumberToSize(*new_len_obj, &new_len_size));
270
  DCHECK(new_array_buffer->byte_length() >= new_len_size);
271 272

  if (new_len_size != 0) {
273
    size_t from_byte_length = array_buffer->byte_length();
274 275 276 277 278 279 280 281 282 283 284 285 286
    USE(from_byte_length);
    DCHECK(first_size <= from_byte_length);
    DCHECK(from_byte_length - first_size >= new_len_size);
    uint8_t* from_data =
        reinterpret_cast<uint8_t*>(array_buffer->backing_store());
    uint8_t* to_data =
        reinterpret_cast<uint8_t*>(new_array_buffer->backing_store());
    CopyBytes(to_data, from_data + first_size, new_len_size);
  }

  return *new_;
}

287 288 289 290 291 292 293 294 295 296 297 298 299
// ES #sec-sharedarraybuffer.prototype.slice
BUILTIN(SharedArrayBufferPrototypeSlice) {
  const char* const kMethodName = "SharedArrayBuffer.prototype.slice";
  return SliceHelper(args, isolate, kMethodName, true);
}

// ES #sec-arraybuffer.prototype.slice
// ArrayBuffer.prototype.slice ( start, end )
BUILTIN(ArrayBufferPrototypeSlice) {
  const char* const kMethodName = "ArrayBuffer.prototype.slice";
  return SliceHelper(args, isolate, kMethodName, false);
}

300 301
}  // namespace internal
}  // namespace v8