GCC Code Coverage Report
Directory: ../ Exec Total Coverage
File: /home/iojs/build/workspace/node-test-commit-linux-coverage-daily/nodes/benchmark/out/../src/string_bytes.cc Lines: 254 309 82.2 %
Date: 2019-07-28 22:34:34 Branches: 139 204 68.1 %

Line Branch Exec Source
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 "string_bytes.h"
23
24
#include "base64.h"
25
#include "env-inl.h"
26
#include "node_buffer.h"
27
#include "node_errors.h"
28
#include "util.h"
29
30
#include <climits>
31
#include <cstring>  // memcpy
32
33
#include <algorithm>
34
#include <vector>
35
36
// When creating strings >= this length v8's gc spins up and consumes
37
// most of the execution time. For these cases it's more performant to
38
// use external string resources.
39
#define EXTERN_APEX 0xFBEE9
40
41
namespace node {
42
43
using v8::HandleScope;
44
using v8::Isolate;
45
using v8::Just;
46
using v8::Local;
47
using v8::Maybe;
48
using v8::MaybeLocal;
49
using v8::Nothing;
50
using v8::String;
51
using v8::Value;
52
53
namespace {
54
55
template <typename ResourceType, typename TypeName>
56
class ExternString: public ResourceType {
57
 public:
58
64
  ~ExternString() override {
59
32
    free(const_cast<TypeName*>(data_));
60
32
    isolate()->AdjustAmountOfExternalAllocatedMemory(-byte_length());
61

96
  }
62
63
95
  const TypeName* data() const override {
64
95
    return data_;
65
  }
66
67
204
  size_t length() const override {
68
204
    return length_;
69
  }
70
71
64
  int64_t byte_length() const {
72
64
    return length() * sizeof(*data());
73
  }
74
75
9716
  static MaybeLocal<Value> NewFromCopy(Isolate* isolate,
76
                                       const TypeName* data,
77
                                       size_t length,
78
                                       Local<Value>* error) {
79

9716
    if (length == 0)
80
2
      return String::Empty(isolate);
81
82

9714
    if (length < EXTERN_APEX)
83
9700
      return NewSimpleFromCopy(isolate, data, length, error);
84
85
14
    TypeName* new_data = node::UncheckedMalloc<TypeName>(length);
86

14
    if (new_data == nullptr) {
87
      *error = node::ERR_MEMORY_ALLOCATION_FAILED(isolate);
88
      return MaybeLocal<Value>();
89
    }
90
14
    memcpy(new_data, data, length * sizeof(*new_data));
91
92
    return ExternString<ResourceType, TypeName>::New(isolate,
93
                                                     new_data,
94
                                                     length,
95
14
                                                     error);
96
  }
97
98
  // uses "data" for external resource, and will be free'd on gc
99
814249
  static MaybeLocal<Value> New(Isolate* isolate,
100
                               TypeName* data,
101
                               size_t length,
102
                               Local<Value>* error) {
103

814249
    if (length == 0)
104
      return String::Empty(isolate);
105
106

814249
    if (length < EXTERN_APEX) {
107
814217
      MaybeLocal<Value> str = NewSimpleFromCopy(isolate, data, length, error);
108
814217
      free(data);
109
814217
      return str;
110
    }
111
112
    ExternString* h_str = new ExternString<ResourceType, TypeName>(isolate,
113
                                                                   data,
114
32
                                                                   length);
115
32
    MaybeLocal<Value> str = NewExternal(isolate, h_str);
116
32
    isolate->AdjustAmountOfExternalAllocatedMemory(h_str->byte_length());
117
118

32
    if (str.IsEmpty()) {
119

5
      delete h_str;
120
5
      *error = node::ERR_STRING_TOO_LONG(isolate);
121
5
      return MaybeLocal<Value>();
122
    }
123
124
27
    return str.ToLocalChecked();
125
  }
126
127
32
  inline Isolate* isolate() const { return isolate_; }
128
129
 private:
130
32
  ExternString(Isolate* isolate, const TypeName* data, size_t length)
131
32
    : isolate_(isolate), data_(data), length_(length) { }
132
  static MaybeLocal<Value> NewExternal(Isolate* isolate,
133
                                       ExternString* h_str);
134
135
  // This method does not actually create ExternString instances.
136
  static MaybeLocal<Value> NewSimpleFromCopy(Isolate* isolate,
137
                                             const TypeName* data,
138
                                             size_t length,
139
                                             Local<Value>* error);
140
141
  Isolate* isolate_;
142
  const TypeName* data_;
143
  size_t length_;
144
};
145
146
147
typedef ExternString<String::ExternalOneByteStringResource,
148
                     char> ExternOneByteString;
149
typedef ExternString<String::ExternalStringResource,
150
                     uint16_t> ExternTwoByteString;
151
152
153
template <>
154
27
MaybeLocal<Value> ExternOneByteString::NewExternal(
155
    Isolate* isolate, ExternOneByteString* h_str) {
156
54
  return String::NewExternalOneByte(isolate, h_str).FromMaybe(Local<Value>());
157
}
158
159
160
template <>
161
5
MaybeLocal<Value> ExternTwoByteString::NewExternal(
162
    Isolate* isolate, ExternTwoByteString* h_str) {
163
10
  return String::NewExternalTwoByte(isolate, h_str).FromMaybe(Local<Value>());
164
}
165
166
template <>
167
820353
MaybeLocal<Value> ExternOneByteString::NewSimpleFromCopy(Isolate* isolate,
168
                                                         const char* data,
169
                                                         size_t length,
170
                                                         Local<Value>* error) {
171
  MaybeLocal<String> str =
172
      String::NewFromOneByte(isolate,
173
                             reinterpret_cast<const uint8_t*>(data),
174
                             v8::NewStringType::kNormal,
175
820353
                             length);
176
820353
  if (str.IsEmpty()) {
177
    *error = node::ERR_STRING_TOO_LONG(isolate);
178
    return MaybeLocal<Value>();
179
  }
180
820353
  return str.ToLocalChecked();
181
}
182
183
184
template <>
185
3564
MaybeLocal<Value> ExternTwoByteString::NewSimpleFromCopy(Isolate* isolate,
186
                                                         const uint16_t* data,
187
                                                         size_t length,
188
                                                         Local<Value>* error) {
189
  MaybeLocal<String> str =
190
      String::NewFromTwoByte(isolate,
191
                             data,
192
                             v8::NewStringType::kNormal,
193
3564
                             length);
194
3564
  if (str.IsEmpty()) {
195
    *error = node::ERR_STRING_TOO_LONG(isolate);
196
    return MaybeLocal<Value>();
197
  }
198
3564
  return str.ToLocalChecked();
199
}
200
201
}  // anonymous namespace
202
203
// supports regular and URL-safe base64
204
const int8_t unbase64_table[256] =
205
  { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -2, -1, -1, -2, -1, -1,
206
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
207
    -2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, 62, -1, 63,
208
    52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1,
209
    -1,  0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14,
210
    15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, 63,
211
    -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
212
    41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1,
213
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
214
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
215
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
216
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
217
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
218
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
219
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
220
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
221
  };
222
223
224
static const int8_t unhex_table[256] =
225
  { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
226
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
227
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
228
     0,  1,  2,  3,  4,  5,  6,  7,  8,  9, -1, -1, -1, -1, -1, -1,
229
    -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1,
230
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
231
    -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1,
232
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
233
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
234
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
235
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
236
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
237
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
238
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
239
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
240
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
241
  };
242
243
45241260
static inline unsigned unhex(uint8_t x) {
244
45241260
  return unhex_table[x];
245
}
246
247
template <typename TypeName>
248
2335
static size_t hex_decode(char* buf,
249
                         size_t len,
250
                         const TypeName* src,
251
                         const size_t srcLen) {
252
  size_t i;
253


22622956
  for (i = 0; i < len && i * 2 + 1 < srcLen; ++i) {
254
22620630
    unsigned a = unhex(src[i * 2 + 0]);
255
22620630
    unsigned b = unhex(src[i * 2 + 1]);
256


22620630
    if (!~a || !~b)
257
9
      return i;
258
22620621
    buf[i] = (a << 4) | b;
259
  }
260
261
2326
  return i;
262
}
263
264
522
size_t StringBytes::WriteUCS2(Isolate* isolate,
265
                              char* buf,
266
                              size_t buflen,
267
                              Local<String> str,
268
                              int flags,
269
                              size_t* chars_written) {
270
522
  uint16_t* const dst = reinterpret_cast<uint16_t*>(buf);
271
272
522
  size_t max_chars = buflen / sizeof(*dst);
273
522
  if (max_chars == 0) {
274
5
    return 0;
275
  }
276
277
  size_t nchars;
278
517
  size_t alignment = reinterpret_cast<uintptr_t>(dst) % sizeof(*dst);
279
517
  if (alignment == 0) {
280
1024
    nchars = str->Write(isolate, dst, 0, max_chars, flags);
281
512
    *chars_written = nchars;
282
512
    return nchars * sizeof(*dst);
283
  }
284
285
  uint16_t* aligned_dst =
286
5
      reinterpret_cast<uint16_t*>(buf + sizeof(*dst) - alignment);
287
5
  CHECK_EQ(reinterpret_cast<uintptr_t>(aligned_dst) % sizeof(*dst), 0);
288
289
  // Write all but the last char
290
5
  max_chars = std::min(max_chars, static_cast<size_t>(str->Length()));
291
5
  if (max_chars == 0) return 0;
292
10
  nchars = str->Write(isolate, aligned_dst, 0, max_chars - 1, flags);
293
5
  CHECK_EQ(nchars, max_chars - 1);
294
295
  // Shift everything to unaligned-left
296
5
  memmove(dst, aligned_dst, nchars * sizeof(*dst));
297
298
  // One more char to be written
299
  uint16_t last;
300
10
  CHECK_EQ(str->Write(isolate, &last, nchars, 1, flags), 1);
301
5
  memcpy(buf + nchars * sizeof(*dst), &last, sizeof(last));
302
5
  nchars++;
303
304
5
  *chars_written = nchars;
305
5
  return nchars * sizeof(*dst);
306
}
307
308
309
2481787
size_t StringBytes::Write(Isolate* isolate,
310
                          char* buf,
311
                          size_t buflen,
312
                          Local<Value> val,
313
                          enum encoding encoding,
314
                          int* chars_written) {
315
2481787
  HandleScope scope(isolate);
316
  size_t nbytes;
317
  int nchars;
318
319
2481787
  if (chars_written == nullptr)
320
2481787
    chars_written = &nchars;
321
322
4963574
  CHECK(val->IsString() == true);
323
2481787
  Local<String> str = val.As<String>();
324
325
  int flags = String::HINT_MANY_WRITES_EXPECTED |
326
              String::NO_NULL_TERMINATION |
327
2481787
              String::REPLACE_INVALID_UTF8;
328
329

2481787
  switch (encoding) {
330
    case ASCII:
331
    case LATIN1:
332
133576
      if (str->IsExternalOneByte()) {
333
1
        auto ext = str->GetExternalOneByteStringResource();
334
1
        nbytes = std::min(buflen, ext->length());
335
1
        memcpy(buf, ext->data(), nbytes);
336
      } else {
337
133575
        uint8_t* const dst = reinterpret_cast<uint8_t*>(buf);
338
267150
        nbytes = str->WriteOneByte(isolate, dst, 0, buflen, flags);
339
      }
340
133576
      *chars_written = nbytes;
341
133576
      break;
342
343
    case BUFFER:
344
    case UTF8:
345
3887310
      nbytes = str->WriteUtf8(isolate, buf, buflen, chars_written, flags);
346
1943655
      break;
347
348
    case UCS2: {
349
      size_t nchars;
350
351
522
      nbytes = WriteUCS2(isolate, buf, buflen, str, flags, &nchars);
352
522
      *chars_written = static_cast<int>(nchars);
353
354
      // Node's "ucs2" encoding wants LE character data stored in
355
      // the Buffer, so we need to reorder on BE platforms.  See
356
      // https://nodejs.org/api/buffer.html regarding Node's "ucs2"
357
      // encoding specification
358
522
      if (IsBigEndian())
359
        SwapBytes16(buf, nbytes);
360
361
522
      break;
362
    }
363
364
    case BASE64:
365
401699
      if (str->IsExternalOneByte()) {
366
4
        auto ext = str->GetExternalOneByteStringResource();
367
4
        nbytes = base64_decode(buf, buflen, ext->data(), ext->length());
368
      } else {
369
401695
        String::Value value(isolate, str);
370
401695
        nbytes = base64_decode(buf, buflen, *value, value.length());
371
      }
372
401699
      *chars_written = nbytes;
373
401699
      break;
374
375
    case HEX:
376
2335
      if (str->IsExternalOneByte()) {
377
22
        auto ext = str->GetExternalOneByteStringResource();
378
22
        nbytes = hex_decode(buf, buflen, ext->data(), ext->length());
379
      } else {
380
2313
        String::Value value(isolate, str);
381
2313
        nbytes = hex_decode(buf, buflen, *value, value.length());
382
      }
383
2335
      *chars_written = nbytes;
384
2335
      break;
385
386
    default:
387
      CHECK(0 && "unknown encoding");
388
      break;
389
  }
390
391
2481787
  return nbytes;
392
}
393
394
395
402611
bool StringBytes::IsValidString(Local<String> string,
396
                                enum encoding enc) {
397

402741
  if (enc == HEX && string->Length() % 2 != 0)
398
3
    return false;
399
  // TODO(bnoordhuis) Add BASE64 check?
400
402608
  return true;
401
}
402
403
404
// Quick and dirty size calculation
405
// Will always be at least big enough, but may have some extra
406
// UTF8 can be as much as 3x the size, Base64 can have 1-2 extra bytes
407
7328393
Maybe<size_t> StringBytes::StorageSize(Isolate* isolate,
408
                                       Local<Value> val,
409
                                       enum encoding encoding) {
410
7328393
  HandleScope scope(isolate);
411
7328396
  size_t data_size = 0;
412
7328396
  bool is_buffer = Buffer::HasInstance(val);
413
414

7328397
  if (is_buffer && (encoding == BUFFER || encoding == LATIN1)) {
415
    return Just(Buffer::Length(val));
416
  }
417
418
  Local<String> str;
419
21985184
  if (!val->ToString(isolate->GetCurrentContext()).ToLocal(&str))
420
    return Nothing<size_t>();
421
422

7328394
  switch (encoding) {
423
    case ASCII:
424
    case LATIN1:
425
131678
      data_size = str->Length();
426
131678
      break;
427
428
    case BUFFER:
429
    case UTF8:
430
      // A single UCS2 codepoint never takes up more than 3 utf8 bytes.
431
      // It is an exercise for the caller to decide when a string is
432
      // long enough to justify calling Size() instead of StorageSize()
433
7195547
      data_size = 3 * str->Length();
434
7195543
      break;
435
436
    case UCS2:
437
6
      data_size = str->Length() * sizeof(uint16_t);
438
6
      break;
439
440
    case BASE64:
441
10
      data_size = base64_decoded_size_fast(str->Length());
442
10
      break;
443
444
    case HEX:
445

1153
      CHECK(str->Length() % 2 == 0 && "invalid hex string length");
446
1153
      data_size = str->Length() / 2;
447
1153
      break;
448
449
    default:
450
      CHECK(0 && "unknown encoding");
451
      break;
452
  }
453
454
7328390
  return Just(data_size);
455
}
456
457
1097
Maybe<size_t> StringBytes::Size(Isolate* isolate,
458
                                Local<Value> val,
459
                                enum encoding encoding) {
460
1097
  HandleScope scope(isolate);
461
462


1097
  if (Buffer::HasInstance(val) && (encoding == BUFFER || encoding == LATIN1))
463
    return Just(Buffer::Length(val));
464
465
  Local<String> str;
466
3291
  if (!val->ToString(isolate->GetCurrentContext()).ToLocal(&str))
467
    return Nothing<size_t>();
468
469

1097
  switch (encoding) {
470
    case ASCII:
471
    case LATIN1:
472
17
      return Just<size_t>(str->Length());
473
474
    case BUFFER:
475
    case UTF8:
476
954
      return Just<size_t>(str->Utf8Length(isolate));
477
478
    case UCS2:
479
97
      return Just(str->Length() * sizeof(uint16_t));
480
481
    case BASE64: {
482
5
      String::Value value(isolate, str);
483
5
      return Just(base64_decoded_size(*value, value.length()));
484
    }
485
486
    case HEX:
487
24
      return Just<size_t>(str->Length() / 2);
488
  }
489
490
  UNREACHABLE();
491
}
492
493
494
495
496
4654
static bool contains_non_ascii_slow(const char* buf, size_t len) {
497
22114
  for (size_t i = 0; i < len; ++i) {
498
17617
    if (buf[i] & 0x80)
499
157
      return true;
500
  }
501
4497
  return false;
502
}
503
504
505
5729
static bool contains_non_ascii(const char* src, size_t len) {
506
5729
  if (len < 16) {
507
4548
    return contains_non_ascii_slow(src, len);
508
  }
509
510
1181
  const unsigned bytes_per_word = sizeof(uintptr_t);
511
1181
  const unsigned align_mask = bytes_per_word - 1;
512
1181
  const unsigned unaligned = reinterpret_cast<uintptr_t>(src) & align_mask;
513
514
1181
  if (unaligned > 0) {
515
51
    const unsigned n = bytes_per_word - unaligned;
516
51
    if (contains_non_ascii_slow(src, n))
517
17
      return true;
518
34
    src += n;
519
34
    len -= n;
520
  }
521
522
523
#if defined(_WIN64) || defined(_LP64)
524
1164
  const uintptr_t mask = 0x8080808080808080ll;
525
#else
526
  const uintptr_t mask = 0x80808080l;
527
#endif
528
529
1164
  const uintptr_t* srcw = reinterpret_cast<const uintptr_t*>(src);
530
531
139600646
  for (size_t i = 0, n = len / bytes_per_word; i < n; ++i) {
532
139599917
    if (srcw[i] & mask)
533
435
      return true;
534
  }
535
536
729
  const unsigned remainder = len & align_mask;
537
729
  if (remainder > 0) {
538
55
    const size_t offset = len - remainder;
539
55
    if (contains_non_ascii_slow(src + offset, remainder))
540
      return true;
541
  }
542
543
729
  return false;
544
}
545
546
547
541
static void force_ascii_slow(const char* src, char* dst, size_t len) {
548
5354
  for (size_t i = 0; i < len; ++i) {
549
4813
    dst[i] = src[i] & 0x7f;
550
  }
551
541
}
552
553
554
592
static void force_ascii(const char* src, char* dst, size_t len) {
555
592
  if (len < 16) {
556
140
    force_ascii_slow(src, dst, len);
557
140
    return;
558
  }
559
560
452
  const unsigned bytes_per_word = sizeof(uintptr_t);
561
452
  const unsigned align_mask = bytes_per_word - 1;
562
452
  const unsigned src_unalign = reinterpret_cast<uintptr_t>(src) & align_mask;
563
452
  const unsigned dst_unalign = reinterpret_cast<uintptr_t>(dst) & align_mask;
564
565
452
  if (src_unalign > 0) {
566
50
    if (src_unalign == dst_unalign) {
567
      const unsigned unalign = bytes_per_word - src_unalign;
568
      force_ascii_slow(src, dst, unalign);
569
      src += unalign;
570
      dst += unalign;
571
      len -= src_unalign;
572
    } else {
573
50
      force_ascii_slow(src, dst, len);
574
50
      return;
575
    }
576
  }
577
578
#if defined(_WIN64) || defined(_LP64)
579
402
  const uintptr_t mask = ~0x8080808080808080ll;
580
#else
581
  const uintptr_t mask = ~0x80808080l;
582
#endif
583
584
402
  const uintptr_t* srcw = reinterpret_cast<const uintptr_t*>(src);
585
402
  uintptr_t* dstw = reinterpret_cast<uintptr_t*>(dst);
586
587
2869
  for (size_t i = 0, n = len / bytes_per_word; i < n; ++i) {
588
2467
    dstw[i] = srcw[i] & mask;
589
  }
590
591
402
  const unsigned remainder = len & align_mask;
592
402
  if (remainder > 0) {
593
351
    const size_t offset = len - remainder;
594
351
    force_ascii_slow(src + offset, dst + offset, remainder);
595
  }
596
}
597
598
599
807897
static size_t hex_encode(const char* src, size_t slen, char* dst, size_t dlen) {
600
  // We know how much we'll write, just make sure that there's space.
601
807897
  CHECK(dlen >= slen * 2 &&
602
      "not enough space provided for hex encode");
603
604
807897
  dlen = slen * 2;
605
1114638921
  for (uint32_t i = 0, k = 0; k < dlen; i += 1, k += 2) {
606
    static const char hex[] = "0123456789abcdef";
607
1113831024
    uint8_t val = static_cast<uint8_t>(src[i]);
608
1113831024
    dst[k + 0] = hex[val >> 4];
609
1113831024
    dst[k + 1] = hex[val & 15];
610
  }
611
612
807897
  return dlen;
613
}
614
615
616
#define CHECK_BUFLEN_IN_RANGE(len)                                    \
617
  do {                                                                \
618
    if ((len) > Buffer::kMaxLength) {                                 \
619
      *error = node::ERR_BUFFER_TOO_LARGE(isolate);                   \
620
      return MaybeLocal<Value>();                                     \
621
    }                                                                 \
622
  } while (0)
623
624
625
1599286
MaybeLocal<Value> StringBytes::Encode(Isolate* isolate,
626
                                      const char* buf,
627
                                      size_t buflen,
628
                                      enum encoding encoding,
629
                                      Local<Value>* error) {
630
1599286
  CHECK_BUFLEN_IN_RANGE(buflen);
631
632

1599286
  if (!buflen && encoding != BUFFER) {
633
172
    return String::Empty(isolate);
634
  }
635
636
  MaybeLocal<String> val;
637
638


1599114
  switch (encoding) {
639
    case BUFFER:
640
      {
641
5175
        if (buflen > node::Buffer::kMaxLength) {
642
          *error = node::ERR_BUFFER_TOO_LARGE(isolate);
643
          return MaybeLocal<Value>();
644
        }
645
5175
        auto maybe_buf = Buffer::Copy(isolate, buf, buflen);
646
5175
        if (maybe_buf.IsEmpty()) {
647
          *error = node::ERR_MEMORY_ALLOCATION_FAILED(isolate);
648
          return MaybeLocal<Value>();
649
        }
650
5175
        return maybe_buf.ToLocalChecked();
651
      }
652
653
    case ASCII:
654
5729
      if (contains_non_ascii(buf, buflen)) {
655
592
        char* out = node::UncheckedMalloc(buflen);
656
592
        if (out == nullptr) {
657
          *error = node::ERR_MEMORY_ALLOCATION_FAILED(isolate);
658
          return MaybeLocal<Value>();
659
        }
660
592
        force_ascii(buf, out, buflen);
661
592
        return ExternOneByteString::New(isolate, out, buflen, error);
662
      } else {
663
5137
        return ExternOneByteString::NewFromCopy(isolate, buf, buflen, error);
664
      }
665
666
    case UTF8:
667
      val = String::NewFromUtf8(isolate,
668
                                buf,
669
                                v8::NewStringType::kNormal,
670
769988
                                buflen);
671
769988
      if (val.IsEmpty()) {
672
3
        *error = node::ERR_STRING_TOO_LONG(isolate);
673
3
        return MaybeLocal<Value>();
674
      }
675
769985
      return val.ToLocalChecked();
676
677
    case LATIN1:
678
1147
      return ExternOneByteString::NewFromCopy(isolate, buf, buflen, error);
679
680
    case BASE64: {
681
5607
      size_t dlen = base64_encoded_size(buflen);
682
5607
      char* dst = node::UncheckedMalloc(dlen);
683
5607
      if (dst == nullptr) {
684
        *error = node::ERR_MEMORY_ALLOCATION_FAILED(isolate);
685
        return MaybeLocal<Value>();
686
      }
687
688
5607
      size_t written = base64_encode(buf, buflen, dst, dlen);
689
5607
      CHECK_EQ(written, dlen);
690
691
5607
      return ExternOneByteString::New(isolate, dst, dlen, error);
692
    }
693
694
    case HEX: {
695
807897
      size_t dlen = buflen * 2;
696
807897
      char* dst = node::UncheckedMalloc(dlen);
697
807897
      if (dst == nullptr) {
698
        *error = node::ERR_MEMORY_ALLOCATION_FAILED(isolate);
699
        return MaybeLocal<Value>();
700
      }
701
807897
      size_t written = hex_encode(buf, buflen, dst, dlen);
702
807897
      CHECK_EQ(written, dlen);
703
704
807897
      return ExternOneByteString::New(isolate, dst, dlen, error);
705
    }
706
707
    case UCS2: {
708
3571
      if (IsBigEndian()) {
709
        uint16_t* dst = node::UncheckedMalloc<uint16_t>(buflen / 2);
710
        if (dst == nullptr) {
711
          *error = node::ERR_MEMORY_ALLOCATION_FAILED(isolate);
712
          return MaybeLocal<Value>();
713
        }
714
        for (size_t i = 0, k = 0; k < buflen / 2; i += 2, k += 1) {
715
          // The input is in *little endian*, because that's what Node.js
716
          // expects, so the high byte comes after the low byte.
717
          const uint8_t hi = static_cast<uint8_t>(buf[i + 1]);
718
          const uint8_t lo = static_cast<uint8_t>(buf[i + 0]);
719
          dst[k] = static_cast<uint16_t>(hi) << 8 | lo;
720
        }
721
        return ExternTwoByteString::New(isolate, dst, buflen / 2, error);
722
      }
723
3571
      if (reinterpret_cast<uintptr_t>(buf) % 2 != 0) {
724
        // Unaligned data still means we can't directly pass it to V8.
725
139
        char* dst = node::UncheckedMalloc(buflen);
726
139
        if (dst == nullptr) {
727
          *error = node::ERR_MEMORY_ALLOCATION_FAILED(isolate);
728
          return MaybeLocal<Value>();
729
        }
730
139
        memcpy(dst, buf, buflen);
731
        return ExternTwoByteString::New(
732
139
            isolate, reinterpret_cast<uint16_t*>(dst), buflen / 2, error);
733
      }
734
      return ExternTwoByteString::NewFromCopy(
735
3432
          isolate, reinterpret_cast<const uint16_t*>(buf), buflen / 2, error);
736
    }
737
738
    default:
739
      CHECK(0 && "unknown encoding");
740
      break;
741
  }
742
743
  UNREACHABLE();
744
}
745
746
747
MaybeLocal<Value> StringBytes::Encode(Isolate* isolate,
748
                                      const uint16_t* buf,
749
                                      size_t buflen,
750
                                      Local<Value>* error) {
751
  CHECK_BUFLEN_IN_RANGE(buflen);
752
753
  // Node's "ucs2" encoding expects LE character data inside a
754
  // Buffer, so we need to reorder on BE platforms.  See
755
  // https://nodejs.org/api/buffer.html regarding Node's "ucs2"
756
  // encoding specification
757
  if (IsBigEndian()) {
758
    uint16_t* dst = node::UncheckedMalloc<uint16_t>(buflen);
759
    if (dst == nullptr) {
760
      *error = node::ERR_MEMORY_ALLOCATION_FAILED(isolate);
761
      return MaybeLocal<Value>();
762
    }
763
    size_t nbytes = buflen * sizeof(uint16_t);
764
    memcpy(dst, buf, nbytes);
765
    SwapBytes16(reinterpret_cast<char*>(dst), nbytes);
766
    return ExternTwoByteString::New(isolate, dst, buflen, error);
767
  } else {
768
    return ExternTwoByteString::NewFromCopy(isolate, buf, buflen, error);
769
  }
770
}
771
772
675135
MaybeLocal<Value> StringBytes::Encode(Isolate* isolate,
773
                                      const char* buf,
774
                                      enum encoding encoding,
775
                                      Local<Value>* error) {
776
675135
  const size_t len = strlen(buf);
777
675135
  return Encode(isolate, buf, len, encoding, error);
778
}
779
780
}  // namespace node