blob: e610e28366d1431d911f788d8612867c9393bd10 [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()");
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +0100232 Add(Debug_Address(Debug::k_debug_break_slot_address).address(),
233 DEBUG_ADDRESS,
234 Debug::k_debug_break_slot_address << kDebugIdShift,
235 "Debug::debug_break_slot_address()");
Steve Blocka7e24c12009-10-30 11:49:00 +0000236 Add(Debug_Address(Debug::k_debug_break_return_address).address(),
237 DEBUG_ADDRESS,
238 Debug::k_debug_break_return_address << kDebugIdShift,
239 "Debug::debug_break_return_address()");
240 const char* debug_register_format = "Debug::register_address(%i)";
Steve Blockd0582a62009-12-15 09:54:21 +0000241 int dr_format_length = StrLength(debug_register_format);
Steve Blocka7e24c12009-10-30 11:49:00 +0000242 for (int i = 0; i < kNumJSCallerSaved; ++i) {
243 Vector<char> name = Vector<char>::New(dr_format_length + 1);
244 OS::SNPrintF(name, debug_register_format, i);
245 Add(Debug_Address(Debug::k_register_address, i).address(),
246 DEBUG_ADDRESS,
247 Debug::k_register_address << kDebugIdShift | i,
248 name.start());
249 }
250#endif
251
252 // Stat counters
253 struct StatsRefTableEntry {
254 StatsCounter* counter;
255 uint16_t id;
256 const char* name;
257 };
258
259 static const StatsRefTableEntry stats_ref_table[] = {
260#define COUNTER_ENTRY(name, caption) \
261 { &Counters::name, \
262 Counters::k_##name, \
263 "Counters::" #name },
264
265 STATS_COUNTER_LIST_1(COUNTER_ENTRY)
266 STATS_COUNTER_LIST_2(COUNTER_ENTRY)
267#undef COUNTER_ENTRY
268 }; // end of stats_ref_table[].
269
270 for (size_t i = 0; i < ARRAY_SIZE(stats_ref_table); ++i) {
271 Add(reinterpret_cast<Address>(
272 GetInternalPointer(stats_ref_table[i].counter)),
273 STATS_COUNTER,
274 stats_ref_table[i].id,
275 stats_ref_table[i].name);
276 }
277
278 // Top addresses
Steve Block3ce2e202009-11-05 08:53:23 +0000279 const char* top_address_format = "Top::%s";
280
281 const char* AddressNames[] = {
282#define C(name) #name,
283 TOP_ADDRESS_LIST(C)
284 TOP_ADDRESS_LIST_PROF(C)
285 NULL
286#undef C
287 };
288
Steve Blockd0582a62009-12-15 09:54:21 +0000289 int top_format_length = StrLength(top_address_format) - 2;
Steve Blocka7e24c12009-10-30 11:49:00 +0000290 for (uint16_t i = 0; i < Top::k_top_address_count; ++i) {
Steve Block3ce2e202009-11-05 08:53:23 +0000291 const char* address_name = AddressNames[i];
292 Vector<char> name =
Steve Blockd0582a62009-12-15 09:54:21 +0000293 Vector<char>::New(top_format_length + StrLength(address_name) + 1);
Steve Blocka7e24c12009-10-30 11:49:00 +0000294 const char* chars = name.start();
Steve Block3ce2e202009-11-05 08:53:23 +0000295 OS::SNPrintF(name, top_address_format, address_name);
Steve Blocka7e24c12009-10-30 11:49:00 +0000296 Add(Top::get_address_from_id((Top::AddressId)i), TOP_ADDRESS, i, chars);
297 }
298
299 // Extensions
300 Add(FUNCTION_ADDR(GCExtension::GC), EXTENSION, 1,
301 "GCExtension::GC");
302
303 // Accessors
304#define ACCESSOR_DESCRIPTOR_DECLARATION(name) \
305 Add((Address)&Accessors::name, \
306 ACCESSOR, \
307 Accessors::k##name, \
308 "Accessors::" #name);
309
310 ACCESSOR_DESCRIPTOR_LIST(ACCESSOR_DESCRIPTOR_DECLARATION)
311#undef ACCESSOR_DESCRIPTOR_DECLARATION
312
313 // Stub cache tables
314 Add(SCTableReference::keyReference(StubCache::kPrimary).address(),
315 STUB_CACHE_TABLE,
316 1,
317 "StubCache::primary_->key");
318 Add(SCTableReference::valueReference(StubCache::kPrimary).address(),
319 STUB_CACHE_TABLE,
320 2,
321 "StubCache::primary_->value");
322 Add(SCTableReference::keyReference(StubCache::kSecondary).address(),
323 STUB_CACHE_TABLE,
324 3,
325 "StubCache::secondary_->key");
326 Add(SCTableReference::valueReference(StubCache::kSecondary).address(),
327 STUB_CACHE_TABLE,
328 4,
329 "StubCache::secondary_->value");
330
331 // Runtime entries
332 Add(ExternalReference::perform_gc_function().address(),
333 RUNTIME_ENTRY,
334 1,
335 "Runtime::PerformGC");
Steve Block6ded16b2010-05-10 14:33:55 +0100336 Add(ExternalReference::fill_heap_number_with_random_function().address(),
Steve Blocka7e24c12009-10-30 11:49:00 +0000337 RUNTIME_ENTRY,
338 2,
Steve Block6ded16b2010-05-10 14:33:55 +0100339 "V8::FillHeapNumberWithRandom");
340
341 Add(ExternalReference::random_uint32_function().address(),
342 RUNTIME_ENTRY,
343 3,
344 "V8::Random");
Steve Blocka7e24c12009-10-30 11:49:00 +0000345
346 // Miscellaneous
Steve Blocka7e24c12009-10-30 11:49:00 +0000347 Add(ExternalReference::the_hole_value_location().address(),
348 UNCLASSIFIED,
349 2,
350 "Factory::the_hole_value().location()");
351 Add(ExternalReference::roots_address().address(),
352 UNCLASSIFIED,
353 3,
354 "Heap::roots_address()");
Steve Blockd0582a62009-12-15 09:54:21 +0000355 Add(ExternalReference::address_of_stack_limit().address(),
Steve Blocka7e24c12009-10-30 11:49:00 +0000356 UNCLASSIFIED,
357 4,
358 "StackGuard::address_of_jslimit()");
Steve Blockd0582a62009-12-15 09:54:21 +0000359 Add(ExternalReference::address_of_real_stack_limit().address(),
Steve Blocka7e24c12009-10-30 11:49:00 +0000360 UNCLASSIFIED,
361 5,
Steve Blockd0582a62009-12-15 09:54:21 +0000362 "StackGuard::address_of_real_jslimit()");
363 Add(ExternalReference::address_of_regexp_stack_limit().address(),
364 UNCLASSIFIED,
365 6,
Steve Blocka7e24c12009-10-30 11:49:00 +0000366 "RegExpStack::limit_address()");
367 Add(ExternalReference::new_space_start().address(),
368 UNCLASSIFIED,
Steve Blockd0582a62009-12-15 09:54:21 +0000369 7,
Steve Blocka7e24c12009-10-30 11:49:00 +0000370 "Heap::NewSpaceStart()");
Andrei Popescu402d9372010-02-26 13:31:12 +0000371 Add(ExternalReference::new_space_mask().address(),
Steve Blocka7e24c12009-10-30 11:49:00 +0000372 UNCLASSIFIED,
Steve Blockd0582a62009-12-15 09:54:21 +0000373 8,
Andrei Popescu402d9372010-02-26 13:31:12 +0000374 "Heap::NewSpaceMask()");
375 Add(ExternalReference::heap_always_allocate_scope_depth().address(),
376 UNCLASSIFIED,
377 9,
Steve Blocka7e24c12009-10-30 11:49:00 +0000378 "Heap::always_allocate_scope_depth()");
379 Add(ExternalReference::new_space_allocation_limit_address().address(),
380 UNCLASSIFIED,
Andrei Popescu402d9372010-02-26 13:31:12 +0000381 10,
Steve Blocka7e24c12009-10-30 11:49:00 +0000382 "Heap::NewSpaceAllocationLimitAddress()");
383 Add(ExternalReference::new_space_allocation_top_address().address(),
384 UNCLASSIFIED,
Andrei Popescu402d9372010-02-26 13:31:12 +0000385 11,
Steve Blocka7e24c12009-10-30 11:49:00 +0000386 "Heap::NewSpaceAllocationTopAddress()");
387#ifdef ENABLE_DEBUGGER_SUPPORT
388 Add(ExternalReference::debug_break().address(),
389 UNCLASSIFIED,
Andrei Popescu402d9372010-02-26 13:31:12 +0000390 12,
Steve Blocka7e24c12009-10-30 11:49:00 +0000391 "Debug::Break()");
392 Add(ExternalReference::debug_step_in_fp_address().address(),
393 UNCLASSIFIED,
Andrei Popescu402d9372010-02-26 13:31:12 +0000394 13,
Steve Blocka7e24c12009-10-30 11:49:00 +0000395 "Debug::step_in_fp_addr()");
396#endif
397 Add(ExternalReference::double_fp_operation(Token::ADD).address(),
398 UNCLASSIFIED,
Andrei Popescu402d9372010-02-26 13:31:12 +0000399 14,
Steve Blocka7e24c12009-10-30 11:49:00 +0000400 "add_two_doubles");
401 Add(ExternalReference::double_fp_operation(Token::SUB).address(),
402 UNCLASSIFIED,
Andrei Popescu402d9372010-02-26 13:31:12 +0000403 15,
Steve Blocka7e24c12009-10-30 11:49:00 +0000404 "sub_two_doubles");
405 Add(ExternalReference::double_fp_operation(Token::MUL).address(),
406 UNCLASSIFIED,
Andrei Popescu402d9372010-02-26 13:31:12 +0000407 16,
Steve Blocka7e24c12009-10-30 11:49:00 +0000408 "mul_two_doubles");
409 Add(ExternalReference::double_fp_operation(Token::DIV).address(),
410 UNCLASSIFIED,
Andrei Popescu402d9372010-02-26 13:31:12 +0000411 17,
Steve Blocka7e24c12009-10-30 11:49:00 +0000412 "div_two_doubles");
413 Add(ExternalReference::double_fp_operation(Token::MOD).address(),
414 UNCLASSIFIED,
Andrei Popescu402d9372010-02-26 13:31:12 +0000415 18,
Steve Blocka7e24c12009-10-30 11:49:00 +0000416 "mod_two_doubles");
417 Add(ExternalReference::compare_doubles().address(),
418 UNCLASSIFIED,
Andrei Popescu402d9372010-02-26 13:31:12 +0000419 19,
Steve Blocka7e24c12009-10-30 11:49:00 +0000420 "compare_doubles");
Steve Block6ded16b2010-05-10 14:33:55 +0100421#ifndef V8_INTERPRETED_REGEXP
422 Add(ExternalReference::re_case_insensitive_compare_uc16().address(),
423 UNCLASSIFIED,
Kristian Monsen25f61362010-05-21 11:50:48 +0100424 20,
Steve Blocka7e24c12009-10-30 11:49:00 +0000425 "NativeRegExpMacroAssembler::CaseInsensitiveCompareUC16()");
426 Add(ExternalReference::re_check_stack_guard_state().address(),
427 UNCLASSIFIED,
Kristian Monsen25f61362010-05-21 11:50:48 +0100428 21,
Steve Blocka7e24c12009-10-30 11:49:00 +0000429 "RegExpMacroAssembler*::CheckStackGuardState()");
430 Add(ExternalReference::re_grow_stack().address(),
431 UNCLASSIFIED,
Kristian Monsen25f61362010-05-21 11:50:48 +0100432 22,
Steve Blocka7e24c12009-10-30 11:49:00 +0000433 "NativeRegExpMacroAssembler::GrowStack()");
Leon Clarkee46be812010-01-19 14:06:41 +0000434 Add(ExternalReference::re_word_character_map().address(),
435 UNCLASSIFIED,
Kristian Monsen25f61362010-05-21 11:50:48 +0100436 23,
Leon Clarkee46be812010-01-19 14:06:41 +0000437 "NativeRegExpMacroAssembler::word_character_map");
Steve Block6ded16b2010-05-10 14:33:55 +0100438#endif // V8_INTERPRETED_REGEXP
Leon Clarkee46be812010-01-19 14:06:41 +0000439 // Keyed lookup cache.
440 Add(ExternalReference::keyed_lookup_cache_keys().address(),
441 UNCLASSIFIED,
Kristian Monsen25f61362010-05-21 11:50:48 +0100442 24,
Leon Clarkee46be812010-01-19 14:06:41 +0000443 "KeyedLookupCache::keys()");
444 Add(ExternalReference::keyed_lookup_cache_field_offsets().address(),
445 UNCLASSIFIED,
Kristian Monsen25f61362010-05-21 11:50:48 +0100446 25,
Leon Clarkee46be812010-01-19 14:06:41 +0000447 "KeyedLookupCache::field_offsets()");
Andrei Popescu402d9372010-02-26 13:31:12 +0000448 Add(ExternalReference::transcendental_cache_array_address().address(),
449 UNCLASSIFIED,
Kristian Monsen25f61362010-05-21 11:50:48 +0100450 26,
Andrei Popescu402d9372010-02-26 13:31:12 +0000451 "TranscendentalCache::caches()");
Steve Blocka7e24c12009-10-30 11:49:00 +0000452}
453
454
455ExternalReferenceEncoder::ExternalReferenceEncoder()
456 : encodings_(Match) {
457 ExternalReferenceTable* external_references =
458 ExternalReferenceTable::instance();
459 for (int i = 0; i < external_references->size(); ++i) {
460 Put(external_references->address(i), i);
461 }
462}
463
464
465uint32_t ExternalReferenceEncoder::Encode(Address key) const {
466 int index = IndexOf(key);
467 return index >=0 ? ExternalReferenceTable::instance()->code(index) : 0;
468}
469
470
471const char* ExternalReferenceEncoder::NameOfAddress(Address key) const {
472 int index = IndexOf(key);
473 return index >=0 ? ExternalReferenceTable::instance()->name(index) : NULL;
474}
475
476
477int ExternalReferenceEncoder::IndexOf(Address key) const {
478 if (key == NULL) return -1;
479 HashMap::Entry* entry =
480 const_cast<HashMap &>(encodings_).Lookup(key, Hash(key), false);
481 return entry == NULL
482 ? -1
483 : static_cast<int>(reinterpret_cast<intptr_t>(entry->value));
484}
485
486
487void ExternalReferenceEncoder::Put(Address key, int index) {
488 HashMap::Entry* entry = encodings_.Lookup(key, Hash(key), true);
Steve Block6ded16b2010-05-10 14:33:55 +0100489 entry->value = reinterpret_cast<void*>(index);
Steve Blocka7e24c12009-10-30 11:49:00 +0000490}
491
492
493ExternalReferenceDecoder::ExternalReferenceDecoder()
494 : encodings_(NewArray<Address*>(kTypeCodeCount)) {
495 ExternalReferenceTable* external_references =
496 ExternalReferenceTable::instance();
497 for (int type = kFirstTypeCode; type < kTypeCodeCount; ++type) {
498 int max = external_references->max_id(type) + 1;
499 encodings_[type] = NewArray<Address>(max + 1);
500 }
501 for (int i = 0; i < external_references->size(); ++i) {
502 Put(external_references->code(i), external_references->address(i));
503 }
504}
505
506
507ExternalReferenceDecoder::~ExternalReferenceDecoder() {
508 for (int type = kFirstTypeCode; type < kTypeCodeCount; ++type) {
509 DeleteArray(encodings_[type]);
510 }
511 DeleteArray(encodings_);
512}
513
514
Steve Blocka7e24c12009-10-30 11:49:00 +0000515bool Serializer::serialization_enabled_ = false;
Steve Blockd0582a62009-12-15 09:54:21 +0000516bool Serializer::too_late_to_enable_now_ = false;
Leon Clarkee46be812010-01-19 14:06:41 +0000517ExternalReferenceDecoder* Deserializer::external_reference_decoder_ = NULL;
Steve Blocka7e24c12009-10-30 11:49:00 +0000518
519
Leon Clarkee46be812010-01-19 14:06:41 +0000520Deserializer::Deserializer(SnapshotByteSource* source) : source_(source) {
Steve Blockd0582a62009-12-15 09:54:21 +0000521}
522
523
524// This routine both allocates a new object, and also keeps
525// track of where objects have been allocated so that we can
526// fix back references when deserializing.
527Address Deserializer::Allocate(int space_index, Space* space, int size) {
528 Address address;
529 if (!SpaceIsLarge(space_index)) {
530 ASSERT(!SpaceIsPaged(space_index) ||
531 size <= Page::kPageSize - Page::kObjectStartOffset);
532 Object* new_allocation;
533 if (space_index == NEW_SPACE) {
534 new_allocation = reinterpret_cast<NewSpace*>(space)->AllocateRaw(size);
535 } else {
536 new_allocation = reinterpret_cast<PagedSpace*>(space)->AllocateRaw(size);
537 }
538 HeapObject* new_object = HeapObject::cast(new_allocation);
539 ASSERT(!new_object->IsFailure());
540 address = new_object->address();
541 high_water_[space_index] = address + size;
542 } else {
543 ASSERT(SpaceIsLarge(space_index));
544 ASSERT(size > Page::kPageSize - Page::kObjectStartOffset);
545 LargeObjectSpace* lo_space = reinterpret_cast<LargeObjectSpace*>(space);
546 Object* new_allocation;
547 if (space_index == kLargeData) {
548 new_allocation = lo_space->AllocateRaw(size);
549 } else if (space_index == kLargeFixedArray) {
550 new_allocation = lo_space->AllocateRawFixedArray(size);
551 } else {
552 ASSERT_EQ(kLargeCode, space_index);
553 new_allocation = lo_space->AllocateRawCode(size);
554 }
555 ASSERT(!new_allocation->IsFailure());
556 HeapObject* new_object = HeapObject::cast(new_allocation);
557 // Record all large objects in the same space.
558 address = new_object->address();
Andrei Popescu31002712010-02-23 13:46:05 +0000559 pages_[LO_SPACE].Add(address);
Steve Blockd0582a62009-12-15 09:54:21 +0000560 }
561 last_object_address_ = address;
562 return address;
563}
564
565
566// This returns the address of an object that has been described in the
567// snapshot as being offset bytes back in a particular space.
568HeapObject* Deserializer::GetAddressFromEnd(int space) {
569 int offset = source_->GetInt();
570 ASSERT(!SpaceIsLarge(space));
571 offset <<= kObjectAlignmentBits;
572 return HeapObject::FromAddress(high_water_[space] - offset);
573}
574
575
576// This returns the address of an object that has been described in the
577// snapshot as being offset bytes into a particular space.
578HeapObject* Deserializer::GetAddressFromStart(int space) {
579 int offset = source_->GetInt();
580 if (SpaceIsLarge(space)) {
581 // Large spaces have one object per 'page'.
582 return HeapObject::FromAddress(pages_[LO_SPACE][offset]);
583 }
584 offset <<= kObjectAlignmentBits;
585 if (space == NEW_SPACE) {
586 // New space has only one space - numbered 0.
587 return HeapObject::FromAddress(pages_[space][0] + offset);
588 }
589 ASSERT(SpaceIsPaged(space));
Leon Clarkee46be812010-01-19 14:06:41 +0000590 int page_of_pointee = offset >> kPageSizeBits;
Steve Blockd0582a62009-12-15 09:54:21 +0000591 Address object_address = pages_[space][page_of_pointee] +
592 (offset & Page::kPageAlignmentMask);
593 return HeapObject::FromAddress(object_address);
594}
595
596
597void Deserializer::Deserialize() {
598 // Don't GC while deserializing - just expand the heap.
599 AlwaysAllocateScope always_allocate;
600 // Don't use the free lists while deserializing.
601 LinearAllocationScope allocate_linearly;
602 // No active threads.
603 ASSERT_EQ(NULL, ThreadState::FirstInUse());
604 // No active handles.
605 ASSERT(HandleScopeImplementer::instance()->blocks()->is_empty());
Leon Clarked91b9f72010-01-27 17:25:45 +0000606 // Make sure the entire partial snapshot cache is traversed, filling it with
607 // valid object pointers.
608 partial_snapshot_cache_length_ = kPartialSnapshotCacheCapacity;
Steve Blockd0582a62009-12-15 09:54:21 +0000609 ASSERT_EQ(NULL, external_reference_decoder_);
610 external_reference_decoder_ = new ExternalReferenceDecoder();
Leon Clarked91b9f72010-01-27 17:25:45 +0000611 Heap::IterateStrongRoots(this, VISIT_ONLY_STRONG);
612 Heap::IterateWeakRoots(this, VISIT_ALL);
Leon Clarkee46be812010-01-19 14:06:41 +0000613}
614
615
616void Deserializer::DeserializePartial(Object** root) {
617 // Don't GC while deserializing - just expand the heap.
618 AlwaysAllocateScope always_allocate;
619 // Don't use the free lists while deserializing.
620 LinearAllocationScope allocate_linearly;
621 if (external_reference_decoder_ == NULL) {
622 external_reference_decoder_ = new ExternalReferenceDecoder();
623 }
624 VisitPointer(root);
625}
626
627
Leon Clarked91b9f72010-01-27 17:25:45 +0000628Deserializer::~Deserializer() {
629 ASSERT(source_->AtEOF());
Leon Clarkee46be812010-01-19 14:06:41 +0000630 if (external_reference_decoder_ != NULL) {
631 delete external_reference_decoder_;
632 external_reference_decoder_ = NULL;
633 }
Steve Blockd0582a62009-12-15 09:54:21 +0000634}
635
636
637// This is called on the roots. It is the driver of the deserialization
638// process. It is also called on the body of each function.
639void Deserializer::VisitPointers(Object** start, Object** end) {
640 // The space must be new space. Any other space would cause ReadChunk to try
641 // to update the remembered using NULL as the address.
642 ReadChunk(start, end, NEW_SPACE, NULL);
643}
644
645
646// This routine writes the new object into the pointer provided and then
647// returns true if the new object was in young space and false otherwise.
648// The reason for this strange interface is that otherwise the object is
649// written very late, which means the ByteArray map is not set up by the
650// time we need to use it to mark the space at the end of a page free (by
651// making it into a byte array).
652void Deserializer::ReadObject(int space_number,
653 Space* space,
654 Object** write_back) {
655 int size = source_->GetInt() << kObjectAlignmentBits;
656 Address address = Allocate(space_number, space, size);
657 *write_back = HeapObject::FromAddress(address);
658 Object** current = reinterpret_cast<Object**>(address);
659 Object** limit = current + (size >> kPointerSizeLog2);
Leon Clarkee46be812010-01-19 14:06:41 +0000660 if (FLAG_log_snapshot_positions) {
661 LOG(SnapshotPositionEvent(address, source_->position()));
662 }
Steve Blockd0582a62009-12-15 09:54:21 +0000663 ReadChunk(current, limit, space_number, address);
664}
665
666
Leon Clarkef7060e22010-06-03 12:02:55 +0100667// This macro is always used with a constant argument so it should all fold
668// away to almost nothing in the generated code. It might be nicer to do this
669// with the ternary operator but there are type issues with that.
670#define ASSIGN_DEST_SPACE(space_number) \
671 Space* dest_space; \
672 if (space_number == NEW_SPACE) { \
673 dest_space = Heap::new_space(); \
674 } else if (space_number == OLD_POINTER_SPACE) { \
675 dest_space = Heap::old_pointer_space(); \
676 } else if (space_number == OLD_DATA_SPACE) { \
677 dest_space = Heap::old_data_space(); \
678 } else if (space_number == CODE_SPACE) { \
679 dest_space = Heap::code_space(); \
680 } else if (space_number == MAP_SPACE) { \
681 dest_space = Heap::map_space(); \
682 } else if (space_number == CELL_SPACE) { \
683 dest_space = Heap::cell_space(); \
684 } else { \
685 ASSERT(space_number >= LO_SPACE); \
686 dest_space = Heap::lo_space(); \
687 }
688
689
690static const int kUnknownOffsetFromStart = -1;
Steve Blockd0582a62009-12-15 09:54:21 +0000691
692
693void Deserializer::ReadChunk(Object** current,
694 Object** limit,
Leon Clarkef7060e22010-06-03 12:02:55 +0100695 int source_space,
Steve Blockd0582a62009-12-15 09:54:21 +0000696 Address address) {
697 while (current < limit) {
698 int data = source_->Get();
699 switch (data) {
Leon Clarkef7060e22010-06-03 12:02:55 +0100700#define CASE_STATEMENT(where, how, within, space_number) \
701 case where + how + within + space_number: \
702 ASSERT((where & ~kPointedToMask) == 0); \
703 ASSERT((how & ~kHowToCodeMask) == 0); \
704 ASSERT((within & ~kWhereToPointMask) == 0); \
705 ASSERT((space_number & ~kSpaceMask) == 0);
706
707#define CASE_BODY(where, how, within, space_number_if_any, offset_from_start) \
708 { \
709 bool emit_write_barrier = false; \
710 bool current_was_incremented = false; \
711 int space_number = space_number_if_any == kAnyOldSpace ? \
712 (data & kSpaceMask) : space_number_if_any; \
713 if (where == kNewObject && how == kPlain && within == kStartOfObject) {\
714 ASSIGN_DEST_SPACE(space_number) \
715 ReadObject(space_number, dest_space, current); \
716 emit_write_barrier = \
717 (space_number == NEW_SPACE && source_space != NEW_SPACE); \
718 } else { \
719 Object* new_object = NULL; /* May not be a real Object pointer. */ \
720 if (where == kNewObject) { \
721 ASSIGN_DEST_SPACE(space_number) \
722 ReadObject(space_number, dest_space, &new_object); \
723 } else if (where == kRootArray) { \
724 int root_id = source_->GetInt(); \
725 new_object = Heap::roots_address()[root_id]; \
726 } else if (where == kPartialSnapshotCache) { \
727 int cache_index = source_->GetInt(); \
728 new_object = partial_snapshot_cache_[cache_index]; \
729 } else if (where == kExternalReference) { \
730 int reference_id = source_->GetInt(); \
731 Address address = \
732 external_reference_decoder_->Decode(reference_id); \
733 new_object = reinterpret_cast<Object*>(address); \
734 } else if (where == kBackref) { \
735 emit_write_barrier = \
736 (space_number == NEW_SPACE && source_space != NEW_SPACE); \
737 new_object = GetAddressFromEnd(data & kSpaceMask); \
738 } else { \
739 ASSERT(where == kFromStart); \
740 if (offset_from_start == kUnknownOffsetFromStart) { \
741 emit_write_barrier = \
742 (space_number == NEW_SPACE && source_space != NEW_SPACE); \
743 new_object = GetAddressFromStart(data & kSpaceMask); \
744 } else { \
745 Address object_address = pages_[space_number][0] + \
746 (offset_from_start << kObjectAlignmentBits); \
747 new_object = HeapObject::FromAddress(object_address); \
748 } \
749 } \
750 if (within == kFirstInstruction) { \
751 Code* new_code_object = reinterpret_cast<Code*>(new_object); \
752 new_object = reinterpret_cast<Object*>( \
753 new_code_object->instruction_start()); \
754 } \
755 if (how == kFromCode) { \
756 Address location_of_branch_data = \
757 reinterpret_cast<Address>(current); \
758 Assembler::set_target_at(location_of_branch_data, \
759 reinterpret_cast<Address>(new_object)); \
760 if (within == kFirstInstruction) { \
761 location_of_branch_data += Assembler::kCallTargetSize; \
762 current = reinterpret_cast<Object**>(location_of_branch_data); \
763 current_was_incremented = true; \
764 } \
765 } else { \
766 *current = new_object; \
767 } \
768 } \
769 if (emit_write_barrier) { \
770 Heap::RecordWrite(address, static_cast<int>( \
771 reinterpret_cast<Address>(current) - address)); \
772 } \
773 if (!current_was_incremented) { \
774 current++; /* Increment current if it wasn't done above. */ \
775 } \
776 break; \
777 } \
778
779// This generates a case and a body for each space. The large object spaces are
780// very rare in snapshots so they are grouped in one body.
781#define ONE_PER_SPACE(where, how, within) \
782 CASE_STATEMENT(where, how, within, NEW_SPACE) \
783 CASE_BODY(where, how, within, NEW_SPACE, kUnknownOffsetFromStart) \
784 CASE_STATEMENT(where, how, within, OLD_DATA_SPACE) \
785 CASE_BODY(where, how, within, OLD_DATA_SPACE, kUnknownOffsetFromStart) \
786 CASE_STATEMENT(where, how, within, OLD_POINTER_SPACE) \
787 CASE_BODY(where, how, within, OLD_POINTER_SPACE, kUnknownOffsetFromStart) \
788 CASE_STATEMENT(where, how, within, CODE_SPACE) \
789 CASE_BODY(where, how, within, CODE_SPACE, kUnknownOffsetFromStart) \
790 CASE_STATEMENT(where, how, within, CELL_SPACE) \
791 CASE_BODY(where, how, within, CELL_SPACE, kUnknownOffsetFromStart) \
792 CASE_STATEMENT(where, how, within, MAP_SPACE) \
793 CASE_BODY(where, how, within, MAP_SPACE, kUnknownOffsetFromStart) \
794 CASE_STATEMENT(where, how, within, kLargeData) \
795 CASE_STATEMENT(where, how, within, kLargeCode) \
796 CASE_STATEMENT(where, how, within, kLargeFixedArray) \
797 CASE_BODY(where, how, within, kAnyOldSpace, kUnknownOffsetFromStart)
798
799// This generates a case and a body for the new space (which has to do extra
800// write barrier handling) and handles the other spaces with 8 fall-through
801// cases and one body.
802#define ALL_SPACES(where, how, within) \
803 CASE_STATEMENT(where, how, within, NEW_SPACE) \
804 CASE_BODY(where, how, within, NEW_SPACE, kUnknownOffsetFromStart) \
805 CASE_STATEMENT(where, how, within, OLD_DATA_SPACE) \
806 CASE_STATEMENT(where, how, within, OLD_POINTER_SPACE) \
807 CASE_STATEMENT(where, how, within, CODE_SPACE) \
808 CASE_STATEMENT(where, how, within, CELL_SPACE) \
809 CASE_STATEMENT(where, how, within, MAP_SPACE) \
810 CASE_STATEMENT(where, how, within, kLargeData) \
811 CASE_STATEMENT(where, how, within, kLargeCode) \
812 CASE_STATEMENT(where, how, within, kLargeFixedArray) \
813 CASE_BODY(where, how, within, kAnyOldSpace, kUnknownOffsetFromStart)
814
815#define EMIT_COMMON_REFERENCE_PATTERNS(pseudo_space_number, \
816 space_number, \
817 offset_from_start) \
818 CASE_STATEMENT(kFromStart, kPlain, kStartOfObject, pseudo_space_number) \
819 CASE_BODY(kFromStart, kPlain, kStartOfObject, space_number, offset_from_start)
820
821 // We generate 15 cases and bodies that process special tags that combine
822 // the raw data tag and the length into one byte.
Steve Blockd0582a62009-12-15 09:54:21 +0000823#define RAW_CASE(index, size) \
Leon Clarkef7060e22010-06-03 12:02:55 +0100824 case kRawData + index: { \
Steve Blockd0582a62009-12-15 09:54:21 +0000825 byte* raw_data_out = reinterpret_cast<byte*>(current); \
826 source_->CopyRaw(raw_data_out, size); \
827 current = reinterpret_cast<Object**>(raw_data_out + size); \
828 break; \
829 }
830 COMMON_RAW_LENGTHS(RAW_CASE)
831#undef RAW_CASE
Leon Clarkef7060e22010-06-03 12:02:55 +0100832
833 // Deserialize a chunk of raw data that doesn't have one of the popular
834 // lengths.
835 case kRawData: {
Steve Blockd0582a62009-12-15 09:54:21 +0000836 int size = source_->GetInt();
837 byte* raw_data_out = reinterpret_cast<byte*>(current);
838 source_->CopyRaw(raw_data_out, size);
839 current = reinterpret_cast<Object**>(raw_data_out + size);
840 break;
841 }
Leon Clarkef7060e22010-06-03 12:02:55 +0100842
843 // Deserialize a new object and write a pointer to it to the current
844 // object.
845 ONE_PER_SPACE(kNewObject, kPlain, kStartOfObject)
846 // Deserialize a new code object and write a pointer to its first
847 // instruction to the current code object.
848 ONE_PER_SPACE(kNewObject, kFromCode, kFirstInstruction)
849 // Find a recently deserialized object using its offset from the current
850 // allocation point and write a pointer to it to the current object.
851 ALL_SPACES(kBackref, kPlain, kStartOfObject)
852 // Find a recently deserialized code object using its offset from the
853 // current allocation point and write a pointer to its first instruction
854 // to the current code object.
855 ALL_SPACES(kBackref, kFromCode, kFirstInstruction)
856 // Find an already deserialized object using its offset from the start
857 // and write a pointer to it to the current object.
858 ALL_SPACES(kFromStart, kPlain, kStartOfObject)
859 // Find an already deserialized code object using its offset from the
860 // start and write a pointer to its first instruction to the current code
861 // object.
862 ALL_SPACES(kFromStart, kFromCode, kFirstInstruction)
863 // Find an already deserialized object at one of the predetermined popular
864 // offsets from the start and write a pointer to it in the current object.
865 COMMON_REFERENCE_PATTERNS(EMIT_COMMON_REFERENCE_PATTERNS)
866 // Find an object in the roots array and write a pointer to it to the
867 // current object.
868 CASE_STATEMENT(kRootArray, kPlain, kStartOfObject, 0)
869 CASE_BODY(kRootArray, kPlain, kStartOfObject, 0, kUnknownOffsetFromStart)
870 // Find an object in the partial snapshots cache and write a pointer to it
871 // to the current object.
872 CASE_STATEMENT(kPartialSnapshotCache, kPlain, kStartOfObject, 0)
873 CASE_BODY(kPartialSnapshotCache,
874 kPlain,
875 kStartOfObject,
876 0,
877 kUnknownOffsetFromStart)
878 // Find an external reference and write a pointer to it to the current
879 // object.
880 CASE_STATEMENT(kExternalReference, kPlain, kStartOfObject, 0)
881 CASE_BODY(kExternalReference,
882 kPlain,
883 kStartOfObject,
884 0,
885 kUnknownOffsetFromStart)
886 // Find an external reference and write a pointer to it in the current
887 // code object.
888 CASE_STATEMENT(kExternalReference, kFromCode, kStartOfObject, 0)
889 CASE_BODY(kExternalReference,
890 kFromCode,
891 kStartOfObject,
892 0,
893 kUnknownOffsetFromStart)
894
895#undef CASE_STATEMENT
896#undef CASE_BODY
897#undef ONE_PER_SPACE
898#undef ALL_SPACES
899#undef EMIT_COMMON_REFERENCE_PATTERNS
900#undef ASSIGN_DEST_SPACE
901
902 case kNewPage: {
Steve Blockd0582a62009-12-15 09:54:21 +0000903 int space = source_->Get();
904 pages_[space].Add(last_object_address_);
Steve Block6ded16b2010-05-10 14:33:55 +0100905 if (space == CODE_SPACE) {
906 CPU::FlushICache(last_object_address_, Page::kPageSize);
907 }
Steve Blockd0582a62009-12-15 09:54:21 +0000908 break;
909 }
Leon Clarkef7060e22010-06-03 12:02:55 +0100910
911 case kNativesStringResource: {
Steve Blockd0582a62009-12-15 09:54:21 +0000912 int index = source_->Get();
913 Vector<const char> source_vector = Natives::GetScriptSource(index);
914 NativesExternalStringResource* resource =
915 new NativesExternalStringResource(source_vector.start());
916 *current++ = reinterpret_cast<Object*>(resource);
917 break;
918 }
Leon Clarkef7060e22010-06-03 12:02:55 +0100919
920 case kSynchronize: {
Leon Clarked91b9f72010-01-27 17:25:45 +0000921 // If we get here then that indicates that you have a mismatch between
922 // the number of GC roots when serializing and deserializing.
923 UNREACHABLE();
924 }
Leon Clarkef7060e22010-06-03 12:02:55 +0100925
Steve Blockd0582a62009-12-15 09:54:21 +0000926 default:
927 UNREACHABLE();
928 }
929 }
930 ASSERT_EQ(current, limit);
931}
932
933
934void SnapshotByteSink::PutInt(uintptr_t integer, const char* description) {
935 const int max_shift = ((kPointerSize * kBitsPerByte) / 7) * 7;
936 for (int shift = max_shift; shift > 0; shift -= 7) {
937 if (integer >= static_cast<uintptr_t>(1u) << shift) {
Andrei Popescu402d9372010-02-26 13:31:12 +0000938 Put((static_cast<int>((integer >> shift)) & 0x7f) | 0x80, "IntPart");
Steve Blockd0582a62009-12-15 09:54:21 +0000939 }
940 }
Andrei Popescu402d9372010-02-26 13:31:12 +0000941 PutSection(static_cast<int>(integer & 0x7f), "IntLastPart");
Steve Blockd0582a62009-12-15 09:54:21 +0000942}
943
Steve Blocka7e24c12009-10-30 11:49:00 +0000944#ifdef DEBUG
Steve Blockd0582a62009-12-15 09:54:21 +0000945
946void Deserializer::Synchronize(const char* tag) {
947 int data = source_->Get();
948 // If this assert fails then that indicates that you have a mismatch between
949 // the number of GC roots when serializing and deserializing.
Leon Clarkef7060e22010-06-03 12:02:55 +0100950 ASSERT_EQ(kSynchronize, data);
Steve Blockd0582a62009-12-15 09:54:21 +0000951 do {
952 int character = source_->Get();
953 if (character == 0) break;
954 if (FLAG_debug_serialization) {
955 PrintF("%c", character);
956 }
957 } while (true);
958 if (FLAG_debug_serialization) {
959 PrintF("\n");
960 }
961}
962
Steve Blocka7e24c12009-10-30 11:49:00 +0000963
964void Serializer::Synchronize(const char* tag) {
Leon Clarkef7060e22010-06-03 12:02:55 +0100965 sink_->Put(kSynchronize, tag);
Steve Blockd0582a62009-12-15 09:54:21 +0000966 int character;
967 do {
968 character = *tag++;
969 sink_->PutSection(character, "TagCharacter");
970 } while (character != 0);
Steve Blocka7e24c12009-10-30 11:49:00 +0000971}
Steve Blockd0582a62009-12-15 09:54:21 +0000972
Steve Blocka7e24c12009-10-30 11:49:00 +0000973#endif
974
Steve Blockd0582a62009-12-15 09:54:21 +0000975Serializer::Serializer(SnapshotByteSink* sink)
976 : sink_(sink),
977 current_root_index_(0),
Andrei Popescu31002712010-02-23 13:46:05 +0000978 external_reference_encoder_(new ExternalReferenceEncoder),
Leon Clarkee46be812010-01-19 14:06:41 +0000979 large_object_total_(0) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000980 for (int i = 0; i <= LAST_SPACE; i++) {
Steve Blockd0582a62009-12-15 09:54:21 +0000981 fullness_[i] = 0;
Steve Blocka7e24c12009-10-30 11:49:00 +0000982 }
983}
984
985
Andrei Popescu31002712010-02-23 13:46:05 +0000986Serializer::~Serializer() {
987 delete external_reference_encoder_;
988}
989
990
Leon Clarked91b9f72010-01-27 17:25:45 +0000991void StartupSerializer::SerializeStrongReferences() {
Steve Blocka7e24c12009-10-30 11:49:00 +0000992 // No active threads.
993 CHECK_EQ(NULL, ThreadState::FirstInUse());
994 // No active or weak handles.
995 CHECK(HandleScopeImplementer::instance()->blocks()->is_empty());
996 CHECK_EQ(0, GlobalHandles::NumberOfWeakHandles());
Steve Blockd0582a62009-12-15 09:54:21 +0000997 // We don't support serializing installed extensions.
998 for (RegisteredExtension* ext = RegisteredExtension::first_extension();
999 ext != NULL;
1000 ext = ext->next()) {
1001 CHECK_NE(v8::INSTALLED, ext->state());
1002 }
Leon Clarked91b9f72010-01-27 17:25:45 +00001003 Heap::IterateStrongRoots(this, VISIT_ONLY_STRONG);
Steve Blocka7e24c12009-10-30 11:49:00 +00001004}
1005
1006
Leon Clarked91b9f72010-01-27 17:25:45 +00001007void PartialSerializer::Serialize(Object** object) {
Leon Clarkee46be812010-01-19 14:06:41 +00001008 this->VisitPointer(object);
Leon Clarked91b9f72010-01-27 17:25:45 +00001009
1010 // After we have done the partial serialization the partial snapshot cache
1011 // will contain some references needed to decode the partial snapshot. We
1012 // fill it up with undefineds so it has a predictable length so the
1013 // deserialization code doesn't need to know the length.
1014 for (int index = partial_snapshot_cache_length_;
1015 index < kPartialSnapshotCacheCapacity;
1016 index++) {
1017 partial_snapshot_cache_[index] = Heap::undefined_value();
1018 startup_serializer_->VisitPointer(&partial_snapshot_cache_[index]);
1019 }
1020 partial_snapshot_cache_length_ = kPartialSnapshotCacheCapacity;
Leon Clarkee46be812010-01-19 14:06:41 +00001021}
1022
1023
Steve Blocka7e24c12009-10-30 11:49:00 +00001024void Serializer::VisitPointers(Object** start, Object** end) {
Steve Blockd0582a62009-12-15 09:54:21 +00001025 for (Object** current = start; current < end; current++) {
1026 if ((*current)->IsSmi()) {
Leon Clarkef7060e22010-06-03 12:02:55 +01001027 sink_->Put(kRawData, "RawData");
Steve Blockd0582a62009-12-15 09:54:21 +00001028 sink_->PutInt(kPointerSize, "length");
1029 for (int i = 0; i < kPointerSize; i++) {
1030 sink_->Put(reinterpret_cast<byte*>(current)[i], "Byte");
1031 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001032 } else {
Leon Clarkef7060e22010-06-03 12:02:55 +01001033 SerializeObject(*current, kPlain, kStartOfObject);
Steve Blocka7e24c12009-10-30 11:49:00 +00001034 }
1035 }
1036}
1037
1038
Leon Clarked91b9f72010-01-27 17:25:45 +00001039Object* SerializerDeserializer::partial_snapshot_cache_[
1040 kPartialSnapshotCacheCapacity];
1041int SerializerDeserializer::partial_snapshot_cache_length_ = 0;
1042
1043
1044// This ensures that the partial snapshot cache keeps things alive during GC and
1045// tracks their movement. When it is called during serialization of the startup
1046// snapshot the partial snapshot is empty, so nothing happens. When the partial
1047// (context) snapshot is created, this array is populated with the pointers that
1048// the partial snapshot will need. As that happens we emit serialized objects to
1049// the startup snapshot that correspond to the elements of this cache array. On
1050// deserialization we therefore need to visit the cache array. This fills it up
1051// with pointers to deserialized objects.
Steve Block6ded16b2010-05-10 14:33:55 +01001052void SerializerDeserializer::Iterate(ObjectVisitor* visitor) {
Leon Clarked91b9f72010-01-27 17:25:45 +00001053 visitor->VisitPointers(
1054 &partial_snapshot_cache_[0],
1055 &partial_snapshot_cache_[partial_snapshot_cache_length_]);
1056}
1057
1058
1059// When deserializing we need to set the size of the snapshot cache. This means
1060// the root iteration code (above) will iterate over array elements, writing the
1061// references to deserialized objects in them.
1062void SerializerDeserializer::SetSnapshotCacheSize(int size) {
1063 partial_snapshot_cache_length_ = size;
1064}
1065
1066
1067int PartialSerializer::PartialSnapshotCacheIndex(HeapObject* heap_object) {
1068 for (int i = 0; i < partial_snapshot_cache_length_; i++) {
1069 Object* entry = partial_snapshot_cache_[i];
1070 if (entry == heap_object) return i;
1071 }
Andrei Popescu31002712010-02-23 13:46:05 +00001072
Leon Clarked91b9f72010-01-27 17:25:45 +00001073 // We didn't find the object in the cache. So we add it to the cache and
1074 // then visit the pointer so that it becomes part of the startup snapshot
1075 // and we can refer to it from the partial snapshot.
1076 int length = partial_snapshot_cache_length_;
1077 CHECK(length < kPartialSnapshotCacheCapacity);
1078 partial_snapshot_cache_[length] = heap_object;
1079 startup_serializer_->VisitPointer(&partial_snapshot_cache_[length]);
1080 // We don't recurse from the startup snapshot generator into the partial
1081 // snapshot generator.
1082 ASSERT(length == partial_snapshot_cache_length_);
1083 return partial_snapshot_cache_length_++;
1084}
1085
1086
1087int PartialSerializer::RootIndex(HeapObject* heap_object) {
Leon Clarkee46be812010-01-19 14:06:41 +00001088 for (int i = 0; i < Heap::kRootListLength; i++) {
1089 Object* root = Heap::roots_address()[i];
1090 if (root == heap_object) return i;
1091 }
1092 return kInvalidRootIndex;
1093}
1094
1095
Leon Clarked91b9f72010-01-27 17:25:45 +00001096// Encode the location of an already deserialized object in order to write its
1097// location into a later object. We can encode the location as an offset from
1098// the start of the deserialized objects or as an offset backwards from the
1099// current allocation pointer.
1100void Serializer::SerializeReferenceToPreviousObject(
1101 int space,
1102 int address,
Leon Clarkef7060e22010-06-03 12:02:55 +01001103 HowToCode how_to_code,
1104 WhereToPoint where_to_point) {
Leon Clarked91b9f72010-01-27 17:25:45 +00001105 int offset = CurrentAllocationAddress(space) - address;
1106 bool from_start = true;
1107 if (SpaceIsPaged(space)) {
1108 // For paged space it is simple to encode back from current allocation if
1109 // the object is on the same page as the current allocation pointer.
1110 if ((CurrentAllocationAddress(space) >> kPageSizeBits) ==
1111 (address >> kPageSizeBits)) {
1112 from_start = false;
1113 address = offset;
1114 }
1115 } else if (space == NEW_SPACE) {
1116 // For new space it is always simple to encode back from current allocation.
1117 if (offset < address) {
1118 from_start = false;
1119 address = offset;
1120 }
1121 }
1122 // If we are actually dealing with real offsets (and not a numbering of
1123 // all objects) then we should shift out the bits that are always 0.
1124 if (!SpaceIsLarge(space)) address >>= kObjectAlignmentBits;
Leon Clarkef7060e22010-06-03 12:02:55 +01001125 if (from_start) {
1126#define COMMON_REFS_CASE(pseudo_space, actual_space, offset) \
1127 if (space == actual_space && address == offset && \
1128 how_to_code == kPlain && where_to_point == kStartOfObject) { \
1129 sink_->Put(kFromStart + how_to_code + where_to_point + \
1130 pseudo_space, "RefSer"); \
1131 } else /* NOLINT */
1132 COMMON_REFERENCE_PATTERNS(COMMON_REFS_CASE)
1133#undef COMMON_REFS_CASE
1134 { /* NOLINT */
1135 sink_->Put(kFromStart + how_to_code + where_to_point + space, "RefSer");
Leon Clarked91b9f72010-01-27 17:25:45 +00001136 sink_->PutInt(address, "address");
1137 }
1138 } else {
Leon Clarkef7060e22010-06-03 12:02:55 +01001139 sink_->Put(kBackref + how_to_code + where_to_point + space, "BackRefSer");
1140 sink_->PutInt(address, "address");
Leon Clarked91b9f72010-01-27 17:25:45 +00001141 }
1142}
1143
1144
1145void StartupSerializer::SerializeObject(
Leon Clarkeeab96aa2010-01-27 16:31:12 +00001146 Object* o,
Leon Clarkef7060e22010-06-03 12:02:55 +01001147 HowToCode how_to_code,
1148 WhereToPoint where_to_point) {
Leon Clarkeeab96aa2010-01-27 16:31:12 +00001149 CHECK(o->IsHeapObject());
1150 HeapObject* heap_object = HeapObject::cast(o);
Leon Clarked91b9f72010-01-27 17:25:45 +00001151
1152 if (address_mapper_.IsMapped(heap_object)) {
Leon Clarkeeab96aa2010-01-27 16:31:12 +00001153 int space = SpaceOfAlreadySerializedObject(heap_object);
Leon Clarked91b9f72010-01-27 17:25:45 +00001154 int address = address_mapper_.MappedTo(heap_object);
1155 SerializeReferenceToPreviousObject(space,
1156 address,
Leon Clarkef7060e22010-06-03 12:02:55 +01001157 how_to_code,
1158 where_to_point);
Leon Clarked91b9f72010-01-27 17:25:45 +00001159 } else {
1160 // Object has not yet been serialized. Serialize it here.
1161 ObjectSerializer object_serializer(this,
1162 heap_object,
1163 sink_,
Leon Clarkef7060e22010-06-03 12:02:55 +01001164 how_to_code,
1165 where_to_point);
Leon Clarked91b9f72010-01-27 17:25:45 +00001166 object_serializer.Serialize();
1167 }
1168}
1169
1170
1171void StartupSerializer::SerializeWeakReferences() {
1172 for (int i = partial_snapshot_cache_length_;
1173 i < kPartialSnapshotCacheCapacity;
1174 i++) {
Leon Clarkef7060e22010-06-03 12:02:55 +01001175 sink_->Put(kRootArray + kPlain + kStartOfObject, "RootSerialization");
Leon Clarked91b9f72010-01-27 17:25:45 +00001176 sink_->PutInt(Heap::kUndefinedValueRootIndex, "root_index");
1177 }
1178 Heap::IterateWeakRoots(this, VISIT_ALL);
1179}
1180
1181
1182void PartialSerializer::SerializeObject(
1183 Object* o,
Leon Clarkef7060e22010-06-03 12:02:55 +01001184 HowToCode how_to_code,
1185 WhereToPoint where_to_point) {
Leon Clarked91b9f72010-01-27 17:25:45 +00001186 CHECK(o->IsHeapObject());
1187 HeapObject* heap_object = HeapObject::cast(o);
1188
1189 int root_index;
1190 if ((root_index = RootIndex(heap_object)) != kInvalidRootIndex) {
Leon Clarkef7060e22010-06-03 12:02:55 +01001191 sink_->Put(kRootArray + how_to_code + where_to_point, "RootSerialization");
Leon Clarked91b9f72010-01-27 17:25:45 +00001192 sink_->PutInt(root_index, "root_index");
1193 return;
1194 }
1195
1196 if (ShouldBeInThePartialSnapshotCache(heap_object)) {
1197 int cache_index = PartialSnapshotCacheIndex(heap_object);
Leon Clarkef7060e22010-06-03 12:02:55 +01001198 sink_->Put(kPartialSnapshotCache + how_to_code + where_to_point,
1199 "PartialSnapshotCache");
Leon Clarked91b9f72010-01-27 17:25:45 +00001200 sink_->PutInt(cache_index, "partial_snapshot_cache_index");
1201 return;
1202 }
1203
1204 // Pointers from the partial snapshot to the objects in the startup snapshot
1205 // should go through the root array or through the partial snapshot cache.
1206 // If this is not the case you may have to add something to the root array.
1207 ASSERT(!startup_serializer_->address_mapper()->IsMapped(heap_object));
1208 // All the symbols that the partial snapshot needs should be either in the
1209 // root table or in the partial snapshot cache.
1210 ASSERT(!heap_object->IsSymbol());
1211
1212 if (address_mapper_.IsMapped(heap_object)) {
1213 int space = SpaceOfAlreadySerializedObject(heap_object);
1214 int address = address_mapper_.MappedTo(heap_object);
1215 SerializeReferenceToPreviousObject(space,
1216 address,
Leon Clarkef7060e22010-06-03 12:02:55 +01001217 how_to_code,
1218 where_to_point);
Steve Blockd0582a62009-12-15 09:54:21 +00001219 } else {
1220 // Object has not yet been serialized. Serialize it here.
1221 ObjectSerializer serializer(this,
1222 heap_object,
1223 sink_,
Leon Clarkef7060e22010-06-03 12:02:55 +01001224 how_to_code,
1225 where_to_point);
Steve Blockd0582a62009-12-15 09:54:21 +00001226 serializer.Serialize();
1227 }
1228}
1229
1230
Steve Blockd0582a62009-12-15 09:54:21 +00001231void Serializer::ObjectSerializer::Serialize() {
1232 int space = Serializer::SpaceOfObject(object_);
1233 int size = object_->Size();
1234
Leon Clarkef7060e22010-06-03 12:02:55 +01001235 sink_->Put(kNewObject + reference_representation_ + space,
1236 "ObjectSerialization");
Steve Blockd0582a62009-12-15 09:54:21 +00001237 sink_->PutInt(size >> kObjectAlignmentBits, "Size in words");
1238
Leon Clarkee46be812010-01-19 14:06:41 +00001239 LOG(SnapshotPositionEvent(object_->address(), sink_->Position()));
1240
Steve Blockd0582a62009-12-15 09:54:21 +00001241 // Mark this object as already serialized.
1242 bool start_new_page;
Leon Clarked91b9f72010-01-27 17:25:45 +00001243 int offset = serializer_->Allocate(space, size, &start_new_page);
1244 serializer_->address_mapper()->AddMapping(object_, offset);
Steve Blockd0582a62009-12-15 09:54:21 +00001245 if (start_new_page) {
Leon Clarkef7060e22010-06-03 12:02:55 +01001246 sink_->Put(kNewPage, "NewPage");
Steve Blockd0582a62009-12-15 09:54:21 +00001247 sink_->PutSection(space, "NewPageSpace");
1248 }
1249
1250 // Serialize the map (first word of the object).
Leon Clarkef7060e22010-06-03 12:02:55 +01001251 serializer_->SerializeObject(object_->map(), kPlain, kStartOfObject);
Steve Blockd0582a62009-12-15 09:54:21 +00001252
1253 // Serialize the rest of the object.
1254 CHECK_EQ(0, bytes_processed_so_far_);
1255 bytes_processed_so_far_ = kPointerSize;
1256 object_->IterateBody(object_->map()->instance_type(), size, this);
1257 OutputRawData(object_->address() + size);
1258}
1259
1260
1261void Serializer::ObjectSerializer::VisitPointers(Object** start,
1262 Object** end) {
1263 Object** current = start;
1264 while (current < end) {
1265 while (current < end && (*current)->IsSmi()) current++;
1266 if (current < end) OutputRawData(reinterpret_cast<Address>(current));
1267
1268 while (current < end && !(*current)->IsSmi()) {
Leon Clarkef7060e22010-06-03 12:02:55 +01001269 serializer_->SerializeObject(*current, kPlain, kStartOfObject);
Steve Blockd0582a62009-12-15 09:54:21 +00001270 bytes_processed_so_far_ += kPointerSize;
1271 current++;
1272 }
1273 }
1274}
1275
1276
1277void Serializer::ObjectSerializer::VisitExternalReferences(Address* start,
1278 Address* end) {
1279 Address references_start = reinterpret_cast<Address>(start);
1280 OutputRawData(references_start);
1281
1282 for (Address* current = start; current < end; current++) {
Leon Clarkef7060e22010-06-03 12:02:55 +01001283 sink_->Put(kExternalReference + kPlain + kStartOfObject, "ExternalRef");
Steve Blockd0582a62009-12-15 09:54:21 +00001284 int reference_id = serializer_->EncodeExternalReference(*current);
1285 sink_->PutInt(reference_id, "reference id");
1286 }
1287 bytes_processed_so_far_ += static_cast<int>((end - start) * kPointerSize);
1288}
1289
1290
1291void Serializer::ObjectSerializer::VisitRuntimeEntry(RelocInfo* rinfo) {
1292 Address target_start = rinfo->target_address_address();
1293 OutputRawData(target_start);
1294 Address target = rinfo->target_address();
1295 uint32_t encoding = serializer_->EncodeExternalReference(target);
1296 CHECK(target == NULL ? encoding == 0 : encoding != 0);
Leon Clarkef7060e22010-06-03 12:02:55 +01001297 int representation;
1298 // Can't use a ternary operator because of gcc.
1299 if (rinfo->IsCodedSpecially()) {
1300 representation = kStartOfObject + kFromCode;
1301 } else {
1302 representation = kStartOfObject + kPlain;
1303 }
1304 sink_->Put(kExternalReference + representation, "ExternalReference");
Steve Blockd0582a62009-12-15 09:54:21 +00001305 sink_->PutInt(encoding, "reference id");
Leon Clarkef7060e22010-06-03 12:02:55 +01001306 bytes_processed_so_far_ += rinfo->target_address_size();
Steve Blockd0582a62009-12-15 09:54:21 +00001307}
1308
1309
1310void Serializer::ObjectSerializer::VisitCodeTarget(RelocInfo* rinfo) {
1311 CHECK(RelocInfo::IsCodeTarget(rinfo->rmode()));
1312 Address target_start = rinfo->target_address_address();
1313 OutputRawData(target_start);
1314 Code* target = Code::GetCodeFromTargetAddress(rinfo->target_address());
Leon Clarkef7060e22010-06-03 12:02:55 +01001315 serializer_->SerializeObject(target, kFromCode, kFirstInstruction);
1316 bytes_processed_so_far_ += rinfo->target_address_size();
Steve Blockd0582a62009-12-15 09:54:21 +00001317}
1318
1319
1320void Serializer::ObjectSerializer::VisitExternalAsciiString(
1321 v8::String::ExternalAsciiStringResource** resource_pointer) {
1322 Address references_start = reinterpret_cast<Address>(resource_pointer);
1323 OutputRawData(references_start);
1324 for (int i = 0; i < Natives::GetBuiltinsCount(); i++) {
1325 Object* source = Heap::natives_source_cache()->get(i);
1326 if (!source->IsUndefined()) {
1327 ExternalAsciiString* string = ExternalAsciiString::cast(source);
1328 typedef v8::String::ExternalAsciiStringResource Resource;
1329 Resource* resource = string->resource();
1330 if (resource == *resource_pointer) {
Leon Clarkef7060e22010-06-03 12:02:55 +01001331 sink_->Put(kNativesStringResource, "NativesStringResource");
Steve Blockd0582a62009-12-15 09:54:21 +00001332 sink_->PutSection(i, "NativesStringResourceEnd");
1333 bytes_processed_so_far_ += sizeof(resource);
1334 return;
1335 }
1336 }
1337 }
1338 // One of the strings in the natives cache should match the resource. We
1339 // can't serialize any other kinds of external strings.
1340 UNREACHABLE();
1341}
1342
1343
1344void Serializer::ObjectSerializer::OutputRawData(Address up_to) {
1345 Address object_start = object_->address();
1346 int up_to_offset = static_cast<int>(up_to - object_start);
1347 int skipped = up_to_offset - bytes_processed_so_far_;
1348 // This assert will fail if the reloc info gives us the target_address_address
1349 // locations in a non-ascending order. Luckily that doesn't happen.
1350 ASSERT(skipped >= 0);
1351 if (skipped != 0) {
1352 Address base = object_start + bytes_processed_so_far_;
1353#define RAW_CASE(index, length) \
1354 if (skipped == length) { \
Leon Clarkef7060e22010-06-03 12:02:55 +01001355 sink_->PutSection(kRawData + index, "RawDataFixed"); \
Steve Blockd0582a62009-12-15 09:54:21 +00001356 } else /* NOLINT */
1357 COMMON_RAW_LENGTHS(RAW_CASE)
1358#undef RAW_CASE
1359 { /* NOLINT */
Leon Clarkef7060e22010-06-03 12:02:55 +01001360 sink_->Put(kRawData, "RawData");
Steve Blockd0582a62009-12-15 09:54:21 +00001361 sink_->PutInt(skipped, "length");
1362 }
1363 for (int i = 0; i < skipped; i++) {
1364 unsigned int data = base[i];
1365 sink_->PutSection(data, "Byte");
1366 }
1367 bytes_processed_so_far_ += skipped;
1368 }
1369}
1370
1371
1372int Serializer::SpaceOfObject(HeapObject* object) {
1373 for (int i = FIRST_SPACE; i <= LAST_SPACE; i++) {
1374 AllocationSpace s = static_cast<AllocationSpace>(i);
1375 if (Heap::InSpace(object, s)) {
1376 if (i == LO_SPACE) {
1377 if (object->IsCode()) {
1378 return kLargeCode;
1379 } else if (object->IsFixedArray()) {
1380 return kLargeFixedArray;
1381 } else {
1382 return kLargeData;
1383 }
1384 }
1385 return i;
1386 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001387 }
1388 UNREACHABLE();
Steve Blockd0582a62009-12-15 09:54:21 +00001389 return 0;
1390}
1391
1392
1393int Serializer::SpaceOfAlreadySerializedObject(HeapObject* object) {
1394 for (int i = FIRST_SPACE; i <= LAST_SPACE; i++) {
1395 AllocationSpace s = static_cast<AllocationSpace>(i);
1396 if (Heap::InSpace(object, s)) {
1397 return i;
1398 }
1399 }
1400 UNREACHABLE();
1401 return 0;
1402}
1403
1404
1405int Serializer::Allocate(int space, int size, bool* new_page) {
1406 CHECK(space >= 0 && space < kNumberOfSpaces);
1407 if (SpaceIsLarge(space)) {
1408 // In large object space we merely number the objects instead of trying to
1409 // determine some sort of address.
1410 *new_page = true;
Leon Clarkee46be812010-01-19 14:06:41 +00001411 large_object_total_ += size;
Steve Blockd0582a62009-12-15 09:54:21 +00001412 return fullness_[LO_SPACE]++;
1413 }
1414 *new_page = false;
1415 if (fullness_[space] == 0) {
1416 *new_page = true;
1417 }
1418 if (SpaceIsPaged(space)) {
1419 // Paged spaces are a little special. We encode their addresses as if the
1420 // pages were all contiguous and each page were filled up in the range
1421 // 0 - Page::kObjectAreaSize. In practice the pages may not be contiguous
1422 // and allocation does not start at offset 0 in the page, but this scheme
1423 // means the deserializer can get the page number quickly by shifting the
1424 // serialized address.
1425 CHECK(IsPowerOf2(Page::kPageSize));
1426 int used_in_this_page = (fullness_[space] & (Page::kPageSize - 1));
1427 CHECK(size <= Page::kObjectAreaSize);
1428 if (used_in_this_page + size > Page::kObjectAreaSize) {
1429 *new_page = true;
1430 fullness_[space] = RoundUp(fullness_[space], Page::kPageSize);
1431 }
1432 }
1433 int allocation_address = fullness_[space];
1434 fullness_[space] = allocation_address + size;
1435 return allocation_address;
Steve Blocka7e24c12009-10-30 11:49:00 +00001436}
1437
1438
1439} } // namespace v8::internal