GCC Code Coverage Report
Directory: ../ Exec Total Coverage
File: /home/iojs/build/workspace/node-test-commit-linux-coverage-daily/nodes/benchmark/out/Release/obj/gen/src/node/inspector/protocol/Protocol.cpp Lines: 428 2048 20.9 %
Date: 2019-07-28 22:34:34 Branches: 183 1935 9.5 %

Line Branch Exec Source
1
// This file is generated by Protocol_cpp.template.
2
3
// Copyright 2016 The Chromium Authors. All rights reserved.
4
// Use of this source code is governed by a BSD-style license that can be
5
// found in the LICENSE file.
6
7
#include "src/node/inspector/protocol/Protocol.h"
8
9
#include <algorithm>
10
#include <climits>
11
#include <cmath>
12
#include <cstring>
13
14
15
// This file is generated by ErrorSupport_cpp.template.
16
17
// Copyright 2016 The Chromium Authors. All rights reserved.
18
// Use of this source code is governed by a BSD-style license that can be
19
// found in the LICENSE file.
20
21
//#include "ErrorSupport.h"
22
23
namespace node {
24
namespace inspector {
25
namespace protocol {
26
27
35
ErrorSupport::ErrorSupport() { }
28
35
ErrorSupport::~ErrorSupport() { }
29
30
45
void ErrorSupport::setName(const char* name)
31
{
32
45
    setName(String(name));
33
45
}
34
35
48
void ErrorSupport::setName(const String& name)
36
{
37
    DCHECK(m_path.size());
38
48
    m_path[m_path.size() - 1] = name;
39
48
}
40
41
34
void ErrorSupport::push()
42
{
43
34
    m_path.push_back(String());
44
34
}
45
46
34
void ErrorSupport::pop()
47
{
48
34
    m_path.pop_back();
49
34
}
50
51
void ErrorSupport::addError(const char* error)
52
{
53
    addError(String(error));
54
}
55
56
void ErrorSupport::addError(const String& error)
57
{
58
    StringBuilder builder;
59
    for (size_t i = 0; i < m_path.size(); ++i) {
60
        if (i)
61
            StringUtil::builderAppend(builder, '.');
62
        StringUtil::builderAppend(builder, m_path[i]);
63
    }
64
    StringUtil::builderAppend(builder, ": ");
65
    StringUtil::builderAppend(builder, error);
66
    m_errors.push_back(StringUtil::builderToString(builder));
67
}
68
69
34
bool ErrorSupport::hasErrors()
70
{
71
34
    return !!m_errors.size();
72
}
73
74
String ErrorSupport::errors()
75
{
76
    StringBuilder builder;
77
    for (size_t i = 0; i < m_errors.size(); ++i) {
78
        if (i)
79
            StringUtil::builderAppend(builder, "; ");
80
        StringUtil::builderAppend(builder, m_errors[i]);
81
    }
82
    return StringUtil::builderToString(builder);
83
}
84
85
} // namespace node
86
} // namespace inspector
87
} // namespace protocol
88
89
90
// This file is generated by Values_cpp.template.
91
92
// Copyright 2016 The Chromium Authors. All rights reserved.
93
// Use of this source code is governed by a BSD-style license that can be
94
// found in the LICENSE file.
95
96
//#include "Values.h"
97
98
namespace node {
99
namespace inspector {
100
namespace protocol {
101
102
namespace {
103
104
const char* const nullValueString = "null";
105
const char* const trueValueString = "true";
106
const char* const falseValueString = "false";
107
108
107159
inline bool escapeChar(uint16_t c, StringBuilder* dst)
109
{
110


107159
    switch (c) {
111
    case '\b': StringUtil::builderAppend(*dst, "\\b"); break;
112
    case '\f': StringUtil::builderAppend(*dst, "\\f"); break;
113
    case '\n': StringUtil::builderAppend(*dst, "\\n"); break;
114
    case '\r': StringUtil::builderAppend(*dst, "\\r"); break;
115
    case '\t': StringUtil::builderAppend(*dst, "\\t"); break;
116
396
    case '\\': StringUtil::builderAppend(*dst, "\\\\"); break;
117
12410
    case '"': StringUtil::builderAppend(*dst, "\\\""); break;
118
    default:
119
94353
        return false;
120
    }
121
12806
    return true;
122
}
123
124
const char hexDigits[17] = "0123456789ABCDEF";
125
126
void appendUnsignedAsHex(uint16_t number, StringBuilder* dst)
127
{
128
    StringUtil::builderAppend(*dst, "\\u");
129
    for (size_t i = 0; i < 4; ++i) {
130
        uint16_t c = hexDigits[(number & 0xF000) >> 12];
131
        StringUtil::builderAppend(*dst, c);
132
        number <<= 4;
133
    }
134
}
135
136
template <typename Char>
137
1384
void escapeStringForJSONInternal(const Char* str, unsigned len,
138
                                 StringBuilder* dst)
139
{
140

108543
    for (unsigned i = 0; i < len; ++i) {
141
107159
        Char c = str[i];
142

107159
        if (escapeChar(c, dst))
143
12806
            continue;
144


94353
        if (c < 32 || c > 126) {
145
            appendUnsignedAsHex(c, dst);
146
        } else {
147
94353
            StringUtil::builderAppend(*dst, c);
148
        }
149
    }
150
1384
}
151
152
// When parsing CBOR, we limit recursion depth for objects and arrays
153
// to this constant.
154
static constexpr int kStackLimitValues = 1000;
155
156
// Below are three parsing routines for CBOR, which cover enough
157
// to roundtrip JSON messages.
158
std::unique_ptr<DictionaryValue> parseMap(int32_t stack_depth, cbor::CBORTokenizer* tokenizer);
159
std::unique_ptr<ListValue> parseArray(int32_t stack_depth, cbor::CBORTokenizer* tokenizer);
160
std::unique_ptr<Value> parseValue(int32_t stack_depth, cbor::CBORTokenizer* tokenizer);
161
162
// |bytes| must start with the indefinite length array byte, so basically,
163
// ParseArray may only be called after an indefinite length array has been
164
// detected.
165
std::unique_ptr<ListValue> parseArray(int32_t stack_depth, cbor::CBORTokenizer* tokenizer) {
166
  DCHECK(tokenizer->TokenTag() == cbor::CBORTokenTag::ARRAY_START);
167
  tokenizer->Next();
168
  auto list = ListValue::create();
169
  while (tokenizer->TokenTag() != cbor::CBORTokenTag::STOP) {
170
    // Error::CBOR_UNEXPECTED_EOF_IN_ARRAY
171
    if (tokenizer->TokenTag() == cbor::CBORTokenTag::DONE) return nullptr;
172
    if (tokenizer->TokenTag() == cbor::CBORTokenTag::ERROR_VALUE) return nullptr;
173
    // Parse value.
174
    auto value = parseValue(stack_depth, tokenizer);
175
    if (!value) return nullptr;
176
    list->pushValue(std::move(value));
177
  }
178
  tokenizer->Next();
179
  return list;
180
}
181
182
std::unique_ptr<Value> parseValue(
183
    int32_t stack_depth, cbor::CBORTokenizer* tokenizer) {
184
  // Error::CBOR_STACK_LIMIT_EXCEEDED
185
  if (stack_depth > kStackLimitValues) return nullptr;
186
  // Skip past the envelope to get to what's inside.
187
  if (tokenizer->TokenTag() == cbor::CBORTokenTag::ENVELOPE)
188
    tokenizer->EnterEnvelope();
189
  switch (tokenizer->TokenTag()) {
190
    case cbor::CBORTokenTag::ERROR_VALUE:
191
      return nullptr;
192
    case cbor::CBORTokenTag::DONE:
193
      // Error::CBOR_UNEXPECTED_EOF_EXPECTED_VALUE
194
      return nullptr;
195
    case cbor::CBORTokenTag::TRUE_VALUE: {
196
      std::unique_ptr<Value> value = FundamentalValue::create(true);
197
      tokenizer->Next();
198
      return value;
199
    }
200
    case cbor::CBORTokenTag::FALSE_VALUE: {
201
      std::unique_ptr<Value> value = FundamentalValue::create(false);
202
      tokenizer->Next();
203
      return value;
204
    }
205
    case cbor::CBORTokenTag::NULL_VALUE: {
206
      std::unique_ptr<Value> value = FundamentalValue::null();
207
      tokenizer->Next();
208
      return value;
209
    }
210
    case cbor::CBORTokenTag::INT32: {
211
      std::unique_ptr<Value> value = FundamentalValue::create(tokenizer->GetInt32());
212
      tokenizer->Next();
213
      return value;
214
    }
215
    case cbor::CBORTokenTag::DOUBLE: {
216
      std::unique_ptr<Value> value = FundamentalValue::create(tokenizer->GetDouble());
217
      tokenizer->Next();
218
      return value;
219
    }
220
    case cbor::CBORTokenTag::STRING8: {
221
      span<uint8_t> str = tokenizer->GetString8();
222
      std::unique_ptr<Value> value =
223
          StringValue::create(StringUtil::fromUTF8(str.data(), str.size()));
224
      tokenizer->Next();
225
      return value;
226
    }
227
    case cbor::CBORTokenTag::STRING16: {
228
      span<uint8_t> wire = tokenizer->GetString16WireRep();
229
      DCHECK_EQ(wire.size() & 1, 0u);
230
      std::unique_ptr<Value> value = StringValue::create(StringUtil::fromUTF16(
231
          reinterpret_cast<const uint16_t*>(wire.data()), wire.size() / 2));
232
      tokenizer->Next();
233
      return value;
234
    }
235
    case cbor::CBORTokenTag::BINARY: {
236
      span<uint8_t> payload = tokenizer->GetBinary();
237
      tokenizer->Next();
238
      return BinaryValue::create(Binary::fromSpan(payload.data(), payload.size()));
239
    }
240
    case cbor::CBORTokenTag::MAP_START:
241
      return parseMap(stack_depth + 1, tokenizer);
242
    case cbor::CBORTokenTag::ARRAY_START:
243
      return parseArray(stack_depth + 1, tokenizer);
244
    default:
245
      // Error::CBOR_UNSUPPORTED_VALUE
246
      return nullptr;
247
  }
248
}
249
250
// |bytes| must start with the indefinite length array byte, so basically,
251
// ParseArray may only be called after an indefinite length array has been
252
// detected.
253
std::unique_ptr<DictionaryValue> parseMap(
254
    int32_t stack_depth, cbor::CBORTokenizer* tokenizer) {
255
  auto dict = DictionaryValue::create();
256
  tokenizer->Next();
257
  while (tokenizer->TokenTag() != cbor::CBORTokenTag::STOP) {
258
    if (tokenizer->TokenTag() == cbor::CBORTokenTag::DONE) {
259
      // Error::CBOR_UNEXPECTED_EOF_IN_MAP
260
      return nullptr;
261
    }
262
    if (tokenizer->TokenTag() == cbor::CBORTokenTag::ERROR_VALUE) return nullptr;
263
    // Parse key.
264
    String key;
265
    if (tokenizer->TokenTag() == cbor::CBORTokenTag::STRING8) {
266
      span<uint8_t> key_span = tokenizer->GetString8();
267
      key = StringUtil::fromUTF8(key_span.data(), key_span.size());
268
      tokenizer->Next();
269
    } else if (tokenizer->TokenTag() == cbor::CBORTokenTag::STRING16) {
270
      return nullptr;  // STRING16 not supported yet.
271
    } else {
272
      // Error::CBOR_INVALID_MAP_KEY
273
      return nullptr;
274
    }
275
    // Parse value.
276
    auto value = parseValue(stack_depth, tokenizer);
277
    if (!value) return nullptr;
278
    dict->setValue(key, std::move(value));
279
  }
280
  tokenizer->Next();
281
  return dict;
282
}
283
284
} // anonymous namespace
285
286
// static
287
std::unique_ptr<Value> Value::parseBinary(const uint8_t* data, size_t size) {
288
  span<uint8_t> bytes(data, size);
289
290
  // Error::CBOR_NO_INPUT
291
  if (bytes.empty()) return nullptr;
292
293
  // Error::CBOR_INVALID_START_BYTE
294
  if (bytes[0] != cbor::InitialByteForEnvelope()) return nullptr;
295
296
  cbor::CBORTokenizer tokenizer(bytes);
297
  if (tokenizer.TokenTag() == cbor::CBORTokenTag::ERROR_VALUE) return nullptr;
298
299
  // We checked for the envelope start byte above, so the tokenizer
300
  // must agree here, since it's not an error.
301
  DCHECK(tokenizer.TokenTag() == cbor::CBORTokenTag::ENVELOPE);
302
  tokenizer.EnterEnvelope();
303
  // Error::MAP_START_EXPECTED
304
  if (tokenizer.TokenTag() != cbor::CBORTokenTag::MAP_START) return nullptr;
305
  std::unique_ptr<Value> result = parseMap(/*stack_depth=*/1, &tokenizer);
306
  if (!result) return nullptr;
307
  if (tokenizer.TokenTag() == cbor::CBORTokenTag::DONE) return result;
308
  if (tokenizer.TokenTag() == cbor::CBORTokenTag::ERROR_VALUE) return nullptr;
309
  // Error::CBOR_TRAILING_JUNK
310
  return nullptr;
311
}
312
313
bool Value::asBoolean(bool*) const
314
{
315
    return false;
316
}
317
318
bool Value::asDouble(double*) const
319
{
320
    return false;
321
}
322
323
bool Value::asInteger(int*) const
324
{
325
    return false;
326
}
327
328
bool Value::asString(String*) const
329
{
330
    return false;
331
}
332
333
bool Value::asBinary(Binary*) const
334
{
335
    return false;
336
}
337
338
void Value::writeJSON(StringBuilder* output) const
339
{
340
    DCHECK(m_type == TypeNull);
341
    StringUtil::builderAppend(*output, nullValueString, 4);
342
}
343
344
void Value::writeBinary(std::vector<uint8_t>* bytes) const {
345
    DCHECK(m_type == TypeNull);
346
    bytes->push_back(cbor::EncodeNull());
347
}
348
349
std::unique_ptr<Value> Value::clone() const
350
{
351
    return Value::null();
352
}
353
354
435
String Value::toJSONString() const
355
{
356
435
    StringBuilder result;
357
435
    StringUtil::builderReserve(result, 512);
358
435
    writeJSON(&result);
359
435
    return StringUtil::builderToString(result);
360
}
361
362
435
String Value::serializeToJSON() {
363
435
    return toJSONString();
364
}
365
366
std::vector<uint8_t> Value::serializeToBinary() {
367
    std::vector<uint8_t> bytes;
368
    writeBinary(&bytes);
369
    return bytes;
370
}
371
372
9
bool FundamentalValue::asBoolean(bool* output) const
373
{
374
9
    if (type() != TypeBoolean)
375
        return false;
376
9
    *output = m_boolValue;
377
9
    return true;
378
}
379
380
bool FundamentalValue::asDouble(double* output) const
381
{
382
    if (type() == TypeDouble) {
383
        *output = m_doubleValue;
384
        return true;
385
    }
386
    if (type() == TypeInteger) {
387
        *output = m_integerValue;
388
        return true;
389
    }
390
    return false;
391
}
392
393
15323
bool FundamentalValue::asInteger(int* output) const
394
{
395
15323
    if (type() != TypeInteger)
396
        return false;
397
15323
    *output = m_integerValue;
398
15323
    return true;
399
}
400
401
43
void FundamentalValue::writeJSON(StringBuilder* output) const
402
{
403
    DCHECK(type() == TypeBoolean || type() == TypeInteger || type() == TypeDouble);
404
43
    if (type() == TypeBoolean) {
405
7
        if (m_boolValue)
406
5
            StringUtil::builderAppend(*output, trueValueString, 4);
407
        else
408
2
            StringUtil::builderAppend(*output, falseValueString, 5);
409
36
    } else if (type() == TypeDouble) {
410
        if (!std::isfinite(m_doubleValue)) {
411
            StringUtil::builderAppend(*output, nullValueString, 4);
412
43
            return;
413
        }
414
        StringUtil::builderAppend(*output, StringUtil::fromDouble(m_doubleValue));
415
36
    } else if (type() == TypeInteger) {
416
36
        StringUtil::builderAppend(*output, StringUtil::fromInteger(m_integerValue));
417
    }
418
}
419
420
void FundamentalValue::writeBinary(std::vector<uint8_t>* bytes) const {
421
    switch (type()) {
422
    case TypeDouble:
423
        cbor::EncodeDouble(m_doubleValue, bytes);
424
        return;
425
    case TypeInteger:
426
        cbor::EncodeInt32(m_integerValue, bytes);
427
        return;
428
    case TypeBoolean:
429
        bytes->push_back(m_boolValue ? cbor::EncodeTrue() : cbor::EncodeFalse());
430
        return;
431
    default:
432
        DCHECK(false);
433
    }
434
}
435
436
std::unique_ptr<Value> FundamentalValue::clone() const
437
{
438
    switch (type()) {
439
    case TypeDouble: return FundamentalValue::create(m_doubleValue);
440
    case TypeInteger: return FundamentalValue::create(m_integerValue);
441
    case TypeBoolean: return FundamentalValue::create(m_boolValue);
442
    default:
443
        DCHECK(false);
444
    }
445
    return nullptr;
446
}
447
448
15356
bool StringValue::asString(String* output) const
449
{
450
15356
    *output = m_stringValue;
451
15356
    return true;
452
}
453
454
562
void StringValue::writeJSON(StringBuilder* output) const
455
{
456
    DCHECK(type() == TypeString);
457
562
    StringUtil::builderAppendQuotedString(*output, m_stringValue);
458
562
}
459
460
namespace {
461
// This routine distinguishes between the current encoding for a given
462
// string |s|, and calls encoding routines that will
463
// - Ensure that all ASCII strings end up being encoded as UTF8 in
464
//   the wire format - e.g., EncodeFromUTF16 will detect ASCII and
465
//   do the (trivial) transcode to STRING8 on the wire, but if it's
466
//   not ASCII it'll do STRING16.
467
// - Select a format that's cheap to convert to. E.g., we don't
468
//   have LATIN1 on the wire, so we call EncodeFromLatin1 which
469
//   transcodes to UTF8 if needed.
470
void EncodeString(const String& s, std::vector<uint8_t>* out) {
471
  if (StringUtil::CharacterCount(s) == 0) {
472
    cbor::EncodeString8(span<uint8_t>(nullptr, 0), out);  // Empty string.
473
  } else if (StringUtil::CharactersLatin1(s)) {
474
    cbor::EncodeFromLatin1(span<uint8_t>(StringUtil::CharactersLatin1(s),
475
		                         StringUtil::CharacterCount(s)),
476
                           out);
477
  } else if (StringUtil::CharactersUTF16(s)) {
478
    cbor::EncodeFromUTF16(span<uint16_t>(StringUtil::CharactersUTF16(s),
479
                                         StringUtil::CharacterCount(s)),
480
                          out);
481
  } else if (StringUtil::CharactersUTF8(s)) {
482
    cbor::EncodeString8(span<uint8_t>(StringUtil::CharactersUTF8(s),
483
                                      StringUtil::CharacterCount(s)),
484
                        out);
485
  }
486
}
487
}  // namespace
488
489
void StringValue::writeBinary(std::vector<uint8_t>* bytes) const {
490
  EncodeString(m_stringValue, bytes);
491
}
492
493
std::unique_ptr<Value> StringValue::clone() const
494
{
495
    return StringValue::create(m_stringValue);
496
}
497
498
bool BinaryValue::asBinary(Binary* output) const
499
{
500
    *output = m_binaryValue;
501
    return true;
502
}
503
504
void BinaryValue::writeJSON(StringBuilder* output) const
505
{
506
    DCHECK(type() == TypeBinary);
507
    StringUtil::builderAppendQuotedString(*output, m_binaryValue.toBase64());
508
}
509
510
void BinaryValue::writeBinary(std::vector<uint8_t>* bytes) const {
511
    cbor::EncodeBinary(span<uint8_t>(m_binaryValue.data(),
512
                                     m_binaryValue.size()), bytes);
513
}
514
515
std::unique_ptr<Value> BinaryValue::clone() const
516
{
517
    return BinaryValue::create(m_binaryValue);
518
}
519
520
217
void SerializedValue::writeJSON(StringBuilder* output) const
521
{
522
    DCHECK(type() == TypeSerialized);
523
217
    StringUtil::builderAppend(*output, m_serializedJSON);
524
217
}
525
526
void SerializedValue::writeBinary(std::vector<uint8_t>* output) const
527
{
528
    DCHECK(type() == TypeSerialized);
529
    output->insert(output->end(), m_serializedBinary.begin(), m_serializedBinary.end());
530
}
531
532
std::unique_ptr<Value> SerializedValue::clone() const
533
{
534
    return std::unique_ptr<SerializedValue>(new SerializedValue(m_serializedJSON, m_serializedBinary));
535
}
536
537
41729
DictionaryValue::~DictionaryValue()
538
{
539
41731
}
540
541
void DictionaryValue::setBoolean(const String& name, bool value)
542
{
543
    setValue(name, FundamentalValue::create(value));
544
}
545
546
36
void DictionaryValue::setInteger(const String& name, int value)
547
{
548
36
    setValue(name, FundamentalValue::create(value));
549
36
}
550
551
void DictionaryValue::setDouble(const String& name, double value)
552
{
553
    setValue(name, FundamentalValue::create(value));
554
}
555
556
184
void DictionaryValue::setString(const String& name, const String& value)
557
{
558
184
    setValue(name, StringValue::create(value));
559
184
}
560
561
46726
void DictionaryValue::setValue(const String& name, std::unique_ptr<Value> value)
562
{
563
46726
    set(name, value);
564
46726
}
565
566
1
void DictionaryValue::setObject(const String& name, std::unique_ptr<DictionaryValue> value)
567
{
568
1
    set(name, value);
569
1
}
570
571
void DictionaryValue::setArray(const String& name, std::unique_ptr<ListValue> value)
572
{
573
    set(name, value);
574
}
575
576
bool DictionaryValue::getBoolean(const String& name, bool* output) const
577
{
578
    protocol::Value* value = get(name);
579
    if (!value)
580
        return false;
581
    return value->asBoolean(output);
582
}
583
584
bool DictionaryValue::getInteger(const String& name, int* output) const
585
{
586
    Value* value = get(name);
587
    if (!value)
588
        return false;
589
    return value->asInteger(output);
590
}
591
592
bool DictionaryValue::getDouble(const String& name, double* output) const
593
{
594
    Value* value = get(name);
595
    if (!value)
596
        return false;
597
    return value->asDouble(output);
598
}
599
600
bool DictionaryValue::getString(const String& name, String* output) const
601
{
602
    protocol::Value* value = get(name);
603
    if (!value)
604
        return false;
605
    return value->asString(output);
606
}
607
608
DictionaryValue* DictionaryValue::getObject(const String& name) const
609
{
610
    return DictionaryValue::cast(get(name));
611
}
612
613
protocol::ListValue* DictionaryValue::getArray(const String& name) const
614
{
615
    return ListValue::cast(get(name));
616
}
617
618
30722
protocol::Value* DictionaryValue::get(const String& name) const
619
{
620
30722
    Dictionary::const_iterator it = m_data.find(name);
621
30722
    if (it == m_data.end())
622
3
        return nullptr;
623
30719
    return it->second.get();
624
}
625
626
DictionaryValue::Entry DictionaryValue::at(size_t index) const
627
{
628
    const String key = m_order[index];
629
    return std::make_pair(key, m_data.find(key)->second.get());
630
}
631
632
bool DictionaryValue::booleanProperty(const String& name, bool defaultValue) const
633
{
634
    bool result = defaultValue;
635
    getBoolean(name, &result);
636
    return result;
637
}
638
639
int DictionaryValue::integerProperty(const String& name, int defaultValue) const
640
{
641
    int result = defaultValue;
642
    getInteger(name, &result);
643
    return result;
644
}
645
646
double DictionaryValue::doubleProperty(const String& name, double defaultValue) const
647
{
648
    double result = defaultValue;
649
    getDouble(name, &result);
650
    return result;
651
}
652
653
void DictionaryValue::remove(const String& name)
654
{
655
    m_data.erase(name);
656
    m_order.erase(std::remove(m_order.begin(), m_order.end(), name), m_order.end());
657
}
658
659
443
void DictionaryValue::writeJSON(StringBuilder* output) const
660
{
661
443
    StringUtil::builderAppend(*output, '{');
662
1266
    for (size_t i = 0; i < m_order.size(); ++i) {
663
823
        Dictionary::const_iterator it = m_data.find(m_order[i]);
664
823
        CHECK(it != m_data.end());
665
823
        if (i)
666
418
            StringUtil::builderAppend(*output, ',');
667
823
        StringUtil::builderAppendQuotedString(*output, it->first);
668
823
        StringUtil::builderAppend(*output, ':');
669
823
        it->second->writeJSON(output);
670
    }
671
443
    StringUtil::builderAppend(*output, '}');
672
443
}
673
674
void DictionaryValue::writeBinary(std::vector<uint8_t>* bytes) const {
675
    cbor::EnvelopeEncoder encoder;
676
    encoder.EncodeStart(bytes);
677
    bytes->push_back(cbor::EncodeIndefiniteLengthMapStart());
678
    for (size_t i = 0; i < m_order.size(); ++i) {
679
        const String& key = m_order[i];
680
        Dictionary::const_iterator value = m_data.find(key);
681
        DCHECK(value != m_data.cend() && value->second);
682
        EncodeString(key, bytes);
683
        value->second->writeBinary(bytes);
684
    }
685
    bytes->push_back(cbor::EncodeStop());
686
    encoder.EncodeStop(bytes);
687
}
688
689
std::unique_ptr<Value> DictionaryValue::clone() const
690
{
691
    std::unique_ptr<DictionaryValue> result = DictionaryValue::create();
692
    for (size_t i = 0; i < m_order.size(); ++i) {
693
        String key = m_order[i];
694
        Dictionary::const_iterator value = m_data.find(key);
695
        DCHECK(value != m_data.cend() && value->second);
696
        result->setValue(key, value->second->clone());
697
    }
698
    return std::move(result);
699
}
700
701
20865
DictionaryValue::DictionaryValue()
702
20865
    : Value(TypeObject)
703
{
704
20866
}
705
706
26
ListValue::~ListValue()
707
{
708
26
}
709
710
1
void ListValue::writeJSON(StringBuilder* output) const
711
{
712
1
    StringUtil::builderAppend(*output, '[');
713
1
    bool first = true;
714
9
    for (const std::unique_ptr<protocol::Value>& value : m_data) {
715
8
        if (!first)
716
7
            StringUtil::builderAppend(*output, ',');
717
8
        value->writeJSON(output);
718
8
        first = false;
719
    }
720
1
    StringUtil::builderAppend(*output, ']');
721
1
}
722
723
void ListValue::writeBinary(std::vector<uint8_t>* bytes) const {
724
    cbor::EnvelopeEncoder encoder;
725
    encoder.EncodeStart(bytes);
726
    bytes->push_back(cbor::EncodeIndefiniteLengthArrayStart());
727
    for (size_t i = 0; i < m_data.size(); ++i) {
728
        m_data[i]->writeBinary(bytes);
729
    }
730
    bytes->push_back(cbor::EncodeStop());
731
    encoder.EncodeStop(bytes);
732
}
733
734
std::unique_ptr<Value> ListValue::clone() const
735
{
736
    std::unique_ptr<ListValue> result = ListValue::create();
737
    for (const std::unique_ptr<protocol::Value>& value : m_data)
738
        result->pushValue(value->clone());
739
    return std::move(result);
740
}
741
742
13
ListValue::ListValue()
743
13
    : Value(TypeArray)
744
{
745
13
}
746
747
13
void ListValue::pushValue(std::unique_ptr<protocol::Value> value)
748
{
749
    DCHECK(value);
750
13
    m_data.push_back(std::move(value));
751
13
}
752
753
3
protocol::Value* ListValue::at(size_t index)
754
{
755
    DCHECK_LT(index, m_data.size());
756
3
    return m_data[index].get();
757
}
758
759
void escapeLatinStringForJSON(const uint8_t* str, unsigned len, StringBuilder* dst)
760
{
761
    escapeStringForJSONInternal<uint8_t>(str, len, dst);
762
}
763
764
1384
void escapeWideStringForJSON(const uint16_t* str, unsigned len, StringBuilder* dst)
765
{
766
1384
    escapeStringForJSONInternal<uint16_t>(str, len, dst);
767
1384
}
768
769
} // namespace node
770
} // namespace inspector
771
} // namespace protocol
772
773
774
// This file is generated by Object_cpp.template.
775
776
// Copyright 2016 The Chromium Authors. All rights reserved.
777
// Use of this source code is governed by a BSD-style license that can be
778
// found in the LICENSE file.
779
780
//#include "Object.h"
781
782
namespace node {
783
namespace inspector {
784
namespace protocol {
785
786
std::unique_ptr<Object> Object::fromValue(protocol::Value* value, ErrorSupport* errors)
787
{
788
    protocol::DictionaryValue* dictionary = DictionaryValue::cast(value);
789
    if (!dictionary) {
790
        errors->addError("object expected");
791
        return nullptr;
792
    }
793
    dictionary = static_cast<protocol::DictionaryValue*>(dictionary->clone().release());
794
    return std::unique_ptr<Object>(new Object(std::unique_ptr<DictionaryValue>(dictionary)));
795
}
796
797
std::unique_ptr<protocol::DictionaryValue> Object::toValue() const
798
{
799
    return DictionaryValue::cast(m_object->clone());
800
}
801
802
std::unique_ptr<Object> Object::clone() const
803
{
804
    return std::unique_ptr<Object>(new Object(DictionaryValue::cast(m_object->clone())));
805
}
806
807
Object::Object(std::unique_ptr<protocol::DictionaryValue> object) : m_object(std::move(object)) { }
808
809
Object::~Object() { }
810
811
} // namespace node
812
} // namespace inspector
813
} // namespace protocol
814
815
816
// This file is generated by DispatcherBase_cpp.template.
817
818
// Copyright 2016 The Chromium Authors. All rights reserved.
819
// Use of this source code is governed by a BSD-style license that can be
820
// found in the LICENSE file.
821
822
//#include "DispatcherBase.h"
823
//#include "Parser.h"
824
825
namespace node {
826
namespace inspector {
827
namespace protocol {
828
829
// static
830
14466
DispatchResponse DispatchResponse::OK()
831
{
832
14466
    DispatchResponse result;
833
14466
    result.m_status = kSuccess;
834
14466
    result.m_errorCode = kParseError;
835
14466
    return result;
836
}
837
838
// static
839
1
DispatchResponse DispatchResponse::Error(const String& error)
840
{
841
1
    DispatchResponse result;
842
1
    result.m_status = kError;
843
1
    result.m_errorCode = kServerError;
844
1
    result.m_errorMessage = error;
845
1
    return result;
846
}
847
848
// static
849
DispatchResponse DispatchResponse::InternalError()
850
{
851
    DispatchResponse result;
852
    result.m_status = kError;
853
    result.m_errorCode = kInternalError;
854
    result.m_errorMessage = "Internal error";
855
    return result;
856
}
857
858
// static
859
DispatchResponse DispatchResponse::InvalidParams(const String& error)
860
{
861
    DispatchResponse result;
862
    result.m_status = kError;
863
    result.m_errorCode = kInvalidParams;
864
    result.m_errorMessage = error;
865
    return result;
866
}
867
868
// static
869
DispatchResponse DispatchResponse::FallThrough()
870
{
871
    DispatchResponse result;
872
    result.m_status = kFallThrough;
873
    result.m_errorCode = kParseError;
874
    return result;
875
}
876
877
// static
878
const char DispatcherBase::kInvalidParamsString[] = "Invalid parameters";
879
880
35
DispatcherBase::WeakPtr::WeakPtr(DispatcherBase* dispatcher) : m_dispatcher(dispatcher) { }
881
882
35
DispatcherBase::WeakPtr::~WeakPtr()
883
{
884
35
    if (m_dispatcher)
885
35
        m_dispatcher->m_weakPtrs.erase(this);
886
35
}
887
888
DispatcherBase::Callback::Callback(std::unique_ptr<DispatcherBase::WeakPtr> backendImpl, int callId, const String& method, const ProtocolMessage& message)
889
    : m_backendImpl(std::move(backendImpl))
890
    , m_callId(callId)
891
    , m_method(method)
892
    , m_message(message) { }
893
894
DispatcherBase::Callback::~Callback() = default;
895
896
void DispatcherBase::Callback::dispose()
897
{
898
    m_backendImpl = nullptr;
899
}
900
901
void DispatcherBase::Callback::sendIfActive(std::unique_ptr<protocol::DictionaryValue> partialMessage, const DispatchResponse& response)
902
{
903
    if (!m_backendImpl || !m_backendImpl->get())
904
        return;
905
    m_backendImpl->get()->sendResponse(m_callId, response, std::move(partialMessage));
906
    m_backendImpl = nullptr;
907
}
908
909
void DispatcherBase::Callback::fallThroughIfActive()
910
{
911
    if (!m_backendImpl || !m_backendImpl->get())
912
        return;
913
    m_backendImpl->get()->channel()->fallThrough(m_callId, m_method, m_message);
914
    m_backendImpl = nullptr;
915
}
916
917
15619
DispatcherBase::DispatcherBase(FrontendChannel* frontendChannel)
918
15619
    : m_frontendChannel(frontendChannel) { }
919
920
28866
DispatcherBase::~DispatcherBase()
921
{
922
14433
    clearFrontend();
923
14433
}
924
925
35
void DispatcherBase::sendResponse(int callId, const DispatchResponse& response, std::unique_ptr<protocol::DictionaryValue> result)
926
{
927
35
    if (!m_frontendChannel)
928
        return;
929
35
    if (response.status() == DispatchResponse::kError) {
930
1
        reportProtocolError(callId, response.errorCode(), response.errorMessage(), nullptr);
931
1
        return;
932
    }
933
34
    m_frontendChannel->sendProtocolResponse(callId, InternalResponse::createResponse(callId, std::move(result)));
934
}
935
936
34
void DispatcherBase::sendResponse(int callId, const DispatchResponse& response)
937
{
938
34
    sendResponse(callId, response, DictionaryValue::create());
939
34
}
940
941
namespace {
942
943
class ProtocolError : public Serializable {
944
public:
945
1
    static std::unique_ptr<ProtocolError> createErrorResponse(int callId, DispatchResponse::ErrorCode code, const String& errorMessage, ErrorSupport* errors)
946
    {
947
1
        std::unique_ptr<ProtocolError> protocolError(new ProtocolError(code, errorMessage));
948
1
        protocolError->m_callId = callId;
949
1
        protocolError->m_hasCallId = true;
950

1
        if (errors && errors->hasErrors())
951
            protocolError->m_data = errors->errors();
952
1
        return protocolError;
953
    }
954
955
    static std::unique_ptr<ProtocolError> createErrorNotification(DispatchResponse::ErrorCode code, const String& errorMessage)
956
    {
957
        return std::unique_ptr<ProtocolError>(new ProtocolError(code, errorMessage));
958
    }
959
960
1
    String serializeToJSON() override
961
    {
962
1
        return serialize()->serializeToJSON();
963
    }
964
965
    std::vector<uint8_t> serializeToBinary() override
966
    {
967
        return serialize()->serializeToBinary();
968
    }
969
970
2
    ~ProtocolError() override {}
971
972
private:
973
1
    ProtocolError(DispatchResponse::ErrorCode code, const String& errorMessage)
974
        : m_code(code)
975
1
        , m_errorMessage(errorMessage)
976
    {
977
1
    }
978
979
1
    std::unique_ptr<DictionaryValue> serialize() {
980
1
        std::unique_ptr<protocol::DictionaryValue> error = DictionaryValue::create();
981
1
        error->setInteger("code", m_code);
982
1
        error->setString("message", m_errorMessage);
983
1
        if (m_data.length())
984
            error->setString("data", m_data);
985
1
        std::unique_ptr<protocol::DictionaryValue> message = DictionaryValue::create();
986
1
        message->setObject("error", std::move(error));
987
1
        if (m_hasCallId)
988
1
            message->setInteger("id", m_callId);
989
1
        return message;
990
    }
991
992
    DispatchResponse::ErrorCode m_code;
993
    String m_errorMessage;
994
    String m_data;
995
    int m_callId = 0;
996
    bool m_hasCallId = false;
997
};
998
999
} // namespace
1000
1001
1
static void reportProtocolErrorTo(FrontendChannel* frontendChannel, int callId, DispatchResponse::ErrorCode code, const String& errorMessage, ErrorSupport* errors)
1002
{
1003
1
    if (frontendChannel)
1004
1
        frontendChannel->sendProtocolResponse(callId, ProtocolError::createErrorResponse(callId, code, errorMessage, errors));
1005
1
}
1006
1007
static void reportProtocolErrorTo(FrontendChannel* frontendChannel, DispatchResponse::ErrorCode code, const String& errorMessage)
1008
{
1009
    if (frontendChannel)
1010
        frontendChannel->sendProtocolNotification(ProtocolError::createErrorNotification(code, errorMessage));
1011
}
1012
1013
1
void DispatcherBase::reportProtocolError(int callId, DispatchResponse::ErrorCode code, const String& errorMessage, ErrorSupport* errors)
1014
{
1015
1
    reportProtocolErrorTo(m_frontendChannel, callId, code, errorMessage, errors);
1016
1
}
1017
1018
14433
void DispatcherBase::clearFrontend()
1019
{
1020
14433
    m_frontendChannel = nullptr;
1021
14433
    for (auto& weak : m_weakPtrs)
1022
        weak->dispose();
1023
14433
    m_weakPtrs.clear();
1024
14433
}
1025
1026
35
std::unique_ptr<DispatcherBase::WeakPtr> DispatcherBase::weakPtr()
1027
{
1028
35
    std::unique_ptr<DispatcherBase::WeakPtr> weak(new DispatcherBase::WeakPtr(this));
1029
35
    m_weakPtrs.insert(weak.get());
1030
35
    return weak;
1031
}
1032
1033
5205
UberDispatcher::UberDispatcher(FrontendChannel* frontendChannel)
1034
5205
    : m_frontendChannel(frontendChannel) { }
1035
1036
15620
void UberDispatcher::registerBackend(const String& name, std::unique_ptr<protocol::DispatcherBase> dispatcher)
1037
{
1038
15620
    m_dispatchers[name] = std::move(dispatcher);
1039
15621
}
1040
1041
15619
void UberDispatcher::setupRedirects(const std::unordered_map<String, String>& redirects)
1042
{
1043
15619
    for (const auto& pair : redirects)
1044
        m_redirects[pair.first] = pair.second;
1045
15620
}
1046
1047
15323
bool UberDispatcher::parseCommand(Value* parsedMessage, int* outCallId, String* outMethod) {
1048
15323
    if (!parsedMessage) {
1049
        reportProtocolErrorTo(m_frontendChannel, DispatchResponse::kParseError, "Message must be a valid JSON");
1050
        return false;
1051
    }
1052
15323
    protocol::DictionaryValue* messageObject = DictionaryValue::cast(parsedMessage);
1053
15323
    if (!messageObject) {
1054
        reportProtocolErrorTo(m_frontendChannel, DispatchResponse::kInvalidRequest, "Message must be an object");
1055
        return false;
1056
    }
1057
1058
15323
    int callId = 0;
1059
15323
    protocol::Value* callIdValue = messageObject->get("id");
1060

15323
    bool success = callIdValue && callIdValue->asInteger(&callId);
1061
15323
    if (!success) {
1062
        reportProtocolErrorTo(m_frontendChannel, DispatchResponse::kInvalidRequest, "Message must have integer 'id' property");
1063
        return false;
1064
    }
1065
15323
    if (outCallId)
1066
15323
      *outCallId = callId;
1067
1068
15323
    protocol::Value* methodValue = messageObject->get("method");
1069
15323
    String method;
1070

15323
    success = methodValue && methodValue->asString(&method);
1071
15323
    if (!success) {
1072
        reportProtocolErrorTo(m_frontendChannel, callId, DispatchResponse::kInvalidRequest, "Message must have string 'method' property", nullptr);
1073
        return false;
1074
    }
1075
15323
    if (outMethod)
1076
15323
      *outMethod = method;
1077
15323
    return true;
1078
}
1079
1080
35
protocol::DispatcherBase* UberDispatcher::findDispatcher(const String& method) {
1081
35
    size_t dotIndex = StringUtil::find(method, ".");
1082
35
    if (dotIndex == StringUtil::kNotFound)
1083
        return nullptr;
1084
35
    String domain = StringUtil::substring(method, 0, dotIndex);
1085
35
    auto it = m_dispatchers.find(domain);
1086
35
    if (it == m_dispatchers.end())
1087
        return nullptr;
1088
35
    if (!it->second->canDispatch(method))
1089
        return nullptr;
1090
35
    return it->second.get();
1091
}
1092
1093
bool UberDispatcher::canDispatch(const String& in_method)
1094
{
1095
    String method = in_method;
1096
    auto redirectIt = m_redirects.find(method);
1097
    if (redirectIt != m_redirects.end())
1098
        method = redirectIt->second;
1099
    return !!findDispatcher(method);
1100
}
1101
1102
35
void UberDispatcher::dispatch(int callId, const String& in_method, std::unique_ptr<Value> parsedMessage, const ProtocolMessage& rawMessage)
1103
{
1104
35
    String method = in_method;
1105
35
    auto redirectIt = m_redirects.find(method);
1106
35
    if (redirectIt != m_redirects.end())
1107
        method = redirectIt->second;
1108
35
    protocol::DispatcherBase* dispatcher = findDispatcher(method);
1109
35
    if (!dispatcher) {
1110
        reportProtocolErrorTo(m_frontendChannel, callId, DispatchResponse::kMethodNotFound, "'" + method + "' wasn't found", nullptr);
1111
35
        return;
1112
    }
1113
70
    std::unique_ptr<protocol::DictionaryValue> messageObject = DictionaryValue::cast(std::move(parsedMessage));
1114
70
    dispatcher->dispatch(callId, method, rawMessage, std::move(messageObject));
1115
}
1116
1117
UberDispatcher::~UberDispatcher() = default;
1118
1119
// static
1120
34
std::unique_ptr<InternalResponse> InternalResponse::createResponse(int callId, std::unique_ptr<Serializable> params)
1121
{
1122
34
    return std::unique_ptr<InternalResponse>(new InternalResponse(callId, String(), std::move(params)));
1123
}
1124
1125
// static
1126
183
std::unique_ptr<InternalResponse> InternalResponse::createNotification(const String& notification, std::unique_ptr<Serializable> params)
1127
{
1128
183
    return std::unique_ptr<InternalResponse>(new InternalResponse(0, notification, std::move(params)));
1129
}
1130
1131
217
String InternalResponse::serializeToJSON()
1132
{
1133
217
    std::unique_ptr<DictionaryValue> result = DictionaryValue::create();
1134

434
    std::unique_ptr<Serializable> params(m_params ? std::move(m_params) : DictionaryValue::create());
1135
217
    if (m_notification.length()) {
1136
183
        result->setString("method", m_notification);
1137
183
        result->setValue("params", SerializedValue::fromJSON(params->serializeToJSON()));
1138
    } else {
1139
34
        result->setInteger("id", m_callId);
1140
34
        result->setValue("result", SerializedValue::fromJSON(params->serializeToJSON()));
1141
    }
1142
434
    return result->serializeToJSON();
1143
}
1144
1145
std::vector<uint8_t> InternalResponse::serializeToBinary()
1146
{
1147
    std::unique_ptr<DictionaryValue> result = DictionaryValue::create();
1148
    std::unique_ptr<Serializable> params(m_params ? std::move(m_params) : DictionaryValue::create());
1149
    if (m_notification.length()) {
1150
        result->setString("method", m_notification);
1151
        result->setValue("params", SerializedValue::fromBinary(params->serializeToBinary()));
1152
    } else {
1153
        result->setInteger("id", m_callId);
1154
        result->setValue("result", SerializedValue::fromBinary(params->serializeToBinary()));
1155
    }
1156
    return result->serializeToBinary();
1157
}
1158
1159
217
InternalResponse::InternalResponse(int callId, const String& notification, std::unique_ptr<Serializable> params)
1160
    : m_callId(callId)
1161
    , m_notification(notification)
1162
217
    , m_params(params ? std::move(params) : nullptr)
1163
{
1164
217
}
1165
1166
} // namespace node
1167
} // namespace inspector
1168
} // namespace protocol
1169
1170
1171
// This file is generated by Parser_cpp.template.
1172
1173
// Copyright 2016 The Chromium Authors. All rights reserved.
1174
// Use of this source code is governed by a BSD-style license that can be
1175
// found in the LICENSE file.
1176
1177
namespace node {
1178
namespace inspector {
1179
namespace protocol {
1180
1181
namespace {
1182
1183
const int stackLimit = 1000;
1184
1185
enum Token {
1186
    ObjectBegin,
1187
    ObjectEnd,
1188
    ArrayBegin,
1189
    ArrayEnd,
1190
    StringLiteral,
1191
    Number,
1192
    BoolTrue,
1193
    BoolFalse,
1194
    NullToken,
1195
    ListSeparator,
1196
    ObjectPairSeparator,
1197
    InvalidToken,
1198
};
1199
1200
const char* const nullString = "null";
1201
const char* const trueString = "true";
1202
const char* const falseString = "false";
1203
1204
368907
bool isASCII(uint16_t c)
1205
{
1206
368907
    return !(c & ~0x7F);
1207
}
1208
1209
353424
bool isSpaceOrNewLine(uint16_t c)
1210
{
1211


353424
    return isASCII(c) && c <= ' ' && (c == ' ' || (c <= 0xD && c >= 0x9));
1212
}
1213
1214
15387
double charactersToDouble(const uint16_t* characters, size_t length, bool* ok)
1215
{
1216
15387
    std::vector<char> buffer;
1217
15387
    buffer.reserve(length + 1);
1218
30871
    for (size_t i = 0; i < length; ++i) {
1219
15484
        if (!isASCII(characters[i])) {
1220
            *ok = false;
1221
            return 0;
1222
        }
1223
15484
        buffer.push_back(static_cast<char>(characters[i]));
1224
    }
1225
15387
    buffer.push_back('\0');
1226
15388
    return StringUtil::toDouble(buffer.data(), length, ok);
1227
}
1228
1229
double charactersToDouble(const uint8_t* characters, size_t length, bool* ok)
1230
{
1231
    std::string buffer(reinterpret_cast<const char*>(characters), length);
1232
    return StringUtil::toDouble(buffer.data(), length, ok);
1233
}
1234
1235
template<typename Char>
1236
9989
bool parseConstToken(const Char* start, const Char* end, const Char** tokenEnd, const char* token)
1237
{
1238




9989
    while (start < end && *token != '\0' && *start++ == *token++) { }
1239

9989
    if (*token != '\0')
1240
        return false;
1241
9989
    *tokenEnd = start;
1242
9989
    return true;
1243
}
1244
1245
template<typename Char>
1246
15387
bool readInt(const Char* start, const Char* end, const Char** tokenEnd, bool canHaveLeadingZeros)
1247
{
1248

15387
    if (start == end)
1249
        return false;
1250
15387
    bool haveLeadingZero = '0' == *start;
1251
15387
    int length = 0;
1252



46257
    while (start < end && '0' <= *start && *start <= '9') {
1253
15483
        ++start;
1254
15483
        ++length;
1255
    }
1256

15387
    if (!length)
1257
        return false;
1258



15387
    if (!canHaveLeadingZeros && length > 1 && haveLeadingZero)
1259
        return false;
1260
15387
    *tokenEnd = start;
1261
15387
    return true;
1262
}
1263
1264
template<typename Char>
1265
15387
bool parseNumberToken(const Char* start, const Char* end, const Char** tokenEnd)
1266
{
1267
    // We just grab the number here. We validate the size in DecodeNumber.
1268
    // According to RFC4627, a valid number is: [minus] int [frac] [exp]
1269

15387
    if (start == end)
1270
        return false;
1271
15387
    Char c = *start;
1272

15387
    if ('-' == c)
1273
        ++start;
1274
1275

15387
    if (!readInt(start, end, &start, false))
1276
        return false;
1277

15387
    if (start == end) {
1278
        *tokenEnd = start;
1279
        return true;
1280
    }
1281
1282
    // Optional fraction part
1283
15387
    c = *start;
1284

15387
    if ('.' == c) {
1285
        ++start;
1286
        if (!readInt(start, end, &start, true))
1287
            return false;
1288
        if (start == end) {
1289
            *tokenEnd = start;
1290
            return true;
1291
        }
1292
        c = *start;
1293
    }
1294
1295
    // Optional exponent part
1296


15387
    if ('e' == c || 'E' == c) {
1297
        ++start;
1298
        if (start == end)
1299
            return false;
1300
        c = *start;
1301
        if ('-' == c || '+' == c) {
1302
            ++start;
1303
            if (start == end)
1304
                return false;
1305
        }
1306
        if (!readInt(start, end, &start, true))
1307
            return false;
1308
    }
1309
1310
15387
    *tokenEnd = start;
1311
15387
    return true;
1312
}
1313
1314
template<typename Char>
1315
bool readHexDigits(const Char* start, const Char* end, const Char** tokenEnd, int digits)
1316
{
1317
    if (end - start < digits)
1318
        return false;
1319
    for (int i = 0; i < digits; ++i) {
1320
        Char c = *start++;
1321
        if (!(('0' <= c && c <= '9') || ('a' <= c && c <= 'f') || ('A' <= c && c <= 'F')))
1322
            return false;
1323
    }
1324
    *tokenEnd = start;
1325
    return true;
1326
}
1327
1328
template<typename Char>
1329
61331
bool parseStringToken(const Char* start, const Char* end, const Char** tokenEnd)
1330
{
1331

730133
    while (start < end) {
1332
668802
        Char c = *start++;
1333

668802
        if ('\\' == c) {
1334

208
	    if (start == end)
1335
	        return false;
1336
208
            c = *start++;
1337
            // Make sure the escaped char is valid.
1338


208
            switch (c) {
1339
            case 'x':
1340
                if (!readHexDigits(start, end, &start, 2))
1341
                    return false;
1342
                break;
1343
            case 'u':
1344
                if (!readHexDigits(start, end, &start, 4))
1345
                    return false;
1346
                break;
1347
            case '\\':
1348
            case '/':
1349
            case 'b':
1350
            case 'f':
1351
            case 'n':
1352
            case 'r':
1353
            case 't':
1354
            case 'v':
1355
            case '"':
1356
208
                break;
1357
            default:
1358
                return false;
1359
            }
1360

668594
        } else if ('"' == c) {
1361
61331
            *tokenEnd = start;
1362
61331
            return true;
1363
        }
1364
    }
1365
    return false;
1366
}
1367
1368
template<typename Char>
1369
bool skipComment(const Char* start, const Char* end, const Char** commentEnd)
1370
{
1371
    if (start == end)
1372
        return false;
1373
1374
    if (*start != '/' || start + 1 >= end)
1375
        return false;
1376
    ++start;
1377
1378
    if (*start == '/') {
1379
        // Single line comment, read to newline.
1380
        for (++start; start < end; ++start) {
1381
            if (*start == '\n' || *start == '\r') {
1382
                *commentEnd = start + 1;
1383
                return true;
1384
            }
1385
        }
1386
        *commentEnd = end;
1387
        // Comment reaches end-of-input, which is fine.
1388
        return true;
1389
    }
1390
1391
    if (*start == '*') {
1392
        Char previous = '\0';
1393
        // Block comment, read until end marker.
1394
        for (++start; start < end; previous = *start++) {
1395
            if (previous == '*' && *start == '/') {
1396
                *commentEnd = start + 1;
1397
                return true;
1398
            }
1399
        }
1400
        // Block comment must close before end-of-input.
1401
        return false;
1402
    }
1403
1404
    return false;
1405
}
1406
1407
template<typename Char>
1408
260185
void skipWhitespaceAndComments(const Char* start, const Char* end, const Char** whitespaceEnd)
1409
{
1410

628937
    while (start < end) {
1411

353423
        if (isSpaceOrNewLine(*start)) {
1412
108567
            ++start;
1413

244865
        } else if (*start == '/') {
1414
            const Char* commentEnd;
1415
            if (!skipComment(start, end, &commentEnd))
1416
                break;
1417
            start = commentEnd;
1418
        } else {
1419
244865
            break;
1420
        }
1421
    }
1422
260194
    *whitespaceEnd = start;
1423
260194
}
1424
1425
template<typename Char>
1426
198955
Token parseToken(const Char* start, const Char* end, const Char** tokenStart, const Char** tokenEnd)
1427
{
1428
198955
    skipWhitespaceAndComments(start, end, tokenStart);
1429
198959
    start = *tokenStart;
1430
1431

198959
    if (start == end)
1432
        return InvalidToken;
1433
1434






198959
    switch (*start) {
1435
    case 'n':
1436

1
        if (parseConstToken(start, end, tokenEnd, nullString))
1437
1
            return NullToken;
1438
        break;
1439
    case 't':
1440

9953
        if (parseConstToken(start, end, tokenEnd, trueString))
1441
9954
            return BoolTrue;
1442
        break;
1443
    case 'f':
1444

34
        if (parseConstToken(start, end, tokenEnd, falseString))
1445
34
            return BoolFalse;
1446
        break;
1447
    case '[':
1448
12
        *tokenEnd = start + 1;
1449
12
        return ArrayBegin;
1450
    case ']':
1451
12
        *tokenEnd = start + 1;
1452
12
        return ArrayEnd;
1453
    case ',':
1454
25483
        *tokenEnd = start + 1;
1455
25483
        return ListSeparator;
1456
    case '{':
1457
20420
        *tokenEnd = start + 1;
1458
20420
        return ObjectBegin;
1459
    case '}':
1460
20422
        *tokenEnd = start + 1;
1461
20422
        return ObjectEnd;
1462
    case ':':
1463
45904
        *tokenEnd = start + 1;
1464
45904
        return ObjectPairSeparator;
1465
    case '0':
1466
    case '1':
1467
    case '2':
1468
    case '3':
1469
    case '4':
1470
    case '5':
1471
    case '6':
1472
    case '7':
1473
    case '8':
1474
    case '9':
1475
    case '-':
1476

15387
        if (parseNumberToken(start, end, tokenEnd))
1477
15386
            return Number;
1478
        break;
1479
    case '"':
1480

61331
        if (parseStringToken(start + 1, end, tokenEnd))
1481
61331
            return StringLiteral;
1482
        break;
1483
    }
1484
    return InvalidToken;
1485
}
1486
1487
template<typename Char>
1488
int hexToInt(Char c)
1489
{
1490
    if ('0' <= c && c <= '9')
1491
        return c - '0';
1492
    if ('A' <= c && c <= 'F')
1493
        return c - 'A' + 10;
1494
    if ('a' <= c && c <= 'f')
1495
        return c - 'a' + 10;
1496
    DCHECK(false);
1497
    return 0;
1498
}
1499
1500
template<typename Char>
1501
61321
bool decodeString(const Char* start, const Char* end, StringBuilder* output)
1502
{
1503

730059
    while (start < end) {
1504
607418
        uint16_t c = *start++;
1505

607418
        if ('\\' != c) {
1506
607210
            StringUtil::builderAppend(*output, c);
1507
607210
            continue;
1508
        }
1509

208
	if (start == end)
1510
	    return false;
1511
208
        c = *start++;
1512
1513

208
        if (c == 'x') {
1514
            // \x is not supported.
1515
            return false;
1516
        }
1517
1518




208
        switch (c) {
1519
        case '"':
1520
        case '/':
1521
        case '\\':
1522
194
            break;
1523
        case 'b':
1524
            c = '\b';
1525
            break;
1526
        case 'f':
1527
            c = '\f';
1528
            break;
1529
        case 'n':
1530
14
            c = '\n';
1531
14
            break;
1532
        case 'r':
1533
            c = '\r';
1534
            break;
1535
        case 't':
1536
            c = '\t';
1537
            break;
1538
        case 'v':
1539
            c = '\v';
1540
            break;
1541
        case 'u':
1542
            c = (hexToInt(*start) << 12) +
1543
                (hexToInt(*(start + 1)) << 8) +
1544
                (hexToInt(*(start + 2)) << 4) +
1545
                hexToInt(*(start + 3));
1546
            start += 4;
1547
            break;
1548
        default:
1549
            return false;
1550
        }
1551
208
        StringUtil::builderAppend(*output, c);
1552
    }
1553
61320
    return true;
1554
}
1555
1556
template<typename Char>
1557
61327
bool decodeString(const Char* start, const Char* end, String* output)
1558
{
1559

61327
    if (start == end) {
1560
6
        *output = "";
1561
6
        return true;
1562
    }
1563

61321
    if (start > end)
1564
        return false;
1565
61321
    StringBuilder buffer;
1566
61320
    StringUtil::builderReserve(buffer, end - start);
1567

61321
    if (!decodeString(start, end, &buffer))
1568
        return false;
1569
61320
    *output = StringUtil::builderToString(buffer);
1570
61320
    return true;
1571
}
1572
1573
template<typename Char>
1574
61232
std::unique_ptr<Value> buildValue(const Char* start, const Char* end, const Char** valueTokenEnd, int depth)
1575
{
1576

61232
    if (depth > stackLimit)
1577
        return nullptr;
1578
1579
61232
    std::unique_ptr<Value> result;
1580
    const Char* tokenStart;
1581
    const Char* tokenEnd;
1582
61232
    Token token = parseToken(start, end, &tokenStart, &tokenEnd);
1583




61230
    switch (token) {
1584
    case InvalidToken:
1585
        return nullptr;
1586
    case NullToken:
1587
1
        result = Value::null();
1588
1
        break;
1589
    case BoolTrue:
1590
9954
        result = FundamentalValue::create(true);
1591
9954
        break;
1592
    case BoolFalse:
1593
34
        result = FundamentalValue::create(false);
1594
34
        break;
1595
    case Number: {
1596
        bool ok;
1597
15387
        double value = charactersToDouble(tokenStart, tokenEnd - tokenStart, &ok);
1598

15387
        if (!ok)
1599
            return nullptr;
1600



15387
        if (value >= INT_MIN && value <= INT_MAX && static_cast<int>(value) == value)
1601
15387
            result = FundamentalValue::create(static_cast<int>(value));
1602
        else
1603
            result = FundamentalValue::create(value);
1604
15387
        break;
1605
    }
1606
    case StringLiteral: {
1607
15422
        String value;
1608
15422
        bool ok = decodeString(tokenStart + 1, tokenEnd - 1, &value);
1609

15422
        if (!ok)
1610
            return nullptr;
1611
15422
        result = StringValue::create(value);
1612

15422
        break;
1613
    }
1614
    case ArrayBegin: {
1615
12
        std::unique_ptr<ListValue> array = ListValue::create();
1616
12
        start = tokenEnd;
1617
12
        token = parseToken(start, end, &tokenStart, &tokenEnd);
1618

5
        while (token != ArrayEnd) {
1619
5
            std::unique_ptr<Value> arrayNode = buildValue(start, end, &tokenEnd, depth + 1);
1620

5
            if (!arrayNode)
1621
                return nullptr;
1622
5
            array->pushValue(std::move(arrayNode));
1623
1624
            // After a list value, we expect a comma or the end of the list.
1625
5
            start = tokenEnd;
1626
5
            token = parseToken(start, end, &tokenStart, &tokenEnd);
1627

5
            if (token == ListSeparator) {
1628
                start = tokenEnd;
1629
                token = parseToken(start, end, &tokenStart, &tokenEnd);
1630
                if (token == ArrayEnd)
1631
                    return nullptr;
1632

5
            } else if (token != ArrayEnd) {
1633
                // Unexpected value after list value. Bail out.
1634
                return nullptr;
1635
            }
1636
        }
1637

12
        if (token != ArrayEnd)
1638
            return nullptr;
1639
12
        result = std::move(array);
1640

12
        break;
1641
    }
1642
    case ObjectBegin: {
1643
20420
        std::unique_ptr<DictionaryValue> object = DictionaryValue::create();
1644
20422
        start = tokenEnd;
1645
20422
        token = parseToken(start, end, &tokenStart, &tokenEnd);
1646

66326
        while (token != ObjectEnd) {
1647

45904
            if (token != StringLiteral)
1648
                return nullptr;
1649
45904
            String key;
1650

45904
            if (!decodeString(tokenStart + 1, tokenEnd - 1, &key))
1651
                return nullptr;
1652
45903
            start = tokenEnd;
1653
1654
45903
            token = parseToken(start, end, &tokenStart, &tokenEnd);
1655

45904
            if (token != ObjectPairSeparator)
1656
                return nullptr;
1657
45904
            start = tokenEnd;
1658
1659

91809
            std::unique_ptr<Value> value = buildValue(start, end, &tokenEnd, depth + 1);
1660

45904
            if (!value)
1661
                return nullptr;
1662
45904
            object->setValue(key, std::move(value));
1663
45904
            start = tokenEnd;
1664
1665
            // After a key/value pair, we expect a comma or the end of the
1666
            // object.
1667
45904
            token = parseToken(start, end, &tokenStart, &tokenEnd);
1668

45905
            if (token == ListSeparator) {
1669
25483
                start = tokenEnd;
1670
25483
                token = parseToken(start, end, &tokenStart, &tokenEnd);
1671

25483
                if (token == ObjectEnd)
1672
                    return nullptr;
1673

20422
            } else if (token != ObjectEnd) {
1674
                // Unexpected value after last object value. Bail out.
1675
                return nullptr;
1676
            }
1677
        }
1678

20422
        if (token != ObjectEnd)
1679
            return nullptr;
1680
20422
        result = std::move(object);
1681

20422
        break;
1682
    }
1683
1684
    default:
1685
        // We got a token that's not a value.
1686
        return nullptr;
1687
    }
1688
1689
61232
    skipWhitespaceAndComments(tokenEnd, end, valueTokenEnd);
1690
61232
    return result;
1691
}
1692
1693
template<typename Char>
1694
15321
std::unique_ptr<Value> parseJSONInternal(const Char* start, unsigned length)
1695
{
1696
15321
    const Char* end = start + length;
1697
    const Char *tokenEnd;
1698
15321
    std::unique_ptr<Value> value = buildValue(start, end, &tokenEnd, 0);
1699



15323
    if (!value || tokenEnd != end)
1700
        return nullptr;
1701
15323
    return value;
1702
}
1703
1704
} // anonymous namespace
1705
1706
15322
std::unique_ptr<Value> parseJSONCharacters(const uint16_t* characters, unsigned length)
1707
{
1708
15322
    return parseJSONInternal<uint16_t>(characters, length);
1709
}
1710
1711
std::unique_ptr<Value> parseJSONCharacters(const uint8_t* characters, unsigned length)
1712
{
1713
    return parseJSONInternal<uint8_t>(characters, length);
1714
}
1715
1716
} // namespace node
1717
} // namespace inspector
1718
} // namespace protocol
1719
1720
1721
// Generated by lib/encoding_cpp.template.
1722
1723
// Copyright 2019 The Chromium Authors. All rights reserved.
1724
// Use of this source code is governed by a BSD-style license that can be
1725
// found in the LICENSE file.
1726
1727
1728
#include <algorithm>
1729
#include <cassert>
1730
#include <cmath>
1731
#include <cstring>
1732
#include <limits>
1733
#include <stack>
1734
1735
namespace node {
1736
namespace inspector {
1737
namespace protocol {
1738
1739
// ===== encoding/encoding.cc =====
1740
1741
// =============================================================================
1742
// Status and Error codes
1743
// =============================================================================
1744
1745
std::string Status::ToASCIIString() const {
1746
  switch (error) {
1747
    case Error::OK:
1748
      return "OK";
1749
    case Error::JSON_PARSER_UNPROCESSED_INPUT_REMAINS:
1750
      return ToASCIIString("JSON: unprocessed input remains");
1751
    case Error::JSON_PARSER_STACK_LIMIT_EXCEEDED:
1752
      return ToASCIIString("JSON: stack limit exceeded");
1753
    case Error::JSON_PARSER_NO_INPUT:
1754
      return ToASCIIString("JSON: no input");
1755
    case Error::JSON_PARSER_INVALID_TOKEN:
1756
      return ToASCIIString("JSON: invalid token");
1757
    case Error::JSON_PARSER_INVALID_NUMBER:
1758
      return ToASCIIString("JSON: invalid number");
1759
    case Error::JSON_PARSER_INVALID_STRING:
1760
      return ToASCIIString("JSON: invalid string");
1761
    case Error::JSON_PARSER_UNEXPECTED_ARRAY_END:
1762
      return ToASCIIString("JSON: unexpected array end");
1763
    case Error::JSON_PARSER_COMMA_OR_ARRAY_END_EXPECTED:
1764
      return ToASCIIString("JSON: comma or array end expected");
1765
    case Error::JSON_PARSER_STRING_LITERAL_EXPECTED:
1766
      return ToASCIIString("JSON: string literal expected");
1767
    case Error::JSON_PARSER_COLON_EXPECTED:
1768
      return ToASCIIString("JSON: colon expected");
1769
    case Error::JSON_PARSER_UNEXPECTED_MAP_END:
1770
      return ToASCIIString("JSON: unexpected map end");
1771
    case Error::JSON_PARSER_COMMA_OR_MAP_END_EXPECTED:
1772
      return ToASCIIString("JSON: comma or map end expected");
1773
    case Error::JSON_PARSER_VALUE_EXPECTED:
1774
      return ToASCIIString("JSON: value expected");
1775
1776
    case Error::CBOR_INVALID_INT32:
1777
      return ToASCIIString("CBOR: invalid int32");
1778
    case Error::CBOR_INVALID_DOUBLE:
1779
      return ToASCIIString("CBOR: invalid double");
1780
    case Error::CBOR_INVALID_ENVELOPE:
1781
      return ToASCIIString("CBOR: invalid envelope");
1782
    case Error::CBOR_INVALID_STRING8:
1783
      return ToASCIIString("CBOR: invalid string8");
1784
    case Error::CBOR_INVALID_STRING16:
1785
      return ToASCIIString("CBOR: invalid string16");
1786
    case Error::CBOR_INVALID_BINARY:
1787
      return ToASCIIString("CBOR: invalid binary");
1788
    case Error::CBOR_UNSUPPORTED_VALUE:
1789
      return ToASCIIString("CBOR: unsupported value");
1790
    case Error::CBOR_NO_INPUT:
1791
      return ToASCIIString("CBOR: no input");
1792
    case Error::CBOR_INVALID_START_BYTE:
1793
      return ToASCIIString("CBOR: invalid start byte");
1794
    case Error::CBOR_UNEXPECTED_EOF_EXPECTED_VALUE:
1795
      return ToASCIIString("CBOR: unexpected eof expected value");
1796
    case Error::CBOR_UNEXPECTED_EOF_IN_ARRAY:
1797
      return ToASCIIString("CBOR: unexpected eof in array");
1798
    case Error::CBOR_UNEXPECTED_EOF_IN_MAP:
1799
      return ToASCIIString("CBOR: unexpected eof in map");
1800
    case Error::CBOR_INVALID_MAP_KEY:
1801
      return ToASCIIString("CBOR: invalid map key");
1802
    case Error::CBOR_STACK_LIMIT_EXCEEDED:
1803
      return ToASCIIString("CBOR: stack limit exceeded");
1804
    case Error::CBOR_TRAILING_JUNK:
1805
      return ToASCIIString("CBOR: trailing junk");
1806
    case Error::CBOR_MAP_START_EXPECTED:
1807
      return ToASCIIString("CBOR: map start expected");
1808
    case Error::CBOR_MAP_STOP_EXPECTED:
1809
      return ToASCIIString("CBOR: map stop expected");
1810
    case Error::CBOR_ENVELOPE_SIZE_LIMIT_EXCEEDED:
1811
      return ToASCIIString("CBOR: envelope size limit exceeded");
1812
  }
1813
  // Some compilers can't figure out that we can't get here.
1814
  return "INVALID ERROR CODE";
1815
}
1816
1817
std::string Status::ToASCIIString(const char* msg) const {
1818
  return std::string(msg) + " at position " + std::to_string(pos);
1819
}
1820
1821
namespace cbor {
1822
namespace {
1823
// Indicates the number of bits the "initial byte" needs to be shifted to the
1824
// right after applying |kMajorTypeMask| to produce the major type in the
1825
// lowermost bits.
1826
static constexpr uint8_t kMajorTypeBitShift = 5u;
1827
// Mask selecting the low-order 5 bits of the "initial byte", which is where
1828
// the additional information is encoded.
1829
static constexpr uint8_t kAdditionalInformationMask = 0x1f;
1830
// Mask selecting the high-order 3 bits of the "initial byte", which indicates
1831
// the major type of the encoded value.
1832
static constexpr uint8_t kMajorTypeMask = 0xe0;
1833
// Indicates the integer is in the following byte.
1834
static constexpr uint8_t kAdditionalInformation1Byte = 24u;
1835
// Indicates the integer is in the next 2 bytes.
1836
static constexpr uint8_t kAdditionalInformation2Bytes = 25u;
1837
// Indicates the integer is in the next 4 bytes.
1838
static constexpr uint8_t kAdditionalInformation4Bytes = 26u;
1839
// Indicates the integer is in the next 8 bytes.
1840
static constexpr uint8_t kAdditionalInformation8Bytes = 27u;
1841
1842
// Encodes the initial byte, consisting of the |type| in the first 3 bits
1843
// followed by 5 bits of |additional_info|.
1844
constexpr uint8_t EncodeInitialByte(MajorType type, uint8_t additional_info) {
1845
  return (static_cast<uint8_t>(type) << kMajorTypeBitShift) |
1846
         (additional_info & kAdditionalInformationMask);
1847
}
1848
1849
// TAG 24 indicates that what follows is a byte string which is
1850
// encoded in CBOR format. We use this as a wrapper for
1851
// maps and arrays, allowing us to skip them, because the
1852
// byte string carries its size (byte length).
1853
// https://tools.ietf.org/html/rfc7049#section-2.4.4.1
1854
static constexpr uint8_t kInitialByteForEnvelope =
1855
    EncodeInitialByte(MajorType::TAG, 24);
1856
// The initial byte for a byte string with at most 2^32 bytes
1857
// of payload. This is used for envelope encoding, even if
1858
// the byte string is shorter.
1859
static constexpr uint8_t kInitialByteFor32BitLengthByteString =
1860
    EncodeInitialByte(MajorType::BYTE_STRING, 26);
1861
1862
// See RFC 7049 Section 2.2.1, indefinite length arrays / maps have additional
1863
// info = 31.
1864
static constexpr uint8_t kInitialByteIndefiniteLengthArray =
1865
    EncodeInitialByte(MajorType::ARRAY, 31);
1866
static constexpr uint8_t kInitialByteIndefiniteLengthMap =
1867
    EncodeInitialByte(MajorType::MAP, 31);
1868
// See RFC 7049 Section 2.3, Table 1; this is used for finishing indefinite
1869
// length maps / arrays.
1870
static constexpr uint8_t kStopByte =
1871
    EncodeInitialByte(MajorType::SIMPLE_VALUE, 31);
1872
1873
// See RFC 7049 Section 2.3, Table 2.
1874
static constexpr uint8_t kEncodedTrue =
1875
    EncodeInitialByte(MajorType::SIMPLE_VALUE, 21);
1876
static constexpr uint8_t kEncodedFalse =
1877
    EncodeInitialByte(MajorType::SIMPLE_VALUE, 20);
1878
static constexpr uint8_t kEncodedNull =
1879
    EncodeInitialByte(MajorType::SIMPLE_VALUE, 22);
1880
static constexpr uint8_t kInitialByteForDouble =
1881
    EncodeInitialByte(MajorType::SIMPLE_VALUE, 27);
1882
1883
// See RFC 7049 Table 3 and Section 2.4.4.2. This is used as a prefix for
1884
// arbitrary binary data encoded as BYTE_STRING.
1885
static constexpr uint8_t kExpectedConversionToBase64Tag =
1886
    EncodeInitialByte(MajorType::TAG, 22);
1887
1888
// Writes the bytes for |v| to |out|, starting with the most significant byte.
1889
// See also: https://commandcenter.blogspot.com/2012/04/byte-order-fallacy.html
1890
template <typename T, class C>
1891
void WriteBytesMostSignificantByteFirst(T v, C* out) {
1892
  for (int shift_bytes = sizeof(T) - 1; shift_bytes >= 0; --shift_bytes)
1893
    out->push_back(0xff & (v >> (shift_bytes * 8)));
1894
}
1895
1896
// Extracts sizeof(T) bytes from |in| to extract a value of type T
1897
// (e.g. uint64_t, uint32_t, ...), most significant byte first.
1898
// See also: https://commandcenter.blogspot.com/2012/04/byte-order-fallacy.html
1899
template <typename T>
1900
T ReadBytesMostSignificantByteFirst(span<uint8_t> in) {
1901
  assert(in.size() >= sizeof(T));
1902
  T result = 0;
1903
  for (size_t shift_bytes = 0; shift_bytes < sizeof(T); ++shift_bytes)
1904
    result |= T(in[sizeof(T) - 1 - shift_bytes]) << (shift_bytes * 8);
1905
  return result;
1906
}
1907
}  // namespace
1908
1909
namespace internals {
1910
// Reads the start of a token with definitive size from |bytes|.
1911
// |type| is the major type as specified in RFC 7049 Section 2.1.
1912
// |value| is the payload (e.g. for MajorType::UNSIGNED) or is the size
1913
// (e.g. for BYTE_STRING).
1914
// If successful, returns the number of bytes read. Otherwise returns -1.
1915
// TODO(johannes): change return type to size_t and use 0 for error.
1916
int8_t ReadTokenStart(span<uint8_t> bytes, MajorType* type, uint64_t* value) {
1917
  if (bytes.empty())
1918
    return -1;
1919
  uint8_t initial_byte = bytes[0];
1920
  *type = MajorType((initial_byte & kMajorTypeMask) >> kMajorTypeBitShift);
1921
1922
  uint8_t additional_information = initial_byte & kAdditionalInformationMask;
1923
  if (additional_information < 24) {
1924
    // Values 0-23 are encoded directly into the additional info of the
1925
    // initial byte.
1926
    *value = additional_information;
1927
    return 1;
1928
  }
1929
  if (additional_information == kAdditionalInformation1Byte) {
1930
    // Values 24-255 are encoded with one initial byte, followed by the value.
1931
    if (bytes.size() < 2)
1932
      return -1;
1933
    *value = ReadBytesMostSignificantByteFirst<uint8_t>(bytes.subspan(1));
1934
    return 2;
1935
  }
1936
  if (additional_information == kAdditionalInformation2Bytes) {
1937
    // Values 256-65535: 1 initial byte + 2 bytes payload.
1938
    if (bytes.size() < 1 + sizeof(uint16_t))
1939
      return -1;
1940
    *value = ReadBytesMostSignificantByteFirst<uint16_t>(bytes.subspan(1));
1941
    return 3;
1942
  }
1943
  if (additional_information == kAdditionalInformation4Bytes) {
1944
    // 32 bit uint: 1 initial byte + 4 bytes payload.
1945
    if (bytes.size() < 1 + sizeof(uint32_t))
1946
      return -1;
1947
    *value = ReadBytesMostSignificantByteFirst<uint32_t>(bytes.subspan(1));
1948
    return 5;
1949
  }
1950
  if (additional_information == kAdditionalInformation8Bytes) {
1951
    // 64 bit uint: 1 initial byte + 8 bytes payload.
1952
    if (bytes.size() < 1 + sizeof(uint64_t))
1953
      return -1;
1954
    *value = ReadBytesMostSignificantByteFirst<uint64_t>(bytes.subspan(1));
1955
    return 9;
1956
  }
1957
  return -1;
1958
}
1959
1960
// Writes the start of a token with |type|. The |value| may indicate the size,
1961
// or it may be the payload if the value is an unsigned integer.
1962
template <typename C>
1963
void WriteTokenStartTmpl(MajorType type, uint64_t value, C* encoded) {
1964
  if (value < 24) {
1965
    // Values 0-23 are encoded directly into the additional info of the
1966
    // initial byte.
1967
    encoded->push_back(EncodeInitialByte(type, /*additional_info=*/value));
1968
    return;
1969
  }
1970
  if (value <= std::numeric_limits<uint8_t>::max()) {
1971
    // Values 24-255 are encoded with one initial byte, followed by the value.
1972
    encoded->push_back(EncodeInitialByte(type, kAdditionalInformation1Byte));
1973
    encoded->push_back(value);
1974
    return;
1975
  }
1976
  if (value <= std::numeric_limits<uint16_t>::max()) {
1977
    // Values 256-65535: 1 initial byte + 2 bytes payload.
1978
    encoded->push_back(EncodeInitialByte(type, kAdditionalInformation2Bytes));
1979
    WriteBytesMostSignificantByteFirst<uint16_t>(value, encoded);
1980
    return;
1981
  }
1982
  if (value <= std::numeric_limits<uint32_t>::max()) {
1983
    // 32 bit uint: 1 initial byte + 4 bytes payload.
1984
    encoded->push_back(EncodeInitialByte(type, kAdditionalInformation4Bytes));
1985
    WriteBytesMostSignificantByteFirst<uint32_t>(static_cast<uint32_t>(value),
1986
                                                 encoded);
1987
    return;
1988
  }
1989
  // 64 bit uint: 1 initial byte + 8 bytes payload.
1990
  encoded->push_back(EncodeInitialByte(type, kAdditionalInformation8Bytes));
1991
  WriteBytesMostSignificantByteFirst<uint64_t>(value, encoded);
1992
}
1993
void WriteTokenStart(MajorType type,
1994
                     uint64_t value,
1995
                     std::vector<uint8_t>* encoded) {
1996
  WriteTokenStartTmpl(type, value, encoded);
1997
}
1998
void WriteTokenStart(MajorType type, uint64_t value, std::string* encoded) {
1999
  WriteTokenStartTmpl(type, value, encoded);
2000
}
2001
}  // namespace internals
2002
2003
// =============================================================================
2004
// Detecting CBOR content
2005
// =============================================================================
2006
2007
uint8_t InitialByteForEnvelope() {
2008
  return kInitialByteForEnvelope;
2009
}
2010
uint8_t InitialByteFor32BitLengthByteString() {
2011
  return kInitialByteFor32BitLengthByteString;
2012
}
2013
bool IsCBORMessage(span<uint8_t> msg) {
2014
  return msg.size() >= 6 && msg[0] == InitialByteForEnvelope() &&
2015
         msg[1] == InitialByteFor32BitLengthByteString();
2016
}
2017
2018
// =============================================================================
2019
// Encoding invidiual CBOR items
2020
// =============================================================================
2021
2022
uint8_t EncodeTrue() {
2023
  return kEncodedTrue;
2024
}
2025
uint8_t EncodeFalse() {
2026
  return kEncodedFalse;
2027
}
2028
uint8_t EncodeNull() {
2029
  return kEncodedNull;
2030
}
2031
2032
uint8_t EncodeIndefiniteLengthArrayStart() {
2033
  return kInitialByteIndefiniteLengthArray;
2034
}
2035
2036
uint8_t EncodeIndefiniteLengthMapStart() {
2037
  return kInitialByteIndefiniteLengthMap;
2038
}
2039
2040
uint8_t EncodeStop() {
2041
  return kStopByte;
2042
}
2043
2044
template <typename C>
2045
void EncodeInt32Tmpl(int32_t value, C* out) {
2046
  if (value >= 0) {
2047
    internals::WriteTokenStart(MajorType::UNSIGNED, value, out);
2048
  } else {
2049
    uint64_t representation = static_cast<uint64_t>(-(value + 1));
2050
    internals::WriteTokenStart(MajorType::NEGATIVE, representation, out);
2051
  }
2052
}
2053
void EncodeInt32(int32_t value, std::vector<uint8_t>* out) {
2054
  EncodeInt32Tmpl(value, out);
2055
}
2056
void EncodeInt32(int32_t value, std::string* out) {
2057
  EncodeInt32Tmpl(value, out);
2058
}
2059
2060
template <typename C>
2061
void EncodeString16Tmpl(span<uint16_t> in, C* out) {
2062
  uint64_t byte_length = static_cast<uint64_t>(in.size_bytes());
2063
  internals::WriteTokenStart(MajorType::BYTE_STRING, byte_length, out);
2064
  // When emitting UTF16 characters, we always write the least significant byte
2065
  // first; this is because it's the native representation for X86.
2066
  // TODO(johannes): Implement a more efficient thing here later, e.g.
2067
  // casting *iff* the machine has this byte order.
2068
  // The wire format for UTF16 chars will probably remain the same
2069
  // (least significant byte first) since this way we can have
2070
  // golden files, unittests, etc. that port easily and universally.
2071
  // See also:
2072
  // https://commandcenter.blogspot.com/2012/04/byte-order-fallacy.html
2073
  for (const uint16_t two_bytes : in) {
2074
    out->push_back(two_bytes);
2075
    out->push_back(two_bytes >> 8);
2076
  }
2077
}
2078
void EncodeString16(span<uint16_t> in, std::vector<uint8_t>* out) {
2079
  EncodeString16Tmpl(in, out);
2080
}
2081
void EncodeString16(span<uint16_t> in, std::string* out) {
2082
  EncodeString16Tmpl(in, out);
2083
}
2084
2085
template <typename C>
2086
void EncodeString8Tmpl(span<uint8_t> in, C* out) {
2087
  internals::WriteTokenStart(MajorType::STRING,
2088
                             static_cast<uint64_t>(in.size_bytes()), out);
2089
  out->insert(out->end(), in.begin(), in.end());
2090
}
2091
void EncodeString8(span<uint8_t> in, std::vector<uint8_t>* out) {
2092
  EncodeString8Tmpl(in, out);
2093
}
2094
void EncodeString8(span<uint8_t> in, std::string* out) {
2095
  EncodeString8Tmpl(in, out);
2096
}
2097
2098
template <typename C>
2099
void EncodeFromLatin1Tmpl(span<uint8_t> latin1, C* out) {
2100
  for (size_t ii = 0; ii < latin1.size(); ++ii) {
2101
    if (latin1[ii] <= 127)
2102
      continue;
2103
    // If there's at least one non-ASCII char, convert to UTF8.
2104
    std::vector<uint8_t> utf8(latin1.begin(), latin1.begin() + ii);
2105
    for (; ii < latin1.size(); ++ii) {
2106
      if (latin1[ii] <= 127) {
2107
        utf8.push_back(latin1[ii]);
2108
      } else {
2109
        // 0xC0 means it's a UTF8 sequence with 2 bytes.
2110
        utf8.push_back((latin1[ii] >> 6) | 0xc0);
2111
        utf8.push_back((latin1[ii] | 0x80) & 0xbf);
2112
      }
2113
    }
2114
    EncodeString8(SpanFrom(utf8), out);
2115
    return;
2116
  }
2117
  EncodeString8(latin1, out);
2118
}
2119
void EncodeFromLatin1(span<uint8_t> latin1, std::vector<uint8_t>* out) {
2120
  EncodeFromLatin1Tmpl(latin1, out);
2121
}
2122
void EncodeFromLatin1(span<uint8_t> latin1, std::string* out) {
2123
  EncodeFromLatin1Tmpl(latin1, out);
2124
}
2125
2126
template <typename C>
2127
void EncodeFromUTF16Tmpl(span<uint16_t> utf16, C* out) {
2128
  // If there's at least one non-ASCII char, encode as STRING16 (UTF16).
2129
  for (uint16_t ch : utf16) {
2130
    if (ch <= 127)
2131
      continue;
2132
    EncodeString16(utf16, out);
2133
    return;
2134
  }
2135
  // It's all US-ASCII, strip out every second byte and encode as UTF8.
2136
  internals::WriteTokenStart(MajorType::STRING,
2137
                             static_cast<uint64_t>(utf16.size()), out);
2138
  out->insert(out->end(), utf16.begin(), utf16.end());
2139
}
2140
void EncodeFromUTF16(span<uint16_t> utf16, std::vector<uint8_t>* out) {
2141
  EncodeFromUTF16Tmpl(utf16, out);
2142
}
2143
void EncodeFromUTF16(span<uint16_t> utf16, std::string* out) {
2144
  EncodeFromUTF16Tmpl(utf16, out);
2145
}
2146
2147
template <typename C>
2148
void EncodeBinaryTmpl(span<uint8_t> in, C* out) {
2149
  out->push_back(kExpectedConversionToBase64Tag);
2150
  uint64_t byte_length = static_cast<uint64_t>(in.size_bytes());
2151
  internals::WriteTokenStart(MajorType::BYTE_STRING, byte_length, out);
2152
  out->insert(out->end(), in.begin(), in.end());
2153
}
2154
void EncodeBinary(span<uint8_t> in, std::vector<uint8_t>* out) {
2155
  EncodeBinaryTmpl(in, out);
2156
}
2157
void EncodeBinary(span<uint8_t> in, std::string* out) {
2158
  EncodeBinaryTmpl(in, out);
2159
}
2160
2161
// A double is encoded with a specific initial byte
2162
// (kInitialByteForDouble) plus the 64 bits of payload for its value.
2163
constexpr size_t kEncodedDoubleSize = 1 + sizeof(uint64_t);
2164
2165
// An envelope is encoded with a specific initial byte
2166
// (kInitialByteForEnvelope), plus the start byte for a BYTE_STRING with a 32
2167
// bit wide length, plus a 32 bit length for that string.
2168
constexpr size_t kEncodedEnvelopeHeaderSize = 1 + 1 + sizeof(uint32_t);
2169
2170
template <typename C>
2171
void EncodeDoubleTmpl(double value, C* out) {
2172
  // The additional_info=27 indicates 64 bits for the double follow.
2173
  // See RFC 7049 Section 2.3, Table 1.
2174
  out->push_back(kInitialByteForDouble);
2175
  union {
2176
    double from_double;
2177
    uint64_t to_uint64;
2178
  } reinterpret;
2179
  reinterpret.from_double = value;
2180
  WriteBytesMostSignificantByteFirst<uint64_t>(reinterpret.to_uint64, out);
2181
}
2182
void EncodeDouble(double value, std::vector<uint8_t>* out) {
2183
  EncodeDoubleTmpl(value, out);
2184
}
2185
void EncodeDouble(double value, std::string* out) {
2186
  EncodeDoubleTmpl(value, out);
2187
}
2188
2189
// =============================================================================
2190
// cbor::EnvelopeEncoder - for wrapping submessages
2191
// =============================================================================
2192
2193
template <typename C>
2194
void EncodeStartTmpl(C* out, size_t* byte_size_pos) {
2195
  assert(*byte_size_pos == 0);
2196
  out->push_back(kInitialByteForEnvelope);
2197
  out->push_back(kInitialByteFor32BitLengthByteString);
2198
  *byte_size_pos = out->size();
2199
  out->resize(out->size() + sizeof(uint32_t));
2200
}
2201
2202
void EnvelopeEncoder::EncodeStart(std::vector<uint8_t>* out) {
2203
  EncodeStartTmpl<std::vector<uint8_t>>(out, &byte_size_pos_);
2204
}
2205
2206
void EnvelopeEncoder::EncodeStart(std::string* out) {
2207
  EncodeStartTmpl<std::string>(out, &byte_size_pos_);
2208
}
2209
2210
template <typename C>
2211
bool EncodeStopTmpl(C* out, size_t* byte_size_pos) {
2212
  assert(*byte_size_pos != 0);
2213
  // The byte size is the size of the payload, that is, all the
2214
  // bytes that were written past the byte size position itself.
2215
  uint64_t byte_size = out->size() - (*byte_size_pos + sizeof(uint32_t));
2216
  // We store exactly 4 bytes, so at most INT32MAX, with most significant
2217
  // byte first.
2218
  if (byte_size > std::numeric_limits<uint32_t>::max())
2219
    return false;
2220
  for (int shift_bytes = sizeof(uint32_t) - 1; shift_bytes >= 0;
2221
       --shift_bytes) {
2222
    (*out)[(*byte_size_pos)++] = 0xff & (byte_size >> (shift_bytes * 8));
2223
  }
2224
  return true;
2225
}
2226
2227
bool EnvelopeEncoder::EncodeStop(std::vector<uint8_t>* out) {
2228
  return EncodeStopTmpl(out, &byte_size_pos_);
2229
}
2230
2231
bool EnvelopeEncoder::EncodeStop(std::string* out) {
2232
  return EncodeStopTmpl(out, &byte_size_pos_);
2233
}
2234
2235
// =============================================================================
2236
// cbor::NewCBOREncoder - for encoding from a streaming parser
2237
// =============================================================================
2238
2239
namespace {
2240
template <typename C>
2241
class CBOREncoder : public StreamingParserHandler {
2242
 public:
2243
  CBOREncoder(C* out, Status* status) : out_(out), status_(status) {
2244
    *status_ = Status();
2245
  }
2246
2247
  void HandleMapBegin() override {
2248
    if (!status_->ok())
2249
      return;
2250
    envelopes_.emplace_back();
2251
    envelopes_.back().EncodeStart(out_);
2252
    out_->push_back(kInitialByteIndefiniteLengthMap);
2253
  }
2254
2255
  void HandleMapEnd() override {
2256
    if (!status_->ok())
2257
      return;
2258
    out_->push_back(kStopByte);
2259
    assert(!envelopes_.empty());
2260
    if (!envelopes_.back().EncodeStop(out_)) {
2261
      HandleError(
2262
          Status(Error::CBOR_ENVELOPE_SIZE_LIMIT_EXCEEDED, out_->size()));
2263
      return;
2264
    }
2265
    envelopes_.pop_back();
2266
  }
2267
2268
  void HandleArrayBegin() override {
2269
    if (!status_->ok())
2270
      return;
2271
    envelopes_.emplace_back();
2272
    envelopes_.back().EncodeStart(out_);
2273
    out_->push_back(kInitialByteIndefiniteLengthArray);
2274
  }
2275
2276
  void HandleArrayEnd() override {
2277
    if (!status_->ok())
2278
      return;
2279
    out_->push_back(kStopByte);
2280
    assert(!envelopes_.empty());
2281
    if (!envelopes_.back().EncodeStop(out_)) {
2282
      HandleError(
2283
          Status(Error::CBOR_ENVELOPE_SIZE_LIMIT_EXCEEDED, out_->size()));
2284
      return;
2285
    }
2286
    envelopes_.pop_back();
2287
  }
2288
2289
  void HandleString8(span<uint8_t> chars) override {
2290
    if (!status_->ok())
2291
      return;
2292
    EncodeString8(chars, out_);
2293
  }
2294
2295
  void HandleString16(span<uint16_t> chars) override {
2296
    if (!status_->ok())
2297
      return;
2298
    EncodeFromUTF16(chars, out_);
2299
  }
2300
2301
  void HandleBinary(span<uint8_t> bytes) override {
2302
    if (!status_->ok())
2303
      return;
2304
    EncodeBinary(bytes, out_);
2305
  }
2306
2307
  void HandleDouble(double value) override {
2308
    if (!status_->ok())
2309
      return;
2310
    EncodeDouble(value, out_);
2311
  }
2312
2313
  void HandleInt32(int32_t value) override {
2314
    if (!status_->ok())
2315
      return;
2316
    EncodeInt32(value, out_);
2317
  }
2318
2319
  void HandleBool(bool value) override {
2320
    if (!status_->ok())
2321
      return;
2322
    // See RFC 7049 Section 2.3, Table 2.
2323
    out_->push_back(value ? kEncodedTrue : kEncodedFalse);
2324
  }
2325
2326
  void HandleNull() override {
2327
    if (!status_->ok())
2328
      return;
2329
    // See RFC 7049 Section 2.3, Table 2.
2330
    out_->push_back(kEncodedNull);
2331
  }
2332
2333
  void HandleError(Status error) override {
2334
    if (!status_->ok())
2335
      return;
2336
    *status_ = error;
2337
    out_->clear();
2338
  }
2339
2340
 private:
2341
  C* out_;
2342
  std::vector<EnvelopeEncoder> envelopes_;
2343
  Status* status_;
2344
};
2345
}  // namespace
2346
2347
std::unique_ptr<StreamingParserHandler> NewCBOREncoder(
2348
    std::vector<uint8_t>* out,
2349
    Status* status) {
2350
  return std::unique_ptr<StreamingParserHandler>(
2351
      new CBOREncoder<std::vector<uint8_t>>(out, status));
2352
}
2353
std::unique_ptr<StreamingParserHandler> NewCBOREncoder(std::string* out,
2354
                                                       Status* status) {
2355
  return std::unique_ptr<StreamingParserHandler>(
2356
      new CBOREncoder<std::string>(out, status));
2357
}
2358
2359
// =============================================================================
2360
// cbor::CBORTokenizer - for parsing individual CBOR items
2361
// =============================================================================
2362
2363
CBORTokenizer::CBORTokenizer(span<uint8_t> bytes) : bytes_(bytes) {
2364
  ReadNextToken(/*enter_envelope=*/false);
2365
}
2366
CBORTokenizer::~CBORTokenizer() {}
2367
2368
CBORTokenTag CBORTokenizer::TokenTag() const {
2369
  return token_tag_;
2370
}
2371
2372
void CBORTokenizer::Next() {
2373
  if (token_tag_ == CBORTokenTag::ERROR_VALUE ||
2374
      token_tag_ == CBORTokenTag::DONE)
2375
    return;
2376
  ReadNextToken(/*enter_envelope=*/false);
2377
}
2378
2379
void CBORTokenizer::EnterEnvelope() {
2380
  assert(token_tag_ == CBORTokenTag::ENVELOPE);
2381
  ReadNextToken(/*enter_envelope=*/true);
2382
}
2383
2384
Status CBORTokenizer::Status() const {
2385
  return status_;
2386
}
2387
2388
// The following accessor functions ::GetInt32, ::GetDouble,
2389
// ::GetString8, ::GetString16WireRep, ::GetBinary, ::GetEnvelopeContents
2390
// assume that a particular token was recognized in ::ReadNextToken.
2391
// That's where all the error checking is done. By design,
2392
// the accessors (assuming the token was recognized) never produce
2393
// an error.
2394
2395
int32_t CBORTokenizer::GetInt32() const {
2396
  assert(token_tag_ == CBORTokenTag::INT32);
2397
  // The range checks happen in ::ReadNextToken().
2398
  return static_cast<int32_t>(
2399
      token_start_type_ == MajorType::UNSIGNED
2400
          ? token_start_internal_value_
2401
          : -static_cast<int64_t>(token_start_internal_value_) - 1);
2402
}
2403
2404
double CBORTokenizer::GetDouble() const {
2405
  assert(token_tag_ == CBORTokenTag::DOUBLE);
2406
  union {
2407
    uint64_t from_uint64;
2408
    double to_double;
2409
  } reinterpret;
2410
  reinterpret.from_uint64 = ReadBytesMostSignificantByteFirst<uint64_t>(
2411
      bytes_.subspan(status_.pos + 1));
2412
  return reinterpret.to_double;
2413
}
2414
2415
span<uint8_t> CBORTokenizer::GetString8() const {
2416
  assert(token_tag_ == CBORTokenTag::STRING8);
2417
  auto length = static_cast<size_t>(token_start_internal_value_);
2418
  return bytes_.subspan(status_.pos + (token_byte_length_ - length), length);
2419
}
2420
2421
span<uint8_t> CBORTokenizer::GetString16WireRep() const {
2422
  assert(token_tag_ == CBORTokenTag::STRING16);
2423
  auto length = static_cast<size_t>(token_start_internal_value_);
2424
  return bytes_.subspan(status_.pos + (token_byte_length_ - length), length);
2425
}
2426
2427
span<uint8_t> CBORTokenizer::GetBinary() const {
2428
  assert(token_tag_ == CBORTokenTag::BINARY);
2429
  auto length = static_cast<size_t>(token_start_internal_value_);
2430
  return bytes_.subspan(status_.pos + (token_byte_length_ - length), length);
2431
}
2432
2433
span<uint8_t> CBORTokenizer::GetEnvelopeContents() const {
2434
  assert(token_tag_ == CBORTokenTag::ENVELOPE);
2435
  auto length = static_cast<size_t>(token_start_internal_value_);
2436
  return bytes_.subspan(status_.pos + kEncodedEnvelopeHeaderSize, length);
2437
}
2438
2439
// All error checking happens in ::ReadNextToken, so that the accessors
2440
// can avoid having to carry an error return value.
2441
//
2442
// With respect to checking the encoded lengths of strings, arrays, etc:
2443
// On the wire, CBOR uses 1,2,4, and 8 byte unsigned integers, so
2444
// we initially read them as uint64_t, usually into token_start_internal_value_.
2445
//
2446
// However, since these containers have a representation on the machine,
2447
// we need to do corresponding size computations on the input byte array,
2448
// output span (e.g. the payload for a string), etc., and size_t is
2449
// machine specific (in practice either 32 bit or 64 bit).
2450
//
2451
// Further, we must avoid overflowing size_t. Therefore, we use this
2452
// kMaxValidLength constant to:
2453
// - Reject values that are larger than the architecture specific
2454
//   max size_t (differs between 32 bit and 64 bit arch).
2455
// - Reserve at least one bit so that we can check against overflows
2456
//   when adding lengths (array / string length / etc.); we do this by
2457
//   ensuring that the inputs to an addition are <= kMaxValidLength,
2458
//   and then checking whether the sum went past it.
2459
//
2460
// See also
2461
// https://chromium.googlesource.com/chromium/src/+/master/docs/security/integer-semantics.md
2462
4828
static const uint64_t kMaxValidLength =
2463
4828
    std::min<uint64_t>(std::numeric_limits<uint64_t>::max() >> 2,
2464
14484
                       std::numeric_limits<size_t>::max());
2465
2466
void CBORTokenizer::ReadNextToken(bool enter_envelope) {
2467
  if (enter_envelope) {
2468
    status_.pos += kEncodedEnvelopeHeaderSize;
2469
  } else {
2470
    status_.pos =
2471
        status_.pos == Status::npos() ? 0 : status_.pos + token_byte_length_;
2472
  }
2473
  status_.error = Error::OK;
2474
  if (status_.pos >= bytes_.size()) {
2475
    token_tag_ = CBORTokenTag::DONE;
2476
    return;
2477
  }
2478
  const size_t remaining_bytes = bytes_.size() - status_.pos;
2479
  switch (bytes_[status_.pos]) {
2480
    case kStopByte:
2481
      SetToken(CBORTokenTag::STOP, 1);
2482
      return;
2483
    case kInitialByteIndefiniteLengthMap:
2484
      SetToken(CBORTokenTag::MAP_START, 1);
2485
      return;
2486
    case kInitialByteIndefiniteLengthArray:
2487
      SetToken(CBORTokenTag::ARRAY_START, 1);
2488
      return;
2489
    case kEncodedTrue:
2490
      SetToken(CBORTokenTag::TRUE_VALUE, 1);
2491
      return;
2492
    case kEncodedFalse:
2493
      SetToken(CBORTokenTag::FALSE_VALUE, 1);
2494
      return;
2495
    case kEncodedNull:
2496
      SetToken(CBORTokenTag::NULL_VALUE, 1);
2497
      return;
2498
    case kExpectedConversionToBase64Tag: {  // BINARY
2499
      const int8_t bytes_read = internals::ReadTokenStart(
2500
          bytes_.subspan(status_.pos + 1), &token_start_type_,
2501
          &token_start_internal_value_);
2502
      if (bytes_read < 0 || token_start_type_ != MajorType::BYTE_STRING ||
2503
          token_start_internal_value_ > kMaxValidLength) {
2504
        SetError(Error::CBOR_INVALID_BINARY);
2505
        return;
2506
      }
2507
      const uint64_t token_byte_length = token_start_internal_value_ +
2508
                                         /* tag before token start: */ 1 +
2509
                                         /* token start: */ bytes_read;
2510
      if (token_byte_length > remaining_bytes) {
2511
        SetError(Error::CBOR_INVALID_BINARY);
2512
        return;
2513
      }
2514
      SetToken(CBORTokenTag::BINARY, static_cast<size_t>(token_byte_length));
2515
      return;
2516
    }
2517
    case kInitialByteForDouble: {  // DOUBLE
2518
      if (kEncodedDoubleSize > remaining_bytes) {
2519
        SetError(Error::CBOR_INVALID_DOUBLE);
2520
        return;
2521
      }
2522
      SetToken(CBORTokenTag::DOUBLE, kEncodedDoubleSize);
2523
      return;
2524
    }
2525
    case kInitialByteForEnvelope: {  // ENVELOPE
2526
      if (kEncodedEnvelopeHeaderSize > remaining_bytes) {
2527
        SetError(Error::CBOR_INVALID_ENVELOPE);
2528
        return;
2529
      }
2530
      // The envelope must be a byte string with 32 bit length.
2531
      if (bytes_[status_.pos + 1] != kInitialByteFor32BitLengthByteString) {
2532
        SetError(Error::CBOR_INVALID_ENVELOPE);
2533
        return;
2534
      }
2535
      // Read the length of the byte string.
2536
      token_start_internal_value_ = ReadBytesMostSignificantByteFirst<uint32_t>(
2537
          bytes_.subspan(status_.pos + 2));
2538
      if (token_start_internal_value_ > kMaxValidLength) {
2539
        SetError(Error::CBOR_INVALID_ENVELOPE);
2540
        return;
2541
      }
2542
      uint64_t token_byte_length =
2543
          token_start_internal_value_ + kEncodedEnvelopeHeaderSize;
2544
      if (token_byte_length > remaining_bytes) {
2545
        SetError(Error::CBOR_INVALID_ENVELOPE);
2546
        return;
2547
      }
2548
      SetToken(CBORTokenTag::ENVELOPE, static_cast<size_t>(token_byte_length));
2549
      return;
2550
    }
2551
    default: {
2552
      const int8_t token_start_length = internals::ReadTokenStart(
2553
          bytes_.subspan(status_.pos), &token_start_type_,
2554
          &token_start_internal_value_);
2555
      const bool success = token_start_length >= 0;
2556
      switch (token_start_type_) {
2557
        case MajorType::UNSIGNED:  // INT32.
2558
          // INT32 is a signed int32 (int32 makes sense for the
2559
          // inspector_protocol, it's not a CBOR limitation), so we check
2560
          // against the signed max, so that the allowable values are
2561
          // 0, 1, 2, ... 2^31 - 1.
2562
          if (!success || std::numeric_limits<int32_t>::max() <
2563
                              token_start_internal_value_) {
2564
            SetError(Error::CBOR_INVALID_INT32);
2565
            return;
2566
          }
2567
          SetToken(CBORTokenTag::INT32, token_start_length);
2568
          return;
2569
        case MajorType::NEGATIVE: {  // INT32.
2570
          // INT32 is a signed int32 (int32 makes sense for the
2571
          // inspector_protocol, it's not a CBOR limitation); in CBOR,
2572
          // the negative values for INT32 are represented as NEGATIVE,
2573
          // that is, -1 INT32 is represented as 1 << 5 | 0 (major type 1,
2574
          // additional info value 0). So here, we compute the INT32 value
2575
          // and then check it against the INT32 min.
2576
          int64_t actual_value =
2577
              -static_cast<int64_t>(token_start_internal_value_) - 1;
2578
          if (!success || actual_value < std::numeric_limits<int32_t>::min()) {
2579
            SetError(Error::CBOR_INVALID_INT32);
2580
            return;
2581
          }
2582
          SetToken(CBORTokenTag::INT32, token_start_length);
2583
          return;
2584
        }
2585
        case MajorType::STRING: {  // STRING8.
2586
          if (!success || token_start_internal_value_ > kMaxValidLength) {
2587
            SetError(Error::CBOR_INVALID_STRING8);
2588
            return;
2589
          }
2590
          uint64_t token_byte_length =
2591
              token_start_internal_value_ + token_start_length;
2592
          if (token_byte_length > remaining_bytes) {
2593
            SetError(Error::CBOR_INVALID_STRING8);
2594
            return;
2595
          }
2596
          SetToken(CBORTokenTag::STRING8,
2597
                   static_cast<size_t>(token_byte_length));
2598
          return;
2599
        }
2600
        case MajorType::BYTE_STRING: {  // STRING16.
2601
          // Length must be divisible by 2 since UTF16 is 2 bytes per
2602
          // character, hence the &1 check.
2603
          if (!success || token_start_internal_value_ > kMaxValidLength ||
2604
              token_start_internal_value_ & 1) {
2605
            SetError(Error::CBOR_INVALID_STRING16);
2606
            return;
2607
          }
2608
          uint64_t token_byte_length =
2609
              token_start_internal_value_ + token_start_length;
2610
          if (token_byte_length > remaining_bytes) {
2611
            SetError(Error::CBOR_INVALID_STRING16);
2612
            return;
2613
          }
2614
          SetToken(CBORTokenTag::STRING16,
2615
                   static_cast<size_t>(token_byte_length));
2616
          return;
2617
        }
2618
        case MajorType::ARRAY:
2619
        case MajorType::MAP:
2620
        case MajorType::TAG:
2621
        case MajorType::SIMPLE_VALUE:
2622
          SetError(Error::CBOR_UNSUPPORTED_VALUE);
2623
          return;
2624
      }
2625
    }
2626
  }
2627
}
2628
2629
void CBORTokenizer::SetToken(CBORTokenTag token_tag, size_t token_byte_length) {
2630
  token_tag_ = token_tag;
2631
  token_byte_length_ = token_byte_length;
2632
}
2633
2634
void CBORTokenizer::SetError(Error error) {
2635
  token_tag_ = CBORTokenTag::ERROR_VALUE;
2636
  status_.error = error;
2637
}
2638
2639
// =============================================================================
2640
// cbor::ParseCBOR - for receiving streaming parser events for CBOR messages
2641
// =============================================================================
2642
2643
namespace {
2644
// When parsing CBOR, we limit recursion depth for objects and arrays
2645
// to this constant.
2646
static constexpr int kStackLimit = 300;
2647
2648
// Below are three parsing routines for CBOR, which cover enough
2649
// to roundtrip JSON messages.
2650
bool ParseMap(int32_t stack_depth,
2651
              CBORTokenizer* tokenizer,
2652
              StreamingParserHandler* out);
2653
bool ParseArray(int32_t stack_depth,
2654
                CBORTokenizer* tokenizer,
2655
                StreamingParserHandler* out);
2656
bool ParseValue(int32_t stack_depth,
2657
                CBORTokenizer* tokenizer,
2658
                StreamingParserHandler* out);
2659
2660
void ParseUTF16String(CBORTokenizer* tokenizer, StreamingParserHandler* out) {
2661
  std::vector<uint16_t> value;
2662
  span<uint8_t> rep = tokenizer->GetString16WireRep();
2663
  for (size_t ii = 0; ii < rep.size(); ii += 2)
2664
    value.push_back((rep[ii + 1] << 8) | rep[ii]);
2665
  out->HandleString16(span<uint16_t>(value.data(), value.size()));
2666
  tokenizer->Next();
2667
}
2668
2669
bool ParseUTF8String(CBORTokenizer* tokenizer, StreamingParserHandler* out) {
2670
  assert(tokenizer->TokenTag() == CBORTokenTag::STRING8);
2671
  out->HandleString8(tokenizer->GetString8());
2672
  tokenizer->Next();
2673
  return true;
2674
}
2675
2676
bool ParseValue(int32_t stack_depth,
2677
                CBORTokenizer* tokenizer,
2678
                StreamingParserHandler* out) {
2679
  if (stack_depth > kStackLimit) {
2680
    out->HandleError(
2681
        Status{Error::CBOR_STACK_LIMIT_EXCEEDED, tokenizer->Status().pos});
2682
    return false;
2683
  }
2684
  // Skip past the envelope to get to what's inside.
2685
  if (tokenizer->TokenTag() == CBORTokenTag::ENVELOPE)
2686
    tokenizer->EnterEnvelope();
2687
  switch (tokenizer->TokenTag()) {
2688
    case CBORTokenTag::ERROR_VALUE:
2689
      out->HandleError(tokenizer->Status());
2690
      return false;
2691
    case CBORTokenTag::DONE:
2692
      out->HandleError(Status{Error::CBOR_UNEXPECTED_EOF_EXPECTED_VALUE,
2693
                              tokenizer->Status().pos});
2694
      return false;
2695
    case CBORTokenTag::TRUE_VALUE:
2696
      out->HandleBool(true);
2697
      tokenizer->Next();
2698
      return true;
2699
    case CBORTokenTag::FALSE_VALUE:
2700
      out->HandleBool(false);
2701
      tokenizer->Next();
2702
      return true;
2703
    case CBORTokenTag::NULL_VALUE:
2704
      out->HandleNull();
2705
      tokenizer->Next();
2706
      return true;
2707
    case CBORTokenTag::INT32:
2708
      out->HandleInt32(tokenizer->GetInt32());
2709
      tokenizer->Next();
2710
      return true;
2711
    case CBORTokenTag::DOUBLE:
2712
      out->HandleDouble(tokenizer->GetDouble());
2713
      tokenizer->Next();
2714
      return true;
2715
    case CBORTokenTag::STRING8:
2716
      return ParseUTF8String(tokenizer, out);
2717
    case CBORTokenTag::STRING16:
2718
      ParseUTF16String(tokenizer, out);
2719
      return true;
2720
    case CBORTokenTag::BINARY: {
2721
      out->HandleBinary(tokenizer->GetBinary());
2722
      tokenizer->Next();
2723
      return true;
2724
    }
2725
    case CBORTokenTag::MAP_START:
2726
      return ParseMap(stack_depth + 1, tokenizer, out);
2727
    case CBORTokenTag::ARRAY_START:
2728
      return ParseArray(stack_depth + 1, tokenizer, out);
2729
    default:
2730
      out->HandleError(
2731
          Status{Error::CBOR_UNSUPPORTED_VALUE, tokenizer->Status().pos});
2732
      return false;
2733
  }
2734
}
2735
2736
// |bytes| must start with the indefinite length array byte, so basically,
2737
// ParseArray may only be called after an indefinite length array has been
2738
// detected.
2739
bool ParseArray(int32_t stack_depth,
2740
                CBORTokenizer* tokenizer,
2741
                StreamingParserHandler* out) {
2742
  assert(tokenizer->TokenTag() == CBORTokenTag::ARRAY_START);
2743
  tokenizer->Next();
2744
  out->HandleArrayBegin();
2745
  while (tokenizer->TokenTag() != CBORTokenTag::STOP) {
2746
    if (tokenizer->TokenTag() == CBORTokenTag::DONE) {
2747
      out->HandleError(
2748
          Status{Error::CBOR_UNEXPECTED_EOF_IN_ARRAY, tokenizer->Status().pos});
2749
      return false;
2750
    }
2751
    if (tokenizer->TokenTag() == CBORTokenTag::ERROR_VALUE) {
2752
      out->HandleError(tokenizer->Status());
2753
      return false;
2754
    }
2755
    // Parse value.
2756
    if (!ParseValue(stack_depth, tokenizer, out))
2757
      return false;
2758
  }
2759
  out->HandleArrayEnd();
2760
  tokenizer->Next();
2761
  return true;
2762
}
2763
2764
// |bytes| must start with the indefinite length array byte, so basically,
2765
// ParseArray may only be called after an indefinite length array has been
2766
// detected.
2767
bool ParseMap(int32_t stack_depth,
2768
              CBORTokenizer* tokenizer,
2769
              StreamingParserHandler* out) {
2770
  assert(tokenizer->TokenTag() == CBORTokenTag::MAP_START);
2771
  out->HandleMapBegin();
2772
  tokenizer->Next();
2773
  while (tokenizer->TokenTag() != CBORTokenTag::STOP) {
2774
    if (tokenizer->TokenTag() == CBORTokenTag::DONE) {
2775
      out->HandleError(
2776
          Status{Error::CBOR_UNEXPECTED_EOF_IN_MAP, tokenizer->Status().pos});
2777
      return false;
2778
    }
2779
    if (tokenizer->TokenTag() == CBORTokenTag::ERROR_VALUE) {
2780
      out->HandleError(tokenizer->Status());
2781
      return false;
2782
    }
2783
    // Parse key.
2784
    if (tokenizer->TokenTag() == CBORTokenTag::STRING8) {
2785
      if (!ParseUTF8String(tokenizer, out))
2786
        return false;
2787
    } else if (tokenizer->TokenTag() == CBORTokenTag::STRING16) {
2788
      ParseUTF16String(tokenizer, out);
2789
    } else {
2790
      out->HandleError(
2791
          Status{Error::CBOR_INVALID_MAP_KEY, tokenizer->Status().pos});
2792
      return false;
2793
    }
2794
    // Parse value.
2795
    if (!ParseValue(stack_depth, tokenizer, out))
2796
      return false;
2797
  }
2798
  out->HandleMapEnd();
2799
  tokenizer->Next();
2800
  return true;
2801
}
2802
}  // namespace
2803
2804
void ParseCBOR(span<uint8_t> bytes, StreamingParserHandler* out) {
2805
  if (bytes.empty()) {
2806
    out->HandleError(Status{Error::CBOR_NO_INPUT, 0});
2807
    return;
2808
  }
2809
  if (bytes[0] != kInitialByteForEnvelope) {
2810
    out->HandleError(Status{Error::CBOR_INVALID_START_BYTE, 0});
2811
    return;
2812
  }
2813
  CBORTokenizer tokenizer(bytes);
2814
  if (tokenizer.TokenTag() == CBORTokenTag::ERROR_VALUE) {
2815
    out->HandleError(tokenizer.Status());
2816
    return;
2817
  }
2818
  // We checked for the envelope start byte above, so the tokenizer
2819
  // must agree here, since it's not an error.
2820
  assert(tokenizer.TokenTag() == CBORTokenTag::ENVELOPE);
2821
  tokenizer.EnterEnvelope();
2822
  if (tokenizer.TokenTag() != CBORTokenTag::MAP_START) {
2823
    out->HandleError(
2824
        Status{Error::CBOR_MAP_START_EXPECTED, tokenizer.Status().pos});
2825
    return;
2826
  }
2827
  if (!ParseMap(/*stack_depth=*/1, &tokenizer, out))
2828
    return;
2829
  if (tokenizer.TokenTag() == CBORTokenTag::DONE)
2830
    return;
2831
  if (tokenizer.TokenTag() == CBORTokenTag::ERROR_VALUE) {
2832
    out->HandleError(tokenizer.Status());
2833
    return;
2834
  }
2835
  out->HandleError(Status{Error::CBOR_TRAILING_JUNK, tokenizer.Status().pos});
2836
}
2837
2838
// =============================================================================
2839
// cbor::AppendString8EntryToMap - for limited in-place editing of messages
2840
// =============================================================================
2841
2842
template <typename C>
2843
Status AppendString8EntryToCBORMapTmpl(span<uint8_t> string8_key,
2844
                                       span<uint8_t> string8_value,
2845
                                       C* cbor) {
2846
  // Careful below: Don't compare (*cbor)[idx] with a uint8_t, since
2847
  // it could be a char (signed!). Instead, use bytes.
2848
  span<uint8_t> bytes(reinterpret_cast<const uint8_t*>(cbor->data()),
2849
                      cbor->size());
2850
  CBORTokenizer tokenizer(bytes);
2851
  if (tokenizer.TokenTag() == CBORTokenTag::ERROR_VALUE)
2852
    return tokenizer.Status();
2853
  if (tokenizer.TokenTag() != CBORTokenTag::ENVELOPE)
2854
    return Status(Error::CBOR_INVALID_ENVELOPE, 0);
2855
  size_t envelope_size = tokenizer.GetEnvelopeContents().size();
2856
  size_t old_size = cbor->size();
2857
  if (old_size != envelope_size + kEncodedEnvelopeHeaderSize)
2858
    return Status(Error::CBOR_INVALID_ENVELOPE, 0);
2859
  if (envelope_size == 0 ||
2860
      (tokenizer.GetEnvelopeContents()[0] != EncodeIndefiniteLengthMapStart()))
2861
    return Status(Error::CBOR_MAP_START_EXPECTED, kEncodedEnvelopeHeaderSize);
2862
  if (bytes[bytes.size() - 1] != EncodeStop())
2863
    return Status(Error::CBOR_MAP_STOP_EXPECTED, cbor->size() - 1);
2864
  cbor->pop_back();
2865
  EncodeString8(string8_key, cbor);
2866
  EncodeString8(string8_value, cbor);
2867
  cbor->push_back(EncodeStop());
2868
  size_t new_envelope_size = envelope_size + (cbor->size() - old_size);
2869
  if (new_envelope_size > std::numeric_limits<uint32_t>::max())
2870
    return Status(Error::CBOR_ENVELOPE_SIZE_LIMIT_EXCEEDED, 0);
2871
  size_t size_pos = cbor->size() - new_envelope_size - sizeof(uint32_t);
2872
  uint8_t* out = reinterpret_cast<uint8_t*>(&cbor->at(size_pos));
2873
  *(out++) = (new_envelope_size >> 24) & 0xff;
2874
  *(out++) = (new_envelope_size >> 16) & 0xff;
2875
  *(out++) = (new_envelope_size >> 8) & 0xff;
2876
  *(out) = new_envelope_size & 0xff;
2877
  return Status();
2878
}
2879
Status AppendString8EntryToCBORMap(span<uint8_t> string8_key,
2880
                                   span<uint8_t> string8_value,
2881
                                   std::vector<uint8_t>* cbor) {
2882
  return AppendString8EntryToCBORMapTmpl(string8_key, string8_value, cbor);
2883
}
2884
Status AppendString8EntryToCBORMap(span<uint8_t> string8_key,
2885
                                   span<uint8_t> string8_value,
2886
                                   std::string* cbor) {
2887
  return AppendString8EntryToCBORMapTmpl(string8_key, string8_value, cbor);
2888
}
2889
}  // namespace cbor
2890
2891
namespace json {
2892
2893
// =============================================================================
2894
// json::NewJSONEncoder - for encoding streaming parser events as JSON
2895
// =============================================================================
2896
2897
namespace {
2898
// Prints |value| to |out| with 4 hex digits, most significant chunk first.
2899
template <typename C>
2900
void PrintHex(uint16_t value, C* out) {
2901
  for (int ii = 3; ii >= 0; --ii) {
2902
    int four_bits = 0xf & (value >> (4 * ii));
2903
    out->push_back(four_bits + ((four_bits <= 9) ? '0' : ('a' - 10)));
2904
  }
2905
}
2906
2907
// In the writer below, we maintain a stack of State instances.
2908
// It is just enough to emit the appropriate delimiters and brackets
2909
// in JSON.
2910
enum class Container {
2911
  // Used for the top-level, initial state.
2912
  NONE,
2913
  // Inside a JSON object.
2914
  MAP,
2915
  // Inside a JSON array.
2916
  ARRAY
2917
};
2918
class State {
2919
 public:
2920
  explicit State(Container container) : container_(container) {}
2921
  void StartElement(std::vector<uint8_t>* out) { StartElementTmpl(out); }
2922
  void StartElement(std::string* out) { StartElementTmpl(out); }
2923
  Container container() const { return container_; }
2924
2925
 private:
2926
  template <typename C>
2927
  void StartElementTmpl(C* out) {
2928
    assert(container_ != Container::NONE || size_ == 0);
2929
    if (size_ != 0) {
2930
      char delim = (!(size_ & 1) || container_ == Container::ARRAY) ? ',' : ':';
2931
      out->push_back(delim);
2932
    }
2933
    ++size_;
2934
  }
2935
2936
  Container container_ = Container::NONE;
2937
  int size_ = 0;
2938
};
2939
2940
constexpr char kBase64Table[] =
2941
    "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
2942
    "abcdefghijklmnopqrstuvwxyz0123456789+/";
2943
2944
template <typename C>
2945
void Base64Encode(const span<uint8_t>& in, C* out) {
2946
  // The following three cases are based on the tables in the example
2947
  // section in https://en.wikipedia.org/wiki/Base64. We process three
2948
  // input bytes at a time, emitting 4 output bytes at a time.
2949
  size_t ii = 0;
2950
2951
  // While possible, process three input bytes.
2952
  for (; ii + 3 <= in.size(); ii += 3) {
2953
    uint32_t twentyfour_bits = (in[ii] << 16) | (in[ii + 1] << 8) | in[ii + 2];
2954
    out->push_back(kBase64Table[(twentyfour_bits >> 18)]);
2955
    out->push_back(kBase64Table[(twentyfour_bits >> 12) & 0x3f]);
2956
    out->push_back(kBase64Table[(twentyfour_bits >> 6) & 0x3f]);
2957
    out->push_back(kBase64Table[twentyfour_bits & 0x3f]);
2958
  }
2959
  if (ii + 2 <= in.size()) {  // Process two input bytes.
2960
    uint32_t twentyfour_bits = (in[ii] << 16) | (in[ii + 1] << 8);
2961
    out->push_back(kBase64Table[(twentyfour_bits >> 18)]);
2962
    out->push_back(kBase64Table[(twentyfour_bits >> 12) & 0x3f]);
2963
    out->push_back(kBase64Table[(twentyfour_bits >> 6) & 0x3f]);
2964
    out->push_back('=');  // Emit padding.
2965
    return;
2966
  }
2967
  if (ii + 1 <= in.size()) {  // Process a single input byte.
2968
    uint32_t twentyfour_bits = (in[ii] << 16);
2969
    out->push_back(kBase64Table[(twentyfour_bits >> 18)]);
2970
    out->push_back(kBase64Table[(twentyfour_bits >> 12) & 0x3f]);
2971
    out->push_back('=');  // Emit padding.
2972
    out->push_back('=');  // Emit padding.
2973
  }
2974
}
2975
2976
// Implements a handler for JSON parser events to emit a JSON string.
2977
template <typename C>
2978
class JSONEncoder : public StreamingParserHandler {
2979
 public:
2980
  JSONEncoder(const Platform* platform, C* out, Status* status)
2981
      : platform_(platform), out_(out), status_(status) {
2982
    *status_ = Status();
2983
    state_.emplace(Container::NONE);
2984
  }
2985
2986
  void HandleMapBegin() override {
2987
    if (!status_->ok())
2988
      return;
2989
    assert(!state_.empty());
2990
    state_.top().StartElement(out_);
2991
    state_.emplace(Container::MAP);
2992
    Emit('{');
2993
  }
2994
2995
  void HandleMapEnd() override {
2996
    if (!status_->ok())
2997
      return;
2998
    assert(state_.size() >= 2 && state_.top().container() == Container::MAP);
2999
    state_.pop();
3000
    Emit('}');
3001
  }
3002
3003
  void HandleArrayBegin() override {
3004
    if (!status_->ok())
3005
      return;
3006
    state_.top().StartElement(out_);
3007
    state_.emplace(Container::ARRAY);
3008
    Emit('[');
3009
  }
3010
3011
  void HandleArrayEnd() override {
3012
    if (!status_->ok())
3013
      return;
3014
    assert(state_.size() >= 2 && state_.top().container() == Container::ARRAY);
3015
    state_.pop();
3016
    Emit(']');
3017
  }
3018
3019
  void HandleString16(span<uint16_t> chars) override {
3020
    if (!status_->ok())
3021
      return;
3022
    state_.top().StartElement(out_);
3023
    Emit('"');
3024
    for (const uint16_t ch : chars) {
3025
      if (ch == '"') {
3026
        Emit("\\\"");
3027
      } else if (ch == '\\') {
3028
        Emit("\\\\");
3029
      } else if (ch == '\b') {
3030
        Emit("\\b");
3031
      } else if (ch == '\f') {
3032
        Emit("\\f");
3033
      } else if (ch == '\n') {
3034
        Emit("\\n");
3035
      } else if (ch == '\r') {
3036
        Emit("\\r");
3037
      } else if (ch == '\t') {
3038
        Emit("\\t");
3039
      } else if (ch >= 32 && ch <= 126) {
3040
        Emit(ch);
3041
      } else {
3042
        Emit("\\u");
3043
        PrintHex(ch, out_);
3044
      }
3045
    }
3046
    Emit('"');
3047
  }
3048
3049
  void HandleString8(span<uint8_t> chars) override {
3050
    if (!status_->ok())
3051
      return;
3052
    state_.top().StartElement(out_);
3053
    Emit('"');
3054
    for (size_t ii = 0; ii < chars.size(); ++ii) {
3055
      uint8_t c = chars[ii];
3056
      if (c == '"') {
3057
        Emit("\\\"");
3058
      } else if (c == '\\') {
3059
        Emit("\\\\");
3060
      } else if (c == '\b') {
3061
        Emit("\\b");
3062
      } else if (c == '\f') {
3063
        Emit("\\f");
3064
      } else if (c == '\n') {
3065
        Emit("\\n");
3066
      } else if (c == '\r') {
3067
        Emit("\\r");
3068
      } else if (c == '\t') {
3069
        Emit("\\t");
3070
      } else if (c >= 32 && c <= 126) {
3071
        Emit(c);
3072
      } else if (c < 32) {
3073
        Emit("\\u");
3074
        PrintHex(static_cast<uint16_t>(c), out_);
3075
      } else {
3076
        // Inspect the leading byte to figure out how long the utf8
3077
        // byte sequence is; while doing this initialize |codepoint|
3078
        // with the first few bits.
3079
        // See table in: https://en.wikipedia.org/wiki/UTF-8
3080
        // byte one is 110x xxxx -> 2 byte utf8 sequence
3081
        // byte one is 1110 xxxx -> 3 byte utf8 sequence
3082
        // byte one is 1111 0xxx -> 4 byte utf8 sequence
3083
        uint32_t codepoint;
3084
        int num_bytes_left;
3085
        if ((c & 0xe0) == 0xc0) {  // 2 byte utf8 sequence
3086
          num_bytes_left = 1;
3087
          codepoint = c & 0x1f;
3088
        } else if ((c & 0xf0) == 0xe0) {  // 3 byte utf8 sequence
3089
          num_bytes_left = 2;
3090
          codepoint = c & 0x0f;
3091
        } else if ((c & 0xf8) == 0xf0) {  // 4 byte utf8 sequence
3092
          codepoint = c & 0x07;
3093
          num_bytes_left = 3;
3094
        } else {
3095
          continue;  // invalid leading byte
3096
        }
3097
3098
        // If we have enough bytes in our input, decode the remaining ones
3099
        // belonging to this Unicode character into |codepoint|.
3100
        if (ii + num_bytes_left > chars.size())
3101
          continue;
3102
        while (num_bytes_left > 0) {
3103
          c = chars[++ii];
3104
          --num_bytes_left;
3105
          // Check the next byte is a continuation byte, that is 10xx xxxx.
3106
          if ((c & 0xc0) != 0x80)
3107
            continue;
3108
          codepoint = (codepoint << 6) | (c & 0x3f);
3109
        }
3110
3111
        // Disallow overlong encodings for ascii characters, as these
3112
        // would include " and other characters significant to JSON
3113
        // string termination / control.
3114
        if (codepoint < 0x7f)
3115
          continue;
3116
        // Invalid in UTF8, and can't be represented in UTF16 anyway.
3117
        if (codepoint > 0x10ffff)
3118
          continue;
3119
3120
        // So, now we transcode to UTF16,
3121
        // using the math described at https://en.wikipedia.org/wiki/UTF-16,
3122
        // for either one or two 16 bit characters.
3123
        if (codepoint < 0xffff) {
3124
          Emit("\\u");
3125
          PrintHex(static_cast<uint16_t>(codepoint), out_);
3126
          continue;
3127
        }
3128
        codepoint -= 0x10000;
3129
        // high surrogate
3130
        Emit("\\u");
3131
        PrintHex(static_cast<uint16_t>((codepoint >> 10) + 0xd800), out_);
3132
        // low surrogate
3133
        Emit("\\u");
3134
        PrintHex(static_cast<uint16_t>((codepoint & 0x3ff) + 0xdc00), out_);
3135
      }
3136
    }
3137
    Emit('"');
3138
  }
3139
3140
  void HandleBinary(span<uint8_t> bytes) override {
3141
    if (!status_->ok())
3142
      return;
3143
    state_.top().StartElement(out_);
3144
    Emit('"');
3145
    Base64Encode(bytes, out_);
3146
    Emit('"');
3147
  }
3148
3149
  void HandleDouble(double value) override {
3150
    if (!status_->ok())
3151
      return;
3152
    state_.top().StartElement(out_);
3153
    // JSON cannot represent NaN or Infinity. So, for compatibility,
3154
    // we behave like the JSON object in web browsers: emit 'null'.
3155
    if (!std::isfinite(value)) {
3156
      Emit("null");
3157
      return;
3158
    }
3159
    std::unique_ptr<char[]> str_value = platform_->DToStr(value);
3160
3161
    // DToStr may fail to emit a 0 before the decimal dot. E.g. this is
3162
    // the case in base::NumberToString in Chromium (which is based on
3163
    // dmg_fp). So, much like
3164
    // https://cs.chromium.org/chromium/src/base/json/json_writer.cc
3165
    // we probe for this and emit the leading 0 anyway if necessary.
3166
    const char* chars = str_value.get();
3167
    if (chars[0] == '.') {
3168
      Emit('0');
3169
    } else if (chars[0] == '-' && chars[1] == '.') {
3170
      Emit("-0");
3171
      ++chars;
3172
    }
3173
    Emit(chars);
3174
  }
3175
3176
  void HandleInt32(int32_t value) override {
3177
    if (!status_->ok())
3178
      return;
3179
    state_.top().StartElement(out_);
3180
    Emit(std::to_string(value));
3181
  }
3182
3183
  void HandleBool(bool value) override {
3184
    if (!status_->ok())
3185
      return;
3186
    state_.top().StartElement(out_);
3187
    Emit(value ? "true" : "false");
3188
  }
3189
3190
  void HandleNull() override {
3191
    if (!status_->ok())
3192
      return;
3193
    state_.top().StartElement(out_);
3194
    Emit("null");
3195
  }
3196
3197
  void HandleError(Status error) override {
3198
    assert(!error.ok());
3199
    *status_ = error;
3200
    out_->clear();
3201
  }
3202
3203
 private:
3204
  void Emit(char c) { out_->push_back(c); }
3205
  void Emit(const char* str) {
3206
    out_->insert(out_->end(), str, str + strlen(str));
3207
  }
3208
  void Emit(const std::string& str) {
3209
    out_->insert(out_->end(), str.begin(), str.end());
3210
  }
3211
3212
  const Platform* platform_;
3213
  C* out_;
3214
  Status* status_;
3215
  std::stack<State> state_;
3216
};
3217
}  // namespace
3218
3219
std::unique_ptr<StreamingParserHandler> NewJSONEncoder(
3220
    const Platform* platform,
3221
    std::vector<uint8_t>* out,
3222
    Status* status) {
3223
  return std::unique_ptr<StreamingParserHandler>(
3224
      new JSONEncoder<std::vector<uint8_t>>(platform, out, status));
3225
}
3226
std::unique_ptr<StreamingParserHandler> NewJSONEncoder(const Platform* platform,
3227
                                                       std::string* out,
3228
                                                       Status* status) {
3229
  return std::unique_ptr<StreamingParserHandler>(
3230
      new JSONEncoder<std::string>(platform, out, status));
3231
}
3232
3233
// =============================================================================
3234
// json::ParseJSON - for receiving streaming parser events for JSON.
3235
// =============================================================================
3236
3237
namespace {
3238
const int kStackLimit = 300;
3239
3240
enum Token {
3241
  ObjectBegin,
3242
  ObjectEnd,
3243
  ArrayBegin,
3244
  ArrayEnd,
3245
  StringLiteral,
3246
  Number,
3247
  BoolTrue,
3248
  BoolFalse,
3249
  NullToken,
3250
  ListSeparator,
3251
  ObjectPairSeparator,
3252
  InvalidToken,
3253
  NoInput
3254
};
3255
3256
const char* const kNullString = "null";
3257
const char* const kTrueString = "true";
3258
const char* const kFalseString = "false";
3259
3260
template <typename Char>
3261
class JsonParser {
3262
 public:
3263
  JsonParser(const Platform* platform, StreamingParserHandler* handler)
3264
      : platform_(platform), handler_(handler) {}
3265
3266
  void Parse(const Char* start, size_t length) {
3267
    start_pos_ = start;
3268
    const Char* end = start + length;
3269
    const Char* tokenEnd = nullptr;
3270
    ParseValue(start, end, &tokenEnd, 0);
3271
    if (error_)
3272
      return;
3273
    if (tokenEnd != end) {
3274
      HandleError(Error::JSON_PARSER_UNPROCESSED_INPUT_REMAINS, tokenEnd);
3275
    }
3276
  }
3277
3278
 private:
3279
  bool CharsToDouble(const uint16_t* chars, size_t length, double* result) {
3280
    std::string buffer;
3281
    buffer.reserve(length + 1);
3282
    for (size_t ii = 0; ii < length; ++ii) {
3283
      bool is_ascii = !(chars[ii] & ~0x7F);
3284
      if (!is_ascii)
3285
        return false;
3286
      buffer.push_back(static_cast<char>(chars[ii]));
3287
    }
3288
    return platform_->StrToD(buffer.c_str(), result);
3289
  }
3290
3291
  bool CharsToDouble(const uint8_t* chars, size_t length, double* result) {
3292
    std::string buffer(reinterpret_cast<const char*>(chars), length);
3293
    return platform_->StrToD(buffer.c_str(), result);
3294
  }
3295
3296
  static bool ParseConstToken(const Char* start,
3297
                              const Char* end,
3298
                              const Char** token_end,
3299
                              const char* token) {
3300
    // |token| is \0 terminated, it's one of the constants at top of the file.
3301
    while (start < end && *token != '\0' && *start++ == *token++) {
3302
    }
3303
    if (*token != '\0')
3304
      return false;
3305
    *token_end = start;
3306
    return true;
3307
  }
3308
3309
  static bool ReadInt(const Char* start,
3310
                      const Char* end,
3311
                      const Char** token_end,
3312
                      bool allow_leading_zeros) {
3313
    if (start == end)
3314
      return false;
3315
    bool has_leading_zero = '0' == *start;
3316
    int length = 0;
3317
    while (start < end && '0' <= *start && *start <= '9') {
3318
      ++start;
3319
      ++length;
3320
    }
3321
    if (!length)
3322
      return false;
3323
    if (!allow_leading_zeros && length > 1 && has_leading_zero)
3324
      return false;
3325
    *token_end = start;
3326
    return true;
3327
  }
3328
3329
  static bool ParseNumberToken(const Char* start,
3330
                               const Char* end,
3331
                               const Char** token_end) {
3332
    // We just grab the number here. We validate the size in DecodeNumber.
3333
    // According to RFC4627, a valid number is: [minus] int [frac] [exp]
3334
    if (start == end)
3335
      return false;
3336
    Char c = *start;
3337
    if ('-' == c)
3338
      ++start;
3339
3340
    if (!ReadInt(start, end, &start, /*allow_leading_zeros=*/false))
3341
      return false;
3342
    if (start == end) {
3343
      *token_end = start;
3344
      return true;
3345
    }
3346
3347
    // Optional fraction part
3348
    c = *start;
3349
    if ('.' == c) {
3350
      ++start;
3351
      if (!ReadInt(start, end, &start, /*allow_leading_zeros=*/true))
3352
        return false;
3353
      if (start == end) {
3354
        *token_end = start;
3355
        return true;
3356
      }
3357
      c = *start;
3358
    }
3359
3360
    // Optional exponent part
3361
    if ('e' == c || 'E' == c) {
3362
      ++start;
3363
      if (start == end)
3364
        return false;
3365
      c = *start;
3366
      if ('-' == c || '+' == c) {
3367
        ++start;
3368
        if (start == end)
3369
          return false;
3370
      }
3371
      if (!ReadInt(start, end, &start, /*allow_leading_zeros=*/true))
3372
        return false;
3373
    }
3374
3375
    *token_end = start;
3376
    return true;
3377
  }
3378
3379
  static bool ReadHexDigits(const Char* start,
3380
                            const Char* end,
3381
                            const Char** token_end,
3382
                            int digits) {
3383
    if (end - start < digits)
3384
      return false;
3385
    for (int i = 0; i < digits; ++i) {
3386
      Char c = *start++;
3387
      if (!(('0' <= c && c <= '9') || ('a' <= c && c <= 'f') ||
3388
            ('A' <= c && c <= 'F')))
3389
        return false;
3390
    }
3391
    *token_end = start;
3392
    return true;
3393
  }
3394
3395
  static bool ParseStringToken(const Char* start,
3396
                               const Char* end,
3397
                               const Char** token_end) {
3398
    while (start < end) {
3399
      Char c = *start++;
3400
      if ('\\' == c) {
3401
        if (start == end)
3402
          return false;
3403
        c = *start++;
3404
        // Make sure the escaped char is valid.
3405
        switch (c) {
3406
          case 'x':
3407
            if (!ReadHexDigits(start, end, &start, 2))
3408
              return false;
3409
            break;
3410
          case 'u':
3411
            if (!ReadHexDigits(start, end, &start, 4))
3412
              return false;
3413
            break;
3414
          case '\\':
3415
          case '/':
3416
          case 'b':
3417
          case 'f':
3418
          case 'n':
3419
          case 'r':
3420
          case 't':
3421
          case 'v':
3422
          case '"':
3423
            break;
3424
          default:
3425
            return false;
3426
        }
3427
      } else if ('"' == c) {
3428
        *token_end = start;
3429
        return true;
3430
      }
3431
    }
3432
    return false;
3433
  }
3434
3435
  static bool SkipComment(const Char* start,
3436
                          const Char* end,
3437
                          const Char** comment_end) {
3438
    if (start == end)
3439
      return false;
3440
3441
    if (*start != '/' || start + 1 >= end)
3442
      return false;
3443
    ++start;
3444
3445
    if (*start == '/') {
3446
      // Single line comment, read to newline.
3447
      for (++start; start < end; ++start) {
3448
        if (*start == '\n' || *start == '\r') {
3449
          *comment_end = start + 1;
3450
          return true;
3451
        }
3452
      }
3453
      *comment_end = end;
3454
      // Comment reaches end-of-input, which is fine.
3455
      return true;
3456
    }
3457
3458
    if (*start == '*') {
3459
      Char previous = '\0';
3460
      // Block comment, read until end marker.
3461
      for (++start; start < end; previous = *start++) {
3462
        if (previous == '*' && *start == '/') {
3463
          *comment_end = start + 1;
3464
          return true;
3465
        }
3466
      }
3467
      // Block comment must close before end-of-input.
3468
      return false;
3469
    }
3470
3471
    return false;
3472
  }
3473
3474
  static bool IsSpaceOrNewLine(Char c) {
3475
    // \v = vertial tab; \f = form feed page break.
3476
    return c == ' ' || c == '\n' || c == '\v' || c == '\f' || c == '\r' ||
3477
           c == '\t';
3478
  }
3479
3480
  static void SkipWhitespaceAndComments(const Char* start,
3481
                                        const Char* end,
3482
                                        const Char** whitespace_end) {
3483
    while (start < end) {
3484
      if (IsSpaceOrNewLine(*start)) {
3485
        ++start;
3486
      } else if (*start == '/') {
3487
        const Char* comment_end = nullptr;
3488
        if (!SkipComment(start, end, &comment_end))
3489
          break;
3490
        start = comment_end;
3491
      } else {
3492
        break;
3493
      }
3494
    }
3495
    *whitespace_end = start;
3496
  }
3497
3498
  static Token ParseToken(const Char* start,
3499
                          const Char* end,
3500
                          const Char** tokenStart,
3501
                          const Char** token_end) {
3502
    SkipWhitespaceAndComments(start, end, tokenStart);
3503
    start = *tokenStart;
3504
3505
    if (start == end)
3506
      return NoInput;
3507
3508
    switch (*start) {
3509
      case 'n':
3510
        if (ParseConstToken(start, end, token_end, kNullString))
3511
          return NullToken;
3512
        break;
3513
      case 't':
3514
        if (ParseConstToken(start, end, token_end, kTrueString))
3515
          return BoolTrue;
3516
        break;
3517
      case 'f':
3518
        if (ParseConstToken(start, end, token_end, kFalseString))
3519
          return BoolFalse;
3520
        break;
3521
      case '[':
3522
        *token_end = start + 1;
3523
        return ArrayBegin;
3524
      case ']':
3525
        *token_end = start + 1;
3526
        return ArrayEnd;
3527
      case ',':
3528
        *token_end = start + 1;
3529
        return ListSeparator;
3530
      case '{':
3531
        *token_end = start + 1;
3532
        return ObjectBegin;
3533
      case '}':
3534
        *token_end = start + 1;
3535
        return ObjectEnd;
3536
      case ':':
3537
        *token_end = start + 1;
3538
        return ObjectPairSeparator;
3539
      case '0':
3540
      case '1':
3541
      case '2':
3542
      case '3':
3543
      case '4':
3544
      case '5':
3545
      case '6':
3546
      case '7':
3547
      case '8':
3548
      case '9':
3549
      case '-':
3550
        if (ParseNumberToken(start, end, token_end))
3551
          return Number;
3552
        break;
3553
      case '"':
3554
        if (ParseStringToken(start + 1, end, token_end))
3555
          return StringLiteral;
3556
        break;
3557
    }
3558
    return InvalidToken;
3559
  }
3560
3561
  static int HexToInt(Char c) {
3562
    if ('0' <= c && c <= '9')
3563
      return c - '0';
3564
    if ('A' <= c && c <= 'F')
3565
      return c - 'A' + 10;
3566
    if ('a' <= c && c <= 'f')
3567
      return c - 'a' + 10;
3568
    assert(false);  // Unreachable.
3569
    return 0;
3570
  }
3571
3572
  static bool DecodeString(const Char* start,
3573
                           const Char* end,
3574
                           std::vector<uint16_t>* output) {
3575
    if (start == end)
3576
      return true;
3577
    if (start > end)
3578
      return false;
3579
    output->reserve(end - start);
3580
    while (start < end) {
3581
      uint16_t c = *start++;
3582
      // If the |Char| we're dealing with is really a byte, then
3583
      // we have utf8 here, and we need to check for multibyte characters
3584
      // and transcode them to utf16 (either one or two utf16 chars).
3585
      if (sizeof(Char) == sizeof(uint8_t) && c >= 0x7f) {
3586
        // Inspect the leading byte to figure out how long the utf8
3587
        // byte sequence is; while doing this initialize |codepoint|
3588
        // with the first few bits.
3589
        // See table in: https://en.wikipedia.org/wiki/UTF-8
3590
        // byte one is 110x xxxx -> 2 byte utf8 sequence
3591
        // byte one is 1110 xxxx -> 3 byte utf8 sequence
3592
        // byte one is 1111 0xxx -> 4 byte utf8 sequence
3593
        uint32_t codepoint;
3594
        int num_bytes_left;
3595
        if ((c & 0xe0) == 0xc0) {  // 2 byte utf8 sequence
3596
          num_bytes_left = 1;
3597
          codepoint = c & 0x1f;
3598
        } else if ((c & 0xf0) == 0xe0) {  // 3 byte utf8 sequence
3599
          num_bytes_left = 2;
3600
          codepoint = c & 0x0f;
3601
        } else if ((c & 0xf8) == 0xf0) {  // 4 byte utf8 sequence
3602
          codepoint = c & 0x07;
3603
          num_bytes_left = 3;
3604
        } else {
3605
          return false;  // invalid leading byte
3606
        }
3607
3608
        // If we have enough bytes in our inpput, decode the remaining ones
3609
        // belonging to this Unicode character into |codepoint|.
3610
        if (start + num_bytes_left > end)
3611
          return false;
3612
        while (num_bytes_left > 0) {
3613
          c = *start++;
3614
          --num_bytes_left;
3615
          // Check the next byte is a continuation byte, that is 10xx xxxx.
3616
          if ((c & 0xc0) != 0x80)