LCOV - code coverage report
Current view: top level - src/snapshot - serializer.cc (source / functions) Hit Total Coverage
Test: app.info Lines: 329 362 90.9 %
Date: 2017-04-26 Functions: 37 41 90.2 %

          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/snapshot/serializer.h"
       6             : 
       7             : #include "src/assembler-inl.h"
       8             : #include "src/deoptimizer.h"
       9             : #include "src/heap/heap-inl.h"
      10             : #include "src/macro-assembler.h"
      11             : #include "src/snapshot/natives.h"
      12             : 
      13             : namespace v8 {
      14             : namespace internal {
      15             : 
      16         835 : Serializer::Serializer(Isolate* isolate)
      17             :     : isolate_(isolate),
      18             :       external_reference_encoder_(isolate),
      19             :       root_index_map_(isolate),
      20             :       recursion_depth_(0),
      21             :       code_address_map_(NULL),
      22             :       num_maps_(0),
      23             :       large_objects_total_size_(0),
      24        5010 :       seen_large_objects_index_(0) {
      25             :   // The serializer is meant to be used only to generate initial heap images
      26             :   // from a context in which there is only one isolate.
      27        3340 :   for (int i = 0; i < kNumberOfPreallocatedSpaces; i++) {
      28        2505 :     pending_chunk_[i] = 0;
      29             :     max_chunk_size_[i] = static_cast<uint32_t>(
      30        2505 :         MemoryAllocator::PageAreaSize(static_cast<AllocationSpace>(i)));
      31             :   }
      32             : 
      33             : #ifdef OBJECT_PRINT
      34             :   if (FLAG_serialization_statistics) {
      35             :     instance_type_count_ = NewArray<int>(kInstanceTypes);
      36             :     instance_type_size_ = NewArray<size_t>(kInstanceTypes);
      37             :     for (int i = 0; i < kInstanceTypes; i++) {
      38             :       instance_type_count_[i] = 0;
      39             :       instance_type_size_[i] = 0;
      40             :     }
      41             :   } else {
      42             :     instance_type_count_ = NULL;
      43             :     instance_type_size_ = NULL;
      44             :   }
      45             : #endif  // OBJECT_PRINT
      46         835 : }
      47             : 
      48        1670 : Serializer::~Serializer() {
      49         835 :   if (code_address_map_ != NULL) delete code_address_map_;
      50             : #ifdef OBJECT_PRINT
      51             :   if (instance_type_count_ != NULL) {
      52             :     DeleteArray(instance_type_count_);
      53             :     DeleteArray(instance_type_size_);
      54             :   }
      55             : #endif  // OBJECT_PRINT
      56         835 : }
      57             : 
      58             : #ifdef OBJECT_PRINT
      59             : void Serializer::CountInstanceType(Map* map, int size) {
      60             :   int instance_type = map->instance_type();
      61             :   instance_type_count_[instance_type]++;
      62             :   instance_type_size_[instance_type] += size;
      63             : }
      64             : #endif  // OBJECT_PRINT
      65             : 
      66         835 : void Serializer::OutputStatistics(const char* name) {
      67        1670 :   if (!FLAG_serialization_statistics) return;
      68           0 :   PrintF("%s:\n", name);
      69           0 :   PrintF("  Spaces (bytes):\n");
      70           0 :   for (int space = 0; space < kNumberOfSpaces; space++) {
      71           0 :     PrintF("%16s", AllocationSpaceName(static_cast<AllocationSpace>(space)));
      72             :   }
      73           0 :   PrintF("\n");
      74           0 :   for (int space = 0; space < kNumberOfPreallocatedSpaces; space++) {
      75           0 :     size_t s = pending_chunk_[space];
      76           0 :     for (uint32_t chunk_size : completed_chunks_[space]) s += chunk_size;
      77           0 :     PrintF("%16" PRIuS, s);
      78             :   }
      79           0 :   PrintF("%16d\n", large_objects_total_size_);
      80             : #ifdef OBJECT_PRINT
      81             :   PrintF("  Instance types (count and bytes):\n");
      82             : #define PRINT_INSTANCE_TYPE(Name)                                 \
      83             :   if (instance_type_count_[Name]) {                               \
      84             :     PrintF("%10d %10" PRIuS "  %s\n", instance_type_count_[Name], \
      85             :            instance_type_size_[Name], #Name);                     \
      86             :   }
      87             :   INSTANCE_TYPE_LIST(PRINT_INSTANCE_TYPE)
      88             : #undef PRINT_INSTANCE_TYPE
      89             :   PrintF("\n");
      90             : #endif  // OBJECT_PRINT
      91             : }
      92             : 
      93         835 : void Serializer::SerializeDeferredObjects() {
      94       13657 :   while (deferred_objects_.length() > 0) {
      95       24809 :     HeapObject* obj = deferred_objects_.RemoveLast();
      96       11987 :     ObjectSerializer obj_serializer(this, obj, &sink_, kPlain, kStartOfObject);
      97       11987 :     obj_serializer.SerializeDeferred();
      98             :   }
      99             :   sink_.Put(kSynchronize, "Finished with deferred objects");
     100         835 : }
     101             : 
     102      351102 : void Serializer::VisitRootPointers(Root root, Object** start, Object** end) {
     103      798089 :   for (Object** current = start; current < end; current++) {
     104      893974 :     if ((*current)->IsSmi()) {
     105        2175 :       PutSmi(Smi::cast(*current));
     106             :     } else {
     107      444812 :       SerializeObject(HeapObject::cast(*current), kPlain, kStartOfObject, 0);
     108             :     }
     109             :   }
     110      351102 : }
     111             : 
     112         835 : void Serializer::EncodeReservations(
     113             :     List<SerializedData::Reservation>* out) const {
     114        3340 :   for (int i = 0; i < kNumberOfPreallocatedSpaces; i++) {
     115        3241 :     for (int j = 0; j < completed_chunks_[i].length(); j++) {
     116        3977 :       out->Add(SerializedData::Reservation(completed_chunks_[i][j]));
     117             :     }
     118             : 
     119        2505 :     if (pending_chunk_[i] > 0 || completed_chunks_[i].length() == 0) {
     120        2505 :       out->Add(SerializedData::Reservation(pending_chunk_[i]));
     121             :     }
     122             :     out->last().mark_as_last();
     123             :   }
     124        1670 :   out->Add(SerializedData::Reservation(num_maps_ * Map::kSize));
     125             :   out->last().mark_as_last();
     126        1670 :   out->Add(SerializedData::Reservation(large_objects_total_size_));
     127             :   out->last().mark_as_last();
     128         835 : }
     129             : 
     130             : #ifdef DEBUG
     131             : bool Serializer::BackReferenceIsAlreadyAllocated(
     132             :     SerializerReference reference) {
     133             :   DCHECK(reference.is_back_reference());
     134             :   AllocationSpace space = reference.space();
     135             :   if (space == LO_SPACE) {
     136             :     return reference.large_object_index() < seen_large_objects_index_;
     137             :   } else if (space == MAP_SPACE) {
     138             :     return reference.map_index() < num_maps_;
     139             :   } else {
     140             :     int chunk_index = reference.chunk_index();
     141             :     if (chunk_index == completed_chunks_[space].length()) {
     142             :       return reference.chunk_offset() < pending_chunk_[space];
     143             :     } else {
     144             :       return chunk_index < completed_chunks_[space].length() &&
     145             :              reference.chunk_offset() < completed_chunks_[space][chunk_index];
     146             :     }
     147             :   }
     148             : }
     149             : #endif  // DEBUG
     150             : 
     151     9036611 : bool Serializer::SerializeHotObject(HeapObject* obj, HowToCode how_to_code,
     152             :                                     WhereToPoint where_to_point, int skip) {
     153     9036611 :   if (how_to_code != kPlain || where_to_point != kStartOfObject) return false;
     154             :   // Encode a reference to a hot object by its index in the working set.
     155             :   int index = hot_objects_.Find(obj);
     156     8093979 :   if (index == HotObjectsList::kNotFound) return false;
     157             :   DCHECK(index >= 0 && index < kNumberOfHotObjects);
     158     1375689 :   if (FLAG_trace_serializer) {
     159           0 :     PrintF(" Encoding hot object %d:", index);
     160           0 :     obj->ShortPrint();
     161           0 :     PrintF("\n");
     162             :   }
     163     1375689 :   if (skip != 0) {
     164        2520 :     sink_.Put(kHotObjectWithSkip + index, "HotObjectWithSkip");
     165        2520 :     sink_.PutInt(skip, "HotObjectSkipDistance");
     166             :   } else {
     167     1373169 :     sink_.Put(kHotObject + index, "HotObject");
     168             :   }
     169             :   return true;
     170             : }
     171     3597085 : bool Serializer::SerializeBackReference(HeapObject* obj, HowToCode how_to_code,
     172             :                                         WhereToPoint where_to_point, int skip) {
     173     3597085 :   SerializerReference reference = reference_map_.Lookup(obj);
     174     3597085 :   if (!reference.is_valid()) return false;
     175             :   // Encode the location of an already deserialized object in order to write
     176             :   // its location into a later object.  We can encode the location as an
     177             :   // offset fromthe start of the deserialized objects or as an offset
     178             :   // backwards from thecurrent allocation pointer.
     179     1583348 :   if (reference.is_attached_reference()) {
     180        3020 :     FlushSkip(skip);
     181        3020 :     if (FLAG_trace_serializer) {
     182             :       PrintF(" Encoding attached reference %d\n",
     183           0 :              reference.attached_reference_index());
     184             :     }
     185        3020 :     PutAttachedReference(reference, how_to_code, where_to_point);
     186             :   } else {
     187             :     DCHECK(reference.is_back_reference());
     188     1580328 :     if (FLAG_trace_serializer) {
     189           0 :       PrintF(" Encoding back reference to: ");
     190           0 :       obj->ShortPrint();
     191           0 :       PrintF("\n");
     192             :     }
     193             : 
     194             :     PutAlignmentPrefix(obj);
     195             :     AllocationSpace space = reference.space();
     196     1580328 :     if (skip == 0) {
     197      796359 :       sink_.Put(kBackref + how_to_code + where_to_point + space, "BackRef");
     198             :     } else {
     199             :       sink_.Put(kBackrefWithSkip + how_to_code + where_to_point + space,
     200      783969 :                 "BackRefWithSkip");
     201      783969 :       sink_.PutInt(skip, "BackRefSkipDistance");
     202             :     }
     203             :     PutBackReference(obj, reference);
     204             :   }
     205             :   return true;
     206             : }
     207             : 
     208     4063837 : void Serializer::PutRoot(int root_index, HeapObject* object,
     209             :                          SerializerDeserializer::HowToCode how_to_code,
     210             :                          SerializerDeserializer::WhereToPoint where_to_point,
     211             :                          int skip) {
     212     4063837 :   if (FLAG_trace_serializer) {
     213           0 :     PrintF(" Encoding root %d:", root_index);
     214           0 :     object->ShortPrint();
     215           0 :     PrintF("\n");
     216             :   }
     217             : 
     218             :   // Assert that the first 32 root array items are a conscious choice. They are
     219             :   // chosen so that the most common ones can be encoded more efficiently.
     220             :   STATIC_ASSERT(Heap::kEmptyDescriptorArrayRootIndex ==
     221             :                 kNumberOfRootArrayConstants - 1);
     222             : 
     223    12191511 :   if (how_to_code == kPlain && where_to_point == kStartOfObject &&
     224     7870759 :       root_index < kNumberOfRootArrayConstants &&
     225             :       !isolate()->heap()->InNewSpace(object)) {
     226     3806922 :     if (skip == 0) {
     227     3805976 :       sink_.Put(kRootArrayConstants + root_index, "RootConstant");
     228             :     } else {
     229         946 :       sink_.Put(kRootArrayConstantsWithSkip + root_index, "RootConstant");
     230         946 :       sink_.PutInt(skip, "SkipInPutRoot");
     231             :     }
     232             :   } else {
     233      256915 :     FlushSkip(skip);
     234      256915 :     sink_.Put(kRootArray + how_to_code + where_to_point, "RootSerialization");
     235      256915 :     sink_.PutInt(root_index, "root_index");
     236             :     hot_objects_.Add(object);
     237             :   }
     238     4063837 : }
     239             : 
     240        2755 : void Serializer::PutSmi(Smi* smi) {
     241             :   sink_.Put(kOnePointerRawData, "Smi");
     242             :   byte* bytes = reinterpret_cast<byte*>(&smi);
     243       24795 :   for (int i = 0; i < kPointerSize; i++) sink_.Put(bytes[i], "Byte");
     244        2755 : }
     245             : 
     246          18 : void Serializer::PutBackReference(HeapObject* object,
     247             :                                   SerializerReference reference) {
     248             :   DCHECK(BackReferenceIsAlreadyAllocated(reference));
     249     1592333 :   sink_.PutInt(reference.back_reference(), "BackRefValue");
     250             :   hot_objects_.Add(object);
     251          18 : }
     252             : 
     253        3528 : void Serializer::PutAttachedReference(SerializerReference reference,
     254             :                                       HowToCode how_to_code,
     255             :                                       WhereToPoint where_to_point) {
     256             :   DCHECK(reference.is_attached_reference());
     257             :   DCHECK((how_to_code == kPlain && where_to_point == kStartOfObject) ||
     258             :          (how_to_code == kPlain && where_to_point == kInnerPointer) ||
     259             :          (how_to_code == kFromCode && where_to_point == kStartOfObject) ||
     260             :          (how_to_code == kFromCode && where_to_point == kInnerPointer));
     261        3528 :   sink_.Put(kAttachedReference + how_to_code + where_to_point, "AttachedRef");
     262        3528 :   sink_.PutInt(reference.attached_reference_index(), "AttachedRefIndex");
     263        3528 : }
     264             : 
     265           0 : int Serializer::PutAlignmentPrefix(HeapObject* object) {
     266             :   AllocationAlignment alignment = object->RequiredAlignment();
     267             :   if (alignment != kWordAligned) {
     268             :     DCHECK(1 <= alignment && alignment <= 3);
     269             :     byte prefix = (kAlignmentPrefix - 1) + alignment;
     270             :     sink_.Put(prefix, "Alignment");
     271             :     return Heap::GetMaximumFillToAlign(alignment);
     272             :   }
     273             :   return 0;
     274             : }
     275             : 
     276           0 : SerializerReference Serializer::AllocateLargeObject(int size) {
     277             :   // Large objects are allocated one-by-one when deserializing. We do not
     278             :   // have to keep track of multiple chunks.
     279          42 :   large_objects_total_size_ += size;
     280          42 :   return SerializerReference::LargeObjectReference(seen_large_objects_index_++);
     281             : }
     282             : 
     283           0 : SerializerReference Serializer::AllocateMap() {
     284             :   // Maps are allocated one-by-one when deserializing.
     285       69700 :   return SerializerReference::MapReference(num_maps_++);
     286             : }
     287             : 
     288     1488467 : SerializerReference Serializer::Allocate(AllocationSpace space, int size) {
     289             :   DCHECK(space >= 0 && space < kNumberOfPreallocatedSpaces);
     290             :   DCHECK(size > 0 && size <= static_cast<int>(max_chunk_size(space)));
     291     1488467 :   uint32_t new_chunk_size = pending_chunk_[space] + size;
     292     1488467 :   if (new_chunk_size > max_chunk_size(space)) {
     293             :     // The new chunk size would not fit onto a single page. Complete the
     294             :     // current chunk and start a new one.
     295             :     sink_.Put(kNextChunk, "NextChunk");
     296             :     sink_.Put(space, "NextChunkSpace");
     297     1488835 :     completed_chunks_[space].Add(pending_chunk_[space]);
     298         368 :     pending_chunk_[space] = 0;
     299             :     new_chunk_size = size;
     300             :   }
     301     1488467 :   uint32_t offset = pending_chunk_[space];
     302     1488467 :   pending_chunk_[space] = new_chunk_size;
     303             :   return SerializerReference::BackReference(
     304     4465401 :       space, completed_chunks_[space].length(), offset);
     305             : }
     306             : 
     307         835 : void Serializer::Pad() {
     308             :   // The non-branching GetInt will read up to 3 bytes too far, so we need
     309             :   // to pad the snapshot to make sure we don't read over the end.
     310        3340 :   for (unsigned i = 0; i < sizeof(int32_t) - 1; i++) {
     311             :     sink_.Put(kNop, "Padding");
     312             :   }
     313             :   // Pad up to pointer size for checksum.
     314        3303 :   while (!IsAligned(sink_.Position(), kPointerAlignment)) {
     315             :     sink_.Put(kNop, "Padding");
     316             :   }
     317         835 : }
     318             : 
     319         278 : void Serializer::InitializeCodeAddressMap() {
     320         278 :   isolate_->InitializeLoggingAndCounters();
     321         278 :   code_address_map_ = new CodeAddressMap(isolate_);
     322         278 : }
     323             : 
     324        1366 : Code* Serializer::CopyCode(Code* code) {
     325             :   code_buffer_.Rewind(0);  // Clear buffer without deleting backing store.
     326             :   int size = code->CodeSize();
     327        2732 :   code_buffer_.AddAll(Vector<byte>(code->address(), size));
     328        1366 :   return Code::cast(HeapObject::FromAddress(&code_buffer_.first()));
     329             : }
     330             : 
     331         145 : bool Serializer::HasNotExceededFirstPageOfEachSpace() {
     332         580 :   for (int i = 0; i < kNumberOfPreallocatedSpaces; i++) {
     333         435 :     if (!completed_chunks_[i].is_empty()) return false;
     334             :   }
     335             :   return true;
     336             : }
     337             : 
     338      971389 : bool Serializer::ObjectSerializer::TryEncodeDeoptimizationEntry(
     339             :     HowToCode how_to_code, Address target, int skip) {
     340     3818314 :   for (int bailout_type = 0; bailout_type <= Deoptimizer::kLastBailoutType;
     341             :        ++bailout_type) {
     342             :     int id = Deoptimizer::GetDeoptimizationId(
     343             :         serializer_->isolate(), target,
     344     2880546 :         static_cast<Deoptimizer::BailoutType>(bailout_type));
     345     2880546 :     if (id == Deoptimizer::kNotDeoptimizationEntry) continue;
     346             :     sink_->Put(how_to_code == kPlain ? kDeoptimizerEntryPlain
     347             :                                      : kDeoptimizerEntryFromCode,
     348       33621 :                "DeoptimizationEntry");
     349       33621 :     sink_->PutInt(skip, "SkipB4DeoptimizationEntry");
     350       33621 :     sink_->Put(bailout_type, "BailoutType");
     351       33621 :     sink_->PutInt(id, "EntryId");
     352       33621 :     return true;
     353             :   }
     354             :   return false;
     355             : }
     356             : 
     357     1558209 : void Serializer::ObjectSerializer::SerializePrologue(AllocationSpace space,
     358             :                                                      int size, Map* map) {
     359     1558209 :   if (serializer_->code_address_map_) {
     360             :     const char* code_name =
     361     1506370 :         serializer_->code_address_map_->Lookup(object_->address());
     362     1506370 :     LOG(serializer_->isolate_,
     363             :         CodeNameEvent(object_->address(), sink_->Position(), code_name));
     364             :   }
     365             : 
     366             :   SerializerReference back_reference;
     367     1558209 :   if (space == LO_SPACE) {
     368             :     sink_->Put(kNewObject + reference_representation_ + space,
     369          42 :                "NewLargeObject");
     370          42 :     sink_->PutInt(size >> kObjectAlignmentBits, "ObjectSizeInWords");
     371          84 :     if (object_->IsCode()) {
     372           0 :       sink_->Put(EXECUTABLE, "executable large object");
     373             :     } else {
     374          42 :       sink_->Put(NOT_EXECUTABLE, "not executable large object");
     375             :     }
     376          42 :     back_reference = serializer_->AllocateLargeObject(size);
     377     1558167 :   } else if (space == MAP_SPACE) {
     378             :     DCHECK_EQ(Map::kSize, size);
     379       69700 :     back_reference = serializer_->AllocateMap();
     380       69700 :     sink_->Put(kNewObject + reference_representation_ + space, "NewMap");
     381             :     // This is redundant, but we include it anyways.
     382       69700 :     sink_->PutInt(size >> kObjectAlignmentBits, "ObjectSizeInWords");
     383             :   } else {
     384             :     int fill = serializer_->PutAlignmentPrefix(object_);
     385     1488467 :     back_reference = serializer_->Allocate(space, size + fill);
     386     1488467 :     sink_->Put(kNewObject + reference_representation_ + space, "NewObject");
     387     1488467 :     sink_->PutInt(size >> kObjectAlignmentBits, "ObjectSizeInWords");
     388             :   }
     389             : 
     390             : #ifdef OBJECT_PRINT
     391             :   if (FLAG_serialization_statistics) {
     392             :     serializer_->CountInstanceType(map, size);
     393             :   }
     394             : #endif  // OBJECT_PRINT
     395             : 
     396             :   // Mark this object as already serialized.
     397     1558209 :   serializer_->reference_map()->Add(object_, back_reference);
     398             : 
     399             :   // Serialize the map (first word of the object).
     400     1558209 :   serializer_->SerializeObject(map, kPlain, kStartOfObject, 0);
     401     1558209 : }
     402             : 
     403        1774 : void Serializer::ObjectSerializer::SerializeExternalString() {
     404        3548 :   Heap* heap = serializer_->isolate()->heap();
     405        3548 :   if (object_->map() != heap->native_source_string_map()) {
     406             :     // Usually we cannot recreate resources for external strings. To work
     407             :     // around this, external strings are serialized to look like ordinary
     408             :     // sequential strings.
     409             :     // The exception are native source code strings, since we can recreate
     410             :     // their resources.
     411          30 :     SerializeExternalStringAsSequentialString();
     412             :   } else {
     413        1744 :     ExternalOneByteString* string = ExternalOneByteString::cast(object_);
     414             :     DCHECK(string->is_short());
     415        1744 :     const NativesExternalStringResource* resource =
     416             :         reinterpret_cast<const NativesExternalStringResource*>(
     417             :             string->resource());
     418             :     // Replace the resource field with the type and index of the native source.
     419             :     string->set_resource(resource->EncodeForSerialization());
     420        1744 :     SerializeContent();
     421             :     // Restore the resource field.
     422             :     string->set_resource(resource);
     423             :   }
     424        1774 : }
     425             : 
     426          30 : void Serializer::ObjectSerializer::SerializeExternalStringAsSequentialString() {
     427             :   // Instead of serializing this as an external string, we serialize
     428             :   // an imaginary sequential string with the same content.
     429          30 :   Isolate* isolate = serializer_->isolate();
     430             :   DCHECK(object_->IsExternalString());
     431             :   DCHECK(object_->map() != isolate->heap()->native_source_string_map());
     432          30 :   ExternalString* string = ExternalString::cast(object_);
     433             :   int length = string->length();
     434             :   Map* map;
     435             :   int content_size;
     436             :   int allocation_size;
     437             :   const byte* resource;
     438             :   // Find the map and size for the imaginary sequential string.
     439             :   bool internalized = object_->IsInternalizedString();
     440          60 :   if (object_->IsExternalOneByteString()) {
     441          12 :     map = internalized ? isolate->heap()->one_byte_internalized_string_map()
     442          36 :                        : isolate->heap()->one_byte_string_map();
     443             :     allocation_size = SeqOneByteString::SizeFor(length);
     444             :     content_size = length * kCharSize;
     445             :     resource = reinterpret_cast<const byte*>(
     446          24 :         ExternalOneByteString::cast(string)->resource()->data());
     447             :   } else {
     448           6 :     map = internalized ? isolate->heap()->internalized_string_map()
     449           6 :                        : isolate->heap()->string_map();
     450             :     allocation_size = SeqTwoByteString::SizeFor(length);
     451           6 :     content_size = length * kShortSize;
     452             :     resource = reinterpret_cast<const byte*>(
     453           6 :         ExternalTwoByteString::cast(string)->resource()->data());
     454             :   }
     455             : 
     456             :   AllocationSpace space =
     457          30 :       (allocation_size > kMaxRegularHeapObjectSize) ? LO_SPACE : OLD_SPACE;
     458          30 :   SerializePrologue(space, allocation_size, map);
     459             : 
     460             :   // Output the rest of the imaginary string.
     461          30 :   int bytes_to_output = allocation_size - HeapObject::kHeaderSize;
     462             : 
     463             :   // Output raw data header. Do not bother with common raw length cases here.
     464          30 :   sink_->Put(kVariableRawData, "RawDataForString");
     465          30 :   sink_->PutInt(bytes_to_output, "length");
     466             : 
     467             :   // Serialize string header (except for map).
     468          30 :   Address string_start = string->address();
     469         510 :   for (int i = HeapObject::kHeaderSize; i < SeqString::kHeaderSize; i++) {
     470         480 :     sink_->PutSection(string_start[i], "StringHeader");
     471             :   }
     472             : 
     473             :   // Serialize string content.
     474          30 :   sink_->PutRaw(resource, content_size, "StringContent");
     475             : 
     476             :   // Since the allocation size is rounded up to object alignment, there
     477             :   // maybe left-over bytes that need to be padded.
     478          30 :   int padding_size = allocation_size - SeqString::kHeaderSize - content_size;
     479             :   DCHECK(0 <= padding_size && padding_size < kObjectAlignment);
     480          84 :   for (int i = 0; i < padding_size; i++) sink_->PutSection(0, "StringPadding");
     481             : 
     482          30 :   sink_->Put(kSkip, "SkipAfterString");
     483          30 :   sink_->PutInt(bytes_to_output, "SkipDistance");
     484          30 : }
     485             : 
     486             : // Clear and later restore the next link in the weak cell or allocation site.
     487             : // TODO(all): replace this with proper iteration of weak slots in serializer.
     488             : class UnlinkWeakNextScope {
     489             :  public:
     490     1558179 :   explicit UnlinkWeakNextScope(HeapObject* object) : object_(nullptr) {
     491     1558179 :     if (object->IsWeakCell()) {
     492      202149 :       object_ = object;
     493      202149 :       next_ = WeakCell::cast(object)->next();
     494      202149 :       WeakCell::cast(object)->clear_next(object->GetHeap()->the_hole_value());
     495     1356030 :     } else if (object->IsAllocationSite()) {
     496         381 :       object_ = object;
     497         381 :       next_ = AllocationSite::cast(object)->weak_next();
     498             :       AllocationSite::cast(object)->set_weak_next(
     499         381 :           object->GetHeap()->undefined_value());
     500             :     }
     501     1558179 :   }
     502             : 
     503     1558179 :   ~UnlinkWeakNextScope() {
     504     1558179 :     if (object_ != nullptr) {
     505      202530 :       if (object_->IsWeakCell()) {
     506      202149 :         WeakCell::cast(object_)->set_next(next_, UPDATE_WEAK_WRITE_BARRIER);
     507             :       } else {
     508             :         AllocationSite::cast(object_)->set_weak_next(next_,
     509         381 :                                                      UPDATE_WEAK_WRITE_BARRIER);
     510             :       }
     511             :     }
     512     1558179 :   }
     513             : 
     514             :  private:
     515             :   HeapObject* object_;
     516             :   Object* next_;
     517             :   DisallowHeapAllocation no_gc_;
     518             : };
     519             : 
     520     1558209 : void Serializer::ObjectSerializer::Serialize() {
     521     1558209 :   if (FLAG_trace_serializer) {
     522           0 :     PrintF(" Encoding heap object: ");
     523           0 :     object_->ShortPrint();
     524           0 :     PrintF("\n");
     525             :   }
     526             : 
     527     3116418 :   if (object_->IsExternalString()) {
     528        1774 :     SerializeExternalString();
     529     1559983 :     return;
     530             :   }
     531             : 
     532             :   // We cannot serialize typed array objects correctly.
     533             :   DCHECK(!object_->IsJSTypedArray());
     534             : 
     535             :   // We don't expect fillers.
     536             :   DCHECK(!object_->IsFiller());
     537             : 
     538     3112870 :   if (object_->IsScript()) {
     539             :     // Clear cached line ends.
     540        2615 :     Object* undefined = serializer_->isolate()->heap()->undefined_value();
     541        2615 :     Script::cast(object_)->set_line_ends(undefined);
     542             :   }
     543             : 
     544     1556435 :   SerializeContent();
     545             : }
     546             : 
     547     1558179 : void Serializer::ObjectSerializer::SerializeContent() {
     548     1558179 :   int size = object_->Size();
     549     1558179 :   Map* map = object_->map();
     550             :   AllocationSpace space =
     551     3116358 :       MemoryChunk::FromAddress(object_->address())->owner()->identity();
     552     1558179 :   SerializePrologue(space, size, map);
     553             : 
     554             :   // Serialize the rest of the object.
     555     1558179 :   CHECK_EQ(0, bytes_processed_so_far_);
     556     1558179 :   bytes_processed_so_far_ = kPointerSize;
     557             : 
     558     1558179 :   RecursionScope recursion(serializer_);
     559             :   // Objects that are immediately post processed during deserialization
     560             :   // cannot be deferred, since post processing requires the object content.
     561     1558179 :   if (recursion.ExceedsMaximum() && CanBeDeferred(object_)) {
     562       11987 :     serializer_->QueueDeferredObject(object_);
     563       11987 :     sink_->Put(kDeferred, "Deferring object content");
     564     1558179 :     return;
     565             :   }
     566             : 
     567     3092384 :   UnlinkWeakNextScope unlink_weak_next(object_);
     568             : 
     569     3092384 :   object_->IterateBody(map->instance_type(), size, this);
     570     1546192 :   OutputRawData(object_->address() + size);
     571             : }
     572             : 
     573       11987 : void Serializer::ObjectSerializer::SerializeDeferred() {
     574       11987 :   if (FLAG_trace_serializer) {
     575           0 :     PrintF(" Encoding deferred heap object: ");
     576           0 :     object_->ShortPrint();
     577           0 :     PrintF("\n");
     578             :   }
     579             : 
     580       11987 :   int size = object_->Size();
     581       11987 :   Map* map = object_->map();
     582             :   SerializerReference back_reference =
     583       11987 :       serializer_->reference_map()->Lookup(object_);
     584             :   DCHECK(back_reference.is_back_reference());
     585             : 
     586             :   // Serialize the rest of the object.
     587       11987 :   CHECK_EQ(0, bytes_processed_so_far_);
     588       11987 :   bytes_processed_so_far_ = kPointerSize;
     589             : 
     590             :   serializer_->PutAlignmentPrefix(object_);
     591       11987 :   sink_->Put(kNewObject + back_reference.space(), "deferred object");
     592       11987 :   serializer_->PutBackReference(object_, back_reference);
     593       11987 :   sink_->PutInt(size >> kPointerSizeLog2, "deferred object size");
     594             : 
     595       11987 :   UnlinkWeakNextScope unlink_weak_next(object_);
     596             : 
     597       23974 :   object_->IterateBody(map->instance_type(), size, this);
     598       11987 :   OutputRawData(object_->address() + size);
     599       11987 : }
     600             : 
     601     1675353 : void Serializer::ObjectSerializer::VisitPointers(HeapObject* host,
     602             :                                                  Object** start, Object** end) {
     603             :   Object** current = start;
     604     5934772 :   while (current < end) {
     605     8141584 :     while (current < end && (*current)->IsSmi()) current++;
     606     2584066 :     if (current < end) OutputRawData(reinterpret_cast<Address>(current));
     607             : 
     608    17196035 :     while (current < end && !(*current)->IsSmi()) {
     609     6773611 :       HeapObject* current_contents = HeapObject::cast(*current);
     610     6773611 :       int root_index = serializer_->root_index_map()->Lookup(current_contents);
     611             :       // Repeats are not subject to the write barrier so we can only use
     612             :       // immortal immovable root members. They are never in new space.
     613    16972119 :       if (current != start && root_index != RootIndexMap::kInvalidRootIndex &&
     614    10187961 :           Heap::RootIsImmortalImmovable(root_index) &&
     615     3414350 :           current_contents == current[-1]) {
     616             :         DCHECK(!serializer_->isolate()->heap()->InNewSpace(current_contents));
     617             :         int repeat_count = 1;
     618     4802404 :         while (&current[repeat_count] < end - 1 &&
     619     2291188 :                current[repeat_count] == current_contents) {
     620     1739067 :           repeat_count++;
     621             :         }
     622             :         current += repeat_count;
     623      772149 :         bytes_processed_so_far_ += repeat_count * kPointerSize;
     624      772149 :         if (repeat_count > kNumberOfFixedRepeat) {
     625        1585 :           sink_->Put(kVariableRepeat, "VariableRepeat");
     626        1585 :           sink_->PutInt(repeat_count, "repeat count");
     627             :         } else {
     628      770564 :           sink_->Put(kFixedRepeatStart + repeat_count, "FixedRepeat");
     629             :         }
     630             :       } else {
     631             :         serializer_->SerializeObject(current_contents, kPlain, kStartOfObject,
     632     6001462 :                                      0);
     633     6001462 :         bytes_processed_so_far_ += kPointerSize;
     634     6001462 :         current++;
     635             :       }
     636             :     }
     637             :   }
     638     1675353 : }
     639             : 
     640       30226 : void Serializer::ObjectSerializer::VisitEmbeddedPointer(Code* host,
     641       60452 :                                                         RelocInfo* rinfo) {
     642             :   int skip = OutputRawData(rinfo->target_address_address(),
     643       30226 :                            kCanReturnSkipInsteadOfSkipping);
     644       30226 :   HowToCode how_to_code = rinfo->IsCodedSpecially() ? kFromCode : kPlain;
     645             :   Object* object = rinfo->target_object();
     646             :   serializer_->SerializeObject(HeapObject::cast(object), how_to_code,
     647       30226 :                                kStartOfObject, skip);
     648       30226 :   bytes_processed_so_far_ += rinfo->target_address_size();
     649       30226 : }
     650             : 
     651       17685 : void Serializer::ObjectSerializer::VisitExternalReference(Foreign* host,
     652             :                                                           Address* p) {
     653             :   int skip = OutputRawData(reinterpret_cast<Address>(p),
     654       17685 :                            kCanReturnSkipInsteadOfSkipping);
     655       17685 :   Address target = *p;
     656       17685 :   if (!TryEncodeDeoptimizationEntry(kPlain, target, skip)) {
     657       17685 :     sink_->Put(kExternalReference + kPlain + kStartOfObject, "ExternalRef");
     658       17685 :     sink_->PutInt(skip, "SkipB4ExternalRef");
     659       35370 :     sink_->PutInt(serializer_->EncodeExternalReference(target), "reference id");
     660             :   }
     661       17685 :   bytes_processed_so_far_ += kPointerSize;
     662       17685 : }
     663             : 
     664      951457 : void Serializer::ObjectSerializer::VisitExternalReference(Code* host,
     665     1902914 :                                                           RelocInfo* rinfo) {
     666             :   int skip = OutputRawData(rinfo->target_address_address(),
     667      951457 :                            kCanReturnSkipInsteadOfSkipping);
     668      951457 :   HowToCode how_to_code = rinfo->IsCodedSpecially() ? kFromCode : kPlain;
     669             :   Address target = rinfo->target_external_reference();
     670      951457 :   if (!TryEncodeDeoptimizationEntry(how_to_code, target, skip)) {
     671             :     sink_->Put(kExternalReference + how_to_code + kStartOfObject,
     672      920083 :                "ExternalRef");
     673      920083 :     sink_->PutInt(skip, "SkipB4ExternalRef");
     674             :     DCHECK_NOT_NULL(target);  // Code does not reference null.
     675     1840166 :     sink_->PutInt(serializer_->EncodeExternalReference(target), "reference id");
     676             :   }
     677      951457 :   bytes_processed_so_far_ += rinfo->target_address_size();
     678      951457 : }
     679             : 
     680      215180 : void Serializer::ObjectSerializer::VisitInternalReference(Code* host,
     681      430360 :                                                           RelocInfo* rinfo) {
     682             :   // We can only reference to internal references of code that has been output.
     683             :   DCHECK(object_->IsCode() && code_has_been_output_);
     684             :   // We do not use skip from last patched pc to find the pc to patch, since
     685             :   // target_address_address may not return addresses in ascending order when
     686             :   // used for internal references. External references may be stored at the
     687             :   // end of the code in the constant pool, whereas internal references are
     688             :   // inline. That would cause the skip to be negative. Instead, we store the
     689             :   // offset from code entry.
     690      215180 :   Address entry = Code::cast(object_)->entry();
     691      215180 :   intptr_t pc_offset = rinfo->target_internal_reference_address() - entry;
     692      215180 :   intptr_t target_offset = rinfo->target_internal_reference() - entry;
     693             :   DCHECK(0 <= pc_offset &&
     694             :          pc_offset <= Code::cast(object_)->instruction_size());
     695             :   DCHECK(0 <= target_offset &&
     696             :          target_offset <= Code::cast(object_)->instruction_size());
     697             :   sink_->Put(rinfo->rmode() == RelocInfo::INTERNAL_REFERENCE
     698             :                  ? kInternalReference
     699             :                  : kInternalReferenceEncoded,
     700      215180 :              "InternalRef");
     701      215180 :   sink_->PutInt(static_cast<uintptr_t>(pc_offset), "internal ref address");
     702      215180 :   sink_->PutInt(static_cast<uintptr_t>(target_offset), "internal ref value");
     703      215180 : }
     704             : 
     705        2247 : void Serializer::ObjectSerializer::VisitRuntimeEntry(Code* host,
     706        4494 :                                                      RelocInfo* rinfo) {
     707             :   int skip = OutputRawData(rinfo->target_address_address(),
     708        2247 :                            kCanReturnSkipInsteadOfSkipping);
     709        2247 :   HowToCode how_to_code = rinfo->IsCodedSpecially() ? kFromCode : kPlain;
     710             :   Address target = rinfo->target_address();
     711        2247 :   if (!TryEncodeDeoptimizationEntry(how_to_code, target, skip)) {
     712             :     sink_->Put(kExternalReference + how_to_code + kStartOfObject,
     713           0 :                "ExternalRef");
     714           0 :     sink_->PutInt(skip, "SkipB4ExternalRef");
     715           0 :     sink_->PutInt(serializer_->EncodeExternalReference(target), "reference id");
     716             :   }
     717        2247 :   bytes_processed_so_far_ += rinfo->target_address_size();
     718        2247 : }
     719             : 
     720      787027 : void Serializer::ObjectSerializer::VisitCodeTarget(Code* host,
     721     1574054 :                                                    RelocInfo* rinfo) {
     722             :   int skip = OutputRawData(rinfo->target_address_address(),
     723      787027 :                            kCanReturnSkipInsteadOfSkipping);
     724      787027 :   Code* object = Code::GetCodeFromTargetAddress(rinfo->target_address());
     725      787027 :   serializer_->SerializeObject(object, kFromCode, kInnerPointer, skip);
     726      787027 :   bytes_processed_so_far_ += rinfo->target_address_size();
     727      787027 : }
     728             : 
     729      155599 : void Serializer::ObjectSerializer::VisitCodeEntry(JSFunction* host,
     730             :                                                   Address entry_address) {
     731      155599 :   int skip = OutputRawData(entry_address, kCanReturnSkipInsteadOfSkipping);
     732      155599 :   Code* object = Code::cast(Code::GetObjectFromEntryAddress(entry_address));
     733      155599 :   serializer_->SerializeObject(object, kPlain, kInnerPointer, skip);
     734      155599 :   bytes_processed_so_far_ += kPointerSize;
     735      155599 : }
     736             : 
     737           6 : void Serializer::ObjectSerializer::VisitCellPointer(Code* host,
     738          12 :                                                     RelocInfo* rinfo) {
     739           6 :   int skip = OutputRawData(rinfo->pc(), kCanReturnSkipInsteadOfSkipping);
     740             :   Cell* object = Cell::cast(rinfo->target_cell());
     741           6 :   serializer_->SerializeObject(object, kPlain, kInnerPointer, skip);
     742           6 :   bytes_processed_so_far_ += kPointerSize;
     743           6 : }
     744             : 
     745      199319 : Address Serializer::ObjectSerializer::PrepareCode() {
     746      199319 :   Code* code = Code::cast(object_);
     747      199319 :   if (FLAG_predictable) {
     748             :     // To make snapshots reproducible, we make a copy of the code object
     749             :     // and wipe all pointers in the copy, which we then serialize.
     750      214296 :     code = serializer_->CopyCode(code);
     751             :     int mode_mask = RelocInfo::kCodeTargetMask |
     752             :                     RelocInfo::ModeMask(RelocInfo::EMBEDDED_OBJECT) |
     753             :                     RelocInfo::ModeMask(RelocInfo::EXTERNAL_REFERENCE) |
     754             :                     RelocInfo::ModeMask(RelocInfo::RUNTIME_ENTRY) |
     755             :                     RelocInfo::ModeMask(RelocInfo::INTERNAL_REFERENCE) |
     756             :                     RelocInfo::ModeMask(RelocInfo::INTERNAL_REFERENCE_ENCODED);
     757       14977 :     for (RelocIterator it(code, mode_mask); !it.done(); it.next()) {
     758             :       RelocInfo* rinfo = it.rinfo();
     759       13611 :       rinfo->WipeOut(serializer_->isolate());
     760             :     }
     761             :     // We need to wipe out the header fields *after* wiping out the
     762             :     // relocations, because some of these fields are needed for the latter.
     763             :     code->WipeOutHeader();
     764             :   }
     765             :   // Code age headers are not serializable.
     766      398638 :   code->MakeYoung(serializer_->isolate());
     767      199319 :   return code->address();
     768             : }
     769             : 
     770     5566686 : int Serializer::ObjectSerializer::OutputRawData(
     771             :     Address up_to, Serializer::ObjectSerializer::ReturnSkip return_skip) {
     772     5566686 :   Address object_start = object_->address();
     773     5566686 :   int base = bytes_processed_so_far_;
     774     5566686 :   int up_to_offset = static_cast<int>(up_to - object_start);
     775     5566686 :   int to_skip = up_to_offset - bytes_processed_so_far_;
     776             :   int bytes_to_output = to_skip;
     777     5566686 :   bytes_processed_so_far_ += to_skip;
     778             :   // This assert will fail if the reloc info gives us the target_address_address
     779             :   // locations in a non-ascending order.  Luckily that doesn't happen.
     780             :   DCHECK(to_skip >= 0);
     781             :   bool outputting_code = false;
     782             :   bool is_code_object = object_->IsCode();
     783     5566686 :   if (to_skip != 0 && is_code_object && !code_has_been_output_) {
     784             :     // Output the code all at once and fix later.
     785      199319 :     bytes_to_output = object_->Size() + to_skip - bytes_processed_so_far_;
     786             :     outputting_code = true;
     787      199319 :     code_has_been_output_ = true;
     788             :   }
     789     5566686 :   if (bytes_to_output != 0 && (!is_code_object || outputting_code)) {
     790     4996561 :     if (!outputting_code && bytes_to_output == to_skip &&
     791     3264601 :         IsAligned(bytes_to_output, kPointerAlignment) &&
     792             :         bytes_to_output <= kNumberOfFixedRawData * kPointerSize) {
     793     1528932 :       int size_in_words = bytes_to_output >> kPointerSizeLog2;
     794     1528932 :       sink_->PutSection(kFixedRawDataStart + size_in_words, "FixedRawData");
     795             :       to_skip = 0;  // This instruction includes skip.
     796             :     } else {
     797             :       // We always end up here if we are outputting the code of a code object.
     798      203028 :       sink_->Put(kVariableRawData, "VariableRawData");
     799      203028 :       sink_->PutInt(bytes_to_output, "length");
     800             :     }
     801             : 
     802     1731960 :     if (is_code_object) object_start = PrepareCode();
     803             : 
     804     1731960 :     const char* description = is_code_object ? "Code" : "Byte";
     805     1731960 :     sink_->PutRaw(object_start + base, bytes_to_output, description);
     806             :   }
     807     5566686 :   if (to_skip != 0 && return_skip == kIgnoringReturn) {
     808      401991 :     sink_->Put(kSkip, "Skip");
     809      401991 :     sink_->PutInt(to_skip, "SkipDistance");
     810             :     to_skip = 0;
     811             :   }
     812     5566686 :   return to_skip;
     813             : }
     814             : 
     815             : }  // namespace internal
     816             : }  // namespace v8

Generated by: LCOV version 1.10