LCOV - code coverage report
Current view: top level - src - json-stringifier.cc (source / functions) Hit Total Coverage
Test: app.info Lines: 280 285 98.2 %
Date: 2017-10-20 Functions: 20 20 100.0 %

          Line data    Source code
       1             : // Copyright 2016 the V8 project authors. All rights reserved.
       2             : // Use of this source code is governed by a BSD-style license that can be
       3             : // found in the LICENSE file.
       4             : 
       5             : #include "src/json-stringifier.h"
       6             : 
       7             : #include "src/conversions.h"
       8             : #include "src/lookup.h"
       9             : #include "src/messages.h"
      10             : #include "src/objects-inl.h"
      11             : #include "src/utils.h"
      12             : 
      13             : namespace v8 {
      14             : namespace internal {
      15             : 
      16             : // Translation table to escape Latin1 characters.
      17             : // Table entries start at a multiple of 8 and are null-terminated.
      18             : const char* const JsonStringifier::JsonEscapeTable =
      19             :     "\\u0000\0 \\u0001\0 \\u0002\0 \\u0003\0 "
      20             :     "\\u0004\0 \\u0005\0 \\u0006\0 \\u0007\0 "
      21             :     "\\b\0     \\t\0     \\n\0     \\u000b\0 "
      22             :     "\\f\0     \\r\0     \\u000e\0 \\u000f\0 "
      23             :     "\\u0010\0 \\u0011\0 \\u0012\0 \\u0013\0 "
      24             :     "\\u0014\0 \\u0015\0 \\u0016\0 \\u0017\0 "
      25             :     "\\u0018\0 \\u0019\0 \\u001a\0 \\u001b\0 "
      26             :     "\\u001c\0 \\u001d\0 \\u001e\0 \\u001f\0 "
      27             :     " \0      !\0      \\\"\0     #\0      "
      28             :     "$\0      %\0      &\0      '\0      "
      29             :     "(\0      )\0      *\0      +\0      "
      30             :     ",\0      -\0      .\0      /\0      "
      31             :     "0\0      1\0      2\0      3\0      "
      32             :     "4\0      5\0      6\0      7\0      "
      33             :     "8\0      9\0      :\0      ;\0      "
      34             :     "<\0      =\0      >\0      ?\0      "
      35             :     "@\0      A\0      B\0      C\0      "
      36             :     "D\0      E\0      F\0      G\0      "
      37             :     "H\0      I\0      J\0      K\0      "
      38             :     "L\0      M\0      N\0      O\0      "
      39             :     "P\0      Q\0      R\0      S\0      "
      40             :     "T\0      U\0      V\0      W\0      "
      41             :     "X\0      Y\0      Z\0      [\0      "
      42             :     "\\\\\0     ]\0      ^\0      _\0      "
      43             :     "`\0      a\0      b\0      c\0      "
      44             :     "d\0      e\0      f\0      g\0      "
      45             :     "h\0      i\0      j\0      k\0      "
      46             :     "l\0      m\0      n\0      o\0      "
      47             :     "p\0      q\0      r\0      s\0      "
      48             :     "t\0      u\0      v\0      w\0      "
      49             :     "x\0      y\0      z\0      {\0      "
      50             :     "|\0      }\0      ~\0      \177\0      "
      51             :     "\200\0      \201\0      \202\0      \203\0      "
      52             :     "\204\0      \205\0      \206\0      \207\0      "
      53             :     "\210\0      \211\0      \212\0      \213\0      "
      54             :     "\214\0      \215\0      \216\0      \217\0      "
      55             :     "\220\0      \221\0      \222\0      \223\0      "
      56             :     "\224\0      \225\0      \226\0      \227\0      "
      57             :     "\230\0      \231\0      \232\0      \233\0      "
      58             :     "\234\0      \235\0      \236\0      \237\0      "
      59             :     "\240\0      \241\0      \242\0      \243\0      "
      60             :     "\244\0      \245\0      \246\0      \247\0      "
      61             :     "\250\0      \251\0      \252\0      \253\0      "
      62             :     "\254\0      \255\0      \256\0      \257\0      "
      63             :     "\260\0      \261\0      \262\0      \263\0      "
      64             :     "\264\0      \265\0      \266\0      \267\0      "
      65             :     "\270\0      \271\0      \272\0      \273\0      "
      66             :     "\274\0      \275\0      \276\0      \277\0      "
      67             :     "\300\0      \301\0      \302\0      \303\0      "
      68             :     "\304\0      \305\0      \306\0      \307\0      "
      69             :     "\310\0      \311\0      \312\0      \313\0      "
      70             :     "\314\0      \315\0      \316\0      \317\0      "
      71             :     "\320\0      \321\0      \322\0      \323\0      "
      72             :     "\324\0      \325\0      \326\0      \327\0      "
      73             :     "\330\0      \331\0      \332\0      \333\0      "
      74             :     "\334\0      \335\0      \336\0      \337\0      "
      75             :     "\340\0      \341\0      \342\0      \343\0      "
      76             :     "\344\0      \345\0      \346\0      \347\0      "
      77             :     "\350\0      \351\0      \352\0      \353\0      "
      78             :     "\354\0      \355\0      \356\0      \357\0      "
      79             :     "\360\0      \361\0      \362\0      \363\0      "
      80             :     "\364\0      \365\0      \366\0      \367\0      "
      81             :     "\370\0      \371\0      \372\0      \373\0      "
      82             :     "\374\0      \375\0      \376\0      \377\0      ";
      83             : 
      84     2321620 : JsonStringifier::JsonStringifier(Isolate* isolate)
      85     2321620 :     : isolate_(isolate), builder_(isolate), gap_(nullptr), indent_(0) {
      86     1160810 :   tojson_string_ = factory()->toJSON_string();
      87     1160810 :   stack_ = factory()->NewJSArray(8);
      88     1160810 : }
      89             : 
      90     1160810 : MaybeHandle<Object> JsonStringifier::Stringify(Handle<Object> object,
      91             :                                                Handle<Object> replacer,
      92         283 :                                                Handle<Object> gap) {
      93     1160810 :   if (!InitializeReplacer(replacer)) return MaybeHandle<Object>();
      94     2321602 :   if (!gap->IsUndefined(isolate_) && !InitializeGap(gap)) {
      95           0 :     return MaybeHandle<Object>();
      96             :   }
      97             :   Result result = SerializeObject(object);
      98     1161084 :   if (result == UNCHANGED) return factory()->undefined_value();
      99     1160518 :   if (result == SUCCESS) return builder_.Finish();
     100             :   DCHECK(result == EXCEPTION);
     101         185 :   return MaybeHandle<Object>();
     102             : }
     103             : 
     104     1161673 : bool JsonStringifier::InitializeReplacer(Handle<Object> replacer) {
     105             :   DCHECK(property_list_.is_null());
     106             :   DCHECK(replacer_function_.is_null());
     107             :   Maybe<bool> is_array = Object::IsArray(replacer);
     108     1160810 :   if (is_array.IsNothing()) return false;
     109     1160810 :   if (is_array.FromJust()) {
     110         316 :     HandleScope handle_scope(isolate_);
     111         316 :     Handle<OrderedHashSet> set = factory()->NewOrderedHashSet();
     112             :     Handle<Object> length_obj;
     113         632 :     ASSIGN_RETURN_ON_EXCEPTION_VALUE(
     114             :         isolate_, length_obj,
     115             :         Object::GetLengthFromArrayLike(isolate_, replacer), false);
     116             :     uint32_t length;
     117         307 :     if (!length_obj->ToUint32(&length)) length = kMaxUInt32;
     118         986 :     for (uint32_t i = 0; i < length; i++) {
     119             :       Handle<Object> element;
     120             :       Handle<String> key;
     121        1972 :       ASSIGN_RETURN_ON_EXCEPTION_VALUE(
     122             :           isolate_, element, Object::GetElement(isolate_, replacer, i), false);
     123        1784 :       if (element->IsNumber() || element->IsString()) {
     124        1034 :         ASSIGN_RETURN_ON_EXCEPTION_VALUE(
     125             :             isolate_, key, Object::ToString(isolate_, element), false);
     126         469 :       } else if (element->IsJSValue()) {
     127          30 :         Handle<Object> value(Handle<JSValue>::cast(element)->value(), isolate_);
     128          40 :         if (value->IsNumber() || value->IsString()) {
     129          60 :           ASSIGN_RETURN_ON_EXCEPTION_VALUE(
     130             :               isolate_, key, Object::ToString(isolate_, element), false);
     131             :         }
     132             :       }
     133         986 :       if (key.is_null()) continue;
     134             :       // Object keys are internalized, so do it here.
     135         547 :       key = factory()->InternalizeString(key);
     136         547 :       set = OrderedHashSet::Add(set, key);
     137             :     }
     138             :     property_list_ = OrderedHashSet::ConvertToKeysArray(
     139         307 :         set, GetKeysConversion::kKeepNumbers);
     140         307 :     property_list_ = handle_scope.CloseAndEscape(property_list_);
     141     1160494 :   } else if (replacer->IsCallable()) {
     142        1736 :     replacer_function_ = Handle<JSReceiver>::cast(replacer);
     143             :   }
     144             :   return true;
     145             : }
     146             : 
     147      201756 : bool JsonStringifier::InitializeGap(Handle<Object> gap) {
     148             :   DCHECK_NULL(gap_);
     149      201756 :   HandleScope scope(isolate_);
     150      201756 :   if (gap->IsJSValue()) {
     151          30 :     Handle<Object> value(Handle<JSValue>::cast(gap)->value(), isolate_);
     152          30 :     if (value->IsString()) {
     153          40 :       ASSIGN_RETURN_ON_EXCEPTION_VALUE(isolate_, gap,
     154             :                                        Object::ToString(isolate_, gap), false);
     155          10 :     } else if (value->IsNumber()) {
     156          20 :       ASSIGN_RETURN_ON_EXCEPTION_VALUE(isolate_, gap, Object::ToNumber(gap),
     157             :                                        false);
     158             :     }
     159             :   }
     160             : 
     161      201756 :   if (gap->IsString()) {
     162             :     Handle<String> gap_string = Handle<String>::cast(gap);
     163        1507 :     if (gap_string->length() > 0) {
     164        4467 :       int gap_length = std::min(gap_string->length(), 10);
     165        1489 :       gap_ = NewArray<uc16>(gap_length + 1);
     166        1489 :       String::WriteToFlat(*gap_string, gap_, 0, gap_length);
     167        3073 :       for (int i = 0; i < gap_length; i++) {
     168        1594 :         if (gap_[i] > String::kMaxOneByteCharCode) {
     169          10 :           builder_.ChangeEncoding();
     170             :           break;
     171             :         }
     172             :       }
     173        1489 :       gap_[gap_length] = '\0';
     174             :     }
     175      200249 :   } else if (gap->IsNumber()) {
     176      200239 :     int num_value = DoubleToInt32(gap->Number());
     177      200239 :     if (num_value > 0) {
     178         220 :       int gap_length = std::min(num_value, 10);
     179         110 :       gap_ = NewArray<uc16>(gap_length + 1);
     180         110 :       for (int i = 0; i < gap_length; i++) gap_[i] = ' ';
     181         110 :       gap_[gap_length] = '\0';
     182             :     }
     183             :   }
     184             :   return true;
     185             : }
     186             : 
     187      390762 : MaybeHandle<Object> JsonStringifier::ApplyToJsonFunction(Handle<Object> object,
     188         246 :                                                          Handle<Object> key) {
     189      390762 :   HandleScope scope(isolate_);
     190             :   LookupIterator it(object, tojson_string_,
     191      390762 :                     LookupIterator::PROTOTYPE_CHAIN_SKIP_INTERCEPTOR);
     192             :   Handle<Object> fun;
     193      781524 :   ASSIGN_RETURN_ON_EXCEPTION(isolate_, fun, Object::GetProperty(&it), Object);
     194      390717 :   if (!fun->IsCallable()) return object;
     195             : 
     196             :   // Call toJSON function.
     197        1103 :   if (key->IsSmi()) key = factory()->NumberToString(key);
     198         857 :   Handle<Object> argv[] = {key};
     199        1714 :   ASSIGN_RETURN_ON_EXCEPTION(isolate_, object,
     200             :                              Execution::Call(isolate_, fun, object, 1, argv),
     201             :                              Object);
     202         837 :   return scope.CloseAndEscape(object);
     203             : }
     204             : 
     205     5447632 : MaybeHandle<Object> JsonStringifier::ApplyReplacerFunction(
     206     5444458 :     Handle<Object> value, Handle<Object> key, Handle<Object> initial_holder) {
     207     5447632 :   HandleScope scope(isolate_);
     208    10892090 :   if (key->IsSmi()) key = factory()->NumberToString(key);
     209     5447632 :   Handle<Object> argv[] = {key, value};
     210     5447632 :   Handle<JSReceiver> holder = CurrentHolder(value, initial_holder);
     211    10895264 :   ASSIGN_RETURN_ON_EXCEPTION(
     212             :       isolate_, value,
     213             :       Execution::Call(isolate_, replacer_function_, holder, 2, argv), Object);
     214     5447632 :   return scope.CloseAndEscape(value);
     215             : }
     216             : 
     217     5447632 : Handle<JSReceiver> JsonStringifier::CurrentHolder(
     218        3472 :     Handle<Object> value, Handle<Object> initial_holder) {
     219             :   int length = Smi::ToInt(stack_->length());
     220     5447632 :   if (length == 0) {
     221             :     Handle<JSObject> holder =
     222        3472 :         factory()->NewJSObject(isolate_->object_function());
     223             :     JSObject::AddProperty(holder, factory()->empty_string(), initial_holder,
     224        1736 :                           NONE);
     225        1736 :     return holder;
     226             :   } else {
     227             :     FixedArray* elements = FixedArray::cast(stack_->elements());
     228             :     return Handle<JSReceiver>(JSReceiver::cast(elements->get(length - 1)),
     229    10891792 :                               isolate_);
     230             :   }
     231             : }
     232             : 
     233      387153 : JsonStringifier::Result JsonStringifier::StackPush(Handle<Object> object) {
     234      387087 :   StackLimitCheck check(isolate_);
     235      387087 :   if (check.HasOverflowed()) {
     236          20 :     isolate_->StackOverflow();
     237          20 :     return EXCEPTION;
     238             :   }
     239             : 
     240             :   int length = Smi::ToInt(stack_->length());
     241             :   {
     242             :     DisallowHeapAllocation no_allocation;
     243             :     FixedArray* elements = FixedArray::cast(stack_->elements());
     244     4598665 :     for (int i = 0; i < length; i++) {
     245     4211664 :       if (elements->get(i) == *object) {
     246             :         AllowHeapAllocation allow_to_return_error;
     247             :         Handle<Object> error =
     248          66 :             factory()->NewTypeError(MessageTemplate::kCircularStructure);
     249          66 :         isolate_->Throw(*error);
     250             :         return EXCEPTION;
     251             :       }
     252             :     }
     253             :   }
     254      387001 :   JSArray::SetLength(stack_, length + 1);
     255      387001 :   FixedArray::cast(stack_->elements())->set(length, *object);
     256      387001 :   return SUCCESS;
     257             : }
     258             : 
     259      374104 : void JsonStringifier::StackPop() {
     260             :   int length = Smi::ToInt(stack_->length());
     261      374104 :   stack_->set_length(Smi::FromInt(length - 1));
     262      374104 : }
     263             : 
     264             : template <bool deferred_string_key>
     265    13077041 : JsonStringifier::Result JsonStringifier::Serialize_(Handle<Object> object,
     266             :                                                     bool comma,
     267             :                                                     Handle<Object> key) {
     268    13077041 :   StackLimitCheck interrupt_check(isolate_);
     269    13077041 :   Handle<Object> initial_value = object;
     270    13077146 :   if (interrupt_check.InterruptRequested() &&
     271         105 :       isolate_->stack_guard()->HandleInterrupts()->IsException(isolate_)) {
     272             :     return EXCEPTION;
     273             :   }
     274    13077040 :   if (object->IsJSReceiver()) {
     275      781524 :     ASSIGN_RETURN_ON_EXCEPTION_VALUE(
     276             :         isolate_, object, ApplyToJsonFunction(object, key), EXCEPTION);
     277             :   }
     278    13076975 :   if (!replacer_function_.is_null()) {
     279    10895264 :     ASSIGN_RETURN_ON_EXCEPTION_VALUE(
     280             :         isolate_, object, ApplyReplacerFunction(object, key, initial_value),
     281             :         EXCEPTION);
     282             :   }
     283             : 
     284    13076975 :   if (object->IsSmi()) {
     285             :     if (deferred_string_key) SerializeDeferredKey(comma, key);
     286      199446 :     return SerializeSmi(Smi::cast(*object));
     287             :   }
     288             : 
     289    13504631 :   switch (HeapObject::cast(*object)->map()->instance_type()) {
     290             :     case HEAP_NUMBER_TYPE:
     291             :     case MUTABLE_HEAP_NUMBER_TYPE:
     292             :       if (deferred_string_key) SerializeDeferredKey(comma, key);
     293        1034 :       return SerializeHeapNumber(Handle<HeapNumber>::cast(object));
     294             :     case ODDBALL_TYPE:
     295    10716330 :       switch (Oddball::cast(*object)->kind()) {
     296             :         case Oddball::kFalse:
     297             :           if (deferred_string_key) SerializeDeferredKey(comma, key);
     298          89 :           builder_.AppendCString("false");
     299             :           return SUCCESS;
     300             :         case Oddball::kTrue:
     301             :           if (deferred_string_key) SerializeDeferredKey(comma, key);
     302         162 :           builder_.AppendCString("true");
     303             :           return SUCCESS;
     304             :         case Oddball::kNull:
     305             :           if (deferred_string_key) SerializeDeferredKey(comma, key);
     306         179 :           builder_.AppendCString("null");
     307             :           return SUCCESS;
     308             :         default:
     309             :           return UNCHANGED;
     310             :       }
     311             :     case JS_ARRAY_TYPE:
     312             :       if (deferred_string_key) SerializeDeferredKey(comma, key);
     313       13155 :       return SerializeJSArray(Handle<JSArray>::cast(object));
     314             :     case JS_VALUE_TYPE:
     315             :       if (deferred_string_key) SerializeDeferredKey(comma, key);
     316         708 :       return SerializeJSValue(Handle<JSValue>::cast(object));
     317             :     case SYMBOL_TYPE:
     318             :       return UNCHANGED;
     319             :     default:
     320     2146266 :       if (object->IsString()) {
     321             :         if (deferred_string_key) SerializeDeferredKey(comma, key);
     322     1769975 :         SerializeString(Handle<String>::cast(object));
     323     1769975 :         return SUCCESS;
     324             :       } else {
     325             :         DCHECK(object->IsJSReceiver());
     326      376291 :         if (object->IsCallable()) return UNCHANGED;
     327             :         // Go to slow path for global proxy and objects requiring access checks.
     328             :         if (deferred_string_key) SerializeDeferredKey(comma, key);
     329      373824 :         if (object->IsJSProxy()) {
     330         405 :           return SerializeJSProxy(Handle<JSProxy>::cast(object));
     331             :         }
     332      373419 :         return SerializeJSObject(Handle<JSObject>::cast(object));
     333             :       }
     334             :   }
     335             : 
     336             :   UNREACHABLE();
     337             : }
     338             : 
     339         708 : JsonStringifier::Result JsonStringifier::SerializeJSValue(
     340             :     Handle<JSValue> object) {
     341         708 :   String* class_name = object->class_name();
     342         708 :   if (class_name == isolate_->heap()->String_string()) {
     343             :     Handle<Object> value;
     344         580 :     ASSIGN_RETURN_ON_EXCEPTION_VALUE(
     345             :         isolate_, value, Object::ToString(isolate_, object), EXCEPTION);
     346         290 :     SerializeString(Handle<String>::cast(value));
     347         418 :   } else if (class_name == isolate_->heap()->Number_string()) {
     348             :     Handle<Object> value;
     349         500 :     ASSIGN_RETURN_ON_EXCEPTION_VALUE(isolate_, value, Object::ToNumber(object),
     350             :                                      EXCEPTION);
     351         250 :     if (value->IsSmi()) return SerializeSmi(Smi::cast(*value));
     352             :     SerializeHeapNumber(Handle<HeapNumber>::cast(value));
     353         168 :   } else if (class_name == isolate_->heap()->Boolean_string()) {
     354             :     Object* value = JSValue::cast(*object)->value();
     355             :     DCHECK(value->IsBoolean());
     356          60 :     builder_.AppendCString(value->IsTrue(isolate_) ? "true" : "false");
     357             :   } else {
     358             :     // ES6 24.3.2.1 step 10.c, serialize as an ordinary JSObject.
     359             :     return SerializeJSObject(object);
     360             :   }
     361             :   return SUCCESS;
     362             : }
     363             : 
     364      203588 : JsonStringifier::Result JsonStringifier::SerializeSmi(Smi* object) {
     365             :   static const int kBufferSize = 100;
     366             :   char chars[kBufferSize];
     367             :   Vector<char> buffer(chars, kBufferSize);
     368      203588 :   builder_.AppendCString(IntToCString(object->value(), buffer));
     369      203588 :   return SUCCESS;
     370             : }
     371             : 
     372        1110 : JsonStringifier::Result JsonStringifier::SerializeDouble(double number) {
     373        1110 :   if (std::isinf(number) || std::isnan(number)) {
     374         178 :     builder_.AppendCString("null");
     375             :     return SUCCESS;
     376             :   }
     377             :   static const int kBufferSize = 100;
     378             :   char chars[kBufferSize];
     379             :   Vector<char> buffer(chars, kBufferSize);
     380         932 :   builder_.AppendCString(DoubleToCString(number, buffer));
     381             :   return SUCCESS;
     382             : }
     383             : 
     384             : JsonStringifier::Result JsonStringifier::SerializeJSArray(
     385             :     Handle<JSArray> object) {
     386       13155 :   HandleScope handle_scope(isolate_);
     387       13155 :   Result stack_push = StackPush(object);
     388       13155 :   if (stack_push != SUCCESS) return stack_push;
     389       13107 :   uint32_t length = 0;
     390       13107 :   CHECK(object->length()->ToArrayLength(&length));
     391             :   DCHECK(!object->IsAccessCheckNeeded());
     392        8966 :   builder_.AppendCharacter('[');
     393             :   Indent();
     394             :   uint32_t i = 0;
     395       13107 :   if (replacer_function_.is_null()) {
     396       12491 :     switch (object->GetElementsKind()) {
     397             :       case PACKED_SMI_ELEMENTS: {
     398         878 :         Handle<FixedArray> elements(FixedArray::cast(object->elements()),
     399         878 :                                     isolate_);
     400         878 :         StackLimitCheck interrupt_check(isolate_);
     401        4810 :         while (i < length) {
     402        3932 :           if (interrupt_check.InterruptRequested() &&
     403             :               isolate_->stack_guard()->HandleInterrupts()->IsException(
     404           0 :                   isolate_)) {
     405           0 :             return EXCEPTION;
     406             :           }
     407             :           Separator(i == 0);
     408        7864 :           SerializeSmi(Smi::cast(elements->get(i)));
     409        3932 :           i++;
     410             :         }
     411         878 :         break;
     412             :       }
     413             :       case PACKED_DOUBLE_ELEMENTS: {
     414             :         // Empty array is FixedArray but not FixedDoubleArray.
     415          22 :         if (length == 0) break;
     416             :         Handle<FixedDoubleArray> elements(
     417          24 :             FixedDoubleArray::cast(object->elements()), isolate_);
     418          12 :         StackLimitCheck interrupt_check(isolate_);
     419          48 :         while (i < length) {
     420          36 :           if (interrupt_check.InterruptRequested() &&
     421             :               isolate_->stack_guard()->HandleInterrupts()->IsException(
     422           0 :                   isolate_)) {
     423           0 :             return EXCEPTION;
     424             :           }
     425             :           Separator(i == 0);
     426          72 :           SerializeDouble(elements->get_scalar(i));
     427          36 :           i++;
     428             :         }
     429             :         break;
     430             :       }
     431             :       case PACKED_ELEMENTS: {
     432       22468 :         Handle<Object> old_length(object->length(), isolate_);
     433      422924 :         while (i < length) {
     434     1254460 :           if (object->length() != *old_length ||
     435      418120 :               object->GetElementsKind() != PACKED_ELEMENTS) {
     436             :             // Fall back to slow path.
     437             :             break;
     438             :           }
     439             :           Separator(i == 0);
     440             :           Result result = SerializeElement(
     441             :               isolate_,
     442      418100 :               Handle<Object>(FixedArray::cast(object->elements())->get(i),
     443             :                              isolate_),
     444     1254300 :               i);
     445      418100 :           if (result == UNCHANGED) {
     446             :             builder_.AppendCString("null");
     447      417986 :           } else if (result != SUCCESS) {
     448             :             return result;
     449             :           }
     450      411690 :           i++;
     451             :         }
     452             :         break;
     453             :       }
     454             :       // The FAST_HOLEY_* cases could be handled in a faster way. They resemble
     455             :       // the non-holey cases except that a lookup is necessary for holes.
     456             :       default:
     457             :         break;
     458             :     }
     459             :   }
     460        6697 :   if (i < length) {
     461             :     // Slow path for non-fast elements and fall-back in edge case.
     462         910 :     Result result = SerializeArrayLikeSlow(object, i, length);
     463         910 :     if (result != SUCCESS) return result;
     464             :   }
     465             :   Unindent();
     466        6655 :   if (length > 0) NewLine();
     467             :   builder_.AppendCharacter(']');
     468        6655 :   StackPop();
     469       13155 :   return SUCCESS;
     470             : }
     471             : 
     472         946 : JsonStringifier::Result JsonStringifier::SerializeArrayLikeSlow(
     473             :     Handle<JSReceiver> object, uint32_t start, uint32_t length) {
     474             :   // We need to write out at least two characters per array element.
     475             :   static const int kMaxSerializableArrayLength = String::kMaxLength / 2;
     476         946 :   if (length > kMaxSerializableArrayLength) {
     477          10 :     isolate_->Throw(*isolate_->factory()->NewInvalidStringLengthError());
     478           5 :     return EXCEPTION;
     479             :   }
     480    10688751 :   for (uint32_t i = start; i < length; i++) {
     481             :     Separator(i == 0);
     482             :     Handle<Object> element;
     483    21377576 :     ASSIGN_RETURN_ON_EXCEPTION_VALUE(
     484             :         isolate_, element, JSReceiver::GetElement(isolate_, object, i),
     485             :         EXCEPTION);
     486    10688778 :     Result result = SerializeElement(isolate_, element, i);
     487    10688778 :     if (result == SUCCESS) continue;
     488    10486341 :     if (result == UNCHANGED) {
     489             :       // Detect overflow sooner for large sparse arrays.
     490    10486314 :       if (builder_.HasOverflowed()) return EXCEPTION;
     491    10486314 :       builder_.AppendCString("null");
     492             :     } else {
     493             :       return result;
     494             :     }
     495             :   }
     496             :   return SUCCESS;
     497             : }
     498             : 
     499             : JsonStringifier::Result JsonStringifier::SerializeJSObject(
     500             :     Handle<JSObject> object) {
     501      373527 :   HandleScope handle_scope(isolate_);
     502      373527 :   Result stack_push = StackPush(object);
     503      373527 :   if (stack_push != SUCCESS) return stack_push;
     504             : 
     505      746680 :   if (property_list_.is_null() &&
     506      746233 :       object->map()->instance_type() > LAST_CUSTOM_ELEMENTS_RECEIVER &&
     507     1119256 :       object->HasFastProperties() &&
     508     1118939 :       Handle<JSObject>::cast(object)->elements()->length() == 0) {
     509             :     DCHECK(object->IsJSObject());
     510             :     DCHECK(!object->IsJSGlobalProxy());
     511      372591 :     Handle<JSObject> js_obj = Handle<JSObject>::cast(object);
     512             :     DCHECK(!js_obj->HasIndexedInterceptor());
     513             :     DCHECK(!js_obj->HasNamedInterceptor());
     514      372591 :     Handle<Map> map(js_obj->map());
     515      255703 :     builder_.AppendCharacter('{');
     516             :     Indent();
     517             :     bool comma = false;
     518     1970557 :     for (int i = 0; i < map->NumberOfOwnDescriptors(); i++) {
     519      805383 :       Handle<Name> name(map->instance_descriptors()->GetKey(i), isolate_);
     520             :       // TODO(rossberg): Should this throw?
     521      805540 :       if (!name->IsString()) continue;
     522      805383 :       Handle<String> key = Handle<String>::cast(name);
     523      805383 :       PropertyDetails details = map->instance_descriptors()->GetDetails(i);
     524      805383 :       if (details.IsDontEnum()) continue;
     525             :       Handle<Object> property;
     526     1609882 :       if (details.location() == kField && *map == js_obj->map()) {
     527             :         DCHECK_EQ(kData, details.kind());
     528      804620 :         FieldIndex field_index = FieldIndex::ForDescriptor(*map, i);
     529             :         property = JSObject::FastPropertyAt(js_obj, details.representation(),
     530      804620 :                                             field_index);
     531             :       } else {
     532        7612 :         ASSIGN_RETURN_ON_EXCEPTION_VALUE(
     533             :             isolate_, property, Object::GetPropertyOrElement(js_obj, key),
     534             :             EXCEPTION);
     535             :       }
     536             :       Result result = SerializeProperty(property, comma, key);
     537      805226 :       if (!comma && result == SUCCESS) comma = true;
     538      805226 :       if (result == EXCEPTION) return result;
     539             :     }
     540             :     Unindent();
     541      366191 :     if (comma) NewLine();
     542             :     builder_.AppendCharacter('}');
     543             :   } else {
     544         898 :     Result result = SerializeJSReceiverSlow(object);
     545         898 :     if (result != SUCCESS) return result;
     546             :   }
     547      367062 :   StackPop();
     548      373527 :   return SUCCESS;
     549             : }
     550             : 
     551        1249 : JsonStringifier::Result JsonStringifier::SerializeJSReceiverSlow(
     552             :     Handle<JSReceiver> object) {
     553        1249 :   Handle<FixedArray> contents = property_list_;
     554        1249 :   if (contents.is_null()) {
     555        1902 :     ASSIGN_RETURN_ON_EXCEPTION_VALUE(
     556             :         isolate_, contents,
     557             :         KeyAccumulator::GetKeys(object, KeyCollectionMode::kOwnOnly,
     558             :                                 ENUMERABLE_STRINGS,
     559             :                                 GetKeysConversion::kConvertToString),
     560             :         EXCEPTION);
     561             :   }
     562        1249 :   builder_.AppendCharacter('{');
     563             :   Indent();
     564             :   bool comma = false;
     565       10716 :   for (int i = 0; i < contents->length(); i++) {
     566        4136 :     Handle<String> key(String::cast(contents->get(i)), isolate_);
     567             :     Handle<Object> property;
     568        8272 :     ASSIGN_RETURN_ON_EXCEPTION_VALUE(isolate_, property,
     569             :                                      Object::GetPropertyOrElement(object, key),
     570             :                                      EXCEPTION);
     571             :     Result result = SerializeProperty(property, comma, key);
     572        4136 :     if (!comma && result == SUCCESS) comma = true;
     573        4136 :     if (result == EXCEPTION) return result;
     574             :   }
     575             :   Unindent();
     576        1222 :   if (comma) NewLine();
     577             :   builder_.AppendCharacter('}');
     578             :   return SUCCESS;
     579             : }
     580             : 
     581         405 : JsonStringifier::Result JsonStringifier::SerializeJSProxy(
     582             :     Handle<JSProxy> object) {
     583         405 :   HandleScope scope(isolate_);
     584         405 :   Result stack_push = StackPush(object);
     585         405 :   if (stack_push != SUCCESS) return stack_push;
     586             :   Maybe<bool> is_array = Object::IsArray(object);
     587         405 :   if (is_array.IsNothing()) return EXCEPTION;
     588         405 :   if (is_array.FromJust()) {
     589             :     Handle<Object> length_object;
     590         126 :     ASSIGN_RETURN_ON_EXCEPTION_VALUE(
     591             :         isolate_, length_object,
     592             :         Object::GetLengthFromArrayLike(isolate_, object), EXCEPTION);
     593             :     uint32_t length;
     594          45 :     if (!length_object->ToUint32(&length)) {
     595             :       // Technically, we need to be able to handle lengths outside the
     596             :       // uint32_t range. However, we would run into string size overflow
     597             :       // if we tried to stringify such an array.
     598          18 :       isolate_->Throw(*isolate_->factory()->NewInvalidStringLengthError());
     599           9 :       return EXCEPTION;
     600             :     }
     601          36 :     builder_.AppendCharacter('[');
     602             :     Indent();
     603          72 :     Result result = SerializeArrayLikeSlow(object, 0, length);
     604          36 :     if (result != SUCCESS) return result;
     605             :     Unindent();
     606          36 :     if (length > 0) NewLine();
     607             :     builder_.AppendCharacter(']');
     608             :   } else {
     609         351 :     Result result = SerializeJSReceiverSlow(object);
     610         351 :     if (result != SUCCESS) return result;
     611             :   }
     612         387 :   StackPop();
     613         387 :   return SUCCESS;
     614             : }
     615             : 
     616             : template <typename SrcChar, typename DestChar>
     617             : void JsonStringifier::SerializeStringUnchecked_(
     618             :     Vector<const SrcChar> src,
     619             :     IncrementalStringBuilder::NoExtend<DestChar>* dest) {
     620             :   // Assert that uc16 character is not truncated down to 8 bit.
     621             :   // The <uc16, char> version of this method must not be called.
     622             :   DCHECK(sizeof(DestChar) >= sizeof(SrcChar));
     623             : 
     624    48147250 :   for (int i = 0; i < src.length(); i++) {
     625    48147250 :     SrcChar c = src[i];
     626    48147250 :     if (DoNotEscape(c)) {
     627             :       dest->Append(c);
     628             :     } else {
     629        4720 :       dest->AppendCString(&JsonEscapeTable[c * kJsonEscapeTableEntrySize]);
     630             :     }
     631             :   }
     632             : }
     633             : 
     634             : template <typename SrcChar, typename DestChar>
     635             : void JsonStringifier::SerializeString_(Handle<String> string) {
     636     2537212 :   int length = string->length();
     637     2537212 :   builder_.Append<uint8_t, DestChar>('"');
     638             :   // We might be able to fit the whole escaped string in the current string
     639             :   // part, or we might need to allocate.
     640     2537212 :   if (int worst_case_length = builder_.EscapedLengthIfCurrentPartFits(length)) {
     641             :     DisallowHeapAllocation no_gc;
     642             :     Vector<const SrcChar> vector = string->GetCharVector<SrcChar>();
     643             :     IncrementalStringBuilder::NoExtendBuilder<DestChar> no_extend(
     644     1429872 :         &builder_, worst_case_length);
     645     1429872 :     SerializeStringUnchecked_(vector, &no_extend);
     646             :   } else {
     647     1107340 :     FlatStringReader reader(isolate_, string);
     648  2710312250 :     for (int i = 0; i < reader.length(); i++) {
     649  2710312250 :       SrcChar c = reader.Get<SrcChar>(i);
     650  2710312250 :       if (DoNotEscape(c)) {
     651             :         builder_.Append<SrcChar, DestChar>(c);
     652             :       } else {
     653    10843844 :         builder_.AppendCString(&JsonEscapeTable[c * kJsonEscapeTableEntrySize]);
     654             :       }
     655     1107340 :     }
     656             :   }
     657             :   builder_.Append<uint8_t, DestChar>('"');
     658             : }
     659             : 
     660             : template <>
     661  2757299627 : bool JsonStringifier::DoNotEscape(uint8_t c) {
     662  2757299627 :   return c >= '#' && c <= '~' && c != '\\';
     663             : }
     664             : 
     665             : template <>
     666     1159873 : bool JsonStringifier::DoNotEscape(uint16_t c) {
     667     1159873 :   return c >= '#' && c != '\\' && c != 0x7f;
     668             : }
     669             : 
     670             : void JsonStringifier::NewLine() {
     671    12241144 :   if (gap_ == nullptr) return;
     672     5344806 :   builder_.AppendCharacter('\n');
     673    10893300 :   for (int i = 0; i < indent_; i++) builder_.AppendCString(gap_);
     674             : }
     675             : 
     676             : void JsonStringifier::Separator(bool first) {
     677    11877803 :   if (!first) builder_.AppendCharacter(',');
     678             :   NewLine();
     679             : }
     680             : 
     681             : void JsonStringifier::SerializeDeferredKey(bool deferred_comma,
     682             :                                            Handle<Object> deferred_key) {
     683             :   Separator(!deferred_comma);
     684      766947 :   SerializeString(Handle<String>::cast(deferred_key));
     685      766947 :   builder_.AppendCharacter(':');
     686      766947 :   if (gap_ != nullptr) builder_.AppendCharacter(' ');
     687             : }
     688             : 
     689     3290318 : void JsonStringifier::SerializeString(Handle<String> object) {
     690     3290318 :   object = String::Flatten(object);
     691     3290318 :   if (builder_.CurrentEncoding() == String::ONE_BYTE_ENCODING) {
     692     2537005 :     if (object->IsOneByteRepresentationUnderneath()) {
     693             :       SerializeString_<uint8_t, uint8_t>(object);
     694             :     } else {
     695      753106 :       builder_.ChangeEncoding();
     696      753106 :       SerializeString(object);
     697             :     }
     698             :   } else {
     699      753313 :     if (object->IsOneByteRepresentationUnderneath()) {
     700             :       SerializeString_<uint8_t, uc16>(object);
     701             :     } else {
     702             :       SerializeString_<uc16, uc16>(object);
     703             :     }
     704             :   }
     705     3290318 : }
     706             : 
     707             : }  // namespace internal
     708             : }  // namespace v8

Generated by: LCOV version 1.10