builtins-sharedarraybuffer.cc 9.75 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 6 7
#include "src/base/macros.h"
#include "src/base/platform/mutex.h"
#include "src/base/platform/time.h"
8
#include "src/builtins/builtins-utils-inl.h"
9
#include "src/builtins/builtins.h"
10
#include "src/codegen/code-factory.h"
11
#include "src/common/globals.h"
12
#include "src/execution/futex-emulation.h"
13
#include "src/heap/factory.h"
14
#include "src/logging/counters.h"
15
#include "src/numbers/conversions-inl.h"
16
#include "src/objects/js-array-buffer-inl.h"
17
#include "src/objects/objects-inl.h"
18 19 20 21

namespace v8 {
namespace internal {

22 23
// See builtins-arraybuffer.cc for implementations of
// SharedArrayBuffer.prototye.byteLength and SharedArrayBuffer.prototype.slice
24

25
// #sec-atomics.islockfree
26
inline bool AtomicIsLockFree(double size) {
27
  // According to the standard, 1, 2, and 4 byte atomics are supposed to be
28 29 30
  // 'lock free' on every platform. 'Lock free' means that all possible uses of
  // those atomics guarantee forward progress for the agent cluster (i.e. all
  // threads in contrast with a single thread).
31
  //
32 33 34 35 36 37 38 39
  // This property is often, but not always, aligned with whether atomic
  // accesses are implemented with software locks such as mutexes.
  //
  // V8 has lock free atomics for all sizes on all supported first-class
  // architectures: ia32, x64, ARM32 variants, and ARM64. Further, this property
  // is depended upon by WebAssembly, which prescribes that all atomic accesses
  // are always lock free.
  return size == 1 || size == 2 || size == 4 || size == 8;
40 41 42 43 44 45
}

// ES #sec-atomics.islockfree
BUILTIN(AtomicsIsLockFree) {
  HandleScope scope(isolate);
  Handle<Object> size = args.atOrUndefined(isolate, 1);
46 47
  ASSIGN_RETURN_FAILURE_ON_EXCEPTION(isolate, size,
                                     Object::ToNumber(isolate, size));
48 49 50 51
  return *isolate->factory()->ToBoolean(AtomicIsLockFree(size->Number()));
}

// ES #sec-validatesharedintegertypedarray
52
V8_WARN_UNUSED_RESULT MaybeHandle<JSTypedArray> ValidateSharedIntegerTypedArray(
53 54
    Isolate* isolate, Handle<Object> object,
    bool only_int32_and_big_int64 = false) {
55 56 57
  if (object->IsJSTypedArray()) {
    Handle<JSTypedArray> typed_array = Handle<JSTypedArray>::cast(object);
    if (typed_array->GetBuffer()->is_shared()) {
58 59 60 61 62
      if (only_int32_and_big_int64) {
        if (typed_array->type() == kExternalInt32Array ||
            typed_array->type() == kExternalBigInt64Array) {
          return typed_array;
        }
63 64 65 66 67 68 69 70 71 72 73
      } else {
        if (typed_array->type() != kExternalFloat32Array &&
            typed_array->type() != kExternalFloat64Array &&
            typed_array->type() != kExternalUint8ClampedArray)
          return typed_array;
      }
    }
  }

  THROW_NEW_ERROR(
      isolate,
74 75 76
      NewTypeError(only_int32_and_big_int64
                       ? MessageTemplate::kNotInt32OrBigInt64SharedTypedArray
                       : MessageTemplate::kNotIntegerSharedTypedArray,
77 78 79 80 81 82
                   object),
      JSTypedArray);
}

// ES #sec-validateatomicaccess
// ValidateAtomicAccess( typedArray, requestIndex )
83
V8_WARN_UNUSED_RESULT Maybe<size_t> ValidateAtomicAccess(
84 85
    Isolate* isolate, Handle<JSTypedArray> typed_array,
    Handle<Object> request_index) {
86 87 88 89 90 91 92
  Handle<Object> access_index_obj;
  ASSIGN_RETURN_ON_EXCEPTION_VALUE(
      isolate, access_index_obj,
      Object::ToIndex(isolate, request_index,
                      MessageTemplate::kInvalidAtomicAccessIndex),
      Nothing<size_t>());

93 94
  size_t access_index;
  if (!TryNumberToSize(*access_index_obj, &access_index) ||
95
      typed_array->WasDetached() || access_index >= typed_array->length()) {
96 97 98 99 100 101 102
    isolate->Throw(*isolate->factory()->NewRangeError(
        MessageTemplate::kInvalidAtomicAccessIndex));
    return Nothing<size_t>();
  }
  return Just<size_t>(access_index);
}

103
namespace {
104 105 106 107 108 109 110 111 112

inline size_t GetAddress64(size_t index, size_t byte_offset) {
  return (index << 3) + byte_offset;
}

inline size_t GetAddress32(size_t index, size_t byte_offset) {
  return (index << 2) + byte_offset;
}

113 114
MaybeHandle<Object> AtomicsWake(Isolate* isolate, Handle<Object> array,
                                Handle<Object> index, Handle<Object> count) {
115
  Handle<JSTypedArray> sta;
116 117 118
  ASSIGN_RETURN_ON_EXCEPTION(
      isolate, sta, ValidateSharedIntegerTypedArray(isolate, array, true),
      Object);
119 120

  Maybe<size_t> maybe_index = ValidateAtomicAccess(isolate, sta, index);
121
  MAYBE_RETURN_NULL(maybe_index);
122 123 124 125 126 127
  size_t i = maybe_index.FromJust();

  uint32_t c;
  if (count->IsUndefined(isolate)) {
    c = kMaxUInt32;
  } else {
128 129
    ASSIGN_RETURN_ON_EXCEPTION(isolate, count,
                               Object::ToInteger(isolate, count), Object);
130 131 132 133 134 135 136 137 138 139
    double count_double = count->Number();
    if (count_double < 0)
      count_double = 0;
    else if (count_double > kMaxUInt32)
      count_double = kMaxUInt32;
    c = static_cast<uint32_t>(count_double);
  }

  Handle<JSArrayBuffer> array_buffer = sta->GetBuffer();

140 141 142 143 144 145 146 147 148 149 150 151
  if (sta->type() == kExternalBigInt64Array) {
    return Handle<Object>(
        FutexEmulation::Wake(array_buffer, GetAddress64(i, sta->byte_offset()),
                             c),
        isolate);
  } else {
    DCHECK(sta->type() == kExternalInt32Array);
    return Handle<Object>(
        FutexEmulation::Wake(array_buffer, GetAddress32(i, sta->byte_offset()),
                             c),
        isolate);
  }
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
}

}  // namespace

// ES #sec-atomics.wake
// Atomics.wake( typedArray, index, count )
BUILTIN(AtomicsWake) {
  HandleScope scope(isolate);
  Handle<Object> array = args.atOrUndefined(isolate, 1);
  Handle<Object> index = args.atOrUndefined(isolate, 2);
  Handle<Object> count = args.atOrUndefined(isolate, 3);

  isolate->CountUsage(v8::Isolate::UseCounterFeature::kAtomicsWake);
  RETURN_RESULT_OR_FAILURE(isolate, AtomicsWake(isolate, array, index, count));
}

// ES #sec-atomics.notify
// Atomics.notify( typedArray, index, count )
BUILTIN(AtomicsNotify) {
  HandleScope scope(isolate);
  Handle<Object> array = args.atOrUndefined(isolate, 1);
  Handle<Object> index = args.atOrUndefined(isolate, 2);
  Handle<Object> count = args.atOrUndefined(isolate, 3);

  isolate->CountUsage(v8::Isolate::UseCounterFeature::kAtomicsNotify);
  RETURN_RESULT_OR_FAILURE(isolate, AtomicsWake(isolate, array, index, count));
178 179
}

180 181 182 183
Object DoWait(Isolate* isolate, FutexEmulation::WaitMode mode,
              Handle<Object> array, Handle<Object> index, Handle<Object> value,
              Handle<Object> timeout) {
  // 1. Let buffer be ? ValidateSharedIntegerTypedArray(typedArray, true).
184 185 186 187
  Handle<JSTypedArray> sta;
  ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
      isolate, sta, ValidateSharedIntegerTypedArray(isolate, array, true));

188
  // 2. Let i be ? ValidateAtomicAccess(typedArray, index).
189
  Maybe<size_t> maybe_index = ValidateAtomicAccess(isolate, sta, index);
190
  if (maybe_index.IsNothing()) return ReadOnlyRoots(isolate).exception();
191 192
  size_t i = maybe_index.FromJust();

193 194 195
  // 3. Let arrayTypeName be typedArray.[[TypedArrayName]].
  // 4. If arrayTypeName is "BigInt64Array", let v be ? ToBigInt64(value).
  // 5. Otherwise, let v be ? ToInt32(value).
196 197 198 199 200 201 202 203
  if (sta->type() == kExternalBigInt64Array) {
    ASSIGN_RETURN_FAILURE_ON_EXCEPTION(isolate, value,
                                       BigInt::FromObject(isolate, value));
  } else {
    DCHECK(sta->type() == kExternalInt32Array);
    ASSIGN_RETURN_FAILURE_ON_EXCEPTION(isolate, value,
                                       Object::ToInt32(isolate, value));
  }
204

205 206
  // 6. Let q be ? ToNumber(timeout).
  // 7. If q is NaN, let t be +∞, else let t be max(q, 0).
207 208
  double timeout_number;
  if (timeout->IsUndefined(isolate)) {
209
    timeout_number = ReadOnlyRoots(isolate).infinity_value().Number();
210 211
  } else {
    ASSIGN_RETURN_FAILURE_ON_EXCEPTION(isolate, timeout,
212
                                       Object::ToNumber(isolate, timeout));
213 214
    timeout_number = timeout->Number();
    if (std::isnan(timeout_number))
215
      timeout_number = ReadOnlyRoots(isolate).infinity_value().Number();
216 217 218 219
    else if (timeout_number < 0)
      timeout_number = 0;
  }

220 221 222 223 224
  // 8. If mode is sync, then
  //   a. Let B be AgentCanSuspend().
  //   b. If B is false, throw a TypeError exception.
  if (mode == FutexEmulation::WaitMode::kSync &&
      !isolate->allow_atomics_wait()) {
225 226 227 228 229 230
    THROW_NEW_ERROR_RETURN_FAILURE(
        isolate, NewTypeError(MessageTemplate::kAtomicsWaitNotAllowed));
  }

