1 // Copyright 2012 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.
5 #ifndef V8_SERIALIZE_H_
6 #define V8_SERIALIZE_H_
8 #include "src/hashmap.h"
9 #include "src/heap-profiler.h"
10 #include "src/isolate.h"
11 #include "src/snapshot/snapshot-source-sink.h"
18 static const int kDeoptTableSerializeEntryCount = 64;
20 // ExternalReferenceTable is a helper class that defines the relationship
21 // between external references and their encodings. It is used to build
22 // hashmaps in ExternalReferenceEncoder and ExternalReferenceDecoder.
23 class ExternalReferenceTable {
25 static ExternalReferenceTable* instance(Isolate* isolate);
27 int size() const { return refs_.length(); }
28 Address address(int i) { return refs_[i].address; }
29 const char* name(int i) { return refs_[i].name; }
31 inline static Address NotAvailable() { return NULL; }
34 struct ExternalReferenceEntry {
39 explicit ExternalReferenceTable(Isolate* isolate);
41 void Add(Address address, const char* name) {
42 ExternalReferenceEntry entry = {address, name};
46 List<ExternalReferenceEntry> refs_;
48 DISALLOW_COPY_AND_ASSIGN(ExternalReferenceTable);
52 class ExternalReferenceEncoder {
54 explicit ExternalReferenceEncoder(Isolate* isolate);
56 uint32_t Encode(Address key) const;
58 const char* NameOfAddress(Isolate* isolate, Address address) const;
61 static uint32_t Hash(Address key) {
62 return static_cast<uint32_t>(reinterpret_cast<uintptr_t>(key) >>
68 DISALLOW_COPY_AND_ASSIGN(ExternalReferenceEncoder);
72 class AddressMapBase {
74 static void SetValue(HashMap::Entry* entry, uint32_t v) {
75 entry->value = reinterpret_cast<void*>(v);
78 static uint32_t GetValue(HashMap::Entry* entry) {
79 return static_cast<uint32_t>(reinterpret_cast<intptr_t>(entry->value));
82 inline static HashMap::Entry* LookupEntry(HashMap* map, HeapObject* obj,
84 return map->Lookup(Key(obj), Hash(obj), insert);
88 static uint32_t Hash(HeapObject* obj) {
89 return static_cast<int32_t>(reinterpret_cast<intptr_t>(obj->address()));
92 static void* Key(HeapObject* obj) {
93 return reinterpret_cast<void*>(obj->address());
98 class RootIndexMap : public AddressMapBase {
100 explicit RootIndexMap(Isolate* isolate);
102 static const int kInvalidRootIndex = -1;
104 int Lookup(HeapObject* obj) {
105 HashMap::Entry* entry = LookupEntry(map_, obj, false);
106 if (entry) return GetValue(entry);
107 return kInvalidRootIndex;
113 DISALLOW_COPY_AND_ASSIGN(RootIndexMap);
117 class PartialCacheIndexMap : public AddressMapBase {
119 PartialCacheIndexMap() : map_(HashMap::PointersMatch) {}
121 static const int kInvalidIndex = -1;
123 // Lookup object in the map. Return its index if found, or create
124 // a new entry with new_index as value, and return kInvalidIndex.
125 int LookupOrInsert(HeapObject* obj, int new_index) {
126 HashMap::Entry* entry = LookupEntry(&map_, obj, false);
127 if (entry != NULL) return GetValue(entry);
128 SetValue(LookupEntry(&map_, obj, true), static_cast<uint32_t>(new_index));
129 return kInvalidIndex;
135 DISALLOW_COPY_AND_ASSIGN(PartialCacheIndexMap);
139 class BackReference {
141 explicit BackReference(uint32_t bitfield) : bitfield_(bitfield) {}
143 BackReference() : bitfield_(kInvalidValue) {}
145 static BackReference SourceReference() { return BackReference(kSourceValue); }
147 static BackReference GlobalProxyReference() {
148 return BackReference(kGlobalProxyValue);
151 static BackReference LargeObjectReference(uint32_t index) {
152 return BackReference(SpaceBits::encode(LO_SPACE) |
153 ChunkOffsetBits::encode(index));
156 static BackReference Reference(AllocationSpace space, uint32_t chunk_index,
157 uint32_t chunk_offset) {
158 DCHECK(IsAligned(chunk_offset, kObjectAlignment));
159 DCHECK_NE(LO_SPACE, space);
160 return BackReference(
161 SpaceBits::encode(space) | ChunkIndexBits::encode(chunk_index) |
162 ChunkOffsetBits::encode(chunk_offset >> kObjectAlignmentBits));
165 bool is_valid() const { return bitfield_ != kInvalidValue; }
166 bool is_source() const { return bitfield_ == kSourceValue; }
167 bool is_global_proxy() const { return bitfield_ == kGlobalProxyValue; }
169 AllocationSpace space() const {
171 return SpaceBits::decode(bitfield_);
174 uint32_t chunk_offset() const {
176 return ChunkOffsetBits::decode(bitfield_) << kObjectAlignmentBits;
179 uint32_t large_object_index() const {
181 DCHECK(chunk_index() == 0);
182 return ChunkOffsetBits::decode(bitfield_);
185 uint32_t chunk_index() const {
187 return ChunkIndexBits::decode(bitfield_);
190 uint32_t reference() const {
192 return bitfield_ & (ChunkOffsetBits::kMask | ChunkIndexBits::kMask);
195 uint32_t bitfield() const { return bitfield_; }
198 static const uint32_t kInvalidValue = 0xFFFFFFFF;
199 static const uint32_t kSourceValue = 0xFFFFFFFE;
200 static const uint32_t kGlobalProxyValue = 0xFFFFFFFD;
201 static const int kChunkOffsetSize = kPageSizeBits - kObjectAlignmentBits;
202 static const int kChunkIndexSize = 32 - kChunkOffsetSize - kSpaceTagSize;
205 static const int kMaxChunkIndex = (1 << kChunkIndexSize) - 1;
208 class ChunkOffsetBits : public BitField<uint32_t, 0, kChunkOffsetSize> {};
210 : public BitField<uint32_t, ChunkOffsetBits::kNext, kChunkIndexSize> {};
212 : public BitField<AllocationSpace, ChunkIndexBits::kNext, kSpaceTagSize> {
219 // Mapping objects to their location after deserialization.
220 // This is used during building, but not at runtime by V8.
221 class BackReferenceMap : public AddressMapBase {
224 : no_allocation_(), map_(new HashMap(HashMap::PointersMatch)) {}
226 ~BackReferenceMap() { delete map_; }
228 BackReference Lookup(HeapObject* obj) {
229 HashMap::Entry* entry = LookupEntry(map_, obj, false);
230 return entry ? BackReference(GetValue(entry)) : BackReference();
233 void Add(HeapObject* obj, BackReference b) {
234 DCHECK(b.is_valid());
235 DCHECK_NULL(LookupEntry(map_, obj, false));
236 HashMap::Entry* entry = LookupEntry(map_, obj, true);
237 SetValue(entry, b.bitfield());
240 void AddSourceString(String* string) {
241 Add(string, BackReference::SourceReference());
244 void AddGlobalProxy(HeapObject* global_proxy) {
245 Add(global_proxy, BackReference::GlobalProxyReference());
249 DisallowHeapAllocation no_allocation_;
251 DISALLOW_COPY_AND_ASSIGN(BackReferenceMap);
255 class HotObjectsList {
257 HotObjectsList() : index_(0) {
258 for (int i = 0; i < kSize; i++) circular_queue_[i] = NULL;
261 void Add(HeapObject* object) {
262 circular_queue_[index_] = object;
263 index_ = (index_ + 1) & kSizeMask;
266 HeapObject* Get(int index) {
267 DCHECK_NOT_NULL(circular_queue_[index]);
268 return circular_queue_[index];
271 static const int kNotFound = -1;
273 int Find(HeapObject* object) {
274 for (int i = 0; i < kSize; i++) {
275 if (circular_queue_[i] == object) return i;
280 static const int kSize = 8;
283 STATIC_ASSERT(IS_POWER_OF_TWO(kSize));
284 static const int kSizeMask = kSize - 1;
285 HeapObject* circular_queue_[kSize];
288 DISALLOW_COPY_AND_ASSIGN(HotObjectsList);
292 // The Serializer/Deserializer class is a common superclass for Serializer and
293 // Deserializer which is used to store common constants and methods used by
295 class SerializerDeserializer: public ObjectVisitor {
297 static void Iterate(Isolate* isolate, ObjectVisitor* visitor);
299 static int nop() { return kNop; }
301 // No reservation for large object space necessary.
302 static const int kNumberOfPreallocatedSpaces = LO_SPACE;
303 static const int kNumberOfSpaces = LAST_SPACE + 1;
306 // ---------- byte code range 0x00..0x7f ----------
307 // Byte codes in this range represent Where, HowToCode and WhereToPoint.
308 // Where the pointed-to object can be found:
310 // 0x00..0x05 Allocate new object, in specified space.
312 // 0x06 Unused (including 0x26, 0x46, 0x66).
313 // 0x07 Unused (including 0x27, 0x47, 0x67).
314 // 0x08..0x0d Reference to previous object from space.
316 // 0x0e Unused (including 0x2e, 0x4e, 0x6e).
317 // 0x0f Unused (including 0x2f, 0x4f, 0x6f).
318 // 0x10..0x15 Reference to previous object from space after skip.
319 kBackrefWithSkip = 0x10,
320 // 0x16 Unused (including 0x36, 0x56, 0x76).
321 // 0x17 Unused (including 0x37, 0x57, 0x77).
322 // 0x18 Root array item.
324 // 0x19 Object in the partial snapshot cache.
325 kPartialSnapshotCache = 0x19,
326 // 0x1a External reference referenced by id.
327 kExternalReference = 0x1a,
328 // 0x1b Object provided in the attached list.
329 kAttachedReference = 0x1b,
330 // 0x1c Builtin code referenced by index.
332 // 0x1d..0x1f Misc (including 0x3d..0x3f, 0x5d..0x5f, 0x7d..0x7f)
335 static const int kWhereMask = 0x1f;
336 static const int kSpaceMask = 7;
337 STATIC_ASSERT(kNumberOfSpaces <= kSpaceMask + 1);
339 // How to code the pointer to the object.
343 // A pointer inlined in code. What this means depends on the architecture.
347 static const int kHowToCodeMask = 0x20;
349 // Where to point within the object.
351 // Points to start of object
353 // Points to instruction in code object or payload of cell.
357 static const int kWhereToPointMask = 0x40;
359 // ---------- Misc ----------
361 static const int kSkip = 0x1d;
362 // Internal reference encoded as offsets of pc and target from code entry.
363 static const int kInternalReference = 0x1e;
364 static const int kInternalReferenceEncoded = 0x1f;
365 // Do nothing, used for padding.
366 static const int kNop = 0x3d;
367 // Move to next reserved chunk.
368 static const int kNextChunk = 0x3e;
369 // A tag emitted at strategic points in the snapshot to delineate sections.
370 // If the deserializer does not find these at the expected moments then it
371 // is an indication that the snapshot and the VM do not fit together.
372 // Examine the build process for architecture, version or configuration
374 static const int kSynchronize = 0x5d;
375 // Used for the source code of the natives, which is in the executable, but
376 // is referred to from external strings in the snapshot.
377 static const int kNativesStringResource = 0x5e;
378 // Raw data of variable length.
379 static const int kVariableRawData = 0x7d;
380 // Repeats of variable length.
381 static const int kVariableRepeat = 0x7e;
383 // ---------- byte code range 0x80..0xff ----------
384 // First 32 root array items.
385 static const int kNumberOfRootArrayConstants = 0x20;
387 static const int kRootArrayConstants = 0x80;
389 static const int kRootArrayConstantsWithSkip = 0xa0;
390 static const int kRootArrayConstantsMask = 0x1f;
392 // 8 hot (recently seen or back-referenced) objects with optional skip.
393 static const int kNumberOfHotObjects = 0x08;
395 static const int kHotObject = 0xc0;
397 static const int kHotObjectWithSkip = 0xc8;
398 static const int kHotObjectMask = 0x07;
400 // 32 common raw data lengths.
401 static const int kNumberOfFixedRawData = 0x20;
403 static const int kFixedRawData = 0xd0;
404 static const int kOnePointerRawData = kFixedRawData;
405 static const int kFixedRawDataStart = kFixedRawData - 1;
407 // 16 repeats lengths.
408 static const int kNumberOfFixedRepeat = 0x10;
410 static const int kFixedRepeat = 0xf0;
411 static const int kFixedRepeatStart = kFixedRepeat - 1;
413 // ---------- special values ----------
414 static const int kAnyOldSpace = -1;
416 // Sentinel after a new object to indicate that double alignment is needed.
417 static const int kDoubleAlignmentSentinel = 0;
419 // Used as index for the attached reference representing the source object.
420 static const int kSourceObjectReference = 0;
422 // Used as index for the attached reference representing the global proxy.
423 static const int kGlobalProxyReference = 0;
425 // ---------- member variable ----------
426 HotObjectsList hot_objects_;
430 class SerializedData {
434 explicit Reservation(uint32_t size)
435 : reservation_(ChunkSizeBits::encode(size)) {}
437 uint32_t chunk_size() const { return ChunkSizeBits::decode(reservation_); }
438 bool is_last() const { return IsLastChunkBits::decode(reservation_); }
440 void mark_as_last() { reservation_ |= IsLastChunkBits::encode(true); }
443 uint32_t reservation_;
446 SerializedData(byte* data, int size)
447 : data_(data), size_(size), owns_data_(false) {}
448 SerializedData() : data_(NULL), size_(0), owns_data_(false) {}
451 if (owns_data_) DeleteArray<byte>(data_);
454 uint32_t GetMagicNumber() const { return GetHeaderValue(kMagicNumberOffset); }
456 class ChunkSizeBits : public BitField<uint32_t, 0, 31> {};
457 class IsLastChunkBits : public BitField<bool, 31, 1> {};
459 static uint32_t ComputeMagicNumber(ExternalReferenceTable* table) {
460 uint32_t external_refs = table->size();
461 return 0xC0DE0000 ^ external_refs;
465 void SetHeaderValue(int offset, uint32_t value) {
466 uint32_t* address = reinterpret_cast<uint32_t*>(data_ + offset);
467 memcpy(reinterpret_cast<uint32_t*>(address), &value, sizeof(value));
470 uint32_t GetHeaderValue(int offset) const {
472 memcpy(&value, reinterpret_cast<int*>(data_ + offset), sizeof(value));
476 void AllocateData(int size);
478 static uint32_t ComputeMagicNumber(Isolate* isolate) {
479 return ComputeMagicNumber(ExternalReferenceTable::instance(isolate));
482 void SetMagicNumber(Isolate* isolate) {
483 SetHeaderValue(kMagicNumberOffset, ComputeMagicNumber(isolate));
486 static const int kMagicNumberOffset = 0;
494 // A Deserializer reads a snapshot and reconstructs the Object graph it defines.
495 class Deserializer: public SerializerDeserializer {
497 // Create a deserializer from a snapshot byte source.
498 template <class Data>
499 explicit Deserializer(Data* data)
501 source_(data->Payload()),
502 magic_number_(data->GetMagicNumber()),
503 external_reference_table_(NULL),
504 deserialized_large_objects_(0),
505 deserializing_user_code_(false) {
506 DecodeReservation(data->Reservations());
509 virtual ~Deserializer();
511 // Deserialize the snapshot into an empty heap.
512 void Deserialize(Isolate* isolate);
514 // Deserialize a single object and the objects reachable from it.
515 MaybeHandle<Object> DeserializePartial(
516 Isolate* isolate, Handle<JSGlobalProxy> global_proxy,
517 Handle<FixedArray>* outdated_contexts_out);
519 // Deserialize a shared function info. Fail gracefully.
520 MaybeHandle<SharedFunctionInfo> DeserializeCode(Isolate* isolate);
522 void FlushICacheForNewCodeObjects();
524 // Pass a vector of externally-provided objects referenced by the snapshot.
525 // The ownership to its backing store is handed over as well.
526 void SetAttachedObjects(Vector<Handle<Object> > attached_objects) {
527 attached_objects_ = attached_objects;
531 virtual void VisitPointers(Object** start, Object** end);
533 virtual void VisitRuntimeEntry(RelocInfo* rinfo) {
537 void Initialize(Isolate* isolate);
539 bool deserializing_user_code() { return deserializing_user_code_; }
541 void DecodeReservation(Vector<const SerializedData::Reservation> res);
545 void UnalignedCopy(Object** dest, Object** src) {
546 memcpy(dest, src, sizeof(*src));
549 // Allocation sites are present in the snapshot, and must be linked into
550 // a list at deserialization time.
551 void RelinkAllocationSite(AllocationSite* site);
553 // Fills in some heap data in an area from start to end (non-inclusive). The
554 // space id is used for the write barrier. The object_address is the address
555 // of the object we are writing into, or NULL if we are not writing into an
556 // object, i.e. if we are writing a series of tagged values that are not on
558 void ReadData(Object** start, Object** end, int space,
559 Address object_address);
560 void ReadObject(int space_number, Object** write_back);
561 Address Allocate(int space_index, int size);
563 // Special handling for serialized code like hooking up internalized strings.
564 HeapObject* ProcessNewObjectFromSerializedCode(HeapObject* obj);
566 // This returns the address of an object that has been described in the
567 // snapshot by chunk index and offset.
568 HeapObject* GetBackReferencedObject(int space);
570 // Cached current isolate.
573 // Objects from the attached object descriptions in the serialized user code.
574 Vector<Handle<Object> > attached_objects_;
576 SnapshotByteSource source_;
577 uint32_t magic_number_;
579 // The address of the next object that will be allocated in each space.
580 // Each space has a number of chunks reserved by the GC, with each chunk
581 // fitting into a page. Deserialized objects are allocated into the
582 // current chunk of the target space by bumping up high water mark.
583 Heap::Reservation reservations_[kNumberOfSpaces];
584 uint32_t current_chunk_[kNumberOfPreallocatedSpaces];
585 Address high_water_[kNumberOfPreallocatedSpaces];
587 ExternalReferenceTable* external_reference_table_;
589 List<HeapObject*> deserialized_large_objects_;
591 bool deserializing_user_code_;
593 DISALLOW_COPY_AND_ASSIGN(Deserializer);
597 class CodeAddressMap;
599 // There can be only one serializer per V8 process.
600 class Serializer : public SerializerDeserializer {
602 Serializer(Isolate* isolate, SnapshotByteSink* sink);
604 void VisitPointers(Object** start, Object** end) OVERRIDE;
606 void EncodeReservations(List<SerializedData::Reservation>* out) const;
608 Isolate* isolate() const { return isolate_; }
610 BackReferenceMap* back_reference_map() { return &back_reference_map_; }
611 RootIndexMap* root_index_map() { return &root_index_map_; }
614 class ObjectSerializer : public ObjectVisitor {
616 ObjectSerializer(Serializer* serializer, Object* o, SnapshotByteSink* sink,
617 HowToCode how_to_code, WhereToPoint where_to_point)
618 : serializer_(serializer),
619 object_(HeapObject::cast(o)),
621 reference_representation_(how_to_code + where_to_point),
622 bytes_processed_so_far_(0),
623 is_code_object_(o->IsCode()),
624 code_has_been_output_(false) {}
626 void VisitPointers(Object** start, Object** end);
627 void VisitEmbeddedPointer(RelocInfo* target);
628 void VisitExternalReference(Address* p);
629 void VisitExternalReference(RelocInfo* rinfo);
630 void VisitInternalReference(RelocInfo* rinfo);
631 void VisitCodeTarget(RelocInfo* target);
632 void VisitCodeEntry(Address entry_address);
633 void VisitCell(RelocInfo* rinfo);
634 void VisitRuntimeEntry(RelocInfo* reloc);
635 // Used for seralizing the external strings that hold the natives source.
636 void VisitExternalOneByteString(
637 v8::String::ExternalOneByteStringResource** resource);
638 // We can't serialize a heap with external two byte strings.
639 void VisitExternalTwoByteString(
640 v8::String::ExternalStringResource** resource) {
645 void SerializePrologue(AllocationSpace space, int size, Map* map);
647 enum ReturnSkip { kCanReturnSkipInsteadOfSkipping, kIgnoringReturn };
648 // This function outputs or skips the raw data between the last pointer and
649 // up to the current position. It optionally can just return the number of
650 // bytes to skip instead of performing a skip instruction, in case the skip
651 // can be merged into the next instruction.
652 int OutputRawData(Address up_to, ReturnSkip return_skip = kIgnoringReturn);
653 // External strings are serialized in a way to resemble sequential strings.
654 void SerializeExternalString();
656 Address PrepareCode();
658 Serializer* serializer_;
660 SnapshotByteSink* sink_;
661 int reference_representation_;
662 int bytes_processed_so_far_;
663 bool is_code_object_;
664 bool code_has_been_output_;
667 virtual void SerializeObject(HeapObject* o, HowToCode how_to_code,
668 WhereToPoint where_to_point, int skip) = 0;
670 void PutRoot(int index, HeapObject* object, HowToCode how, WhereToPoint where,
673 // Returns true if the object was successfully serialized.
674 bool SerializeKnownObject(HeapObject* obj, HowToCode how_to_code,
675 WhereToPoint where_to_point, int skip);
677 inline void FlushSkip(int skip) {
679 sink_->Put(kSkip, "SkipFromSerializeObject");
680 sink_->PutInt(skip, "SkipDistanceFromSerializeObject");
684 bool BackReferenceIsAlreadyAllocated(BackReference back_reference);
686 // This will return the space for an object.
687 BackReference AllocateLargeObject(int size);
688 BackReference Allocate(AllocationSpace space, int size);
689 int EncodeExternalReference(Address addr) {
690 return external_reference_encoder_.Encode(addr);
693 // GetInt reads 4 bytes at once, requiring padding at the end.
696 // Some roots should not be serialized, because their actual value depends on
697 // absolute addresses and they are reset after deserialization, anyway.
698 bool ShouldBeSkipped(Object** current);
700 // We may not need the code address map for logging for every instance
701 // of the serializer. Initialize it on demand.
702 void InitializeCodeAddressMap();
704 Code* CopyCode(Code* code);
706 inline uint32_t max_chunk_size(int space) const {
708 DCHECK_LT(space, kNumberOfSpaces);
709 return max_chunk_size_[space];
712 SnapshotByteSink* sink() const { return sink_; }
716 SnapshotByteSink* sink_;
717 ExternalReferenceEncoder external_reference_encoder_;
719 BackReferenceMap back_reference_map_;
720 RootIndexMap root_index_map_;
722 friend class Deserializer;
723 friend class ObjectSerializer;
724 friend class SnapshotData;
727 CodeAddressMap* code_address_map_;
728 // Objects from the same space are put into chunks for bulk-allocation
729 // when deserializing. We have to make sure that each chunk fits into a
730 // page. So we track the chunk size in pending_chunk_ of a space, but
731 // when it exceeds a page, we complete the current chunk and start a new one.
732 uint32_t pending_chunk_[kNumberOfPreallocatedSpaces];
733 List<uint32_t> completed_chunks_[kNumberOfPreallocatedSpaces];
734 uint32_t max_chunk_size_[kNumberOfPreallocatedSpaces];
736 // We map serialized large objects to indexes for back-referencing.
737 uint32_t large_objects_total_size_;
738 uint32_t seen_large_objects_index_;
740 List<byte> code_buffer_;
742 DISALLOW_COPY_AND_ASSIGN(Serializer);
746 class PartialSerializer : public Serializer {
748 PartialSerializer(Isolate* isolate, Serializer* startup_snapshot_serializer,
749 SnapshotByteSink* sink)
750 : Serializer(isolate, sink),
751 startup_serializer_(startup_snapshot_serializer),
752 outdated_contexts_(0),
753 global_object_(NULL) {
754 InitializeCodeAddressMap();
757 // Serialize the objects reachable from a single object pointer.
758 void Serialize(Object** o);
759 virtual void SerializeObject(HeapObject* o, HowToCode how_to_code,
760 WhereToPoint where_to_point, int skip) OVERRIDE;
763 int PartialSnapshotCacheIndex(HeapObject* o);
764 bool ShouldBeInThePartialSnapshotCache(HeapObject* o) {
765 // Scripts should be referred only through shared function infos. We can't
766 // allow them to be part of the partial snapshot because they contain a
767 // unique ID, and deserializing several partial snapshots containing script
768 // would cause dupes.
769 DCHECK(!o->IsScript());
770 return o->IsName() || o->IsSharedFunctionInfo() ||
771 o->IsHeapNumber() || o->IsCode() ||
774 startup_serializer_->isolate()->heap()->fixed_cow_array_map();
777 void SerializeOutdatedContextsAsFixedArray();
779 Serializer* startup_serializer_;
780 List<BackReference> outdated_contexts_;
781 Object* global_object_;
782 PartialCacheIndexMap partial_cache_index_map_;
783 DISALLOW_COPY_AND_ASSIGN(PartialSerializer);
787 class StartupSerializer : public Serializer {
789 StartupSerializer(Isolate* isolate, SnapshotByteSink* sink)
790 : Serializer(isolate, sink), root_index_wave_front_(0) {
791 // Clear the cache of objects used by the partial snapshot. After the
792 // strong roots have been serialized we can create a partial snapshot
793 // which will repopulate the cache with objects needed by that partial
795 isolate->partial_snapshot_cache()->Clear();
796 InitializeCodeAddressMap();
799 // The StartupSerializer has to serialize the root array, which is slightly
801 void VisitPointers(Object** start, Object** end) OVERRIDE;
803 // Serialize the current state of the heap. The order is:
804 // 1) Strong references.
805 // 2) Partial snapshot cache.
806 // 3) Weak references (e.g. the string table).
807 virtual void SerializeStrongReferences();
808 virtual void SerializeObject(HeapObject* o, HowToCode how_to_code,
809 WhereToPoint where_to_point, int skip) OVERRIDE;
810 void SerializeWeakReferences();
812 SerializeStrongReferences();
813 SerializeWeakReferences();
818 intptr_t root_index_wave_front_;
819 DISALLOW_COPY_AND_ASSIGN(StartupSerializer);
823 class CodeSerializer : public Serializer {
825 static ScriptData* Serialize(Isolate* isolate,
826 Handle<SharedFunctionInfo> info,
827 Handle<String> source);
829 MUST_USE_RESULT static MaybeHandle<SharedFunctionInfo> Deserialize(
830 Isolate* isolate, ScriptData* cached_data, Handle<String> source);
832 static const int kSourceObjectIndex = 0;
833 STATIC_ASSERT(kSourceObjectReference == kSourceObjectIndex);
835 static const int kCodeStubsBaseIndex = 1;
837 String* source() const {
838 DCHECK(!AllowHeapAllocation::IsAllowed());
842 const List<uint32_t>* stub_keys() const { return &stub_keys_; }
843 int num_internalized_strings() const { return num_internalized_strings_; }
846 CodeSerializer(Isolate* isolate, SnapshotByteSink* sink, String* source,
848 : Serializer(isolate, sink),
850 main_code_(main_code),
851 num_internalized_strings_(0) {
852 back_reference_map_.AddSourceString(source);
855 virtual void SerializeObject(HeapObject* o, HowToCode how_to_code,
856 WhereToPoint where_to_point, int skip) OVERRIDE;
858 void SerializeBuiltin(int builtin_index, HowToCode how_to_code,
859 WhereToPoint where_to_point);
860 void SerializeIC(Code* ic, HowToCode how_to_code,
861 WhereToPoint where_to_point);
862 void SerializeCodeStub(uint32_t stub_key, HowToCode how_to_code,
863 WhereToPoint where_to_point);
864 void SerializeGeneric(HeapObject* heap_object, HowToCode how_to_code,
865 WhereToPoint where_to_point);
866 int AddCodeStubKey(uint32_t stub_key);
868 DisallowHeapAllocation no_gc_;
871 int num_internalized_strings_;
872 List<uint32_t> stub_keys_;
873 DISALLOW_COPY_AND_ASSIGN(CodeSerializer);
877 // Wrapper around reservation sizes and the serialization payload.
878 class SnapshotData : public SerializedData {
880 // Used when producing.
881 explicit SnapshotData(const Serializer& ser);
883 // Used when consuming.
884 explicit SnapshotData(const Vector<const byte> snapshot)
885 : SerializedData(const_cast<byte*>(snapshot.begin()), snapshot.length()) {
889 Vector<const Reservation> Reservations() const;
890 Vector<const byte> Payload() const;
892 Vector<const byte> RawData() const {
893 return Vector<const byte>(data_, size_);
899 // The data header consists of uint32_t-sized entries:
900 // [0] magic number and external reference count
902 // [2] number of reservation size entries
903 // [3] payload length
905 // ... serialized payload
906 static const int kCheckSumOffset = kMagicNumberOffset + kInt32Size;
907 static const int kNumReservationsOffset = kCheckSumOffset + kInt32Size;
908 static const int kPayloadLengthOffset = kNumReservationsOffset + kInt32Size;
909 static const int kHeaderSize = kPayloadLengthOffset + kInt32Size;
913 // Wrapper around ScriptData to provide code-serializer-specific functionality.
914 class SerializedCodeData : public SerializedData {
916 // Used when consuming.
917 static SerializedCodeData* FromCachedData(Isolate* isolate,
918 ScriptData* cached_data,
921 // Used when producing.
922 SerializedCodeData(const List<byte>& payload, const CodeSerializer& cs);
924 // Return ScriptData object and relinquish ownership over it to the caller.
925 ScriptData* GetScriptData();
927 Vector<const Reservation> Reservations() const;
928 Vector<const byte> Payload() const;
930 int NumInternalizedStrings() const;
931 Vector<const uint32_t> CodeStubKeys() const;
934 explicit SerializedCodeData(ScriptData* data);
936 enum SanityCheckResult {
938 MAGIC_NUMBER_MISMATCH = 1,
939 VERSION_MISMATCH = 2,
941 CPU_FEATURES_MISMATCH = 4,
943 CHECKSUM_MISMATCH = 6
946 SanityCheckResult SanityCheck(Isolate* isolate, String* source) const;
948 uint32_t SourceHash(String* source) const { return source->length(); }
950 // The data header consists of uint32_t-sized entries:
951 // [ 0] magic number and external reference count
956 // [ 5] number of internalized strings
957 // [ 6] number of code stub keys
958 // [ 7] number of reservation size entries
959 // [ 8] payload length
960 // [ 9] payload checksum part 1
961 // [10] payload checksum part 2
963 // ... code stub keys
964 // ... serialized payload
965 static const int kVersionHashOffset = kMagicNumberOffset + kInt32Size;
966 static const int kSourceHashOffset = kVersionHashOffset + kInt32Size;
967 static const int kCpuFeaturesOffset = kSourceHashOffset + kInt32Size;
968 static const int kFlagHashOffset = kCpuFeaturesOffset + kInt32Size;
969 static const int kNumInternalizedStringsOffset = kFlagHashOffset + kInt32Size;
970 static const int kNumReservationsOffset =
971 kNumInternalizedStringsOffset + kInt32Size;
972 static const int kNumCodeStubKeysOffset = kNumReservationsOffset + kInt32Size;
973 static const int kPayloadLengthOffset = kNumCodeStubKeysOffset + kInt32Size;
974 static const int kChecksum1Offset = kPayloadLengthOffset + kInt32Size;
975 static const int kChecksum2Offset = kChecksum1Offset + kInt32Size;
976 static const int kHeaderSize = kChecksum2Offset + kInt32Size;
978 } } // namespace v8::internal
980 #endif // V8_SERIALIZE_H_