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_errors.h"
25 #include "node_internals.h"
26
27 #include "env-inl.h"
28 #include "string_bytes.h"
29 #include "string_search.h"
30 #include "util-inl.h"
31 #include "v8.h"
32
33 #include <cstring>
34 #include <climits>
35
36 #define THROW_AND_RETURN_UNLESS_BUFFER(env, obj) \
37 THROW_AND_RETURN_IF_NOT_BUFFER(env, obj, "argument") \
38
39 #define THROW_AND_RETURN_IF_OOB(r) \
40 do { \
41 if ((r).IsNothing()) return; \
42 if (!(r).FromJust()) \
43 return node::THROW_ERR_OUT_OF_RANGE(env, "Index out of range"); \
44 } while (0) \
45
46 namespace node {
47 namespace Buffer {
48
49 using v8::ArrayBuffer;
50 using v8::ArrayBufferCreationMode;
51 using v8::ArrayBufferView;
52 using v8::Context;
53 using v8::EscapableHandleScope;
54 using v8::FunctionCallbackInfo;
55 using v8::Global;
56 using v8::HandleScope;
57 using v8::Int32;
58 using v8::Integer;
59 using v8::Isolate;
60 using v8::Just;
61 using v8::Local;
62 using v8::Maybe;
63 using v8::MaybeLocal;
64 using v8::Nothing;
65 using v8::Object;
66 using v8::String;
67 using v8::Uint32;
68 using v8::Uint32Array;
69 using v8::Uint8Array;
70 using v8::Value;
71 using v8::WeakCallbackInfo;
72
73 namespace {
74
75 class CallbackInfo {
76 public:
77 ~CallbackInfo();
78
79 static inline void Free(char* data, void* hint);
80 static inline CallbackInfo* New(Environment* env,
81 Local<ArrayBuffer> object,
82 FreeCallback callback,
83 char* data,
84 void* hint = nullptr);
85
86 CallbackInfo(const CallbackInfo&) = delete;
87 CallbackInfo& operator=(const CallbackInfo&) = delete;
88
89 private:
90 static void CleanupHook(void* data);
91 static void WeakCallback(const WeakCallbackInfo<CallbackInfo>&);
92 inline void WeakCallback(Isolate* isolate);
93 inline CallbackInfo(Environment* env,
94 Local<ArrayBuffer> object,
95 FreeCallback callback,
96 char* data,
97 void* hint);
98 Global<ArrayBuffer> persistent_;
99 FreeCallback const callback_;
100 char* const data_;
101 void* const hint_;
102 Environment* const env_;
103 };
104
105
Free(char * data,void *)106 void CallbackInfo::Free(char* data, void*) {
107 ::free(data);
108 }
109
110
New(Environment * env,Local<ArrayBuffer> object,FreeCallback callback,char * data,void * hint)111 CallbackInfo* CallbackInfo::New(Environment* env,
112 Local<ArrayBuffer> object,
113 FreeCallback callback,
114 char* data,
115 void* hint) {
116 return new CallbackInfo(env, object, callback, data, hint);
117 }
118
119
CallbackInfo(Environment * env,Local<ArrayBuffer> object,FreeCallback callback,char * data,void * hint)120 CallbackInfo::CallbackInfo(Environment* env,
121 Local<ArrayBuffer> object,
122 FreeCallback callback,
123 char* data,
124 void* hint)
125 : persistent_(env->isolate(), object),
126 callback_(callback),
127 data_(data),
128 hint_(hint),
129 env_(env) {
130 ArrayBuffer::Contents obj_c = object->GetContents();
131 CHECK_EQ(data_, static_cast<char*>(obj_c.Data()));
132 if (object->ByteLength() != 0)
133 CHECK_NOT_NULL(data_);
134
135 persistent_.SetWeak(this, WeakCallback, v8::WeakCallbackType::kParameter);
136 env->AddCleanupHook(CleanupHook, this);
137 env->isolate()->AdjustAmountOfExternalAllocatedMemory(sizeof(*this));
138 }
139
140
~CallbackInfo()141 CallbackInfo::~CallbackInfo() {
142 persistent_.Reset();
143 env_->RemoveCleanupHook(CleanupHook, this);
144 }
145
146
CleanupHook(void * data)147 void CallbackInfo::CleanupHook(void* data) {
148 CallbackInfo* self = static_cast<CallbackInfo*>(data);
149
150 {
151 HandleScope handle_scope(self->env_->isolate());
152 Local<ArrayBuffer> ab = self->persistent_.Get(self->env_->isolate());
153 CHECK(!ab.IsEmpty());
154 if (ab->IsDetachable())
155 ab->Detach();
156 }
157
158 self->WeakCallback(self->env_->isolate());
159 }
160
161
WeakCallback(const WeakCallbackInfo<CallbackInfo> & data)162 void CallbackInfo::WeakCallback(
163 const WeakCallbackInfo<CallbackInfo>& data) {
164 CallbackInfo* self = data.GetParameter();
165 self->WeakCallback(data.GetIsolate());
166 }
167
168
WeakCallback(Isolate * isolate)169 void CallbackInfo::WeakCallback(Isolate* isolate) {
170 callback_(data_, hint_);
171 int64_t change_in_bytes = -static_cast<int64_t>(sizeof(*this));
172 isolate->AdjustAmountOfExternalAllocatedMemory(change_in_bytes);
173 delete this;
174 }
175
176
177 // Parse index for external array data. An empty Maybe indicates
178 // a pending exception. `false` indicates that the index is out-of-bounds.
ParseArrayIndex(Environment * env,Local<Value> arg,size_t def,size_t * ret)179 inline MUST_USE_RESULT Maybe<bool> ParseArrayIndex(Environment* env,
180 Local<Value> arg,
181 size_t def,
182 size_t* ret) {
183 if (arg->IsUndefined()) {
184 *ret = def;
185 return Just(true);
186 }
187
188 int64_t tmp_i;
189 if (!arg->IntegerValue(env->context()).To(&tmp_i))
190 return Nothing<bool>();
191
192 if (tmp_i < 0)
193 return Just(false);
194
195 // Check that the result fits in a size_t.
196 const uint64_t kSizeMax = static_cast<uint64_t>(static_cast<size_t>(-1));
197 // coverity[pointless_expression]
198 if (static_cast<uint64_t>(tmp_i) > kSizeMax)
199 return Just(false);
200
201 *ret = static_cast<size_t>(tmp_i);
202 return Just(true);
203 }
204
205 } // anonymous namespace
206
207 // Buffer methods
208
HasInstance(Local<Value> val)209 bool HasInstance(Local<Value> val) {
210 return val->IsArrayBufferView();
211 }
212
213
HasInstance(Local<Object> obj)214 bool HasInstance(Local<Object> obj) {
215 return obj->IsArrayBufferView();
216 }
217
218
Data(Local<Value> val)219 char* Data(Local<Value> val) {
220 CHECK(val->IsArrayBufferView());
221 Local<ArrayBufferView> ui = val.As<ArrayBufferView>();
222 ArrayBuffer::Contents ab_c = ui->Buffer()->GetContents();
223 return static_cast<char*>(ab_c.Data()) + ui->ByteOffset();
224 }
225
226
Data(Local<Object> obj)227 char* Data(Local<Object> obj) {
228 CHECK(obj->IsArrayBufferView());
229 Local<ArrayBufferView> ui = obj.As<ArrayBufferView>();
230 ArrayBuffer::Contents ab_c = ui->Buffer()->GetContents();
231 return static_cast<char*>(ab_c.Data()) + ui->ByteOffset();
232 }
233
234
Length(Local<Value> val)235 size_t Length(Local<Value> val) {
236 CHECK(val->IsArrayBufferView());
237 Local<ArrayBufferView> ui = val.As<ArrayBufferView>();
238 return ui->ByteLength();
239 }
240
241
Length(Local<Object> obj)242 size_t Length(Local<Object> obj) {
243 CHECK(obj->IsArrayBufferView());
244 Local<ArrayBufferView> ui = obj.As<ArrayBufferView>();
245 return ui->ByteLength();
246 }
247
248
New(Environment * env,Local<ArrayBuffer> ab,size_t byte_offset,size_t length)249 MaybeLocal<Uint8Array> New(Environment* env,
250 Local<ArrayBuffer> ab,
251 size_t byte_offset,
252 size_t length) {
253 CHECK(!env->buffer_prototype_object().IsEmpty());
254 Local<Uint8Array> ui = Uint8Array::New(ab, byte_offset, length);
255 Maybe<bool> mb =
256 ui->SetPrototype(env->context(), env->buffer_prototype_object());
257 if (mb.IsNothing())
258 return MaybeLocal<Uint8Array>();
259 return ui;
260 }
261
New(Isolate * isolate,Local<ArrayBuffer> ab,size_t byte_offset,size_t length)262 MaybeLocal<Uint8Array> New(Isolate* isolate,
263 Local<ArrayBuffer> ab,
264 size_t byte_offset,
265 size_t length) {
266 Environment* env = Environment::GetCurrent(isolate);
267 if (env == nullptr) {
268 THROW_ERR_BUFFER_CONTEXT_NOT_AVAILABLE(isolate);
269 return MaybeLocal<Uint8Array>();
270 }
271 return New(env, ab, byte_offset, length);
272 }
273
274
New(Isolate * isolate,Local<String> string,enum encoding enc)275 MaybeLocal<Object> New(Isolate* isolate,
276 Local<String> string,
277 enum encoding enc) {
278 EscapableHandleScope scope(isolate);
279
280 size_t length;
281 if (!StringBytes::Size(isolate, string, enc).To(&length))
282 return Local<Object>();
283 size_t actual = 0;
284 char* data = nullptr;
285
286 if (length > 0) {
287 data = UncheckedMalloc(length);
288
289 if (data == nullptr) {
290 THROW_ERR_MEMORY_ALLOCATION_FAILED(isolate);
291 return Local<Object>();
292 }
293
294 actual = StringBytes::Write(isolate, data, length, string, enc);
295 CHECK(actual <= length);
296
297 if (actual == 0) {
298 free(data);
299 data = nullptr;
300 } else if (actual < length) {
301 data = node::Realloc(data, actual);
302 }
303 }
304
305 return scope.EscapeMaybe(New(isolate, data, actual));
306 }
307
308
New(Isolate * isolate,size_t length)309 MaybeLocal<Object> New(Isolate* isolate, size_t length) {
310 EscapableHandleScope handle_scope(isolate);
311 Local<Object> obj;
312 Environment* env = Environment::GetCurrent(isolate);
313 if (env == nullptr) {
314 THROW_ERR_BUFFER_CONTEXT_NOT_AVAILABLE(isolate);
315 return MaybeLocal<Object>();
316 }
317 if (Buffer::New(env, length).ToLocal(&obj))
318 return handle_scope.Escape(obj);
319 return Local<Object>();
320 }
321
322
New(Environment * env,size_t length)323 MaybeLocal<Object> New(Environment* env, size_t length) {
324 EscapableHandleScope scope(env->isolate());
325
326 // V8 currently only allows a maximum Typed Array index of max Smi.
327 if (length > kMaxLength) {
328 env->isolate()->ThrowException(ERR_BUFFER_TOO_LARGE(env->isolate()));
329 return Local<Object>();
330 }
331
332 AllocatedBuffer ret(env);
333 if (length > 0) {
334 ret = env->AllocateManaged(length, false);
335 if (ret.data() == nullptr) {
336 THROW_ERR_MEMORY_ALLOCATION_FAILED(env);
337 return Local<Object>();
338 }
339 }
340
341 return scope.EscapeMaybe(ret.ToBuffer());
342 }
343
344
Copy(Isolate * isolate,const char * data,size_t length)345 MaybeLocal<Object> Copy(Isolate* isolate, const char* data, size_t length) {
346 EscapableHandleScope handle_scope(isolate);
347 Environment* env = Environment::GetCurrent(isolate);
348 if (env == nullptr) {
349 THROW_ERR_BUFFER_CONTEXT_NOT_AVAILABLE(isolate);
350 return MaybeLocal<Object>();
351 }
352 Local<Object> obj;
353 if (Buffer::Copy(env, data, length).ToLocal(&obj))
354 return handle_scope.Escape(obj);
355 return Local<Object>();
356 }
357
358
Copy(Environment * env,const char * data,size_t length)359 MaybeLocal<Object> Copy(Environment* env, const char* data, size_t length) {
360 EscapableHandleScope scope(env->isolate());
361
362 // V8 currently only allows a maximum Typed Array index of max Smi.
363 if (length > kMaxLength) {
364 env->isolate()->ThrowException(ERR_BUFFER_TOO_LARGE(env->isolate()));
365 return Local<Object>();
366 }
367
368 AllocatedBuffer ret(env);
369 if (length > 0) {
370 CHECK_NOT_NULL(data);
371 ret = env->AllocateManaged(length, false);
372 if (ret.data() == nullptr) {
373 THROW_ERR_MEMORY_ALLOCATION_FAILED(env);
374 return Local<Object>();
375 }
376 memcpy(ret.data(), data, length);
377 }
378
379 return scope.EscapeMaybe(ret.ToBuffer());
380 }
381
382
New(Isolate * isolate,char * data,size_t length,FreeCallback callback,void * hint)383 MaybeLocal<Object> New(Isolate* isolate,
384 char* data,
385 size_t length,
386 FreeCallback callback,
387 void* hint) {
388 EscapableHandleScope handle_scope(isolate);
389 Environment* env = Environment::GetCurrent(isolate);
390 if (env == nullptr) {
391 callback(data, hint);
392 THROW_ERR_BUFFER_CONTEXT_NOT_AVAILABLE(isolate);
393 return MaybeLocal<Object>();
394 }
395 return handle_scope.EscapeMaybe(
396 Buffer::New(env, data, length, callback, hint));
397 }
398
399
New(Environment * env,char * data,size_t length,FreeCallback callback,void * hint)400 MaybeLocal<Object> New(Environment* env,
401 char* data,
402 size_t length,
403 FreeCallback callback,
404 void* hint) {
405 EscapableHandleScope scope(env->isolate());
406
407 if (length > kMaxLength) {
408 env->isolate()->ThrowException(ERR_BUFFER_TOO_LARGE(env->isolate()));
409 callback(data, hint);
410 return Local<Object>();
411 }
412
413 Local<ArrayBuffer> ab = ArrayBuffer::New(env->isolate(), data, length);
414 if (ab->SetPrivate(env->context(),
415 env->untransferable_object_private_symbol(),
416 True(env->isolate())).IsNothing()) {
417 callback(data, hint);
418 return Local<Object>();
419 }
420 MaybeLocal<Uint8Array> ui = Buffer::New(env, ab, 0, length);
421
422 CallbackInfo::New(env, ab, callback, data, hint);
423
424 if (ui.IsEmpty())
425 return MaybeLocal<Object>();
426
427 return scope.Escape(ui.ToLocalChecked());
428 }
429
430 // Warning: This function needs `data` to be allocated with malloc() and not
431 // necessarily isolate's ArrayBuffer::Allocator.
New(Isolate * isolate,char * data,size_t length)432 MaybeLocal<Object> New(Isolate* isolate, char* data, size_t length) {
433 EscapableHandleScope handle_scope(isolate);
434 Environment* env = Environment::GetCurrent(isolate);
435 if (env == nullptr) {
436 free(data);
437 THROW_ERR_BUFFER_CONTEXT_NOT_AVAILABLE(isolate);
438 return MaybeLocal<Object>();
439 }
440 Local<Object> obj;
441 if (Buffer::New(env, data, length, true).ToLocal(&obj))
442 return handle_scope.Escape(obj);
443 return Local<Object>();
444 }
445
446 // Warning: If this call comes through the public node_buffer.h API,
447 // the contract for this function is that `data` is allocated with malloc()
448 // and not necessarily isolate's ArrayBuffer::Allocator.
New(Environment * env,char * data,size_t length,bool uses_malloc)449 MaybeLocal<Object> New(Environment* env,
450 char* data,
451 size_t length,
452 bool uses_malloc) {
453 if (length > 0) {
454 CHECK_NOT_NULL(data);
455 CHECK(length <= kMaxLength);
456 }
457
458 if (uses_malloc) {
459 if (!env->isolate_data()->uses_node_allocator()) {
460 // We don't know for sure that the allocator is malloc()-based, so we need
461 // to fall back to the FreeCallback variant.
462 auto free_callback = [](char* data, void* hint) { free(data); };
463 return New(env, data, length, free_callback, nullptr);
464 } else {
465 // This is malloc()-based, so we can acquire it into our own
466 // ArrayBufferAllocator.
467 CHECK_NOT_NULL(env->isolate_data()->node_allocator());
468 env->isolate_data()->node_allocator()->RegisterPointer(data, length);
469 }
470 }
471
472 Local<ArrayBuffer> ab =
473 ArrayBuffer::New(env->isolate(),
474 data,
475 length,
476 ArrayBufferCreationMode::kInternalized);
477 return Buffer::New(env, ab, 0, length).FromMaybe(Local<Object>());
478 }
479
480 namespace {
481
CreateFromString(const FunctionCallbackInfo<Value> & args)482 void CreateFromString(const FunctionCallbackInfo<Value>& args) {
483 CHECK(args[0]->IsString());
484 CHECK(args[1]->IsInt32());
485
486 enum encoding enc = static_cast<enum encoding>(args[1].As<Int32>()->Value());
487 Local<Object> buf;
488 if (New(args.GetIsolate(), args[0].As<String>(), enc).ToLocal(&buf))
489 args.GetReturnValue().Set(buf);
490 }
491
492
493 template <encoding encoding>
StringSlice(const FunctionCallbackInfo<Value> & args)494 void StringSlice(const FunctionCallbackInfo<Value>& args) {
495 Environment* env = Environment::GetCurrent(args);
496 Isolate* isolate = env->isolate();
497
498 THROW_AND_RETURN_UNLESS_BUFFER(env, args.This());
499 ArrayBufferViewContents<char> buffer(args.This());
500
501 if (buffer.length() == 0)
502 return args.GetReturnValue().SetEmptyString();
503
504 size_t start = 0;
505 size_t end = 0;
506 THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[0], 0, &start));
507 THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[1], buffer.length(), &end));
508 if (end < start) end = start;
509 THROW_AND_RETURN_IF_OOB(Just(end <= buffer.length()));
510 size_t length = end - start;
511
512 Local<Value> error;
513 MaybeLocal<Value> ret =
514 StringBytes::Encode(isolate,
515 buffer.data() + start,
516 length,
517 encoding,
518 &error);
519 if (ret.IsEmpty()) {
520 CHECK(!error.IsEmpty());
521 isolate->ThrowException(error);
522 return;
523 }
524 args.GetReturnValue().Set(ret.ToLocalChecked());
525 }
526
527
528 // bytesCopied = copy(buffer, target[, targetStart][, sourceStart][, sourceEnd])
Copy(const FunctionCallbackInfo<Value> & args)529 void Copy(const FunctionCallbackInfo<Value> &args) {
530 Environment* env = Environment::GetCurrent(args);
531
532 THROW_AND_RETURN_UNLESS_BUFFER(env, args[0]);
533 THROW_AND_RETURN_UNLESS_BUFFER(env, args[1]);
534 ArrayBufferViewContents<char> source(args[0]);
535 Local<Object> target_obj = args[1].As<Object>();
536 SPREAD_BUFFER_ARG(target_obj, target);
537
538 size_t target_start = 0;
539 size_t source_start = 0;
540 size_t source_end = 0;
541
542 THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[2], 0, &target_start));
543 THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[3], 0, &source_start));
544 THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[4], source.length(),
545 &source_end));
546
547 // Copy 0 bytes; we're done
548 if (target_start >= target_length || source_start >= source_end)
549 return args.GetReturnValue().Set(0);
550
551 if (source_start > source.length())
552 return THROW_ERR_OUT_OF_RANGE(
553 env, "The value of \"sourceStart\" is out of range.");
554
555 if (source_end - source_start > target_length - target_start)
556 source_end = source_start + target_length - target_start;
557
558 uint32_t to_copy = std::min(
559 std::min(source_end - source_start, target_length - target_start),
560 source.length() - source_start);
561
562 memmove(target_data + target_start, source.data() + source_start, to_copy);
563 args.GetReturnValue().Set(to_copy);
564 }
565
566
Fill(const FunctionCallbackInfo<Value> & args)567 void Fill(const FunctionCallbackInfo<Value>& args) {
568 Environment* env = Environment::GetCurrent(args);
569 Local<Context> ctx = env->context();
570
571 THROW_AND_RETURN_UNLESS_BUFFER(env, args[0]);
572 SPREAD_BUFFER_ARG(args[0], ts_obj);
573
574 size_t start;
575 THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[2], 0, &start));
576 size_t end;
577 THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[3], 0, &end));
578
579 size_t fill_length = end - start;
580 Local<String> str_obj;
581 size_t str_length;
582 enum encoding enc;
583
584 // OOB Check. Throw the error in JS.
585 if (start > end || fill_length + start > ts_obj_length)
586 return args.GetReturnValue().Set(-2);
587
588 // First check if Buffer has been passed.
589 if (Buffer::HasInstance(args[1])) {
590 SPREAD_BUFFER_ARG(args[1], fill_obj);
591 str_length = fill_obj_length;
592 memcpy(
593 ts_obj_data + start, fill_obj_data, std::min(str_length, fill_length));
594 goto start_fill;
595 }
596
597 // Then coerce everything that's not a string.
598 if (!args[1]->IsString()) {
599 uint32_t val;
600 if (!args[1]->Uint32Value(ctx).To(&val)) return;
601 int value = val & 255;
602 memset(ts_obj_data + start, value, fill_length);
603 return;
604 }
605
606 str_obj = args[1]->ToString(env->context()).ToLocalChecked();
607 enc = ParseEncoding(env->isolate(), args[4], UTF8);
608
609 // Can't use StringBytes::Write() in all cases. For example if attempting
610 // to write a two byte character into a one byte Buffer.
611 if (enc == UTF8) {
612 str_length = str_obj->Utf8Length(env->isolate());
613 node::Utf8Value str(env->isolate(), args[1]);
614 memcpy(ts_obj_data + start, *str, std::min(str_length, fill_length));
615
616 } else if (enc == UCS2) {
617 str_length = str_obj->Length() * sizeof(uint16_t);
618 node::TwoByteValue str(env->isolate(), args[1]);
619 if (IsBigEndian())
620 SwapBytes16(reinterpret_cast<char*>(&str[0]), str_length);
621
622 memcpy(ts_obj_data + start, *str, std::min(str_length, fill_length));
623
624 } else {
625 // Write initial String to Buffer, then use that memory to copy remainder
626 // of string. Correct the string length for cases like HEX where less than
627 // the total string length is written.
628 str_length = StringBytes::Write(env->isolate(),
629 ts_obj_data + start,
630 fill_length,
631 str_obj,
632 enc,
633 nullptr);
634 }
635
636 start_fill:
637
638 if (str_length >= fill_length)
639 return;
640
641 // If str_length is zero, then either an empty buffer was provided, or Write()
642 // indicated that no bytes could be written. If no bytes could be written,
643 // then return -1 because the fill value is invalid. This will trigger a throw
644 // in JavaScript. Silently failing should be avoided because it can lead to
645 // buffers with unexpected contents.
646 if (str_length == 0)
647 return args.GetReturnValue().Set(-1);
648
649 size_t in_there = str_length;
650 char* ptr = ts_obj_data + start + str_length;
651
652 while (in_there < fill_length - in_there) {
653 memcpy(ptr, ts_obj_data + start, in_there);
654 ptr += in_there;
655 in_there *= 2;
656 }
657
658 if (in_there < fill_length) {
659 memcpy(ptr, ts_obj_data + start, fill_length - in_there);
660 }
661 }
662
663
664 template <encoding encoding>
StringWrite(const FunctionCallbackInfo<Value> & args)665 void StringWrite(const FunctionCallbackInfo<Value>& args) {
666 Environment* env = Environment::GetCurrent(args);
667
668 THROW_AND_RETURN_UNLESS_BUFFER(env, args.This());
669 SPREAD_BUFFER_ARG(args.This(), ts_obj);
670
671 THROW_AND_RETURN_IF_NOT_STRING(env, args[0], "argument");
672
673 Local<String> str = args[0]->ToString(env->context()).ToLocalChecked();
674
675 size_t offset;
676 size_t max_length;
677
678 THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[1], 0, &offset));
679 if (offset > ts_obj_length) {
680 return node::THROW_ERR_BUFFER_OUT_OF_BOUNDS(
681 env, "\"offset\" is outside of buffer bounds");
682 }
683
684 THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[2], ts_obj_length - offset,
685 &max_length));
686
687 max_length = std::min(ts_obj_length - offset, max_length);
688
689 if (max_length == 0)
690 return args.GetReturnValue().Set(0);
691
692 uint32_t written = StringBytes::Write(env->isolate(),
693 ts_obj_data + offset,
694 max_length,
695 str,
696 encoding,
697 nullptr);
698 args.GetReturnValue().Set(written);
699 }
700
ByteLengthUtf8(const FunctionCallbackInfo<Value> & args)701 void ByteLengthUtf8(const FunctionCallbackInfo<Value> &args) {
702 Environment* env = Environment::GetCurrent(args);
703 CHECK(args[0]->IsString());
704
705 // Fast case: avoid StringBytes on UTF8 string. Jump to v8.
706 args.GetReturnValue().Set(args[0].As<String>()->Utf8Length(env->isolate()));
707 }
708
709 // Normalize val to be an integer in the range of [1, -1] since
710 // implementations of memcmp() can vary by platform.
normalizeCompareVal(int val,size_t a_length,size_t b_length)711 static int normalizeCompareVal(int val, size_t a_length, size_t b_length) {
712 if (val == 0) {
713 if (a_length > b_length)
714 return 1;
715 else if (a_length < b_length)
716 return -1;
717 } else {
718 if (val > 0)
719 return 1;
720 else
721 return -1;
722 }
723 return val;
724 }
725
CompareOffset(const FunctionCallbackInfo<Value> & args)726 void CompareOffset(const FunctionCallbackInfo<Value> &args) {
727 Environment* env = Environment::GetCurrent(args);
728
729 THROW_AND_RETURN_UNLESS_BUFFER(env, args[0]);
730 THROW_AND_RETURN_UNLESS_BUFFER(env, args[1]);
731 ArrayBufferViewContents<char> source(args[0]);
732 ArrayBufferViewContents<char> target(args[1]);
733
734 size_t target_start = 0;
735 size_t source_start = 0;
736 size_t source_end = 0;
737 size_t target_end = 0;
738
739 THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[2], 0, &target_start));
740 THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[3], 0, &source_start));
741 THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[4], target.length(),
742 &target_end));
743 THROW_AND_RETURN_IF_OOB(ParseArrayIndex(env, args[5], source.length(),
744 &source_end));
745
746 if (source_start > source.length())
747 return THROW_ERR_OUT_OF_RANGE(
748 env, "The value of \"sourceStart\" is out of range.");
749 if (target_start > target.length())
750 return THROW_ERR_OUT_OF_RANGE(
751 env, "The value of \"targetStart\" is out of range.");
752
753 CHECK_LE(source_start, source_end);
754 CHECK_LE(target_start, target_end);
755
756 size_t to_cmp =
757 std::min(std::min(source_end - source_start, target_end - target_start),
758 source.length() - source_start);
759
760 int val = normalizeCompareVal(to_cmp > 0 ?
761 memcmp(source.data() + source_start,
762 target.data() + target_start,
763 to_cmp) : 0,
764 source_end - source_start,
765 target_end - target_start);
766
767 args.GetReturnValue().Set(val);
768 }
769
Compare(const FunctionCallbackInfo<Value> & args)770 void Compare(const FunctionCallbackInfo<Value> &args) {
771 Environment* env = Environment::GetCurrent(args);
772
773 THROW_AND_RETURN_UNLESS_BUFFER(env, args[0]);
774 THROW_AND_RETURN_UNLESS_BUFFER(env, args[1]);
775 ArrayBufferViewContents<char> a(args[0]);
776 ArrayBufferViewContents<char> b(args[1]);
777
778 size_t cmp_length = std::min(a.length(), b.length());
779
780 int val = normalizeCompareVal(cmp_length > 0 ?
781 memcmp(a.data(), b.data(), cmp_length) : 0,
782 a.length(), b.length());
783 args.GetReturnValue().Set(val);
784 }
785
786
787 // Computes the offset for starting an indexOf or lastIndexOf search.
788 // Returns either a valid offset in [0...<length - 1>], ie inside the Buffer,
789 // 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)790 int64_t IndexOfOffset(size_t length,
791 int64_t offset_i64,
792 int64_t needle_length,
793 bool is_forward) {
794 int64_t length_i64 = static_cast<int64_t>(length);
795 if (offset_i64 < 0) {
796 if (offset_i64 + length_i64 >= 0) {
797 // Negative offsets count backwards from the end of the buffer.
798 return length_i64 + offset_i64;
799 } else if (is_forward || needle_length == 0) {
800 // indexOf from before the start of the buffer: search the whole buffer.
801 return 0;
802 } else {
803 // lastIndexOf from before the start of the buffer: no match.
804 return -1;
805 }
806 } else {
807 if (offset_i64 + needle_length <= length_i64) {
808 // Valid positive offset.
809 return offset_i64;
810 } else if (needle_length == 0) {
811 // Out of buffer bounds, but empty needle: point to end of buffer.
812 return length_i64;
813 } else if (is_forward) {
814 // indexOf from past the end of the buffer: no match.
815 return -1;
816 } else {
817 // lastIndexOf from past the end of the buffer: search the whole buffer.
818 return length_i64 - 1;
819 }
820 }
821 }
822
IndexOfString(const FunctionCallbackInfo<Value> & args)823 void IndexOfString(const FunctionCallbackInfo<Value>& args) {
824 Environment* env = Environment::GetCurrent(args);
825 Isolate* isolate = env->isolate();
826
827 CHECK(args[1]->IsString());
828 CHECK(args[2]->IsNumber());
829 CHECK(args[3]->IsInt32());
830 CHECK(args[4]->IsBoolean());
831
832 enum encoding enc = static_cast<enum encoding>(args[3].As<Int32>()->Value());
833
834 THROW_AND_RETURN_UNLESS_BUFFER(env, args[0]);
835 ArrayBufferViewContents<char> buffer(args[0]);
836
837 Local<String> needle = args[1].As<String>();
838 int64_t offset_i64 = args[2].As<Integer>()->Value();
839 bool is_forward = args[4]->IsTrue();
840
841 const char* haystack = buffer.data();
842 // Round down to the nearest multiple of 2 in case of UCS2.
843 const size_t haystack_length = (enc == UCS2) ?
844 buffer.length() &~ 1 : buffer.length(); // NOLINT(whitespace/operators)
845
846 size_t needle_length;
847 if (!StringBytes::Size(isolate, needle, enc).To(&needle_length)) return;
848
849 int64_t opt_offset = IndexOfOffset(haystack_length,
850 offset_i64,
851 needle_length,
852 is_forward);
853
854 if (needle_length == 0) {
855 // Match String#indexOf() and String#lastIndexOf() behavior.
856 args.GetReturnValue().Set(static_cast<double>(opt_offset));
857 return;
858 }
859
860 if (haystack_length == 0) {
861 return args.GetReturnValue().Set(-1);
862 }
863
864 if (opt_offset <= -1) {
865 return args.GetReturnValue().Set(-1);
866 }
867 size_t offset = static_cast<size_t>(opt_offset);
868 CHECK_LT(offset, haystack_length);
869 if ((is_forward && needle_length + offset > haystack_length) ||
870 needle_length > haystack_length) {
871 return args.GetReturnValue().Set(-1);
872 }
873
874 size_t result = haystack_length;
875
876 if (enc == UCS2) {
877 String::Value needle_value(isolate, needle);
878 if (*needle_value == nullptr)
879 return args.GetReturnValue().Set(-1);
880
881 if (haystack_length < 2 || needle_value.length() < 1) {
882 return args.GetReturnValue().Set(-1);
883 }
884
885 if (IsBigEndian()) {
886 StringBytes::InlineDecoder decoder;
887 if (decoder.Decode(env, needle, args[3], UCS2).IsNothing()) return;
888 const uint16_t* decoded_string =
889 reinterpret_cast<const uint16_t*>(decoder.out());
890
891 if (decoded_string == nullptr)
892 return args.GetReturnValue().Set(-1);
893
894 result = SearchString(reinterpret_cast<const uint16_t*>(haystack),
895 haystack_length / 2,
896 decoded_string,
897 decoder.size() / 2,
898 offset / 2,
899 is_forward);
900 } else {
901 result = SearchString(reinterpret_cast<const uint16_t*>(haystack),
902 haystack_length / 2,
903 reinterpret_cast<const uint16_t*>(*needle_value),
904 needle_value.length(),
905 offset / 2,
906 is_forward);
907 }
908 result *= 2;
909 } else if (enc == UTF8) {
910 String::Utf8Value needle_value(isolate, needle);
911 if (*needle_value == nullptr)
912 return args.GetReturnValue().Set(-1);
913
914 result = SearchString(reinterpret_cast<const uint8_t*>(haystack),
915 haystack_length,
916 reinterpret_cast<const uint8_t*>(*needle_value),
917 needle_length,
918 offset,
919 is_forward);
920 } else if (enc == LATIN1) {
921 uint8_t* needle_data = node::UncheckedMalloc<uint8_t>(needle_length);
922 if (needle_data == nullptr) {
923 return args.GetReturnValue().Set(-1);
924 }
925 needle->WriteOneByte(
926 isolate, needle_data, 0, needle_length, String::NO_NULL_TERMINATION);
927
928 result = SearchString(reinterpret_cast<const uint8_t*>(haystack),
929 haystack_length,
930 needle_data,
931 needle_length,
932 offset,
933 is_forward);
934 free(needle_data);
935 }
936
937 args.GetReturnValue().Set(
938 result == haystack_length ? -1 : static_cast<int>(result));
939 }
940
IndexOfBuffer(const FunctionCallbackInfo<Value> & args)941 void IndexOfBuffer(const FunctionCallbackInfo<Value>& args) {
942 CHECK(args[1]->IsObject());
943 CHECK(args[2]->IsNumber());
944 CHECK(args[3]->IsInt32());
945 CHECK(args[4]->IsBoolean());
946
947 enum encoding enc = static_cast<enum encoding>(args[3].As<Int32>()->Value());
948
949 THROW_AND_RETURN_UNLESS_BUFFER(Environment::GetCurrent(args), args[0]);
950 THROW_AND_RETURN_UNLESS_BUFFER(Environment::GetCurrent(args), args[1]);
951 ArrayBufferViewContents<char> haystack_contents(args[0]);
952 ArrayBufferViewContents<char> needle_contents(args[1]);
953 int64_t offset_i64 = args[2].As<Integer>()->Value();
954 bool is_forward = args[4]->IsTrue();
955
956 const char* haystack = haystack_contents.data();
957 const size_t haystack_length = haystack_contents.length();
958 const char* needle = needle_contents.data();
959 const size_t needle_length = needle_contents.length();
960
961 int64_t opt_offset = IndexOfOffset(haystack_length,
962 offset_i64,
963 needle_length,
964 is_forward);
965
966 if (needle_length == 0) {
967 // Match String#indexOf() and String#lastIndexOf() behavior.
968 args.GetReturnValue().Set(static_cast<double>(opt_offset));
969 return;
970 }
971
972 if (haystack_length == 0) {
973 return args.GetReturnValue().Set(-1);
974 }
975
976 if (opt_offset <= -1) {
977 return args.GetReturnValue().Set(-1);
978 }
979 size_t offset = static_cast<size_t>(opt_offset);
980 CHECK_LT(offset, haystack_length);
981 if ((is_forward && needle_length + offset > haystack_length) ||
982 needle_length > haystack_length) {
983 return args.GetReturnValue().Set(-1);
984 }
985
986 size_t result = haystack_length;
987
988 if (enc == UCS2) {
989 if (haystack_length < 2 || needle_length < 2) {
990 return args.GetReturnValue().Set(-1);
991 }
992 result = SearchString(
993 reinterpret_cast<const uint16_t*>(haystack),
994 haystack_length / 2,
995 reinterpret_cast<const uint16_t*>(needle),
996 needle_length / 2,
997 offset / 2,
998 is_forward);
999 result *= 2;
1000 } else {
1001 result = SearchString(
1002 reinterpret_cast<const uint8_t*>(haystack),
1003 haystack_length,
1004 reinterpret_cast<const uint8_t*>(needle),
1005 needle_length,
1006 offset,
1007 is_forward);
1008 }
1009
1010 args.GetReturnValue().Set(
1011 result == haystack_length ? -1 : static_cast<int>(result));
1012 }
1013
IndexOfNumber(const FunctionCallbackInfo<Value> & args)1014 void IndexOfNumber(const FunctionCallbackInfo<Value>& args) {
1015 CHECK(args[1]->IsUint32());
1016 CHECK(args[2]->IsNumber());
1017 CHECK(args[3]->IsBoolean());
1018
1019 THROW_AND_RETURN_UNLESS_BUFFER(Environment::GetCurrent(args), args[0]);
1020 ArrayBufferViewContents<char> buffer(args[0]);
1021
1022 uint32_t needle = args[1].As<Uint32>()->Value();
1023 int64_t offset_i64 = args[2].As<Integer>()->Value();
1024 bool is_forward = args[3]->IsTrue();
1025
1026 int64_t opt_offset =
1027 IndexOfOffset(buffer.length(), offset_i64, 1, is_forward);
1028 if (opt_offset <= -1 || buffer.length() == 0) {
1029 return args.GetReturnValue().Set(-1);
1030 }
1031 size_t offset = static_cast<size_t>(opt_offset);
1032 CHECK_LT(offset, buffer.length());
1033
1034 const void* ptr;
1035 if (is_forward) {
1036 ptr = memchr(buffer.data() + offset, needle, buffer.length() - offset);
1037 } else {
1038 ptr = node::stringsearch::MemrchrFill(buffer.data(), needle, offset + 1);
1039 }
1040 const char* ptr_char = static_cast<const char*>(ptr);
1041 args.GetReturnValue().Set(ptr ? static_cast<int>(ptr_char - buffer.data())
1042 : -1);
1043 }
1044
1045
Swap16(const FunctionCallbackInfo<Value> & args)1046 void Swap16(const FunctionCallbackInfo<Value>& args) {
1047 Environment* env = Environment::GetCurrent(args);
1048 THROW_AND_RETURN_UNLESS_BUFFER(env, args[0]);
1049 SPREAD_BUFFER_ARG(args[0], ts_obj);
1050 SwapBytes16(ts_obj_data, ts_obj_length);
1051 args.GetReturnValue().Set(args[0]);
1052 }
1053
1054
Swap32(const FunctionCallbackInfo<Value> & args)1055 void Swap32(const FunctionCallbackInfo<Value>& args) {
1056 Environment* env = Environment::GetCurrent(args);
1057 THROW_AND_RETURN_UNLESS_BUFFER(env, args[0]);
1058 SPREAD_BUFFER_ARG(args[0], ts_obj);
1059 SwapBytes32(ts_obj_data, ts_obj_length);
1060 args.GetReturnValue().Set(args[0]);
1061 }
1062
1063
Swap64(const FunctionCallbackInfo<Value> & args)1064 void Swap64(const FunctionCallbackInfo<Value>& args) {
1065 Environment* env = Environment::GetCurrent(args);
1066 THROW_AND_RETURN_UNLESS_BUFFER(env, args[0]);
1067 SPREAD_BUFFER_ARG(args[0], ts_obj);
1068 SwapBytes64(ts_obj_data, ts_obj_length);
1069 args.GetReturnValue().Set(args[0]);
1070 }
1071
1072
1073 // Encode a single string to a UTF-8 Uint8Array (not Buffer).
1074 // Used in TextEncoder.prototype.encode.
EncodeUtf8String(const FunctionCallbackInfo<Value> & args)1075 static void EncodeUtf8String(const FunctionCallbackInfo<Value>& args) {
1076 Environment* env = Environment::GetCurrent(args);
1077 Isolate* isolate = env->isolate();
1078 CHECK_GE(args.Length(), 1);
1079 CHECK(args[0]->IsString());
1080
1081 Local<String> str = args[0].As<String>();
1082 size_t length = str->Utf8Length(isolate);
1083 AllocatedBuffer buf = env->AllocateManaged(length);
1084 str->WriteUtf8(isolate,
1085 buf.data(),
1086 -1, // We are certain that `data` is sufficiently large
1087 nullptr,
1088 String::NO_NULL_TERMINATION | String::REPLACE_INVALID_UTF8);
1089 auto array = Uint8Array::New(buf.ToArrayBuffer(), 0, length);
1090 args.GetReturnValue().Set(array);
1091 }
1092
1093
EncodeInto(const FunctionCallbackInfo<Value> & args)1094 static void EncodeInto(const FunctionCallbackInfo<Value>& args) {
1095 Environment* env = Environment::GetCurrent(args);
1096 Isolate* isolate = env->isolate();
1097 CHECK_GE(args.Length(), 3);
1098 CHECK(args[0]->IsString());
1099 CHECK(args[1]->IsUint8Array());
1100 CHECK(args[2]->IsUint32Array());
1101
1102 Local<String> source = args[0].As<String>();
1103
1104 Local<Uint8Array> dest = args[1].As<Uint8Array>();
1105 Local<ArrayBuffer> buf = dest->Buffer();
1106 char* write_result =
1107 static_cast<char*>(buf->GetContents().Data()) + dest->ByteOffset();
1108 size_t dest_length = dest->ByteLength();
1109
1110 // results = [ read, written ]
1111 Local<Uint32Array> result_arr = args[2].As<Uint32Array>();
1112 uint32_t* results = reinterpret_cast<uint32_t*>(
1113 static_cast<char*>(result_arr->Buffer()->GetContents().Data()) +
1114 result_arr->ByteOffset());
1115
1116 int nchars;
1117 int written = source->WriteUtf8(
1118 isolate,
1119 write_result,
1120 dest_length,
1121 &nchars,
1122 String::NO_NULL_TERMINATION | String::REPLACE_INVALID_UTF8);
1123 results[0] = nchars;
1124 results[1] = written;
1125 }
1126
1127
SetBufferPrototype(const FunctionCallbackInfo<Value> & args)1128 void SetBufferPrototype(const FunctionCallbackInfo<Value>& args) {
1129 Environment* env = Environment::GetCurrent(args);
1130
1131 CHECK(args[0]->IsObject());
1132 Local<Object> proto = args[0].As<Object>();
1133 env->set_buffer_prototype_object(proto);
1134 }
1135
1136
Initialize(Local<Object> target,Local<Value> unused,Local<Context> context,void * priv)1137 void Initialize(Local<Object> target,
1138 Local<Value> unused,
1139 Local<Context> context,
1140 void* priv) {
1141 Environment* env = Environment::GetCurrent(context);
1142
1143 env->SetMethod(target, "setBufferPrototype", SetBufferPrototype);
1144 env->SetMethodNoSideEffect(target, "createFromString", CreateFromString);
1145
1146 env->SetMethodNoSideEffect(target, "byteLengthUtf8", ByteLengthUtf8);
1147 env->SetMethod(target, "copy", Copy);
1148 env->SetMethodNoSideEffect(target, "compare", Compare);
1149 env->SetMethodNoSideEffect(target, "compareOffset", CompareOffset);
1150 env->SetMethod(target, "fill", Fill);
1151 env->SetMethodNoSideEffect(target, "indexOfBuffer", IndexOfBuffer);
1152 env->SetMethodNoSideEffect(target, "indexOfNumber", IndexOfNumber);
1153 env->SetMethodNoSideEffect(target, "indexOfString", IndexOfString);
1154
1155 env->SetMethod(target, "swap16", Swap16);
1156 env->SetMethod(target, "swap32", Swap32);
1157 env->SetMethod(target, "swap64", Swap64);
1158
1159 env->SetMethod(target, "encodeInto", EncodeInto);
1160 env->SetMethodNoSideEffect(target, "encodeUtf8String", EncodeUtf8String);
1161
1162 target->Set(env->context(),
1163 FIXED_ONE_BYTE_STRING(env->isolate(), "kMaxLength"),
1164 Integer::NewFromUnsigned(env->isolate(), kMaxLength)).Check();
1165
1166 target->Set(env->context(),
1167 FIXED_ONE_BYTE_STRING(env->isolate(), "kStringMaxLength"),
1168 Integer::New(env->isolate(), String::kMaxLength)).Check();
1169
1170 env->SetMethodNoSideEffect(target, "asciiSlice", StringSlice<ASCII>);
1171 env->SetMethodNoSideEffect(target, "base64Slice", StringSlice<BASE64>);
1172 env->SetMethodNoSideEffect(target, "latin1Slice", StringSlice<LATIN1>);
1173 env->SetMethodNoSideEffect(target, "hexSlice", StringSlice<HEX>);
1174 env->SetMethodNoSideEffect(target, "ucs2Slice", StringSlice<UCS2>);
1175 env->SetMethodNoSideEffect(target, "utf8Slice", StringSlice<UTF8>);
1176
1177 env->SetMethod(target, "asciiWrite", StringWrite<ASCII>);
1178 env->SetMethod(target, "base64Write", StringWrite<BASE64>);
1179 env->SetMethod(target, "latin1Write", StringWrite<LATIN1>);
1180 env->SetMethod(target, "hexWrite", StringWrite<HEX>);
1181 env->SetMethod(target, "ucs2Write", StringWrite<UCS2>);
1182 env->SetMethod(target, "utf8Write", StringWrite<UTF8>);
1183
1184 // It can be a nullptr when running inside an isolate where we
1185 // do not own the ArrayBuffer allocator.
1186 if (NodeArrayBufferAllocator* allocator =
1187 env->isolate_data()->node_allocator()) {
1188 uint32_t* zero_fill_field = allocator->zero_fill_field();
1189 Local<ArrayBuffer> array_buffer = ArrayBuffer::New(
1190 env->isolate(), zero_fill_field, sizeof(*zero_fill_field));
1191 array_buffer->SetPrivate(
1192 env->context(),
1193 env->untransferable_object_private_symbol(),
1194 True(env->isolate())).Check();
1195 CHECK(target
1196 ->Set(env->context(),
1197 FIXED_ONE_BYTE_STRING(env->isolate(), "zeroFill"),
1198 Uint32Array::New(array_buffer, 0, 1))
1199 .FromJust());
1200 }
1201 }
1202
1203 } // anonymous namespace
1204 } // namespace Buffer
1205 } // namespace node
1206
1207 NODE_MODULE_CONTEXT_AWARE_INTERNAL(buffer, node::Buffer::Initialize)
1208