blob: ad8e20f61bb765561591aa547c7afe0def5d4888 [file] [log] [blame]
Steve Blocka7e24c12009-10-30 11:49:00 +00001// Copyright 2006-2008 the V8 project authors. All rights reserved.
2// Redistribution and use in source and binary forms, with or without
3// modification, are permitted provided that the following conditions are
4// met:
5//
6// * Redistributions of source code must retain the above copyright
7// notice, this list of conditions and the following disclaimer.
8// * Redistributions in binary form must reproduce the above
9// copyright notice, this list of conditions and the following
10// disclaimer in the documentation and/or other materials provided
11// with the distribution.
12// * Neither the name of Google Inc. nor the names of its
13// contributors may be used to endorse or promote products derived
14// from this software without specific prior written permission.
15//
16// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
20// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27
28#include "v8.h"
29
30#include "accessors.h"
31#include "api.h"
32#include "execution.h"
33#include "global-handles.h"
34#include "ic-inl.h"
35#include "natives.h"
36#include "platform.h"
37#include "runtime.h"
38#include "serialize.h"
39#include "stub-cache.h"
40#include "v8threads.h"
Steve Block3ce2e202009-11-05 08:53:23 +000041#include "top.h"
Steve Blockd0582a62009-12-15 09:54:21 +000042#include "bootstrapper.h"
Steve Blocka7e24c12009-10-30 11:49:00 +000043
44namespace v8 {
45namespace internal {
46
Steve Blocka7e24c12009-10-30 11:49:00 +000047
48// -----------------------------------------------------------------------------
49// Coding of external references.
50
51// The encoding of an external reference. The type is in the high word.
52// The id is in the low word.
53static uint32_t EncodeExternal(TypeCode type, uint16_t id) {
54 return static_cast<uint32_t>(type) << 16 | id;
55}
56
57
58static int* GetInternalPointer(StatsCounter* counter) {
59 // All counters refer to dummy_counter, if deserializing happens without
60 // setting up counters.
61 static int dummy_counter = 0;
62 return counter->Enabled() ? counter->GetInternalPointer() : &dummy_counter;
63}
64
65
66// ExternalReferenceTable is a helper class that defines the relationship
67// between external references and their encodings. It is used to build
68// hashmaps in ExternalReferenceEncoder and ExternalReferenceDecoder.
69class ExternalReferenceTable {
70 public:
71 static ExternalReferenceTable* instance() {
72 if (!instance_) instance_ = new ExternalReferenceTable();
73 return instance_;
74 }
75
76 int size() const { return refs_.length(); }
77
78 Address address(int i) { return refs_[i].address; }
79
80 uint32_t code(int i) { return refs_[i].code; }
81
82 const char* name(int i) { return refs_[i].name; }
83
84 int max_id(int code) { return max_id_[code]; }
85
86 private:
87 static ExternalReferenceTable* instance_;
88
89 ExternalReferenceTable() : refs_(64) { PopulateTable(); }
90 ~ExternalReferenceTable() { }
91
92 struct ExternalReferenceEntry {
93 Address address;
94 uint32_t code;
95 const char* name;
96 };
97
98 void PopulateTable();
99
100 // For a few types of references, we can get their address from their id.
101 void AddFromId(TypeCode type, uint16_t id, const char* name);
102
103 // For other types of references, the caller will figure out the address.
104 void Add(Address address, TypeCode type, uint16_t id, const char* name);
105
106 List<ExternalReferenceEntry> refs_;
107 int max_id_[kTypeCodeCount];
108};
109
110
111ExternalReferenceTable* ExternalReferenceTable::instance_ = NULL;
112
113
114void ExternalReferenceTable::AddFromId(TypeCode type,
115 uint16_t id,
116 const char* name) {
117 Address address;
118 switch (type) {
119 case C_BUILTIN: {
120 ExternalReference ref(static_cast<Builtins::CFunctionId>(id));
121 address = ref.address();
122 break;
123 }
124 case BUILTIN: {
125 ExternalReference ref(static_cast<Builtins::Name>(id));
126 address = ref.address();
127 break;
128 }
129 case RUNTIME_FUNCTION: {
130 ExternalReference ref(static_cast<Runtime::FunctionId>(id));
131 address = ref.address();
132 break;
133 }
134 case IC_UTILITY: {
135 ExternalReference ref(IC_Utility(static_cast<IC::UtilityId>(id)));
136 address = ref.address();
137 break;
138 }
139 default:
140 UNREACHABLE();
141 return;
142 }
143 Add(address, type, id, name);
144}
145
146
147void ExternalReferenceTable::Add(Address address,
148 TypeCode type,
149 uint16_t id,
150 const char* name) {
Steve Blockd0582a62009-12-15 09:54:21 +0000151 ASSERT_NE(NULL, address);
Steve Blocka7e24c12009-10-30 11:49:00 +0000152 ExternalReferenceEntry entry;
153 entry.address = address;
154 entry.code = EncodeExternal(type, id);
155 entry.name = name;
Steve Blockd0582a62009-12-15 09:54:21 +0000156 ASSERT_NE(0, entry.code);
Steve Blocka7e24c12009-10-30 11:49:00 +0000157 refs_.Add(entry);
158 if (id > max_id_[type]) max_id_[type] = id;
159}
160
161
162void ExternalReferenceTable::PopulateTable() {
163 for (int type_code = 0; type_code < kTypeCodeCount; type_code++) {
164 max_id_[type_code] = 0;
165 }
166
167 // The following populates all of the different type of external references
168 // into the ExternalReferenceTable.
169 //
170 // NOTE: This function was originally 100k of code. It has since been
171 // rewritten to be mostly table driven, as the callback macro style tends to
172 // very easily cause code bloat. Please be careful in the future when adding
173 // new references.
174
175 struct RefTableEntry {
176 TypeCode type;
177 uint16_t id;
178 const char* name;
179 };
180
181 static const RefTableEntry ref_table[] = {
182 // Builtins
Leon Clarkee46be812010-01-19 14:06:41 +0000183#define DEF_ENTRY_C(name, ignored) \
Steve Blocka7e24c12009-10-30 11:49:00 +0000184 { C_BUILTIN, \
185 Builtins::c_##name, \
186 "Builtins::" #name },
187
188 BUILTIN_LIST_C(DEF_ENTRY_C)
189#undef DEF_ENTRY_C
190
Leon Clarkee46be812010-01-19 14:06:41 +0000191#define DEF_ENTRY_C(name, ignored) \
Steve Blocka7e24c12009-10-30 11:49:00 +0000192 { BUILTIN, \
193 Builtins::name, \
194 "Builtins::" #name },
Leon Clarkee46be812010-01-19 14:06:41 +0000195#define DEF_ENTRY_A(name, kind, state) DEF_ENTRY_C(name, ignored)
Steve Blocka7e24c12009-10-30 11:49:00 +0000196
197 BUILTIN_LIST_C(DEF_ENTRY_C)
198 BUILTIN_LIST_A(DEF_ENTRY_A)
199 BUILTIN_LIST_DEBUG_A(DEF_ENTRY_A)
200#undef DEF_ENTRY_C
201#undef DEF_ENTRY_A
202
203 // Runtime functions
204#define RUNTIME_ENTRY(name, nargs, ressize) \
205 { RUNTIME_FUNCTION, \
206 Runtime::k##name, \
207 "Runtime::" #name },
208
209 RUNTIME_FUNCTION_LIST(RUNTIME_ENTRY)
210#undef RUNTIME_ENTRY
211
212 // IC utilities
213#define IC_ENTRY(name) \
214 { IC_UTILITY, \
215 IC::k##name, \
216 "IC::" #name },
217
218 IC_UTIL_LIST(IC_ENTRY)
219#undef IC_ENTRY
220 }; // end of ref_table[].
221
222 for (size_t i = 0; i < ARRAY_SIZE(ref_table); ++i) {
223 AddFromId(ref_table[i].type, ref_table[i].id, ref_table[i].name);
224 }
225
226#ifdef ENABLE_DEBUGGER_SUPPORT
227 // Debug addresses
228 Add(Debug_Address(Debug::k_after_break_target_address).address(),
229 DEBUG_ADDRESS,
230 Debug::k_after_break_target_address << kDebugIdShift,
231 "Debug::after_break_target_address()");
232 Add(Debug_Address(Debug::k_debug_break_return_address).address(),
233 DEBUG_ADDRESS,
234 Debug::k_debug_break_return_address << kDebugIdShift,
235 "Debug::debug_break_return_address()");
236 const char* debug_register_format = "Debug::register_address(%i)";
Steve Blockd0582a62009-12-15 09:54:21 +0000237 int dr_format_length = StrLength(debug_register_format);
Steve Blocka7e24c12009-10-30 11:49:00 +0000238 for (int i = 0; i < kNumJSCallerSaved; ++i) {
239 Vector<char> name = Vector<char>::New(dr_format_length + 1);
240 OS::SNPrintF(name, debug_register_format, i);
241 Add(Debug_Address(Debug::k_register_address, i).address(),
242 DEBUG_ADDRESS,
243 Debug::k_register_address << kDebugIdShift | i,
244 name.start());
245 }
246#endif
247
248 // Stat counters
249 struct StatsRefTableEntry {
250 StatsCounter* counter;
251 uint16_t id;
252 const char* name;
253 };
254
255 static const StatsRefTableEntry stats_ref_table[] = {
256#define COUNTER_ENTRY(name, caption) \
257 { &Counters::name, \
258 Counters::k_##name, \
259 "Counters::" #name },
260
261 STATS_COUNTER_LIST_1(COUNTER_ENTRY)
262 STATS_COUNTER_LIST_2(COUNTER_ENTRY)
263#undef COUNTER_ENTRY
264 }; // end of stats_ref_table[].
265
266 for (size_t i = 0; i < ARRAY_SIZE(stats_ref_table); ++i) {
267 Add(reinterpret_cast<Address>(
268 GetInternalPointer(stats_ref_table[i].counter)),
269 STATS_COUNTER,
270 stats_ref_table[i].id,
271 stats_ref_table[i].name);
272 }
273
274 // Top addresses
Steve Block3ce2e202009-11-05 08:53:23 +0000275 const char* top_address_format = "Top::%s";
276
277 const char* AddressNames[] = {
278#define C(name) #name,
279 TOP_ADDRESS_LIST(C)
280 TOP_ADDRESS_LIST_PROF(C)
281 NULL
282#undef C
283 };
284
Steve Blockd0582a62009-12-15 09:54:21 +0000285 int top_format_length = StrLength(top_address_format) - 2;
Steve Blocka7e24c12009-10-30 11:49:00 +0000286 for (uint16_t i = 0; i < Top::k_top_address_count; ++i) {
Steve Block3ce2e202009-11-05 08:53:23 +0000287 const char* address_name = AddressNames[i];
288 Vector<char> name =
Steve Blockd0582a62009-12-15 09:54:21 +0000289 Vector<char>::New(top_format_length + StrLength(address_name) + 1);
Steve Blocka7e24c12009-10-30 11:49:00 +0000290 const char* chars = name.start();
Steve Block3ce2e202009-11-05 08:53:23 +0000291 OS::SNPrintF(name, top_address_format, address_name);
Steve Blocka7e24c12009-10-30 11:49:00 +0000292 Add(Top::get_address_from_id((Top::AddressId)i), TOP_ADDRESS, i, chars);
293 }
294
295 // Extensions
296 Add(FUNCTION_ADDR(GCExtension::GC), EXTENSION, 1,
297 "GCExtension::GC");
298
299 // Accessors
300#define ACCESSOR_DESCRIPTOR_DECLARATION(name) \
301 Add((Address)&Accessors::name, \
302 ACCESSOR, \
303 Accessors::k##name, \
304 "Accessors::" #name);
305
306 ACCESSOR_DESCRIPTOR_LIST(ACCESSOR_DESCRIPTOR_DECLARATION)
307#undef ACCESSOR_DESCRIPTOR_DECLARATION
308
309 // Stub cache tables
310 Add(SCTableReference::keyReference(StubCache::kPrimary).address(),
311 STUB_CACHE_TABLE,
312 1,
313 "StubCache::primary_->key");
314 Add(SCTableReference::valueReference(StubCache::kPrimary).address(),
315 STUB_CACHE_TABLE,
316 2,
317 "StubCache::primary_->value");
318 Add(SCTableReference::keyReference(StubCache::kSecondary).address(),
319 STUB_CACHE_TABLE,
320 3,
321 "StubCache::secondary_->key");
322 Add(SCTableReference::valueReference(StubCache::kSecondary).address(),
323 STUB_CACHE_TABLE,
324 4,
325 "StubCache::secondary_->value");
326
327 // Runtime entries
328 Add(ExternalReference::perform_gc_function().address(),
329 RUNTIME_ENTRY,
330 1,
331 "Runtime::PerformGC");
332 Add(ExternalReference::random_positive_smi_function().address(),
333 RUNTIME_ENTRY,
334 2,
335 "V8::RandomPositiveSmi");
336
337 // Miscellaneous
Steve Blocka7e24c12009-10-30 11:49:00 +0000338 Add(ExternalReference::the_hole_value_location().address(),
339 UNCLASSIFIED,
340 2,
341 "Factory::the_hole_value().location()");
342 Add(ExternalReference::roots_address().address(),
343 UNCLASSIFIED,
344 3,
345 "Heap::roots_address()");
Steve Blockd0582a62009-12-15 09:54:21 +0000346 Add(ExternalReference::address_of_stack_limit().address(),
Steve Blocka7e24c12009-10-30 11:49:00 +0000347 UNCLASSIFIED,
348 4,
349 "StackGuard::address_of_jslimit()");
Steve Blockd0582a62009-12-15 09:54:21 +0000350 Add(ExternalReference::address_of_real_stack_limit().address(),
Steve Blocka7e24c12009-10-30 11:49:00 +0000351 UNCLASSIFIED,
352 5,
Steve Blockd0582a62009-12-15 09:54:21 +0000353 "StackGuard::address_of_real_jslimit()");
354 Add(ExternalReference::address_of_regexp_stack_limit().address(),
355 UNCLASSIFIED,
356 6,
Steve Blocka7e24c12009-10-30 11:49:00 +0000357 "RegExpStack::limit_address()");
358 Add(ExternalReference::new_space_start().address(),
359 UNCLASSIFIED,
Steve Blockd0582a62009-12-15 09:54:21 +0000360 7,
Steve Blocka7e24c12009-10-30 11:49:00 +0000361 "Heap::NewSpaceStart()");
362 Add(ExternalReference::heap_always_allocate_scope_depth().address(),
363 UNCLASSIFIED,
Steve Blockd0582a62009-12-15 09:54:21 +0000364 8,
Steve Blocka7e24c12009-10-30 11:49:00 +0000365 "Heap::always_allocate_scope_depth()");
366 Add(ExternalReference::new_space_allocation_limit_address().address(),
367 UNCLASSIFIED,
Steve Blockd0582a62009-12-15 09:54:21 +0000368 9,
Steve Blocka7e24c12009-10-30 11:49:00 +0000369 "Heap::NewSpaceAllocationLimitAddress()");
370 Add(ExternalReference::new_space_allocation_top_address().address(),
371 UNCLASSIFIED,
Steve Blockd0582a62009-12-15 09:54:21 +0000372 10,
Steve Blocka7e24c12009-10-30 11:49:00 +0000373 "Heap::NewSpaceAllocationTopAddress()");
374#ifdef ENABLE_DEBUGGER_SUPPORT
375 Add(ExternalReference::debug_break().address(),
376 UNCLASSIFIED,
Steve Blockd0582a62009-12-15 09:54:21 +0000377 11,
Steve Blocka7e24c12009-10-30 11:49:00 +0000378 "Debug::Break()");
379 Add(ExternalReference::debug_step_in_fp_address().address(),
380 UNCLASSIFIED,
Steve Blockd0582a62009-12-15 09:54:21 +0000381 12,
Steve Blocka7e24c12009-10-30 11:49:00 +0000382 "Debug::step_in_fp_addr()");
383#endif
384 Add(ExternalReference::double_fp_operation(Token::ADD).address(),
385 UNCLASSIFIED,
Steve Blockd0582a62009-12-15 09:54:21 +0000386 13,
Steve Blocka7e24c12009-10-30 11:49:00 +0000387 "add_two_doubles");
388 Add(ExternalReference::double_fp_operation(Token::SUB).address(),
389 UNCLASSIFIED,
Steve Blockd0582a62009-12-15 09:54:21 +0000390 14,
Steve Blocka7e24c12009-10-30 11:49:00 +0000391 "sub_two_doubles");
392 Add(ExternalReference::double_fp_operation(Token::MUL).address(),
393 UNCLASSIFIED,
Steve Blockd0582a62009-12-15 09:54:21 +0000394 15,
Steve Blocka7e24c12009-10-30 11:49:00 +0000395 "mul_two_doubles");
396 Add(ExternalReference::double_fp_operation(Token::DIV).address(),
397 UNCLASSIFIED,
Steve Blockd0582a62009-12-15 09:54:21 +0000398 16,
Steve Blocka7e24c12009-10-30 11:49:00 +0000399 "div_two_doubles");
400 Add(ExternalReference::double_fp_operation(Token::MOD).address(),
401 UNCLASSIFIED,
Steve Blockd0582a62009-12-15 09:54:21 +0000402 17,
Steve Blocka7e24c12009-10-30 11:49:00 +0000403 "mod_two_doubles");
404 Add(ExternalReference::compare_doubles().address(),
405 UNCLASSIFIED,
Steve Blockd0582a62009-12-15 09:54:21 +0000406 18,
Steve Blocka7e24c12009-10-30 11:49:00 +0000407 "compare_doubles");
408#ifdef V8_NATIVE_REGEXP
409 Add(ExternalReference::re_case_insensitive_compare_uc16().address(),
410 UNCLASSIFIED,
Steve Blockd0582a62009-12-15 09:54:21 +0000411 19,
Steve Blocka7e24c12009-10-30 11:49:00 +0000412 "NativeRegExpMacroAssembler::CaseInsensitiveCompareUC16()");
413 Add(ExternalReference::re_check_stack_guard_state().address(),
414 UNCLASSIFIED,
Steve Blockd0582a62009-12-15 09:54:21 +0000415 20,
Steve Blocka7e24c12009-10-30 11:49:00 +0000416 "RegExpMacroAssembler*::CheckStackGuardState()");
417 Add(ExternalReference::re_grow_stack().address(),
418 UNCLASSIFIED,
Steve Blockd0582a62009-12-15 09:54:21 +0000419 21,
Steve Blocka7e24c12009-10-30 11:49:00 +0000420 "NativeRegExpMacroAssembler::GrowStack()");
Leon Clarkee46be812010-01-19 14:06:41 +0000421 Add(ExternalReference::re_word_character_map().address(),
422 UNCLASSIFIED,
423 22,
424 "NativeRegExpMacroAssembler::word_character_map");
Steve Blocka7e24c12009-10-30 11:49:00 +0000425#endif
Leon Clarkee46be812010-01-19 14:06:41 +0000426 // Keyed lookup cache.
427 Add(ExternalReference::keyed_lookup_cache_keys().address(),
428 UNCLASSIFIED,
429 23,
430 "KeyedLookupCache::keys()");
431 Add(ExternalReference::keyed_lookup_cache_field_offsets().address(),
432 UNCLASSIFIED,
433 24,
434 "KeyedLookupCache::field_offsets()");
Steve Blocka7e24c12009-10-30 11:49:00 +0000435}
436
437
438ExternalReferenceEncoder::ExternalReferenceEncoder()
439 : encodings_(Match) {
440 ExternalReferenceTable* external_references =
441 ExternalReferenceTable::instance();
442 for (int i = 0; i < external_references->size(); ++i) {
443 Put(external_references->address(i), i);
444 }
445}
446
447
448uint32_t ExternalReferenceEncoder::Encode(Address key) const {
449 int index = IndexOf(key);
450 return index >=0 ? ExternalReferenceTable::instance()->code(index) : 0;
451}
452
453
454const char* ExternalReferenceEncoder::NameOfAddress(Address key) const {
455 int index = IndexOf(key);
456 return index >=0 ? ExternalReferenceTable::instance()->name(index) : NULL;
457}
458
459
460int ExternalReferenceEncoder::IndexOf(Address key) const {
461 if (key == NULL) return -1;
462 HashMap::Entry* entry =
463 const_cast<HashMap &>(encodings_).Lookup(key, Hash(key), false);
464 return entry == NULL
465 ? -1
466 : static_cast<int>(reinterpret_cast<intptr_t>(entry->value));
467}
468
469
470void ExternalReferenceEncoder::Put(Address key, int index) {
471 HashMap::Entry* entry = encodings_.Lookup(key, Hash(key), true);
472 entry->value = reinterpret_cast<void *>(index);
473}
474
475
476ExternalReferenceDecoder::ExternalReferenceDecoder()
477 : encodings_(NewArray<Address*>(kTypeCodeCount)) {
478 ExternalReferenceTable* external_references =
479 ExternalReferenceTable::instance();
480 for (int type = kFirstTypeCode; type < kTypeCodeCount; ++type) {
481 int max = external_references->max_id(type) + 1;
482 encodings_[type] = NewArray<Address>(max + 1);
483 }
484 for (int i = 0; i < external_references->size(); ++i) {
485 Put(external_references->code(i), external_references->address(i));
486 }
487}
488
489
490ExternalReferenceDecoder::~ExternalReferenceDecoder() {
491 for (int type = kFirstTypeCode; type < kTypeCodeCount; ++type) {
492 DeleteArray(encodings_[type]);
493 }
494 DeleteArray(encodings_);
495}
496
497
Steve Blocka7e24c12009-10-30 11:49:00 +0000498bool Serializer::serialization_enabled_ = false;
Steve Blockd0582a62009-12-15 09:54:21 +0000499bool Serializer::too_late_to_enable_now_ = false;
Leon Clarkee46be812010-01-19 14:06:41 +0000500ExternalReferenceDecoder* Deserializer::external_reference_decoder_ = NULL;
Steve Blocka7e24c12009-10-30 11:49:00 +0000501
502
Leon Clarkee46be812010-01-19 14:06:41 +0000503Deserializer::Deserializer(SnapshotByteSource* source) : source_(source) {
Steve Blockd0582a62009-12-15 09:54:21 +0000504}
505
506
507// This routine both allocates a new object, and also keeps
508// track of where objects have been allocated so that we can
509// fix back references when deserializing.
510Address Deserializer::Allocate(int space_index, Space* space, int size) {
511 Address address;
512 if (!SpaceIsLarge(space_index)) {
513 ASSERT(!SpaceIsPaged(space_index) ||
514 size <= Page::kPageSize - Page::kObjectStartOffset);
515 Object* new_allocation;
516 if (space_index == NEW_SPACE) {
517 new_allocation = reinterpret_cast<NewSpace*>(space)->AllocateRaw(size);
518 } else {
519 new_allocation = reinterpret_cast<PagedSpace*>(space)->AllocateRaw(size);
520 }
521 HeapObject* new_object = HeapObject::cast(new_allocation);
522 ASSERT(!new_object->IsFailure());
523 address = new_object->address();
524 high_water_[space_index] = address + size;
525 } else {
526 ASSERT(SpaceIsLarge(space_index));
527 ASSERT(size > Page::kPageSize - Page::kObjectStartOffset);
528 LargeObjectSpace* lo_space = reinterpret_cast<LargeObjectSpace*>(space);
529 Object* new_allocation;
530 if (space_index == kLargeData) {
531 new_allocation = lo_space->AllocateRaw(size);
532 } else if (space_index == kLargeFixedArray) {
533 new_allocation = lo_space->AllocateRawFixedArray(size);
534 } else {
535 ASSERT_EQ(kLargeCode, space_index);
536 new_allocation = lo_space->AllocateRawCode(size);
537 }
538 ASSERT(!new_allocation->IsFailure());
539 HeapObject* new_object = HeapObject::cast(new_allocation);
540 // Record all large objects in the same space.
541 address = new_object->address();
Andrei Popescu31002712010-02-23 13:46:05 +0000542 pages_[LO_SPACE].Add(address);
Steve Blockd0582a62009-12-15 09:54:21 +0000543 }
544 last_object_address_ = address;
545 return address;
546}
547
548
549// This returns the address of an object that has been described in the
550// snapshot as being offset bytes back in a particular space.
551HeapObject* Deserializer::GetAddressFromEnd(int space) {
552 int offset = source_->GetInt();
553 ASSERT(!SpaceIsLarge(space));
554 offset <<= kObjectAlignmentBits;
555 return HeapObject::FromAddress(high_water_[space] - offset);
556}
557
558
559// This returns the address of an object that has been described in the
560// snapshot as being offset bytes into a particular space.
561HeapObject* Deserializer::GetAddressFromStart(int space) {
562 int offset = source_->GetInt();
563 if (SpaceIsLarge(space)) {
564 // Large spaces have one object per 'page'.
565 return HeapObject::FromAddress(pages_[LO_SPACE][offset]);
566 }
567 offset <<= kObjectAlignmentBits;
568 if (space == NEW_SPACE) {
569 // New space has only one space - numbered 0.
570 return HeapObject::FromAddress(pages_[space][0] + offset);
571 }
572 ASSERT(SpaceIsPaged(space));
Leon Clarkee46be812010-01-19 14:06:41 +0000573 int page_of_pointee = offset >> kPageSizeBits;
Steve Blockd0582a62009-12-15 09:54:21 +0000574 Address object_address = pages_[space][page_of_pointee] +
575 (offset & Page::kPageAlignmentMask);
576 return HeapObject::FromAddress(object_address);
577}
578
579
580void Deserializer::Deserialize() {
581 // Don't GC while deserializing - just expand the heap.
582 AlwaysAllocateScope always_allocate;
583 // Don't use the free lists while deserializing.
584 LinearAllocationScope allocate_linearly;
585 // No active threads.
586 ASSERT_EQ(NULL, ThreadState::FirstInUse());
587 // No active handles.
588 ASSERT(HandleScopeImplementer::instance()->blocks()->is_empty());
Leon Clarked91b9f72010-01-27 17:25:45 +0000589 // Make sure the entire partial snapshot cache is traversed, filling it with
590 // valid object pointers.
591 partial_snapshot_cache_length_ = kPartialSnapshotCacheCapacity;
Steve Blockd0582a62009-12-15 09:54:21 +0000592 ASSERT_EQ(NULL, external_reference_decoder_);
593 external_reference_decoder_ = new ExternalReferenceDecoder();
Leon Clarked91b9f72010-01-27 17:25:45 +0000594 Heap::IterateStrongRoots(this, VISIT_ONLY_STRONG);
595 Heap::IterateWeakRoots(this, VISIT_ALL);
Leon Clarkee46be812010-01-19 14:06:41 +0000596}
597
598
599void Deserializer::DeserializePartial(Object** root) {
600 // Don't GC while deserializing - just expand the heap.
601 AlwaysAllocateScope always_allocate;
602 // Don't use the free lists while deserializing.
603 LinearAllocationScope allocate_linearly;
604 if (external_reference_decoder_ == NULL) {
605 external_reference_decoder_ = new ExternalReferenceDecoder();
606 }
607 VisitPointer(root);
608}
609
610
Leon Clarked91b9f72010-01-27 17:25:45 +0000611Deserializer::~Deserializer() {
612 ASSERT(source_->AtEOF());
Leon Clarkee46be812010-01-19 14:06:41 +0000613 if (external_reference_decoder_ != NULL) {
614 delete external_reference_decoder_;
615 external_reference_decoder_ = NULL;
616 }
Steve Blockd0582a62009-12-15 09:54:21 +0000617}
618
619
620// This is called on the roots. It is the driver of the deserialization
621// process. It is also called on the body of each function.
622void Deserializer::VisitPointers(Object** start, Object** end) {
623 // The space must be new space. Any other space would cause ReadChunk to try
624 // to update the remembered using NULL as the address.
625 ReadChunk(start, end, NEW_SPACE, NULL);
626}
627
628
629// This routine writes the new object into the pointer provided and then
630// returns true if the new object was in young space and false otherwise.
631// The reason for this strange interface is that otherwise the object is
632// written very late, which means the ByteArray map is not set up by the
633// time we need to use it to mark the space at the end of a page free (by
634// making it into a byte array).
635void Deserializer::ReadObject(int space_number,
636 Space* space,
637 Object** write_back) {
638 int size = source_->GetInt() << kObjectAlignmentBits;
639 Address address = Allocate(space_number, space, size);
640 *write_back = HeapObject::FromAddress(address);
641 Object** current = reinterpret_cast<Object**>(address);
642 Object** limit = current + (size >> kPointerSizeLog2);
Leon Clarkee46be812010-01-19 14:06:41 +0000643 if (FLAG_log_snapshot_positions) {
644 LOG(SnapshotPositionEvent(address, source_->position()));
645 }
Steve Blockd0582a62009-12-15 09:54:21 +0000646 ReadChunk(current, limit, space_number, address);
647}
648
649
650#define ONE_CASE_PER_SPACE(base_tag) \
651 case (base_tag) + NEW_SPACE: /* NOLINT */ \
652 case (base_tag) + OLD_POINTER_SPACE: /* NOLINT */ \
653 case (base_tag) + OLD_DATA_SPACE: /* NOLINT */ \
654 case (base_tag) + CODE_SPACE: /* NOLINT */ \
655 case (base_tag) + MAP_SPACE: /* NOLINT */ \
656 case (base_tag) + CELL_SPACE: /* NOLINT */ \
657 case (base_tag) + kLargeData: /* NOLINT */ \
658 case (base_tag) + kLargeCode: /* NOLINT */ \
659 case (base_tag) + kLargeFixedArray: /* NOLINT */
660
661
662void Deserializer::ReadChunk(Object** current,
663 Object** limit,
664 int space,
665 Address address) {
666 while (current < limit) {
667 int data = source_->Get();
668 switch (data) {
669#define RAW_CASE(index, size) \
670 case RAW_DATA_SERIALIZATION + index: { \
671 byte* raw_data_out = reinterpret_cast<byte*>(current); \
672 source_->CopyRaw(raw_data_out, size); \
673 current = reinterpret_cast<Object**>(raw_data_out + size); \
674 break; \
675 }
676 COMMON_RAW_LENGTHS(RAW_CASE)
677#undef RAW_CASE
678 case RAW_DATA_SERIALIZATION: {
679 int size = source_->GetInt();
680 byte* raw_data_out = reinterpret_cast<byte*>(current);
681 source_->CopyRaw(raw_data_out, size);
682 current = reinterpret_cast<Object**>(raw_data_out + size);
683 break;
684 }
685 case OBJECT_SERIALIZATION + NEW_SPACE: {
686 ReadObject(NEW_SPACE, Heap::new_space(), current);
687 if (space != NEW_SPACE) {
688 Heap::RecordWrite(address, static_cast<int>(
689 reinterpret_cast<Address>(current) - address));
690 }
691 current++;
692 break;
693 }
694 case OBJECT_SERIALIZATION + OLD_DATA_SPACE:
695 ReadObject(OLD_DATA_SPACE, Heap::old_data_space(), current++);
696 break;
697 case OBJECT_SERIALIZATION + OLD_POINTER_SPACE:
698 ReadObject(OLD_POINTER_SPACE, Heap::old_pointer_space(), current++);
699 break;
700 case OBJECT_SERIALIZATION + MAP_SPACE:
701 ReadObject(MAP_SPACE, Heap::map_space(), current++);
702 break;
703 case OBJECT_SERIALIZATION + CODE_SPACE:
704 ReadObject(CODE_SPACE, Heap::code_space(), current++);
Steve Blockd0582a62009-12-15 09:54:21 +0000705 break;
706 case OBJECT_SERIALIZATION + CELL_SPACE:
707 ReadObject(CELL_SPACE, Heap::cell_space(), current++);
708 break;
709 case OBJECT_SERIALIZATION + kLargeData:
710 ReadObject(kLargeData, Heap::lo_space(), current++);
711 break;
712 case OBJECT_SERIALIZATION + kLargeCode:
713 ReadObject(kLargeCode, Heap::lo_space(), current++);
Steve Blockd0582a62009-12-15 09:54:21 +0000714 break;
715 case OBJECT_SERIALIZATION + kLargeFixedArray:
716 ReadObject(kLargeFixedArray, Heap::lo_space(), current++);
717 break;
718 case CODE_OBJECT_SERIALIZATION + kLargeCode: {
719 Object* new_code_object = NULL;
720 ReadObject(kLargeCode, Heap::lo_space(), &new_code_object);
721 Code* code_object = reinterpret_cast<Code*>(new_code_object);
Steve Blockd0582a62009-12-15 09:54:21 +0000722 // Setting a branch/call to another code object from code.
723 Address location_of_branch_data = reinterpret_cast<Address>(current);
724 Assembler::set_target_at(location_of_branch_data,
725 code_object->instruction_start());
726 location_of_branch_data += Assembler::kCallTargetSize;
727 current = reinterpret_cast<Object**>(location_of_branch_data);
728 break;
729 }
730 case CODE_OBJECT_SERIALIZATION + CODE_SPACE: {
731 Object* new_code_object = NULL;
732 ReadObject(CODE_SPACE, Heap::code_space(), &new_code_object);
733 Code* code_object = reinterpret_cast<Code*>(new_code_object);
Steve Blockd0582a62009-12-15 09:54:21 +0000734 // Setting a branch/call to another code object from code.
735 Address location_of_branch_data = reinterpret_cast<Address>(current);
736 Assembler::set_target_at(location_of_branch_data,
737 code_object->instruction_start());
738 location_of_branch_data += Assembler::kCallTargetSize;
739 current = reinterpret_cast<Object**>(location_of_branch_data);
740 break;
741 }
742 ONE_CASE_PER_SPACE(BACKREF_SERIALIZATION) {
743 // Write a backreference to an object we unpacked earlier.
744 int backref_space = (data & kSpaceMask);
745 if (backref_space == NEW_SPACE && space != NEW_SPACE) {
746 Heap::RecordWrite(address, static_cast<int>(
747 reinterpret_cast<Address>(current) - address));
748 }
749 *current++ = GetAddressFromEnd(backref_space);
750 break;
751 }
752 ONE_CASE_PER_SPACE(REFERENCE_SERIALIZATION) {
753 // Write a reference to an object we unpacked earlier.
754 int reference_space = (data & kSpaceMask);
755 if (reference_space == NEW_SPACE && space != NEW_SPACE) {
756 Heap::RecordWrite(address, static_cast<int>(
757 reinterpret_cast<Address>(current) - address));
758 }
759 *current++ = GetAddressFromStart(reference_space);
760 break;
761 }
762#define COMMON_REFS_CASE(index, reference_space, address) \
763 case REFERENCE_SERIALIZATION + index: { \
764 ASSERT(SpaceIsPaged(reference_space)); \
765 Address object_address = \
766 pages_[reference_space][0] + (address << kObjectAlignmentBits); \
767 *current++ = HeapObject::FromAddress(object_address); \
768 break; \
769 }
770 COMMON_REFERENCE_PATTERNS(COMMON_REFS_CASE)
771#undef COMMON_REFS_CASE
772 ONE_CASE_PER_SPACE(CODE_BACKREF_SERIALIZATION) {
773 int backref_space = (data & kSpaceMask);
774 // Can't use Code::cast because heap is not set up yet and assertions
775 // will fail.
776 Code* code_object =
777 reinterpret_cast<Code*>(GetAddressFromEnd(backref_space));
778 // Setting a branch/call to previously decoded code object from code.
779 Address location_of_branch_data = reinterpret_cast<Address>(current);
780 Assembler::set_target_at(location_of_branch_data,
781 code_object->instruction_start());
782 location_of_branch_data += Assembler::kCallTargetSize;
783 current = reinterpret_cast<Object**>(location_of_branch_data);
784 break;
785 }
786 ONE_CASE_PER_SPACE(CODE_REFERENCE_SERIALIZATION) {
787 int backref_space = (data & kSpaceMask);
788 // Can't use Code::cast because heap is not set up yet and assertions
789 // will fail.
790 Code* code_object =
791 reinterpret_cast<Code*>(GetAddressFromStart(backref_space));
792 // Setting a branch/call to previously decoded code object from code.
793 Address location_of_branch_data = reinterpret_cast<Address>(current);
794 Assembler::set_target_at(location_of_branch_data,
795 code_object->instruction_start());
796 location_of_branch_data += Assembler::kCallTargetSize;
797 current = reinterpret_cast<Object**>(location_of_branch_data);
798 break;
799 }
800 case EXTERNAL_REFERENCE_SERIALIZATION: {
801 int reference_id = source_->GetInt();
802 Address address = external_reference_decoder_->Decode(reference_id);
803 *current++ = reinterpret_cast<Object*>(address);
804 break;
805 }
806 case EXTERNAL_BRANCH_TARGET_SERIALIZATION: {
807 int reference_id = source_->GetInt();
808 Address address = external_reference_decoder_->Decode(reference_id);
809 Address location_of_branch_data = reinterpret_cast<Address>(current);
810 Assembler::set_external_target_at(location_of_branch_data, address);
811 location_of_branch_data += Assembler::kExternalTargetSize;
812 current = reinterpret_cast<Object**>(location_of_branch_data);
813 break;
814 }
815 case START_NEW_PAGE_SERIALIZATION: {
816 int space = source_->Get();
817 pages_[space].Add(last_object_address_);
818 break;
819 }
820 case NATIVES_STRING_RESOURCE: {
821 int index = source_->Get();
822 Vector<const char> source_vector = Natives::GetScriptSource(index);
823 NativesExternalStringResource* resource =
824 new NativesExternalStringResource(source_vector.start());
825 *current++ = reinterpret_cast<Object*>(resource);
826 break;
827 }
Leon Clarkee46be812010-01-19 14:06:41 +0000828 case ROOT_SERIALIZATION: {
829 int root_id = source_->GetInt();
830 *current++ = Heap::roots_address()[root_id];
831 break;
832 }
Leon Clarked91b9f72010-01-27 17:25:45 +0000833 case PARTIAL_SNAPSHOT_CACHE_ENTRY: {
834 int cache_index = source_->GetInt();
835 *current++ = partial_snapshot_cache_[cache_index];
836 break;
837 }
838 case SYNCHRONIZE: {
839 // If we get here then that indicates that you have a mismatch between
840 // the number of GC roots when serializing and deserializing.
841 UNREACHABLE();
842 }
Steve Blockd0582a62009-12-15 09:54:21 +0000843 default:
844 UNREACHABLE();
845 }
846 }
847 ASSERT_EQ(current, limit);
848}
849
850
851void SnapshotByteSink::PutInt(uintptr_t integer, const char* description) {
852 const int max_shift = ((kPointerSize * kBitsPerByte) / 7) * 7;
853 for (int shift = max_shift; shift > 0; shift -= 7) {
854 if (integer >= static_cast<uintptr_t>(1u) << shift) {
855 Put(((integer >> shift) & 0x7f) | 0x80, "IntPart");
856 }
857 }
858 PutSection(integer & 0x7f, "IntLastPart");
859}
860
Steve Blocka7e24c12009-10-30 11:49:00 +0000861#ifdef DEBUG
Steve Blockd0582a62009-12-15 09:54:21 +0000862
863void Deserializer::Synchronize(const char* tag) {
864 int data = source_->Get();
865 // If this assert fails then that indicates that you have a mismatch between
866 // the number of GC roots when serializing and deserializing.
867 ASSERT_EQ(SYNCHRONIZE, data);
868 do {
869 int character = source_->Get();
870 if (character == 0) break;
871 if (FLAG_debug_serialization) {
872 PrintF("%c", character);
873 }
874 } while (true);
875 if (FLAG_debug_serialization) {
876 PrintF("\n");
877 }
878}
879
Steve Blocka7e24c12009-10-30 11:49:00 +0000880
881void Serializer::Synchronize(const char* tag) {
Steve Blockd0582a62009-12-15 09:54:21 +0000882 sink_->Put(SYNCHRONIZE, tag);
883 int character;
884 do {
885 character = *tag++;
886 sink_->PutSection(character, "TagCharacter");
887 } while (character != 0);
Steve Blocka7e24c12009-10-30 11:49:00 +0000888}
Steve Blockd0582a62009-12-15 09:54:21 +0000889
Steve Blocka7e24c12009-10-30 11:49:00 +0000890#endif
891
Steve Blockd0582a62009-12-15 09:54:21 +0000892Serializer::Serializer(SnapshotByteSink* sink)
893 : sink_(sink),
894 current_root_index_(0),
Andrei Popescu31002712010-02-23 13:46:05 +0000895 external_reference_encoder_(new ExternalReferenceEncoder),
Leon Clarkee46be812010-01-19 14:06:41 +0000896 large_object_total_(0) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000897 for (int i = 0; i <= LAST_SPACE; i++) {
Steve Blockd0582a62009-12-15 09:54:21 +0000898 fullness_[i] = 0;
Steve Blocka7e24c12009-10-30 11:49:00 +0000899 }
900}
901
902
Andrei Popescu31002712010-02-23 13:46:05 +0000903Serializer::~Serializer() {
904 delete external_reference_encoder_;
905}
906
907
Leon Clarked91b9f72010-01-27 17:25:45 +0000908void StartupSerializer::SerializeStrongReferences() {
Steve Blocka7e24c12009-10-30 11:49:00 +0000909 // No active threads.
910 CHECK_EQ(NULL, ThreadState::FirstInUse());
911 // No active or weak handles.
912 CHECK(HandleScopeImplementer::instance()->blocks()->is_empty());
913 CHECK_EQ(0, GlobalHandles::NumberOfWeakHandles());
Steve Blockd0582a62009-12-15 09:54:21 +0000914 // We don't support serializing installed extensions.
915 for (RegisteredExtension* ext = RegisteredExtension::first_extension();
916 ext != NULL;
917 ext = ext->next()) {
918 CHECK_NE(v8::INSTALLED, ext->state());
919 }
Leon Clarked91b9f72010-01-27 17:25:45 +0000920 Heap::IterateStrongRoots(this, VISIT_ONLY_STRONG);
Steve Blocka7e24c12009-10-30 11:49:00 +0000921}
922
923
Leon Clarked91b9f72010-01-27 17:25:45 +0000924void PartialSerializer::Serialize(Object** object) {
Leon Clarkee46be812010-01-19 14:06:41 +0000925 this->VisitPointer(object);
Leon Clarked91b9f72010-01-27 17:25:45 +0000926
927 // After we have done the partial serialization the partial snapshot cache
928 // will contain some references needed to decode the partial snapshot. We
929 // fill it up with undefineds so it has a predictable length so the
930 // deserialization code doesn't need to know the length.
931 for (int index = partial_snapshot_cache_length_;
932 index < kPartialSnapshotCacheCapacity;
933 index++) {
934 partial_snapshot_cache_[index] = Heap::undefined_value();
935 startup_serializer_->VisitPointer(&partial_snapshot_cache_[index]);
936 }
937 partial_snapshot_cache_length_ = kPartialSnapshotCacheCapacity;
Leon Clarkee46be812010-01-19 14:06:41 +0000938}
939
940
Steve Blocka7e24c12009-10-30 11:49:00 +0000941void Serializer::VisitPointers(Object** start, Object** end) {
Steve Blockd0582a62009-12-15 09:54:21 +0000942 for (Object** current = start; current < end; current++) {
943 if ((*current)->IsSmi()) {
944 sink_->Put(RAW_DATA_SERIALIZATION, "RawData");
945 sink_->PutInt(kPointerSize, "length");
946 for (int i = 0; i < kPointerSize; i++) {
947 sink_->Put(reinterpret_cast<byte*>(current)[i], "Byte");
948 }
Steve Blocka7e24c12009-10-30 11:49:00 +0000949 } else {
Steve Blockd0582a62009-12-15 09:54:21 +0000950 SerializeObject(*current, TAGGED_REPRESENTATION);
Steve Blocka7e24c12009-10-30 11:49:00 +0000951 }
952 }
953}
954
955
Leon Clarked91b9f72010-01-27 17:25:45 +0000956Object* SerializerDeserializer::partial_snapshot_cache_[
957 kPartialSnapshotCacheCapacity];
958int SerializerDeserializer::partial_snapshot_cache_length_ = 0;
959
960
961// This ensures that the partial snapshot cache keeps things alive during GC and
962// tracks their movement. When it is called during serialization of the startup
963// snapshot the partial snapshot is empty, so nothing happens. When the partial
964// (context) snapshot is created, this array is populated with the pointers that
965// the partial snapshot will need. As that happens we emit serialized objects to
966// the startup snapshot that correspond to the elements of this cache array. On
967// deserialization we therefore need to visit the cache array. This fills it up
968// with pointers to deserialized objects.
969void SerializerDeserializer::Iterate(ObjectVisitor *visitor) {
970 visitor->VisitPointers(
971 &partial_snapshot_cache_[0],
972 &partial_snapshot_cache_[partial_snapshot_cache_length_]);
973}
974
975
976// When deserializing we need to set the size of the snapshot cache. This means
977// the root iteration code (above) will iterate over array elements, writing the
978// references to deserialized objects in them.
979void SerializerDeserializer::SetSnapshotCacheSize(int size) {
980 partial_snapshot_cache_length_ = size;
981}
982
983
984int PartialSerializer::PartialSnapshotCacheIndex(HeapObject* heap_object) {
985 for (int i = 0; i < partial_snapshot_cache_length_; i++) {
986 Object* entry = partial_snapshot_cache_[i];
987 if (entry == heap_object) return i;
988 }
Andrei Popescu31002712010-02-23 13:46:05 +0000989
Leon Clarked91b9f72010-01-27 17:25:45 +0000990 // We didn't find the object in the cache. So we add it to the cache and
991 // then visit the pointer so that it becomes part of the startup snapshot
992 // and we can refer to it from the partial snapshot.
993 int length = partial_snapshot_cache_length_;
994 CHECK(length < kPartialSnapshotCacheCapacity);
995 partial_snapshot_cache_[length] = heap_object;
996 startup_serializer_->VisitPointer(&partial_snapshot_cache_[length]);
997 // We don't recurse from the startup snapshot generator into the partial
998 // snapshot generator.
999 ASSERT(length == partial_snapshot_cache_length_);
1000 return partial_snapshot_cache_length_++;
1001}
1002
1003
1004int PartialSerializer::RootIndex(HeapObject* heap_object) {
Leon Clarkee46be812010-01-19 14:06:41 +00001005 for (int i = 0; i < Heap::kRootListLength; i++) {
1006 Object* root = Heap::roots_address()[i];
1007 if (root == heap_object) return i;
1008 }
1009 return kInvalidRootIndex;
1010}
1011
1012
Leon Clarked91b9f72010-01-27 17:25:45 +00001013// Encode the location of an already deserialized object in order to write its
1014// location into a later object. We can encode the location as an offset from
1015// the start of the deserialized objects or as an offset backwards from the
1016// current allocation pointer.
1017void Serializer::SerializeReferenceToPreviousObject(
1018 int space,
1019 int address,
1020 ReferenceRepresentation reference_representation) {
1021 int offset = CurrentAllocationAddress(space) - address;
1022 bool from_start = true;
1023 if (SpaceIsPaged(space)) {
1024 // For paged space it is simple to encode back from current allocation if
1025 // the object is on the same page as the current allocation pointer.
1026 if ((CurrentAllocationAddress(space) >> kPageSizeBits) ==
1027 (address >> kPageSizeBits)) {
1028 from_start = false;
1029 address = offset;
1030 }
1031 } else if (space == NEW_SPACE) {
1032 // For new space it is always simple to encode back from current allocation.
1033 if (offset < address) {
1034 from_start = false;
1035 address = offset;
1036 }
1037 }
1038 // If we are actually dealing with real offsets (and not a numbering of
1039 // all objects) then we should shift out the bits that are always 0.
1040 if (!SpaceIsLarge(space)) address >>= kObjectAlignmentBits;
1041 // On some architectures references between code objects are encoded
1042 // specially (as relative offsets). Such references have their own
1043 // special tags to simplify the deserializer.
1044 if (reference_representation == CODE_TARGET_REPRESENTATION) {
1045 if (from_start) {
1046 sink_->Put(CODE_REFERENCE_SERIALIZATION + space, "RefCodeSer");
1047 sink_->PutInt(address, "address");
1048 } else {
1049 sink_->Put(CODE_BACKREF_SERIALIZATION + space, "BackRefCodeSer");
1050 sink_->PutInt(address, "address");
1051 }
1052 } else {
1053 // Regular absolute references.
1054 CHECK_EQ(TAGGED_REPRESENTATION, reference_representation);
1055 if (from_start) {
1056 // There are some common offsets that have their own specialized encoding.
1057#define COMMON_REFS_CASE(tag, common_space, common_offset) \
1058 if (space == common_space && address == common_offset) { \
1059 sink_->PutSection(tag + REFERENCE_SERIALIZATION, "RefSer"); \
1060 } else /* NOLINT */
1061 COMMON_REFERENCE_PATTERNS(COMMON_REFS_CASE)
1062#undef COMMON_REFS_CASE
1063 { /* NOLINT */
1064 sink_->Put(REFERENCE_SERIALIZATION + space, "RefSer");
1065 sink_->PutInt(address, "address");
1066 }
1067 } else {
1068 sink_->Put(BACKREF_SERIALIZATION + space, "BackRefSer");
1069 sink_->PutInt(address, "address");
1070 }
1071 }
1072}
1073
1074
1075void StartupSerializer::SerializeObject(
Leon Clarkeeab96aa2010-01-27 16:31:12 +00001076 Object* o,
Leon Clarke888f6722010-01-27 15:57:47 +00001077 ReferenceRepresentation reference_representation) {
Leon Clarkeeab96aa2010-01-27 16:31:12 +00001078 CHECK(o->IsHeapObject());
1079 HeapObject* heap_object = HeapObject::cast(o);
Leon Clarked91b9f72010-01-27 17:25:45 +00001080
1081 if (address_mapper_.IsMapped(heap_object)) {
Leon Clarkeeab96aa2010-01-27 16:31:12 +00001082 int space = SpaceOfAlreadySerializedObject(heap_object);
Leon Clarked91b9f72010-01-27 17:25:45 +00001083 int address = address_mapper_.MappedTo(heap_object);
1084 SerializeReferenceToPreviousObject(space,
1085 address,
1086 reference_representation);
1087 } else {
1088 // Object has not yet been serialized. Serialize it here.
1089 ObjectSerializer object_serializer(this,
1090 heap_object,
1091 sink_,
1092 reference_representation);
1093 object_serializer.Serialize();
1094 }
1095}
1096
1097
1098void StartupSerializer::SerializeWeakReferences() {
1099 for (int i = partial_snapshot_cache_length_;
1100 i < kPartialSnapshotCacheCapacity;
1101 i++) {
1102 sink_->Put(ROOT_SERIALIZATION, "RootSerialization");
1103 sink_->PutInt(Heap::kUndefinedValueRootIndex, "root_index");
1104 }
1105 Heap::IterateWeakRoots(this, VISIT_ALL);
1106}
1107
1108
1109void PartialSerializer::SerializeObject(
1110 Object* o,
1111 ReferenceRepresentation reference_representation) {
1112 CHECK(o->IsHeapObject());
1113 HeapObject* heap_object = HeapObject::cast(o);
1114
1115 int root_index;
1116 if ((root_index = RootIndex(heap_object)) != kInvalidRootIndex) {
1117 sink_->Put(ROOT_SERIALIZATION, "RootSerialization");
1118 sink_->PutInt(root_index, "root_index");
1119 return;
1120 }
1121
1122 if (ShouldBeInThePartialSnapshotCache(heap_object)) {
1123 int cache_index = PartialSnapshotCacheIndex(heap_object);
1124 sink_->Put(PARTIAL_SNAPSHOT_CACHE_ENTRY, "PartialSnapshotCache");
1125 sink_->PutInt(cache_index, "partial_snapshot_cache_index");
1126 return;
1127 }
1128
1129 // Pointers from the partial snapshot to the objects in the startup snapshot
1130 // should go through the root array or through the partial snapshot cache.
1131 // If this is not the case you may have to add something to the root array.
1132 ASSERT(!startup_serializer_->address_mapper()->IsMapped(heap_object));
1133 // All the symbols that the partial snapshot needs should be either in the
1134 // root table or in the partial snapshot cache.
1135 ASSERT(!heap_object->IsSymbol());
1136
1137 if (address_mapper_.IsMapped(heap_object)) {
1138 int space = SpaceOfAlreadySerializedObject(heap_object);
1139 int address = address_mapper_.MappedTo(heap_object);
1140 SerializeReferenceToPreviousObject(space,
1141 address,
1142 reference_representation);
Steve Blockd0582a62009-12-15 09:54:21 +00001143 } else {
1144 // Object has not yet been serialized. Serialize it here.
1145 ObjectSerializer serializer(this,
1146 heap_object,
1147 sink_,
1148 reference_representation);
1149 serializer.Serialize();
1150 }
1151}
1152
1153
Steve Blockd0582a62009-12-15 09:54:21 +00001154void Serializer::ObjectSerializer::Serialize() {
1155 int space = Serializer::SpaceOfObject(object_);
1156 int size = object_->Size();
1157
1158 if (reference_representation_ == TAGGED_REPRESENTATION) {
1159 sink_->Put(OBJECT_SERIALIZATION + space, "ObjectSerialization");
1160 } else {
1161 CHECK_EQ(CODE_TARGET_REPRESENTATION, reference_representation_);
1162 sink_->Put(CODE_OBJECT_SERIALIZATION + space, "ObjectSerialization");
1163 }
1164 sink_->PutInt(size >> kObjectAlignmentBits, "Size in words");
1165
Leon Clarkee46be812010-01-19 14:06:41 +00001166 LOG(SnapshotPositionEvent(object_->address(), sink_->Position()));
1167
Steve Blockd0582a62009-12-15 09:54:21 +00001168 // Mark this object as already serialized.
1169 bool start_new_page;
Leon Clarked91b9f72010-01-27 17:25:45 +00001170 int offset = serializer_->Allocate(space, size, &start_new_page);
1171 serializer_->address_mapper()->AddMapping(object_, offset);
Steve Blockd0582a62009-12-15 09:54:21 +00001172 if (start_new_page) {
1173 sink_->Put(START_NEW_PAGE_SERIALIZATION, "NewPage");
1174 sink_->PutSection(space, "NewPageSpace");
1175 }
1176
1177 // Serialize the map (first word of the object).
1178 serializer_->SerializeObject(object_->map(), TAGGED_REPRESENTATION);
1179
1180 // Serialize the rest of the object.
1181 CHECK_EQ(0, bytes_processed_so_far_);
1182 bytes_processed_so_far_ = kPointerSize;
1183 object_->IterateBody(object_->map()->instance_type(), size, this);
1184 OutputRawData(object_->address() + size);
1185}
1186
1187
1188void Serializer::ObjectSerializer::VisitPointers(Object** start,
1189 Object** end) {
1190 Object** current = start;
1191 while (current < end) {
1192 while (current < end && (*current)->IsSmi()) current++;
1193 if (current < end) OutputRawData(reinterpret_cast<Address>(current));
1194
1195 while (current < end && !(*current)->IsSmi()) {
1196 serializer_->SerializeObject(*current, TAGGED_REPRESENTATION);
1197 bytes_processed_so_far_ += kPointerSize;
1198 current++;
1199 }
1200 }
1201}
1202
1203
1204void Serializer::ObjectSerializer::VisitExternalReferences(Address* start,
1205 Address* end) {
1206 Address references_start = reinterpret_cast<Address>(start);
1207 OutputRawData(references_start);
1208
1209 for (Address* current = start; current < end; current++) {
1210 sink_->Put(EXTERNAL_REFERENCE_SERIALIZATION, "ExternalReference");
1211 int reference_id = serializer_->EncodeExternalReference(*current);
1212 sink_->PutInt(reference_id, "reference id");
1213 }
1214 bytes_processed_so_far_ += static_cast<int>((end - start) * kPointerSize);
1215}
1216
1217
1218void Serializer::ObjectSerializer::VisitRuntimeEntry(RelocInfo* rinfo) {
1219 Address target_start = rinfo->target_address_address();
1220 OutputRawData(target_start);
1221 Address target = rinfo->target_address();
1222 uint32_t encoding = serializer_->EncodeExternalReference(target);
1223 CHECK(target == NULL ? encoding == 0 : encoding != 0);
1224 sink_->Put(EXTERNAL_BRANCH_TARGET_SERIALIZATION, "ExternalReference");
1225 sink_->PutInt(encoding, "reference id");
1226 bytes_processed_so_far_ += Assembler::kExternalTargetSize;
1227}
1228
1229
1230void Serializer::ObjectSerializer::VisitCodeTarget(RelocInfo* rinfo) {
1231 CHECK(RelocInfo::IsCodeTarget(rinfo->rmode()));
1232 Address target_start = rinfo->target_address_address();
1233 OutputRawData(target_start);
1234 Code* target = Code::GetCodeFromTargetAddress(rinfo->target_address());
1235 serializer_->SerializeObject(target, CODE_TARGET_REPRESENTATION);
1236 bytes_processed_so_far_ += Assembler::kCallTargetSize;
1237}
1238
1239
1240void Serializer::ObjectSerializer::VisitExternalAsciiString(
1241 v8::String::ExternalAsciiStringResource** resource_pointer) {
1242 Address references_start = reinterpret_cast<Address>(resource_pointer);
1243 OutputRawData(references_start);
1244 for (int i = 0; i < Natives::GetBuiltinsCount(); i++) {
1245 Object* source = Heap::natives_source_cache()->get(i);
1246 if (!source->IsUndefined()) {
1247 ExternalAsciiString* string = ExternalAsciiString::cast(source);
1248 typedef v8::String::ExternalAsciiStringResource Resource;
1249 Resource* resource = string->resource();
1250 if (resource == *resource_pointer) {
1251 sink_->Put(NATIVES_STRING_RESOURCE, "NativesStringResource");
1252 sink_->PutSection(i, "NativesStringResourceEnd");
1253 bytes_processed_so_far_ += sizeof(resource);
1254 return;
1255 }
1256 }
1257 }
1258 // One of the strings in the natives cache should match the resource. We
1259 // can't serialize any other kinds of external strings.
1260 UNREACHABLE();
1261}
1262
1263
1264void Serializer::ObjectSerializer::OutputRawData(Address up_to) {
1265 Address object_start = object_->address();
1266 int up_to_offset = static_cast<int>(up_to - object_start);
1267 int skipped = up_to_offset - bytes_processed_so_far_;
1268 // This assert will fail if the reloc info gives us the target_address_address
1269 // locations in a non-ascending order. Luckily that doesn't happen.
1270 ASSERT(skipped >= 0);
1271 if (skipped != 0) {
1272 Address base = object_start + bytes_processed_so_far_;
1273#define RAW_CASE(index, length) \
1274 if (skipped == length) { \
1275 sink_->PutSection(RAW_DATA_SERIALIZATION + index, "RawDataFixed"); \
1276 } else /* NOLINT */
1277 COMMON_RAW_LENGTHS(RAW_CASE)
1278#undef RAW_CASE
1279 { /* NOLINT */
1280 sink_->Put(RAW_DATA_SERIALIZATION, "RawData");
1281 sink_->PutInt(skipped, "length");
1282 }
1283 for (int i = 0; i < skipped; i++) {
1284 unsigned int data = base[i];
1285 sink_->PutSection(data, "Byte");
1286 }
1287 bytes_processed_so_far_ += skipped;
1288 }
1289}
1290
1291
1292int Serializer::SpaceOfObject(HeapObject* object) {
1293 for (int i = FIRST_SPACE; i <= LAST_SPACE; i++) {
1294 AllocationSpace s = static_cast<AllocationSpace>(i);
1295 if (Heap::InSpace(object, s)) {
1296 if (i == LO_SPACE) {
1297 if (object->IsCode()) {
1298 return kLargeCode;
1299 } else if (object->IsFixedArray()) {
1300 return kLargeFixedArray;
1301 } else {
1302 return kLargeData;
1303 }
1304 }
1305 return i;
1306 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001307 }
1308 UNREACHABLE();
Steve Blockd0582a62009-12-15 09:54:21 +00001309 return 0;
1310}
1311
1312
1313int Serializer::SpaceOfAlreadySerializedObject(HeapObject* object) {
1314 for (int i = FIRST_SPACE; i <= LAST_SPACE; i++) {
1315 AllocationSpace s = static_cast<AllocationSpace>(i);
1316 if (Heap::InSpace(object, s)) {
1317 return i;
1318 }
1319 }
1320 UNREACHABLE();
1321 return 0;
1322}
1323
1324
1325int Serializer::Allocate(int space, int size, bool* new_page) {
1326 CHECK(space >= 0 && space < kNumberOfSpaces);
1327 if (SpaceIsLarge(space)) {
1328 // In large object space we merely number the objects instead of trying to
1329 // determine some sort of address.
1330 *new_page = true;
Leon Clarkee46be812010-01-19 14:06:41 +00001331 large_object_total_ += size;
Steve Blockd0582a62009-12-15 09:54:21 +00001332 return fullness_[LO_SPACE]++;
1333 }
1334 *new_page = false;
1335 if (fullness_[space] == 0) {
1336 *new_page = true;
1337 }
1338 if (SpaceIsPaged(space)) {
1339 // Paged spaces are a little special. We encode their addresses as if the
1340 // pages were all contiguous and each page were filled up in the range
1341 // 0 - Page::kObjectAreaSize. In practice the pages may not be contiguous
1342 // and allocation does not start at offset 0 in the page, but this scheme
1343 // means the deserializer can get the page number quickly by shifting the
1344 // serialized address.
1345 CHECK(IsPowerOf2(Page::kPageSize));
1346 int used_in_this_page = (fullness_[space] & (Page::kPageSize - 1));
1347 CHECK(size <= Page::kObjectAreaSize);
1348 if (used_in_this_page + size > Page::kObjectAreaSize) {
1349 *new_page = true;
1350 fullness_[space] = RoundUp(fullness_[space], Page::kPageSize);
1351 }
1352 }
1353 int allocation_address = fullness_[space];
1354 fullness_[space] = allocation_address + size;
1355 return allocation_address;
Steve Blocka7e24c12009-10-30 11:49:00 +00001356}
1357
1358
1359} } // namespace v8::internal