GCC Code Coverage Report
Directory: ../ Exec Total Coverage
File: /home/iojs/build/workspace/node-test-commit-linux-coverage-daily/nodes/benchmark/out/../src/string_decoder.cc Lines: 134 140 95.7 %
Date: 2019-09-24 22:36:24 Branches: 91 112 81.3 %

Line Branch Exec Source
1
#include "string_decoder.h"  // NOLINT(build/include_inline)
2
#include "string_decoder-inl.h"
3
4
#include "env-inl.h"
5
#include "node_buffer.h"
6
#include "string_bytes.h"
7
#include "util.h"
8
9
using v8::Array;
10
using v8::ArrayBufferView;
11
using v8::Context;
12
using v8::FunctionCallbackInfo;
13
using v8::Integer;
14
using v8::Isolate;
15
using v8::Local;
16
using v8::MaybeLocal;
17
using v8::Object;
18
using v8::String;
19
using v8::Value;
20
21
namespace node {
22
23
namespace {
24
25
80972
MaybeLocal<String> MakeString(Isolate* isolate,
26
                              const char* data,
27
                              size_t length,
28
                              enum encoding encoding) {
29
  Local<Value> error;
30
  MaybeLocal<Value> ret;
31
80972
  if (encoding == UTF8) {
32
    return String::NewFromUtf8(
33
        isolate,
34
        data,
35
        v8::NewStringType::kNormal,
36
70812
        length);
37
  } else {
38
    ret = StringBytes::Encode(
39
        isolate,
40
        data,
41
        length,
42
        encoding,
43
10160
        &error);
44
  }
45
46
10160
  if (ret.IsEmpty()) {
47
    CHECK(!error.IsEmpty());
48
    isolate->ThrowException(error);
49
  }
50
51
  DCHECK(ret.IsEmpty() || ret.ToLocalChecked()->IsString());
52
20320
  return ret.FromMaybe(Local<Value>()).As<String>();
53
}
54
55
}  // anonymous namespace
56
57
58
82275
MaybeLocal<String> StringDecoder::DecodeData(Isolate* isolate,
59
                                             const char* data,
60
                                             size_t* nread_ptr) {
61
  Local<String> prepend, body;
62
63
82275
  size_t nread = *nread_ptr;
64
65


82275
  if (Encoding() == UTF8 || Encoding() == UCS2 || Encoding() == BASE64) {
66
    // See if we want bytes to finish a character from the previous
67
    // chunk; if so, copy the new bytes to the missing bytes buffer
68
    // and create a small string from it that is to be prepended to the
69
    // main body.
70
75677
    if (MissingBytes() > 0) {
71
      // There are never more bytes missing than the pre-calculated maximum.
72
3380
      CHECK_LE(MissingBytes() + BufferedBytes(),
73
               kIncompleteCharactersEnd);
74
3380
      if (Encoding() == UTF8) {
75
        // For UTF-8, we need special treatment to align with the V8 decoder:
76
        // If an incomplete character is found at a chunk boundary, we use
77
        // its remainder and pass it to V8 as-is.
78

3306
        for (size_t i = 0; i < nread && i < MissingBytes(); ++i) {
79
1864
          if ((data[i] & 0xC0) != 0x80) {
80
            // This byte is not a continuation byte even though it should have
81
            // been one. We stop decoding of the incomplete character at this
82
            // point (but still use the rest of the incomplete bytes from this
83
            // chunk) and assume that the new, unexpected byte starts a new one.
84
123
            state_[kMissingBytes] = 0;
85
123
            memcpy(IncompleteCharacterBuffer() + BufferedBytes(), data, i);
86
123
            state_[kBufferedBytes] += i;
87
123
            data += i;
88
123
            nread -= i;
89
123
            break;
90
          }
91
        }
92
      }
93
94
      size_t found_bytes =
95
3380
          std::min(nread, static_cast<size_t>(MissingBytes()));
96
6760
      memcpy(IncompleteCharacterBuffer() + BufferedBytes(),
97
             data,
98
6760
             found_bytes);
99
      // Adjust the two buffers.
100
3380
      data += found_bytes;
101
3380
      nread -= found_bytes;
102
103
3380
      state_[kMissingBytes] -= found_bytes;
104
3380
      state_[kBufferedBytes] += found_bytes;
105
106
3380
      if (LIKELY(MissingBytes() == 0)) {
107
        // If no more bytes are missing, create a small string that we
108
        // will later prepend.
109
6060
        if (!MakeString(isolate,
110
3030
                        IncompleteCharacterBuffer(),
111
3030
                        BufferedBytes(),
112
15150
                        Encoding()).ToLocal(&prepend)) {
113
          return MaybeLocal<String>();
114
        }
115
116
3030
        *nread_ptr += BufferedBytes();
117
        // No more buffered bytes.
118
3030
        state_[kBufferedBytes] = 0;
119
      }
120
    }
121
122
    // It could be that trying to finish the previous chunk already
123
    // consumed all data that we received in this chunk.
124
75677
    if (UNLIKELY(nread == 0)) {
125
3074
      body = !prepend.IsEmpty() ? prepend : String::Empty(isolate);
126
2412
      prepend = Local<String>();
127
    } else {
128
      // If not, that means is no character left to finish at this point.
129
      DCHECK_EQ(MissingBytes(), 0);
130
      DCHECK_EQ(BufferedBytes(), 0);
131
132
      // See whether there is a character that we may have to cut off and
133
      // finish when receiving the next chunk.
134

73265
      if (Encoding() == UTF8 && data[nread - 1] & 0x80) {
135
        // This is UTF-8 encoded data and we ended on a non-ASCII UTF-8 byte.
136
        // This means we'll need to figure out where the character to which
137
        // the byte belongs begins.
138
2828
        for (size_t i = nread - 1; ; --i) {
139
          DCHECK_LT(i, nread);
140
2828
          state_[kBufferedBytes]++;
141
2828
          if ((data[i] & 0xC0) == 0x80) {
142
            // This byte does not start a character (a "trailing" byte).
143

1054
            if (state_[kBufferedBytes] >= 4 || i == 0) {
144
              // We either have more then 4 trailing bytes (which means
145
              // the current character would not be inside the range for
146
              // valid Unicode, and in particular cannot be represented
147
              // through JavaScript's UTF-16-based approach to strings), or the
148
              // current buffer does not contain the start of an UTF-8 character
149
              // at all. Either way, this is invalid UTF8 and we can just
150
              // let the engine's decoder handle it.
151
47
              state_[kBufferedBytes] = 0;
152
47
              break;
153
            }
154
          } else {
155
            // Found the first byte of a UTF-8 character. By looking at the
156
            // upper bits we can tell how long the character *should* be.
157
1774
            if ((data[i] & 0xE0) == 0xC0) {
158
526
              state_[kMissingBytes] = 2;
159
1248
            } else if ((data[i] & 0xF0) == 0xE0) {
160
1123
              state_[kMissingBytes] = 3;
161
125
            } else if ((data[i] & 0xF8) == 0xF0) {
162
46
              state_[kMissingBytes] = 4;
163
            } else {
164
              // This lead byte would indicate a character outside of the
165
              // representable range.
166
79
              state_[kBufferedBytes] = 0;
167
79
              break;
168
            }
169
170
1695
            if (BufferedBytes() >= MissingBytes()) {
171
              // Received more or exactly as many trailing bytes than the lead
172
              // character would indicate. In the "==" case, we have valid
173
              // data and don't need to slice anything off;
174
              // in the ">" case, this is invalid UTF-8 anyway.
175
381
              state_[kMissingBytes] = 0;
176
381
              state_[kBufferedBytes] = 0;
177
            }
178
179
1695
            state_[kMissingBytes] -= state_[kBufferedBytes];
180
1695
            break;
181
          }
182
1007
        }
183
71444
      } else if (Encoding() == UCS2) {
184
2575
        if ((nread % 2) == 1) {
185
          // We got half a codepoint, and need the second byte of it.
186
1620
          state_[kBufferedBytes] = 1;
187
1620
          state_[kMissingBytes] = 1;
188
955
        } else if ((data[nread - 1] & 0xFC) == 0xD8) {
189
          // Half a split UTF-16 character.
190
10
          state_[kBufferedBytes] = 2;
191
10
          state_[kMissingBytes] = 2;
192
        }
193
68869
      } else if (Encoding() == BASE64) {
194
425
        state_[kBufferedBytes] = nread % 3;
195
425
        if (state_[kBufferedBytes] > 0)
196
298
          state_[kMissingBytes] = 3 - BufferedBytes();
197
      }
198
199
73265
      if (BufferedBytes() > 0) {
200
        // Copy the requested number of buffered bytes from the end of the
201
        // input into the incomplete character buffer.
202
3242
        nread -= BufferedBytes();
203
3242
        *nread_ptr -= BufferedBytes();
204
3242
        memcpy(IncompleteCharacterBuffer(), data + nread, BufferedBytes());
205
      }
206
207
73265
      if (nread > 0) {
208
142418
        if (!MakeString(isolate, data, nread, Encoding()).ToLocal(&body))
209
          return MaybeLocal<String>();
210
      } else {
211
2056
        body = String::Empty(isolate);
212
      }
213
    }
214
215
75677
    if (prepend.IsEmpty()) {
216
74397
      return body;
217
    } else {
218
2560
      return String::Concat(isolate, prepend, body);
219
    }
220
  } else {
221


6598
    CHECK(Encoding() == ASCII || Encoding() == HEX || Encoding() == LATIN1);
222
6598
    return MakeString(isolate, data, nread, Encoding());
223
  }
224
}
225
226
212
MaybeLocal<String> StringDecoder::FlushData(Isolate* isolate) {
227


212
  if (Encoding() == ASCII || Encoding() == HEX || Encoding() == LATIN1) {
228
    CHECK_EQ(MissingBytes(), 0);
229
    CHECK_EQ(BufferedBytes(), 0);
230
  }
231
232

212
  if (Encoding() == UCS2 && BufferedBytes() % 2 == 1) {
233
    // Ignore a single trailing byte, like the JS decoder does.
234
78
    state_[kMissingBytes]--;
235
78
    state_[kBufferedBytes]--;
236
  }
237
238
212
  if (BufferedBytes() == 0)
239
77
    return String::Empty(isolate);
240
241
  MaybeLocal<String> ret =
242
      MakeString(isolate,
243
135
                 IncompleteCharacterBuffer(),
244
135
                 BufferedBytes(),
245
405
                 Encoding());
246
247
135
  state_[kMissingBytes] = 0;
248
135
  state_[kBufferedBytes] = 0;
249
250
135
  return ret;
251
}
252
253
namespace {
254
255
82275
void DecodeData(const FunctionCallbackInfo<Value>& args) {
256
  StringDecoder* decoder =
257
82275
      reinterpret_cast<StringDecoder*>(Buffer::Data(args[0]));
258
82275
  CHECK_NOT_NULL(decoder);
259
260
164550
  CHECK(args[1]->IsArrayBufferView());
261
164550
  ArrayBufferViewContents<char> content(args[1].As<ArrayBufferView>());
262
82275
  size_t length = content.length();
263
264
  MaybeLocal<String> ret =
265
164550
      decoder->DecodeData(args.GetIsolate(), content.data(), &length);
266
82275
  if (!ret.IsEmpty())
267
164550
    args.GetReturnValue().Set(ret.ToLocalChecked());
268
82275
}
269
270
212
void FlushData(const FunctionCallbackInfo<Value>& args) {
271
  StringDecoder* decoder =
272
212
      reinterpret_cast<StringDecoder*>(Buffer::Data(args[0]));
273
212
  CHECK_NOT_NULL(decoder);
274
212
  MaybeLocal<String> ret = decoder->FlushData(args.GetIsolate());
275
212
  if (!ret.IsEmpty())
276
424
    args.GetReturnValue().Set(ret.ToLocalChecked());
277
212
}
278
279
5103
void InitializeStringDecoder(Local<Object> target,
280
                             Local<Value> unused,
281
                             Local<Context> context,
282
                             void* priv) {
283
5103
  Environment* env = Environment::GetCurrent(context);
284
5103
  Isolate* isolate = env->isolate();
285
286
#define SET_DECODER_CONSTANT(name)                                            \
287
  target->Set(context,                                                        \
288
              FIXED_ONE_BYTE_STRING(isolate, #name),                          \
289
              Integer::New(isolate, StringDecoder::name)).FromJust()
290
291
20412
  SET_DECODER_CONSTANT(kIncompleteCharactersStart);
292
20412
  SET_DECODER_CONSTANT(kIncompleteCharactersEnd);
293
20412
  SET_DECODER_CONSTANT(kMissingBytes);
294
20412
  SET_DECODER_CONSTANT(kBufferedBytes);
295
20412
  SET_DECODER_CONSTANT(kEncodingField);
296
20412
  SET_DECODER_CONSTANT(kNumFields);
297
298
5103
  Local<Array> encodings = Array::New(isolate);
299
#define ADD_TO_ENCODINGS_ARRAY(cname, jsname)                                 \
300
  encodings->Set(context,                                                     \
301
                 static_cast<int32_t>(cname),                                 \
302
                 FIXED_ONE_BYTE_STRING(isolate, jsname)).FromJust()
303
15309
  ADD_TO_ENCODINGS_ARRAY(ASCII, "ascii");
304
15309
  ADD_TO_ENCODINGS_ARRAY(UTF8, "utf8");
305
15309
  ADD_TO_ENCODINGS_ARRAY(BASE64, "base64");
306
15309
  ADD_TO_ENCODINGS_ARRAY(UCS2, "utf16le");
307
15309
  ADD_TO_ENCODINGS_ARRAY(HEX, "hex");
308
15309
  ADD_TO_ENCODINGS_ARRAY(BUFFER, "buffer");
309
15309
  ADD_TO_ENCODINGS_ARRAY(LATIN1, "latin1");
310
311
  target->Set(context,
312
              FIXED_ONE_BYTE_STRING(isolate, "encodings"),
313
15309
              encodings).Check();
314
315
  target->Set(context,
316
              FIXED_ONE_BYTE_STRING(isolate, "kSize"),
317
20412
              Integer::New(isolate, sizeof(StringDecoder))).Check();
318
319
5103
  env->SetMethod(target, "decode", DecodeData);
320
5103
  env->SetMethod(target, "flush", FlushData);
321
5103
}
322
323
}  // anonymous namespace
324
325
}  // namespace node
326
327
4957
NODE_MODULE_CONTEXT_AWARE_INTERNAL(string_decoder,
328
                                   node::InitializeStringDecoder)