  Handle<JSArrayBuffer> array_buffer = sta->GetBuffer();

231 232
  if (sta->type() == kExternalBigInt64Array) {
    return FutexEmulation::WaitJs64(
233
        isolate, mode, array_buffer, GetAddress64(i, sta->byte_offset()),
234 235 236
        Handle<BigInt>::cast(value)->AsInt64(), timeout_number);
  } else {
    DCHECK(sta->type() == kExternalInt32Array);
237
    return FutexEmulation::WaitJs32(isolate, mode, array_buffer,
238 239 240
                                    GetAddress32(i, sta->byte_offset()),
                                    NumberToInt32(*value), timeout_number);
  }
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
// ES #sec-atomics.wait
// Atomics.wait( typedArray, index, value, timeout )
BUILTIN(AtomicsWait) {
  HandleScope scope(isolate);
  Handle<Object> array = args.atOrUndefined(isolate, 1);
  Handle<Object> index = args.atOrUndefined(isolate, 2);
  Handle<Object> value = args.atOrUndefined(isolate, 3);
  Handle<Object> timeout = args.atOrUndefined(isolate, 4);

  return DoWait(isolate, FutexEmulation::WaitMode::kSync, array, index, value,
                timeout);
}

BUILTIN(AtomicsWaitAsync) {
  HandleScope scope(isolate);
  Handle<Object> array = args.atOrUndefined(isolate, 1);
  Handle<Object> index = args.atOrUndefined(isolate, 2);
  Handle<Object> value = args.atOrUndefined(isolate, 3);
  Handle<Object> timeout = args.atOrUndefined(isolate, 4);

  return DoWait(isolate, FutexEmulation::WaitMode::kAsync, array, index, value,
                timeout);
}

267 268
}  // namespace internal
}  // namespace v8