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: 252 307 82.1 %
Date: 2019-02-13 22:28:58 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 <limits.h>
31
#include <string.h>  // 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
62
  ~ExternString() override {
59
31
    free(const_cast<TypeName*>(data_));
60
31
    isolate()->AdjustAmountOfExternalAllocatedMemory(-byte_length());
61

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

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

9720
    if (length < EXTERN_APEX)
83
9706
      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
10561
  static MaybeLocal<Value> New(Isolate* isolate,
100
                               TypeName* data,
101
                               size_t length,
102
                               Local<Value>* error) {
103

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

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

31
    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
26
    return str.ToLocalChecked();
125
  }
126
127
31
  inline Isolate* isolate() const { return isolate_; }
128
129
 private:
130
31
  ExternString(Isolate* isolate, const TypeName* data, size_t length)
131
31
    : 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
26
MaybeLocal<Value> ExternOneByteString::NewExternal(
155
    Isolate* isolate, ExternOneByteString* h_str) {
156
52
  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
16494
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
16494
                             length);
176
16494
  if (str.IsEmpty()) {
177
    *error = node::ERR_STRING_TOO_LONG(isolate);
178
    return MaybeLocal<Value>();
179
  }
180
16494
  return str.ToLocalChecked();
181
}
182
183
184
template <>
185
3742
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
3742
                             length);
194
3742
  if (str.IsEmpty()) {
195
    *error = node::ERR_STRING_TOO_LONG(isolate);
196
    return MaybeLocal<Value>();
197
  }
198
3742
  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
45240394
static inline unsigned unhex(uint8_t x) {
244
45240394
  return unhex_table[x];
245
}
246
247
template <typename TypeName>
248
2324
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


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


22620197
    if (!~a || !~b)
257
9
      return i;
258
22620188
    buf[i] = (a << 4) | b;
259
  }
260
261
2315
  return i;
262
}
263
264
513
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
513
  uint16_t* const dst = reinterpret_cast<uint16_t*>(buf);
271
272
513
  size_t max_chars = buflen / sizeof(*dst);
273
513
  if (max_chars == 0) {
274
5
    return 0;
275
  }
276
277
  size_t nchars;
278
508
  size_t alignment = reinterpret_cast<uintptr_t>(dst) % sizeof(*dst);
279
508
  if (alignment == 0) {
280
1008
    nchars = str->Write(isolate, dst, 0, max_chars, flags);
281
504
    *chars_written = nchars;
282
504
    return nchars * sizeof(*dst);
283
  }
284
285
  uint16_t* aligned_dst =
286
4
      reinterpret_cast<uint16_t*>(buf + sizeof(*dst) - alignment);
287
4
  CHECK_EQ(reinterpret_cast<uintptr_t>(aligned_dst) % sizeof(*dst), 0);
288
289
  // Write all but the last char
290
8
  nchars = str->Write(isolate, aligned_dst, 0, max_chars - 1, flags);
291
292
  // Shift everything to unaligned-left
293
4
  memmove(dst, aligned_dst, nchars * sizeof(*dst));
294
295
  // One more char to be written
296
  uint16_t last;
297

8
  if (nchars == max_chars - 1 &&
298
8
      str->Write(isolate, &last, nchars, 1, flags) != 0) {
299
4
    memcpy(buf + nchars * sizeof(*dst), &last, sizeof(last));
300
4
    nchars++;
301
  }
302
303
4
  *chars_written = nchars;
304
4
  return nchars * sizeof(*dst);
305
}
306
307
308
1280654
size_t StringBytes::Write(Isolate* isolate,
309
                          char* buf,
310
                          size_t buflen,
311
                          Local<Value> val,
312
                          enum encoding encoding,
313
                          int* chars_written) {
314
1280654
  HandleScope scope(isolate);
315
  size_t nbytes;
316
  int nchars;
317
318
1280654
  if (chars_written == nullptr)
319
1280654
    chars_written = &nchars;
320
321
2561308
  CHECK(val->IsString() == true);
322
1280654
  Local<String> str = val.As<String>();
323
324
  int flags = String::HINT_MANY_WRITES_EXPECTED |
325
              String::NO_NULL_TERMINATION |
326
1280654
              String::REPLACE_INVALID_UTF8;
327
328

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

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

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

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

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


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

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

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


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