1 // Copyright Joyent, Inc. and other Node contributors.
2 //
3 // Permission is hereby granted, free of charge, to any person obtaining a
4 // copy of this software and associated documentation files (the
5 // "Software"), to deal in the Software without restriction, including
6 // without limitation the rights to use, copy, modify, merge, publish,
7 // distribute, sublicense, and/or sell copies of the Software, and to permit
8 // persons to whom the Software is furnished to do so, subject to the
9 // following conditions:
10 //
11 // The above copyright notice and this permission notice shall be included
12 // in all copies or substantial portions of the Software.
13 //
14 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
15 // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
17 // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
18 // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
19 // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
20 // USE OR OTHER DEALINGS IN THE SOFTWARE.
21 
22 #include "node_buffer.h"
23 #include "node.h"
24 #include "node_blob.h"
25 #include "node_errors.h"
26 #include "node_external_reference.h"
27 #include "node_i18n.h"
28 #include "node_internals.h"
29 
30 #include "env-inl.h"
31 #include "simdutf.h"
32 #include "string_bytes.h"
33 #include "string_search.h"
34 #include "util-inl.h"
35 #include "v8.h"
36 
37 #include <cstring>
38 #include <climits>
39 
40 #define THROW_AND_RETURN_UNLESS_BUFFER(env, obj)                            \
41   THROW_AND_RETURN_IF_NOT_BUFFER(env, obj, "argument")                      \
42 
43 #define THROW_AND_RETURN_IF_OOB(r)                                          \
44   do {                                                                      \
45     Maybe<bool> m = (r);                                                    \
46     if (m.IsNothing()) return;                                              \
47     if (!m.FromJust())                                                      \
48       return node::THROW_ERR_OUT_OF_RANGE(env, "Index out of range");       \
49   } while (0)                                                               \
50 
51 namespace node {
52 namespace Buffer {
53 
54 using v8::ArrayBuffer;
55 using v8::ArrayBufferView;
56 using v8::BackingStore;
57 using v8::Context;
58 using v8::EscapableHandleScope;
59 using v8::FunctionCallbackInfo;
60 using v8::Global;
61 using v8::HandleScope;
62 using v8::Int32;
63 using v8::Integer;
64 using v8::Isolate;
65 using v8::Just;
66 using v8::Local;
67 using v8::Maybe;
68 using v8::MaybeLocal;
69 using v8::Nothing;
70 using v8::Number;
71 using v8::Object;
72 using v8::SharedArrayBuffer;
73 using v8::String;
74 using v8::Uint32;
75 using v8::Uint32Array;
76 using v8::Uint8Array;
77 using v8::Value;
78 
79 namespace {
80 
81 class CallbackInfo {
82  public:
83   static inline Local<ArrayBuffer> CreateTrackedArrayBuffer(
84       Environment* env,
85       char* data,
86       size_t length,
87       FreeCallback callback,
88       void* hint);
89 
90   CallbackInfo(const CallbackInfo&) = delete;
91   CallbackInfo& operator=(const CallbackInfo&) = delete;
92 
93  private:
94   static void CleanupHook(void* data);
95   inline void OnBackingStoreFree();
96   inline void CallAndResetCallback();
97   inline CallbackInfo(Environment* env,
98                       FreeCallback callback,
99                       char* data,
100                       void* hint);
101   Global<ArrayBuffer> persistent_;
102   Mutex mutex_;  // Protects callback_.
103   FreeCallback callback_;
104   char* const data_;
105   void* const hint_;
106   Environment* const env_;
107 };
108 
109 
CreateTrackedArrayBuffer( Environment* env, char* data, size_t length, FreeCallback callback, void* hint)110 Local<ArrayBuffer> CallbackInfo::CreateTrackedArrayBuffer(
111     Environment* env,
112     char* data,
113     size_t length,
114     FreeCallback callback,
115     void* hint) {
116   CHECK_NOT_NULL(callback);
117   CHECK_IMPLIES(data == nullptr, length == 0);
118 
119   CallbackInfo* self = new CallbackInfo(env, callback, data, hint);
120   std::unique_ptr<BackingStore> bs =
121       ArrayBuffer::NewBackingStore(data, length, [](void*, size_t, void* arg) {
122         static_cast<CallbackInfo*>(arg)->OnBackingStoreFree();
123       }, self);
124   Local<ArrayBuffer> ab = ArrayBuffer::New(env->isolate(), std::move(bs));
125 
126   // V8 simply ignores the BackingStore deleter callback if data == nullptr,
127   // but our API contract requires it being called.
128   if (data == nullptr) {
129     ab->Detach();
130     self->OnBackingStoreFree();  // This calls `callback` asynchronously.
131   } else {
132     // Store the ArrayBuffer so that we can detach it later.
133     self->persistent_.Reset(env->isolate(), ab);
134     self->persistent_.SetWeak();
135   }
136 
137   return ab;
138 }
139 
140 
CallbackInfo(Environment* env, FreeCallback callback, char* data, void* hint)141 CallbackInfo::CallbackInfo(Environment* env,
142                            FreeCallback callback,
143                            char* data,
144                            void* hint)
145     : callback_(callback),
146       data_(data),
147       hint_(hint),
148       env_(env) {
149   env->AddCleanupHook(CleanupHook, this);
150   env->isolate()->AdjustAmountOfExternalAllocatedMemory(sizeof(*this));
151 }
152 
CleanupHook(void* data)153 void CallbackInfo::CleanupHook(void* data) {
154   CallbackInfo* self = static_cast<CallbackInfo*>(data);
155 
156   {
157     HandleScope handle_scope(self->env_->isolate());
158     Local<ArrayBuffer> ab = self->persistent_.Get(self->env_->isolate());
159     if (!ab.IsEmpty() && ab->IsDetachable()) {
160       ab->Detach();
161       self->persistent_.Reset();
162     }
163   }
164 
165   // Call the callback in this case, but don't delete `this` yet because the
166   // BackingStore deleter callback will do so later.
167   self->CallAndResetCallback();
168 }
169 
CallAndResetCallback()170 void CallbackInfo::CallAndResetCallback() {
171   FreeCallback callback;
172   {
173     Mutex::ScopedLock lock(mutex_);
174     callback = callback_;
175     callback_ = nullptr;
176   }
177   if (callback != nullptr) {
178     // Clean up all Environment-related state and run the callback.
179     env_->RemoveCleanupHook(CleanupHook, this);
180     int64_t change_in_bytes = -static_cast<int64_t>(sizeof(*this));
181     env_->isolate()->AdjustAmountOfExternalAllocatedMemory(change_in_bytes);
182 
183     callback(data_, hint_);
184   }
185 }
186 
OnBackingStoreFree()187 void CallbackInfo::OnBackingStoreFree() {
188   // This method should always release the memory for `this`.
189   std::unique_ptr<CallbackInfo> self { this };
190   Mutex::ScopedLock lock(mutex_);
191   // If callback_ == nullptr, that means that the callback has already run from
192   // the cleanup hook, and there is nothing left to do here besides to clean
193   // up the memory involved. In particular, the underlying `Environment` may
194   // be gone at this point, so don’t attempt to call SetImmediateThreadsafe().
195   if (callback_ == nullptr) return;
196 
197   env_->SetImmediateThreadsafe([self = std::move(self)](Environment* env) {
198     CHECK_EQ(self->env_, env);  // Consistency check.
199 
200     self->CallAndResetCallback();
201   });
202 }
203 
204 
205 // Parse index for external array data. An empty Maybe indicates
206 // a pending exception. `false` indicates that the index is out-of-bounds.
ParseArrayIndex(Environment* env, Local<Value> arg, size_t def, size_t* ret)207 inline MUST_USE_RESULT Maybe<bool> ParseArrayIndex(Environment* env,
208                                                    Local<Value> arg,
209                                                    size_t def,
210                                                    size_t* ret) {
211   if (arg->IsUndefined()) {
212     *ret = def;
213     return Just(true);
214   }
215 
216   int64_t tmp_i;
217   if (!arg->IntegerValue(env->context()).To(&tmp_i))
218     return Nothing<bool>();
219 
220   if (tmp_i < 0)
221     return Just(false);
222 
223   // Check that the result fits in a size_t.
224   // coverity[pointless_expression]
225   if (static_cast<uint64_t>(tmp_i) > std::numeric_limits<size_t>::max())
226     return Just(false);
227 
228   *ret = static_cast<size_t>(tmp_i);
229   return Just(true);
230 }
231 
232 }  // anonymous namespace
233 
234 // Buffer methods
235 
HasInstance(Local<Value> val)236 bool HasInstance(Local<Value> val) {
237   return val->IsArrayBufferView();
238 }
239 
240 
HasInstance(Local<Object> obj)241 bool HasInstance(Local<Object> obj) {
242   return obj->IsArrayBufferView();
243 }
244 
245 
Data(Local<Value> val)246 char* Data(Local<Value> val) {
247   CHECK(val->IsArrayBufferView());
248   Local<ArrayBufferView> ui = val.As<ArrayBufferView>();
249   return static_cast<char*>(ui->Buffer()->Data()) + ui->ByteOffset();
250 }
251 
252 
Data(Local<Object> obj)253 char* Data(Local<Object> obj) {
254   return Data(obj.As<Value>());
255 }
256 
257 
Length(Local<Value> val)258 size_t Length(Local<Value> val) {
259   CHECK(val->IsArrayBufferView());
260   Local<ArrayBufferView> ui = val.As<ArrayBufferView>();
261   return ui->ByteLength();
262 }
263 
264 
Length(Local<Object> obj)265 size_t Length(Local<Object> obj) {
266   CHECK(obj->IsArrayBufferView());
267   Local<ArrayBufferView> ui = obj.As<ArrayBufferView>();
268   return ui->ByteLength();
269 }
270 
271 
New(Environment* env, Local<ArrayBuffer> ab, size_t byte_offset, size_t length)272 MaybeLocal<Uint8Array> New(Environment* env,
273                            Local<ArrayBuffer> ab,
274                            size_t byte_offset,
275                            size_t length) {
276   CHECK(!env->buffer_prototype_object().IsEmpty());
277   Local<Uint8Array> ui = Uint8Array::New(ab, byte_offset, length);
278   Maybe<bool> mb =
279       ui->SetPrototype(env->context(), env->buffer_prototype_object());
280   if (mb.IsNothing())
281     return MaybeLocal<Uint8Array>();
282   return ui;
283 }
284 
New(Isolate* isolate, Local<ArrayBuffer> ab, size_t byte_offset, size_t length)285 MaybeLocal<Uint8Array> New(Isolate* isolate,
286                            Local<ArrayBuffer> ab,
287                            size_t byte_offset,
288                            size_t length) {
289   Environment* env = Environment::GetCurrent(isolate);
290   if (env == nullptr) {
291     THROW_ERR_BUFFER_CONTEXT_NOT_AVAILABLE(isolate);
292     return MaybeLocal<Uint8Array>();
293   }
294   return New(env, ab, byte_offset, length);
295 }
296 
297 
New(Isolate* isolate, Local<String> string, enum encoding enc)298 MaybeLocal<Object> New(Isolate* isolate,
299                        Local<String> string,
300                        enum encoding enc) {
301   EscapableHandleScope scope(isolate);
302 
303   size_t length;
304   if (!StringBytes::Size(isolate, string, enc).To(&length))
305     return Local<Object>();
306   size_t actual = 0;
307   std::unique_ptr<BackingStore> store;
308 
309   if (length > 0) {
310     store = ArrayBuffer::NewBackingStore(isolate, length);
311 
312     if (UNLIKELY(!store)) {
313       THROW_ERR_MEMORY_ALLOCATION_FAILED(isolate);
314       return Local<Object>();
315     }
316 
317     actual = StringBytes::Write(
318         isolate,
319         static_cast<char*>(store->Data()),
320         length,
321         string,
322         enc);
323     CHECK(actual <= length);
324 
325     if (LIKELY(actual > 0)) {
326       if (actual < length)
327         store = BackingStore::Reallocate(isolate, std::move(store), actual);
328       Local<ArrayBuffer> buf = ArrayBuffer::New(isolate, std::move(store));
329       Local<Object> obj;
330       if (UNLIKELY(!New(isolate, buf, 0, actual).ToLocal(&obj)))
331         return MaybeLocal<Object>();
332       return scope.Escape(obj);
333     }
334   }
335 
336   return scope.EscapeMaybe(New(isolate, 0));
337 }
338 
339 
New(Isolate* isolate, size_t length)340 MaybeLocal<Object> New(Isolate* isolate, size_t length) {
341   EscapableHandleScope handle_scope(isolate);
342   Local<Object> obj;
343   Environment* env = Environment::GetCurrent(isolate);
344   if (env == nullptr) {
345     THROW_ERR_BUFFER_CONTEXT_NOT_AVAILABLE(isolate);
346     return MaybeLocal<Object>();
347   }
348   if (Buffer::New(env, length).ToLocal(&obj))
349     return handle_scope.Escape(obj);
350   return Local<Object>();
351 }
352 
353 
New(Environment* env, size_t length)354 MaybeLocal<Object> New(Environment* env, size_t length) {
355   Isolate* isolate(env->isolate());
356   EscapableHandleScope scope(isolate);
357 
358   // V8 currently only allows a maximum Typed Array index of max Smi.
359   if (length > kMaxLength) {
360     isolate->ThrowException(ERR_BUFFER_TOO_LARGE(isolate));
361     return Local<Object>();
362   }
363 
364   Local<ArrayBuffer> ab;
365   {
366     NoArrayBufferZeroFillScope no_zero_fill_scope(env->isolate_data());
367     std::unique_ptr<BackingStore> bs =
368         ArrayBuffer::NewBackingStore(isolate, length);
369 
370     CHECK(bs);
371 
372     ab = ArrayBuffer::New(isolate, std::move(bs));
373   }
374 
375   MaybeLocal<Object> obj =
376       New(env, ab, 0, ab->ByteLength())
377           .FromMaybe(Local<Uint8Array>());
378 
379   return scope.EscapeMaybe(obj);
380 }
381 
382 
Copy(Isolate* isolate, const char* data, size_t length)383 MaybeLocal<Object> Copy(Isolate* isolate, const char* data, size_t length) {
384   EscapableHandleScope handle_scope(isolate);
385   Environment* env = Environment::GetCurrent(isolate);
386   if (env == nullptr) {
387     THROW_ERR_BUFFER_CONTEXT_NOT_AVAILABLE(isolate);
388     return MaybeLocal<Object>();
389   }
390   Local<Object> obj;
391   if (Buffer::Copy(env, data, length).ToLocal(&obj))
392     return handle_scope.Escape(obj);
393   return Local<Object>();
394 }
395 
396 
Copy(Environment* env, const char* data, size_t length)397 MaybeLocal<Object> Copy(Environment* env, const char* data, size_t length) {
398   Isolate* isolate(env->isolate());
399   EscapableHandleScope scope(isolate);
400 
401   // V8 currently only allows a maximum Typed Array index of max Smi.
402   if (length > kMaxLength) {
403     isolate->ThrowException(ERR_BUFFER_TOO_LARGE(isolate));
404     return Local<Object>();
405   }
406 
407   Local<ArrayBuffer> ab;
408   {
409     NoArrayBufferZeroFillScope no_zero_fill_scope(env->isolate_data());
410     std::unique_ptr<BackingStore> bs =
411         ArrayBuffer::NewBackingStore(isolate, length);
412 
413     CHECK(bs);
414 
415     memcpy(bs->Data(), data, length);
416 
417     ab = ArrayBuffer::New(isolate, std::move(bs));
418   }
419 
420   MaybeLocal<Object> obj =
421       New(env, ab, 0, ab->ByteLength())
422           .FromMaybe(Local<Uint8Array>());
423 
424   return scope.EscapeMaybe(obj);
425 }
426 
427 
New(Isolate* isolate, char* data, size_t length, FreeCallback callback, void* hint)428 MaybeLocal<Object> New(Isolate* isolate,
429                        char* data,
430                        size_t length,
431                        FreeCallback callback,
432                        void* hint) {
433   EscapableHandleScope handle_scope(isolate);
434   Environment* env = Environment::GetCurrent(isolate);
435   if (env == nullptr) {
436     callback(data, hint);
437     THROW_ERR_BUFFER_CONTEXT_NOT_AVAILABLE(isolate);
438     return MaybeLocal<Object>();
439   }
440   return handle_scope.EscapeMaybe(
441       Buffer::New(env, data, length, callback, hint));
442 }
443 
444 
New(Environment* env, char* data, size_t length, FreeCallback callback, void* hint)445 MaybeLocal<Object> New(Environment* env,
446                        char* data,
447                        size_t length,
448                        FreeCallback callback,
449                        void* hint) {
450   EscapableHandleScope scope(env->isolate());
451 
452   if (length > kMaxLength) {
453     env->isolate()->ThrowException(ERR_BUFFER_TOO_LARGE(env->isolate()));
454     callback(data, hint);
455     return Local<Object>();
456   }
457 
458   Local<ArrayBuffer> ab =
459       CallbackInfo::CreateTrackedArrayBuffer(env, data, length, callback, hint);
460   if (ab->SetPrivate(env->context(),
461                      env->untransferable_object_private_symbol(),
462                      True(env->isolate())).IsNothing()) {
463     return Local<Object>();
464   }
465   MaybeLocal<Uint8Array> maybe_ui = Buffer::New(env, ab, 0, length);
466 
467   Local<Uint8Array> ui;
468   if (!maybe_ui.ToLocal(&ui))
469     return MaybeLocal<Object>();
470 
471   return scope.Escape(ui);
472 }
473 
474 // Warning: This function needs `data` to be allocated with malloc() and not
475 // necessarily isolate's ArrayBuffer::Allocator.
New(Isolate* isolate, char* data, size_t length)476 MaybeLocal<Object> New(Isolate* isolate, char* data, size_t length) {
477   EscapableHandleScope handle_scope(isolate);
478   Environment* env = Environment::GetCurrent(isolate);
479   if (env == nullptr) {
480     free(data);
481     THROW_ERR_BUFFER_CONTEXT_NOT_AVAILABLE(isolate);
482     return MaybeLocal<Object>();
483   }
484   Local<Object> obj;
485   if (Buffer::New(env, data, length).ToLocal(&obj))
486     return handle_scope.Escape(obj);
487   return Local<Object>();
488 }
489 
490 // The contract for this function is that `data` is allocated with malloc()
491 // and not necessarily isolate's ArrayBuffer::Allocator.
New(Environment* env, char* data, size_t length)492 MaybeLocal<Object> New(Environment* env,
493                        char* data,
494                        size_t length) {
495   if (length > 0) {
496     CHECK_NOT_NULL(data);
497     // V8 currently only allows a maximum Typed Array index of max Smi.
498     if (length > kMaxLength) {
499       Isolate* isolate(env->isolate());
500       isolate->ThrowException(ERR_BUFFER_TOO_LARGE(isolate));
501       free(data);
502       return Local<Object>();
503     }
504   }
505 
506   EscapableHandleScope handle_scope(env->isolate());
507 
508   auto free_callback = [](void* data, size_t length, void* deleter_data) {
509     free(data);
510   };
511   std::unique_ptr<BackingStore> bs =
512       v8::ArrayBuffer::NewBackingStore(data, length, free_callback, nullptr);
513 
514   Local<ArrayBuffer> ab = v8::ArrayBuffer::New(env->isolate(), std::move(bs));
515 
516   Local<Object> obj;
517   if (Buffer::New(env, ab, 0, length).ToLocal(&obj))
518     return handle_scope.Escape(obj);
519   return Local<Object>();
520 }
521 
522 namespace {
523 
CreateFromString(const FunctionCallbackInfo<Value>& args)524 void CreateFromString(const FunctionCallbackInfo<Value>& args) {
525   CHECK(args[0]->IsString());
526   CHECK(args[1]->IsInt32());
527 
528   enum encoding enc = static_cast<enum encoding>(args[1].As<Int32>()->Value());
529   Local<Object> buf;
530   if (New(args.GetIsolate(), args[0].As<String>(), enc).ToLocal(&buf))
531     args.GetReturnValue().Set(buf);
532 }
533 
534 
535 template <encoding encoding>
StringSlice(const FunctionCallbackInfo<Value>& args)536 void StringSlice(const FunctionCallbackInfo<Value>& args) {
537   Environment* env = Environment::GetCurrent(args);
538   Isolate* isolate = env->isolate();
539 
540   THROW_AND_RETURN_UNLESS_BUFFER(env, args.This());
541   ArrayBufferViewContents<char> buffer(args.This());
542 
543   if (buffer.length() == 0)
544     return args.GetReturnValue().SetEmptyString();
545 
546   size_t start = 0;
547   size_t end = 0;
548   THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[0], 0, &start));
549   THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[1], buffer.length(), &end));
550   if (end < start) end = start;
551   THROW_AND_RETURN_IF_OOB(Just(end <= buffer.length()));
552   size_t length = end - start;
553 
554   Local<Value> error;
555   MaybeLocal<Value> maybe_ret =
556       StringBytes::Encode(isolate,
557                           buffer.data() + start,
558                           length,
559                           encoding,
560                           &error);
561   Local<Value> ret;
562   if (!maybe_ret.ToLocal(&ret)) {
563     CHECK(!error.IsEmpty());
564     isolate->ThrowException(error);
565     return;
566   }
567   args.GetReturnValue().Set(ret);
568 }
569 
570 // Convert the input into an encoded string
DecodeUTF8(const FunctionCallbackInfo<Value>& args)571 void DecodeUTF8(const FunctionCallbackInfo<Value>& args) {
572   Environment* env = Environment::GetCurrent(args);  // list, flags
573 
574   CHECK_GE(args.Length(), 1);
575 
576   if (!(args[0]->IsArrayBuffer() || args[0]->IsSharedArrayBuffer() ||
577         args[0]->IsArrayBufferView())) {
578     return node::THROW_ERR_INVALID_ARG_TYPE(
579         env->isolate(),
580         "The \"list\" argument must be an instance of SharedArrayBuffer, "
581         "ArrayBuffer or ArrayBufferView.");
582   }
583 
584   ArrayBufferViewContents<char> buffer(args[0]);
585 
586   bool ignore_bom = args[1]->IsTrue();
587   bool has_fatal = args[2]->IsTrue();
588 
589   const char* data = buffer.data();
590   size_t length = buffer.length();
591 
592   if (has_fatal) {
593     auto result = simdutf::validate_utf8_with_errors(data, length);
594 
595     if (result.error) {
596       return node::THROW_ERR_ENCODING_INVALID_ENCODED_DATA(
597           env->isolate(), "The encoded data was not valid for encoding utf-8");
598     }
599   }
600 
601   if (!ignore_bom && length >= 3) {
602     if (memcmp(data, "\xEF\xBB\xBF", 3) == 0) {
603       data += 3;
604       length -= 3;
605     }
606   }
607 
608   if (length == 0) return args.GetReturnValue().SetEmptyString();
609 
610   Local<Value> error;
611   MaybeLocal<Value> maybe_ret =
612       StringBytes::Encode(env->isolate(), data, length, UTF8, &error);
613   Local<Value> ret;
614 
615   if (!maybe_ret.ToLocal(&ret)) {
616     CHECK(!error.IsEmpty());
617     env->isolate()->ThrowException(error);
618     return;
619   }
620 
621   args.GetReturnValue().Set(ret);
622 }
623 
624 // bytesCopied = copy(buffer, target[, targetStart][, sourceStart][, sourceEnd])
Copy(const FunctionCallbackInfo<Value> &args)625 void Copy(const FunctionCallbackInfo<Value> &args) {
626   Environment* env = Environment::GetCurrent(args);
627 
628   THROW_AND_RETURN_UNLESS_BUFFER(env, args[0]);
629   THROW_AND_RETURN_UNLESS_BUFFER(env, args[1]);
630   ArrayBufferViewContents<char> source(args[0]);
631   Local<Object> target_obj = args[1].As<Object>();
632   SPREAD_BUFFER_ARG(target_obj, target);
633 
634   size_t target_start = 0;
635   size_t source_start = 0;
636   size_t source_end = 0;
637 
638   THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[2], 0, &target_start));
639   THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[3], 0, &source_start));
640   THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[4], source.length(),
641                                           &source_end));
642 
643   // Copy 0 bytes; we're done
644   if (target_start >= target_length || source_start >= source_end)
645     return args.GetReturnValue().Set(0);
646 
647   if (source_start > source.length())
648     return THROW_ERR_OUT_OF_RANGE(
649         env, "The value of \"sourceStart\" is out of range.");
650 
651   if (source_end - source_start > target_length - target_start)
652     source_end = source_start + target_length - target_start;
653 
654   uint32_t to_copy = std::min(
655       std::min(source_end - source_start, target_length - target_start),
656       source.length() - source_start);
657 
658   memmove(target_data + target_start, source.data() + source_start, to_copy);
659   args.GetReturnValue().Set(to_copy);
660 }
661 
662 
Fill(const FunctionCallbackInfo<Value>& args)663 void Fill(const FunctionCallbackInfo<Value>& args) {
664   Environment* env = Environment::GetCurrent(args);
665   Local<Context> ctx = env->context();
666 
667   THROW_AND_RETURN_UNLESS_BUFFER(env, args[0]);
668   SPREAD_BUFFER_ARG(args[0], ts_obj);
669 
670   size_t start = 0;
671   THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[2], 0, &start));
672   size_t end;
673   THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[3], 0, &end));
674 
675   size_t fill_length = end - start;
676   Local<String> str_obj;
677   size_t str_length;
678   enum encoding enc;
679 
680   // OOB Check. Throw the error in JS.
681   if (start > end || fill_length + start > ts_obj_length)
682     return args.GetReturnValue().Set(-2);
683 
684   // First check if Buffer has been passed.
685   if (Buffer::HasInstance(args[1])) {
686     SPREAD_BUFFER_ARG(args[1], fill_obj);
687     str_length = fill_obj_length;
688     memcpy(
689         ts_obj_data + start, fill_obj_data, std::min(str_length, fill_length));
690     goto start_fill;
691   }
692 
693   // Then coerce everything that's not a string.
694   if (!args[1]->IsString()) {
695     uint32_t val;
696     if (!args[1]->Uint32Value(ctx).To(&val)) return;
697     int value = val & 255;
698     memset(ts_obj_data + start, value, fill_length);
699     return;
700   }
701 
702   str_obj = args[1]->ToString(env->context()).ToLocalChecked();
703   enc = ParseEncoding(env->isolate(), args[4], UTF8);
704 
705   // Can't use StringBytes::Write() in all cases. For example if attempting
706   // to write a two byte character into a one byte Buffer.
707   if (enc == UTF8) {
708     str_length = str_obj->Utf8Length(env->isolate());
709     node::Utf8Value str(env->isolate(), args[1]);
710     memcpy(ts_obj_data + start, *str, std::min(str_length, fill_length));
711 
712   } else if (enc == UCS2) {
713     str_length = str_obj->Length() * sizeof(uint16_t);
714     node::TwoByteValue str(env->isolate(), args[1]);
715     if (IsBigEndian())
716       SwapBytes16(reinterpret_cast<char*>(&str[0]), str_length);
717 
718     memcpy(ts_obj_data + start, *str, std::min(str_length, fill_length));
719 
720   } else {
721     // Write initial String to Buffer, then use that memory to copy remainder
722     // of string. Correct the string length for cases like HEX where less than
723     // the total string length is written.
724     str_length = StringBytes::Write(
725         env->isolate(), ts_obj_data + start, fill_length, str_obj, enc);
726   }
727 
728 start_fill:
729 
730   if (str_length >= fill_length)
731     return;
732 
733   // If str_length is zero, then either an empty buffer was provided, or Write()
734   // indicated that no bytes could be written. If no bytes could be written,
735   // then return -1 because the fill value is invalid. This will trigger a throw
736   // in JavaScript. Silently failing should be avoided because it can lead to
737   // buffers with unexpected contents.
738   if (str_length == 0)
739     return args.GetReturnValue().Set(-1);
740 
741   size_t in_there = str_length;
742   char* ptr = ts_obj_data + start + str_length;
743 
744   while (in_there < fill_length - in_there) {
745     memcpy(ptr, ts_obj_data + start, in_there);
746     ptr += in_there;
747     in_there *= 2;
748   }
749 
750   if (in_there < fill_length) {
751     memcpy(ptr, ts_obj_data + start, fill_length - in_there);
752   }
753 }
754 
755 
756 template <encoding encoding>
StringWrite(const FunctionCallbackInfo<Value>& args)757 void StringWrite(const FunctionCallbackInfo<Value>& args) {
758   Environment* env = Environment::GetCurrent(args);
759 
760   THROW_AND_RETURN_UNLESS_BUFFER(env, args.This());
761   SPREAD_BUFFER_ARG(args.This(), ts_obj);
762 
763   THROW_AND_RETURN_IF_NOT_STRING(env, args[0], "argument");
764 
765   Local<String> str = args[0]->ToString(env->context()).ToLocalChecked();
766 
767   size_t offset = 0;
768   size_t max_length = 0;
769 
770   THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[1], 0, &offset));
771   if (offset > ts_obj_length) {
772     return node::THROW_ERR_BUFFER_OUT_OF_BOUNDS(
773         env, "\"offset\" is outside of buffer bounds");
774   }
775 
776   THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[2], ts_obj_length - offset,
777                                           &max_length));
778 
779   max_length = std::min(ts_obj_length - offset, max_length);
780 
781   if (max_length == 0)
782     return args.GetReturnValue().Set(0);
783 
784   uint32_t written = StringBytes::Write(
785       env->isolate(), ts_obj_data + offset, max_length, str, encoding);
786   args.GetReturnValue().Set(written);
787 }
788 
ByteLengthUtf8(const FunctionCallbackInfo<Value> &args)789 void ByteLengthUtf8(const FunctionCallbackInfo<Value> &args) {
790   Environment* env = Environment::GetCurrent(args);
791   CHECK(args[0]->IsString());
792 
793   // Fast case: avoid StringBytes on UTF8 string. Jump to v8.
794   args.GetReturnValue().Set(args[0].As<String>()->Utf8Length(env->isolate()));
795 }
796 
797 // Normalize val to be an integer in the range of [1, -1] since
798 // implementations of memcmp() can vary by platform.
normalizeCompareVal(int val, size_t a_length, size_t b_length)799 static int normalizeCompareVal(int val, size_t a_length, size_t b_length) {
800   if (val == 0) {
801     if (a_length > b_length)
802       return 1;
803     else if (a_length < b_length)
804       return -1;
805   } else {
806     if (val > 0)
807       return 1;
808     else
809       return -1;
810   }
811   return val;
812 }
813 
CompareOffset(const FunctionCallbackInfo<Value> &args)814 void CompareOffset(const FunctionCallbackInfo<Value> &args) {
815   Environment* env = Environment::GetCurrent(args);
816 
817   THROW_AND_RETURN_UNLESS_BUFFER(env, args[0]);
818   THROW_AND_RETURN_UNLESS_BUFFER(env, args[1]);
819   ArrayBufferViewContents<char> source(args[0]);
820   ArrayBufferViewContents<char> target(args[1]);
821 
822   size_t target_start = 0;
823   size_t source_start = 0;
824   size_t source_end = 0;
825   size_t target_end = 0;
826 
827   THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[2], 0, &target_start));
828   THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[3], 0, &source_start));
829   THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[4], target.length(),
830                                           &target_end));
831   THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[5], source.length(),
832                                           &source_end));
833 
834   if (source_start > source.length())
835     return THROW_ERR_OUT_OF_RANGE(
836         env, "The value of \"sourceStart\" is out of range.");
837   if (target_start > target.length())
838     return THROW_ERR_OUT_OF_RANGE(
839         env, "The value of \"targetStart\" is out of range.");
840 
841   CHECK_LE(source_start, source_end);
842   CHECK_LE(target_start, target_end);
843 
844   size_t to_cmp =
845       std::min(std::min(source_end - source_start, target_end - target_start),
846                source.length() - source_start);
847 
848   int val = normalizeCompareVal(to_cmp > 0 ?
849                                   memcmp(source.data() + source_start,
850                                          target.data() + target_start,
851                                          to_cmp) : 0,
852                                 source_end - source_start,
853                                 target_end - target_start);
854 
855   args.GetReturnValue().Set(val);
856 }
857 
Compare(const FunctionCallbackInfo<Value> &args)858 void Compare(const FunctionCallbackInfo<Value> &args) {
859   Environment* env = Environment::GetCurrent(args);
860 
861   THROW_AND_RETURN_UNLESS_BUFFER(env, args[0]);
862   THROW_AND_RETURN_UNLESS_BUFFER(env, args[1]);
863   ArrayBufferViewContents<char> a(args[0]);
864   ArrayBufferViewContents<char> b(args[1]);
865 
866   size_t cmp_length = std::min(a.length(), b.length());
867 
868   int val = normalizeCompareVal(cmp_length > 0 ?
869                                 memcmp(a.data(), b.data(), cmp_length) : 0,
870                                 a.length(), b.length());
871   args.GetReturnValue().Set(val);
872 }
873 
874 
875 // Computes the offset for starting an indexOf or lastIndexOf search.
876 // Returns either a valid offset in [0...<length - 1>], ie inside the Buffer,
877 // or -1 to signal that there is no possible match.
IndexOfOffset(size_t length, int64_t offset_i64, int64_t needle_length, bool is_forward)878 int64_t IndexOfOffset(size_t length,
879                       int64_t offset_i64,
880                       int64_t needle_length,
881                       bool is_forward) {
882   int64_t length_i64 = static_cast<int64_t>(length);
883   if (offset_i64 < 0) {
884     if (offset_i64 + length_i64 >= 0) {
885       // Negative offsets count backwards from the end of the buffer.
886       return length_i64 + offset_i64;
887     } else if (is_forward || needle_length == 0) {
888       // indexOf from before the start of the buffer: search the whole buffer.
889       return 0;
890     } else {
891       // lastIndexOf from before the start of the buffer: no match.
892       return -1;
893     }
894   } else {
895     if (offset_i64 + needle_length <= length_i64) {
896       // Valid positive offset.
897       return offset_i64;
898     } else if (needle_length == 0) {
899       // Out of buffer bounds, but empty needle: point to end of buffer.
900       return length_i64;
901     } else if (is_forward) {
902       // indexOf from past the end of the buffer: no match.
903       return -1;
904     } else {
905       // lastIndexOf from past the end of the buffer: search the whole buffer.
906       return length_i64 - 1;
907     }
908   }
909 }
910 
IndexOfString(const FunctionCallbackInfo<Value>& args)911 void IndexOfString(const FunctionCallbackInfo<Value>& args) {
912   Environment* env = Environment::GetCurrent(args);
913   Isolate* isolate = env->isolate();
914 
915   CHECK(args[1]->IsString());
916   CHECK(args[2]->IsNumber());
917   CHECK(args[3]->IsInt32());
918   CHECK(args[4]->IsBoolean());
919 
920   enum encoding enc = static_cast<enum encoding>(args[3].As<Int32>()->Value());
921 
922   THROW_AND_RETURN_UNLESS_BUFFER(env, args[0]);
923   ArrayBufferViewContents<char> buffer(args[0]);
924 
925   Local<String> needle = args[1].As<String>();
926   int64_t offset_i64 = args[2].As<Integer>()->Value();
927   bool is_forward = args[4]->IsTrue();
928 
929   const char* haystack = buffer.data();
930   // Round down to the nearest multiple of 2 in case of UCS2.
931   const size_t haystack_length = (enc == UCS2) ?
932       buffer.length() &~ 1 : buffer.length();  // NOLINT(whitespace/operators)
933 
934   size_t needle_length;
935   if (!StringBytes::Size(isolate, needle, enc).To(&needle_length)) return;
936 
937   int64_t opt_offset = IndexOfOffset(haystack_length,
938                                      offset_i64,
939                                      needle_length,
940                                      is_forward);
941 
942   if (needle_length == 0) {
943     // Match String#indexOf() and String#lastIndexOf() behavior.
944     args.GetReturnValue().Set(static_cast<double>(opt_offset));
945     return;
946   }
947 
948   if (haystack_length == 0) {
949     return args.GetReturnValue().Set(-1);
950   }
951 
952   if (opt_offset <= -1) {
953     return args.GetReturnValue().Set(-1);
954   }
955   size_t offset = static_cast<size_t>(opt_offset);
956   CHECK_LT(offset, haystack_length);
957   if ((is_forward && needle_length + offset > haystack_length) ||
958       needle_length > haystack_length) {
959     return args.GetReturnValue().Set(-1);
960   }
961 
962   size_t result = haystack_length;
963 
964   if (enc == UCS2) {
965     String::Value needle_value(isolate, needle);
966     if (*needle_value == nullptr)
967       return args.GetReturnValue().Set(-1);
968 
969     if (haystack_length < 2 || needle_value.length() < 1) {
970       return args.GetReturnValue().Set(-1);
971     }
972 
973     if (IsBigEndian()) {
974       StringBytes::InlineDecoder decoder;
975       if (decoder.Decode(env, needle, enc).IsNothing()) return;
976       const uint16_t* decoded_string =
977           reinterpret_cast<const uint16_t*>(decoder.out());
978 
979       if (decoded_string == nullptr)
980         return args.GetReturnValue().Set(-1);
981 
982       result = SearchString(reinterpret_cast<const uint16_t*>(haystack),
983                             haystack_length / 2,
984                             decoded_string,
985                             decoder.size() / 2,
986                             offset / 2,
987                             is_forward);
988     } else {
989       result = SearchString(reinterpret_cast<const uint16_t*>(haystack),
990                             haystack_length / 2,
991                             reinterpret_cast<const uint16_t*>(*needle_value),
992                             needle_value.length(),
993                             offset / 2,
994                             is_forward);
995     }
996     result *= 2;
997   } else if (enc == UTF8) {
998     String::Utf8Value needle_value(isolate, needle);
999     if (*needle_value == nullptr)
1000       return args.GetReturnValue().Set(-1);
1001 
1002     result = SearchString(reinterpret_cast<const uint8_t*>(haystack),
1003                           haystack_length,
1004                           reinterpret_cast<const uint8_t*>(*needle_value),
1005                           needle_length,
1006                           offset,
1007                           is_forward);
1008   } else if (enc == LATIN1) {
1009     uint8_t* needle_data = node::UncheckedMalloc<uint8_t>(needle_length);
1010     if (needle_data == nullptr) {
1011       return args.GetReturnValue().Set(-1);
1012     }
1013     needle->WriteOneByte(
1014         isolate, needle_data, 0, needle_length, String::NO_NULL_TERMINATION);
1015 
1016     result = SearchString(reinterpret_cast<const uint8_t*>(haystack),
1017                           haystack_length,
1018                           needle_data,
1019                           needle_length,
1020                           offset,
1021                           is_forward);
1022     free(needle_data);
1023   }
1024 
1025   args.GetReturnValue().Set(
1026       result == haystack_length ? -1 : static_cast<int>(result));
1027 }
1028 
IndexOfBuffer(const FunctionCallbackInfo<Value>& args)1029 void IndexOfBuffer(const FunctionCallbackInfo<Value>& args) {
1030   CHECK(args[1]->IsObject());
1031   CHECK(args[2]->IsNumber());
1032   CHECK(args[3]->IsInt32());
1033   CHECK(args[4]->IsBoolean());
1034 
1035   enum encoding enc = static_cast<enum encoding>(args[3].As<Int32>()->Value());
1036 
1037   THROW_AND_RETURN_UNLESS_BUFFER(Environment::GetCurrent(args), args[0]);
1038   THROW_AND_RETURN_UNLESS_BUFFER(Environment::GetCurrent(args), args[1]);
1039   ArrayBufferViewContents<char> haystack_contents(args[0]);
1040   ArrayBufferViewContents<char> needle_contents(args[1]);
1041   int64_t offset_i64 = args[2].As<Integer>()->Value();
1042   bool is_forward = args[4]->IsTrue();
1043 
1044   const char* haystack = haystack_contents.data();
1045   const size_t haystack_length = haystack_contents.length();
1046   const char* needle = needle_contents.data();
1047   const size_t needle_length = needle_contents.length();
1048 
1049   int64_t opt_offset = IndexOfOffset(haystack_length,
1050                                      offset_i64,
1051                                      needle_length,
1052                                      is_forward);
1053 
1054   if (needle_length == 0) {
1055     // Match String#indexOf() and String#lastIndexOf() behavior.
1056     args.GetReturnValue().Set(static_cast<double>(opt_offset));
1057     return;
1058   }
1059 
1060   if (haystack_length == 0) {
1061     return args.GetReturnValue().Set(-1);
1062   }
1063 
1064   if (opt_offset <= -1) {
1065     return args.GetReturnValue().Set(-1);
1066   }
1067   size_t offset = static_cast<size_t>(opt_offset);
1068   CHECK_LT(offset, haystack_length);
1069   if ((is_forward && needle_length + offset > haystack_length) ||
1070       needle_length > haystack_length) {
1071     return args.GetReturnValue().Set(-1);
1072   }
1073 
1074   size_t result = haystack_length;
1075 
1076   if (enc == UCS2) {
1077     if (haystack_length < 2 || needle_length < 2) {
1078       return args.GetReturnValue().Set(-1);
1079     }
1080     result = SearchString(
1081         reinterpret_cast<const uint16_t*>(haystack),
1082         haystack_length / 2,
1083         reinterpret_cast<const uint16_t*>(needle),
1084         needle_length / 2,
1085         offset / 2,
1086         is_forward);
1087     result *= 2;
1088   } else {
1089     result = SearchString(
1090         reinterpret_cast<const uint8_t*>(haystack),
1091         haystack_length,
1092         reinterpret_cast<const uint8_t*>(needle),
1093         needle_length,
1094         offset,
1095         is_forward);
1096   }
1097 
1098   args.GetReturnValue().Set(
1099       result == haystack_length ? -1 : static_cast<int>(result));
1100 }
1101 
IndexOfNumber(const FunctionCallbackInfo<Value>& args)1102 void IndexOfNumber(const FunctionCallbackInfo<Value>& args) {
1103   CHECK(args[1]->IsUint32());
1104   CHECK(args[2]->IsNumber());
1105   CHECK(args[3]->IsBoolean());
1106 
1107   THROW_AND_RETURN_UNLESS_BUFFER(Environment::GetCurrent(args), args[0]);
1108   ArrayBufferViewContents<char> buffer(args[0]);
1109 
1110   uint32_t needle = args[1].As<Uint32>()->Value();
1111   int64_t offset_i64 = args[2].As<Integer>()->Value();
1112   bool is_forward = args[3]->IsTrue();
1113 
1114   int64_t opt_offset =
1115       IndexOfOffset(buffer.length(), offset_i64, 1, is_forward);
1116   if (opt_offset <= -1 || buffer.length() == 0) {
1117     return args.GetReturnValue().Set(-1);
1118   }
1119   size_t offset = static_cast<size_t>(opt_offset);
1120   CHECK_LT(offset, buffer.length());
1121 
1122   const void* ptr;
1123   if (is_forward) {
1124     ptr = memchr(buffer.data() + offset, needle, buffer.length() - offset);
1125   } else {
1126     ptr = node::stringsearch::MemrchrFill(buffer.data(), needle, offset + 1);
1127   }
1128   const char* ptr_char = static_cast<const char*>(ptr);
1129   args.GetReturnValue().Set(ptr ? static_cast<int>(ptr_char - buffer.data())
1130                                 : -1);
1131 }
1132 
1133 
Swap16(const FunctionCallbackInfo<Value>& args)1134 void Swap16(const FunctionCallbackInfo<Value>& args) {
1135   Environment* env = Environment::GetCurrent(args);
1136   THROW_AND_RETURN_UNLESS_BUFFER(env, args[0]);
1137   SPREAD_BUFFER_ARG(args[0], ts_obj);
1138   SwapBytes16(ts_obj_data, ts_obj_length);
1139   args.GetReturnValue().Set(args[0]);
1140 }
1141 
1142 
Swap32(const FunctionCallbackInfo<Value>& args)1143 void Swap32(const FunctionCallbackInfo<Value>& args) {
1144   Environment* env = Environment::GetCurrent(args);
1145   THROW_AND_RETURN_UNLESS_BUFFER(env, args[0]);
1146   SPREAD_BUFFER_ARG(args[0], ts_obj);
1147   SwapBytes32(ts_obj_data, ts_obj_length);
1148   args.GetReturnValue().Set(args[0]);
1149 }
1150 
1151 
Swap64(const FunctionCallbackInfo<Value>& args)1152 void Swap64(const FunctionCallbackInfo<Value>& args) {
1153   Environment* env = Environment::GetCurrent(args);
1154   THROW_AND_RETURN_UNLESS_BUFFER(env, args[0]);
1155   SPREAD_BUFFER_ARG(args[0], ts_obj);
1156   SwapBytes64(ts_obj_data, ts_obj_length);
1157   args.GetReturnValue().Set(args[0]);
1158 }
1159 
1160 
1161 // Encode a single string to a UTF-8 Uint8Array (not Buffer).
1162 // Used in TextEncoder.prototype.encode.
EncodeUtf8String(const FunctionCallbackInfo<Value>& args)1163 static void EncodeUtf8String(const FunctionCallbackInfo<Value>& args) {
1164   Environment* env = Environment::GetCurrent(args);
1165   Isolate* isolate = env->isolate();
1166   CHECK_GE(args.Length(), 1);
1167   CHECK(args[0]->IsString());
1168 
1169   Local<String> str = args[0].As<String>();
1170   size_t length = str->Utf8Length(isolate);
1171 
1172   Local<ArrayBuffer> ab;
1173   {
1174     NoArrayBufferZeroFillScope no_zero_fill_scope(env->isolate_data());
1175     std::unique_ptr<BackingStore> bs =
1176         ArrayBuffer::NewBackingStore(isolate, length);
1177 
1178     CHECK(bs);
1179 
1180     str->WriteUtf8(isolate,
1181                    static_cast<char*>(bs->Data()),
1182                    -1,  // We are certain that `data` is sufficiently large
1183                    nullptr,
1184                    String::NO_NULL_TERMINATION | String::REPLACE_INVALID_UTF8);
1185 
1186     ab = ArrayBuffer::New(isolate, std::move(bs));
1187   }
1188 
1189   auto array = Uint8Array::New(ab, 0, length);
1190   args.GetReturnValue().Set(array);
1191 }
1192 
1193 
EncodeInto(const FunctionCallbackInfo<Value>& args)1194 static void EncodeInto(const FunctionCallbackInfo<Value>& args) {
1195   Environment* env = Environment::GetCurrent(args);
1196   Isolate* isolate = env->isolate();
1197   CHECK_GE(args.Length(), 3);
1198   CHECK(args[0]->IsString());
1199   CHECK(args[1]->IsUint8Array());
1200   CHECK(args[2]->IsUint32Array());
1201 
1202   Local<String> source = args[0].As<String>();
1203 
1204   Local<Uint8Array> dest = args[1].As<Uint8Array>();
1205   Local<ArrayBuffer> buf = dest->Buffer();
1206   char* write_result = static_cast<char*>(buf->Data()) + dest->ByteOffset();
1207   size_t dest_length = dest->ByteLength();
1208 
1209   // results = [ read, written ]
1210   Local<Uint32Array> result_arr = args[2].As<Uint32Array>();
1211   uint32_t* results = reinterpret_cast<uint32_t*>(
1212       static_cast<char*>(result_arr->Buffer()->Data()) +
1213       result_arr->ByteOffset());
1214 
1215   int nchars;
1216   int written = source->WriteUtf8(
1217       isolate,
1218       write_result,
1219       dest_length,
1220       &nchars,
1221       String::NO_NULL_TERMINATION | String::REPLACE_INVALID_UTF8);
1222   results[0] = nchars;
1223   results[1] = written;
1224 }
1225 
IsUtf8(const FunctionCallbackInfo<Value>& args)1226 static void IsUtf8(const FunctionCallbackInfo<Value>& args) {
1227   Environment* env = Environment::GetCurrent(args);
1228   CHECK_EQ(args.Length(), 1);
1229   CHECK(args[0]->IsTypedArray() || args[0]->IsArrayBuffer() ||
1230         args[0]->IsSharedArrayBuffer());
1231   ArrayBufferViewContents<char> abv(args[0]);
1232 
1233   if (abv.WasDetached()) {
1234     return node::THROW_ERR_INVALID_STATE(
1235         env, "Cannot validate on a detached buffer");
1236   }
1237 
1238   args.GetReturnValue().Set(simdutf::validate_utf8(abv.data(), abv.length()));
1239 }
1240 
IsAscii(const FunctionCallbackInfo<Value>& args)1241 static void IsAscii(const FunctionCallbackInfo<Value>& args) {
1242   Environment* env = Environment::GetCurrent(args);
1243   CHECK_EQ(args.Length(), 1);
1244   CHECK(args[0]->IsTypedArray() || args[0]->IsArrayBuffer() ||
1245         args[0]->IsSharedArrayBuffer());
1246   ArrayBufferViewContents<char> abv(args[0]);
1247 
1248   if (abv.WasDetached()) {
1249     return node::THROW_ERR_INVALID_STATE(
1250         env, "Cannot validate on a detached buffer");
1251   }
1252 
1253   args.GetReturnValue().Set(simdutf::validate_ascii(abv.data(), abv.length()));
1254 }
1255 
SetBufferPrototype(const FunctionCallbackInfo<Value>& args)1256 void SetBufferPrototype(const FunctionCallbackInfo<Value>& args) {
1257   Environment* env = Environment::GetCurrent(args);
1258 
1259   CHECK(args[0]->IsObject());
1260   Local<Object> proto = args[0].As<Object>();
1261   env->set_buffer_prototype_object(proto);
1262 }
1263 
GetZeroFillToggle(const FunctionCallbackInfo<Value>& args)1264 void GetZeroFillToggle(const FunctionCallbackInfo<Value>& args) {
1265   Environment* env = Environment::GetCurrent(args);
1266   NodeArrayBufferAllocator* allocator = env->isolate_data()->node_allocator();
1267   Local<ArrayBuffer> ab;
1268   // It can be a nullptr when running inside an isolate where we
1269   // do not own the ArrayBuffer allocator.
1270   if (allocator == nullptr) {
1271     // Create a dummy Uint32Array - the JS land can only toggle the C++ land
1272     // setting when the allocator uses our toggle. With this the toggle in JS
1273     // land results in no-ops.
1274     ab = ArrayBuffer::New(env->isolate(), sizeof(uint32_t));
1275   } else {
1276     uint32_t* zero_fill_field = allocator->zero_fill_field();
1277     std::unique_ptr<BackingStore> backing =
1278         ArrayBuffer::NewBackingStore(zero_fill_field,
1279                                      sizeof(*zero_fill_field),
1280                                      [](void*, size_t, void*) {},
1281                                      nullptr);
1282     ab = ArrayBuffer::New(env->isolate(), std::move(backing));
1283   }
1284 
1285   ab->SetPrivate(
1286       env->context(),
1287       env->untransferable_object_private_symbol(),
1288       True(env->isolate())).Check();
1289 
1290   args.GetReturnValue().Set(Uint32Array::New(ab, 0, 1));
1291 }
1292 
DetachArrayBuffer(const FunctionCallbackInfo<Value>& args)1293 void DetachArrayBuffer(const FunctionCallbackInfo<Value>& args) {
1294   Environment* env = Environment::GetCurrent(args);
1295   if (args[0]->IsArrayBuffer()) {
1296     Local<ArrayBuffer> buf = args[0].As<ArrayBuffer>();
1297     if (buf->IsDetachable()) {
1298       std::shared_ptr<BackingStore> store = buf->GetBackingStore();
1299       buf->Detach();
1300       args.GetReturnValue().Set(ArrayBuffer::New(env->isolate(), store));
1301     }
1302   }
1303 }
1304 
1305 namespace {
1306 
DecomposeBufferToParts(Local<Value> buffer)1307 std::pair<void*, size_t> DecomposeBufferToParts(Local<Value> buffer) {
1308   void* pointer;
1309   size_t byte_length;
1310   if (buffer->IsArrayBuffer()) {
1311     Local<ArrayBuffer> ab = buffer.As<ArrayBuffer>();
1312     pointer = ab->Data();
1313     byte_length = ab->ByteLength();
1314   } else if (buffer->IsSharedArrayBuffer()) {
1315     Local<SharedArrayBuffer> ab = buffer.As<SharedArrayBuffer>();
1316     pointer = ab->Data();
1317     byte_length = ab->ByteLength();
1318   } else {
1319     UNREACHABLE();  // Caller must validate.
1320   }
1321   return {pointer, byte_length};
1322 }
1323 
1324 }  // namespace
1325 
CopyArrayBuffer(const FunctionCallbackInfo<Value>& args)1326 void CopyArrayBuffer(const FunctionCallbackInfo<Value>& args) {
1327   // args[0] == Destination ArrayBuffer
1328   // args[1] == Destination ArrayBuffer Offset
1329   // args[2] == Source ArrayBuffer
1330   // args[3] == Source ArrayBuffer Offset
1331   // args[4] == bytesToCopy
1332 
1333   CHECK(args[0]->IsArrayBuffer() || args[0]->IsSharedArrayBuffer());
1334   CHECK(args[1]->IsUint32());
1335   CHECK(args[2]->IsArrayBuffer() || args[2]->IsSharedArrayBuffer());
1336   CHECK(args[3]->IsUint32());
1337   CHECK(args[4]->IsUint32());
1338 
1339   void* destination;
1340   size_t destination_byte_length;
1341   std::tie(destination, destination_byte_length) =
1342       DecomposeBufferToParts(args[0]);
1343 
1344   void* source;
1345   size_t source_byte_length;
1346   std::tie(source, source_byte_length) = DecomposeBufferToParts(args[2]);
1347 
1348   uint32_t destination_offset = args[1].As<Uint32>()->Value();
1349   uint32_t source_offset = args[3].As<Uint32>()->Value();
1350   size_t bytes_to_copy = args[4].As<Uint32>()->Value();
1351 
1352   CHECK_GE(destination_byte_length - destination_offset, bytes_to_copy);
1353   CHECK_GE(source_byte_length - source_offset, bytes_to_copy);
1354 
1355   uint8_t* dest = static_cast<uint8_t*>(destination) + destination_offset;
1356   uint8_t* src = static_cast<uint8_t*>(source) + source_offset;
1357   memcpy(dest, src, bytes_to_copy);
1358 }
1359 
Initialize(Local<Object> target, Local<Value> unused, Local<Context> context, void* priv)1360 void Initialize(Local<Object> target,
1361                 Local<Value> unused,
1362                 Local<Context> context,
1363                 void* priv) {
1364   Environment* env = Environment::GetCurrent(context);
1365   Isolate* isolate = env->isolate();
1366 
1367   SetMethod(context, target, "setBufferPrototype", SetBufferPrototype);
1368   SetMethodNoSideEffect(context, target, "createFromString", CreateFromString);
1369   SetMethodNoSideEffect(context, target, "decodeUTF8", DecodeUTF8);
1370 
1371   SetMethodNoSideEffect(context, target, "byteLengthUtf8", ByteLengthUtf8);
1372   SetMethod(context, target, "copy", Copy);
1373   SetMethodNoSideEffect(context, target, "compare", Compare);
1374   SetMethodNoSideEffect(context, target, "compareOffset", CompareOffset);
1375   SetMethod(context, target, "fill", Fill);
1376   SetMethodNoSideEffect(context, target, "indexOfBuffer", IndexOfBuffer);
1377   SetMethodNoSideEffect(context, target, "indexOfNumber", IndexOfNumber);
1378   SetMethodNoSideEffect(context, target, "indexOfString", IndexOfString);
1379 
1380   SetMethod(context, target, "detachArrayBuffer", DetachArrayBuffer);
1381   SetMethod(context, target, "copyArrayBuffer", CopyArrayBuffer);
1382 
1383   SetMethod(context, target, "swap16", Swap16);
1384   SetMethod(context, target, "swap32", Swap32);
1385   SetMethod(context, target, "swap64", Swap64);
1386 
1387   SetMethod(context, target, "encodeInto", EncodeInto);
1388   SetMethodNoSideEffect(context, target, "encodeUtf8String", EncodeUtf8String);
1389 
1390   SetMethodNoSideEffect(context, target, "isUtf8", IsUtf8);
1391   SetMethodNoSideEffect(context, target, "isAscii", IsAscii);
1392 
1393   target
1394       ->Set(context,
1395             FIXED_ONE_BYTE_STRING(isolate, "kMaxLength"),
1396             Number::New(isolate, kMaxLength))
1397       .Check();
1398 
1399   target
1400       ->Set(context,
1401             FIXED_ONE_BYTE_STRING(isolate, "kStringMaxLength"),
1402             Integer::New(isolate, String::kMaxLength))
1403       .Check();
1404 
1405   SetMethodNoSideEffect(context, target, "asciiSlice", StringSlice<ASCII>);
1406   SetMethodNoSideEffect(context, target, "base64Slice", StringSlice<BASE64>);
1407   SetMethodNoSideEffect(
1408       context, target, "base64urlSlice", StringSlice<BASE64URL>);
1409   SetMethodNoSideEffect(context, target, "latin1Slice", StringSlice<LATIN1>);
1410   SetMethodNoSideEffect(context, target, "hexSlice", StringSlice<HEX>);
1411   SetMethodNoSideEffect(context, target, "ucs2Slice", StringSlice<UCS2>);
1412   SetMethodNoSideEffect(context, target, "utf8Slice", StringSlice<UTF8>);
1413 
1414   SetMethod(context, target, "asciiWrite", StringWrite<ASCII>);
1415   SetMethod(context, target, "base64Write", StringWrite<BASE64>);
1416   SetMethod(context, target, "base64urlWrite", StringWrite<BASE64URL>);
1417   SetMethod(context, target, "latin1Write", StringWrite<LATIN1>);
1418   SetMethod(context, target, "hexWrite", StringWrite<HEX>);
1419   SetMethod(context, target, "ucs2Write", StringWrite<UCS2>);
1420   SetMethod(context, target, "utf8Write", StringWrite<UTF8>);
1421 
1422   SetMethod(context, target, "getZeroFillToggle", GetZeroFillToggle);
1423 }
1424 
1425 }  // anonymous namespace
1426 
RegisterExternalReferences(ExternalReferenceRegistry* registry)1427 void RegisterExternalReferences(ExternalReferenceRegistry* registry) {
1428   registry->Register(SetBufferPrototype);
1429   registry->Register(CreateFromString);
1430   registry->Register(DecodeUTF8);
1431 
1432   registry->Register(ByteLengthUtf8);
1433   registry->Register(Copy);
1434   registry->Register(Compare);
1435   registry->Register(CompareOffset);
1436   registry->Register(Fill);
1437   registry->Register(IndexOfBuffer);
1438   registry->Register(IndexOfNumber);
1439   registry->Register(IndexOfString);
1440 
1441   registry->Register(Swap16);
1442   registry->Register(Swap32);
1443   registry->Register(Swap64);
1444 
1445   registry->Register(EncodeInto);
1446   registry->Register(EncodeUtf8String);
1447 
1448   registry->Register(IsUtf8);
1449   registry->Register(IsAscii);
1450 
1451   registry->Register(StringSlice<ASCII>);
1452   registry->Register(StringSlice<BASE64>);
1453   registry->Register(StringSlice<BASE64URL>);
1454   registry->Register(StringSlice<LATIN1>);
1455   registry->Register(StringSlice<HEX>);
1456   registry->Register(StringSlice<UCS2>);
1457   registry->Register(StringSlice<UTF8>);
1458 
1459   registry->Register(StringWrite<ASCII>);
1460   registry->Register(StringWrite<BASE64>);
1461   registry->Register(StringWrite<BASE64URL>);
1462   registry->Register(StringWrite<LATIN1>);
1463   registry->Register(StringWrite<HEX>);
1464   registry->Register(StringWrite<UCS2>);
1465   registry->Register(StringWrite<UTF8>);
1466   registry->Register(GetZeroFillToggle);
1467 
1468   registry->Register(DetachArrayBuffer);
1469   registry->Register(CopyArrayBuffer);
1470 }
1471 
1472 }  // namespace Buffer
1473 }  // namespace node
1474 
1475 NODE_BINDING_CONTEXT_AWARE_INTERNAL(buffer, node::Buffer::Initialize)
1476 NODE_BINDING_EXTERNAL_REFERENCE(buffer,
1477                                 node::Buffer::RegisterExternalReferences)
1478