blob: 68412677f49bb0c76a25f2a1bd337c59ef7c1159 [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");
Steve Block6ded16b2010-05-10 14:33:55 +0100332 Add(ExternalReference::fill_heap_number_with_random_function().address(),
Steve Blocka7e24c12009-10-30 11:49:00 +0000333 RUNTIME_ENTRY,
334 2,
Steve Block6ded16b2010-05-10 14:33:55 +0100335 "V8::FillHeapNumberWithRandom");
336
337 Add(ExternalReference::random_uint32_function().address(),
338 RUNTIME_ENTRY,
339 3,
340 "V8::Random");
Steve Blocka7e24c12009-10-30 11:49:00 +0000341
342 // Miscellaneous
Steve Blocka7e24c12009-10-30 11:49:00 +0000343 Add(ExternalReference::the_hole_value_location().address(),
344 UNCLASSIFIED,
345 2,
346 "Factory::the_hole_value().location()");
347 Add(ExternalReference::roots_address().address(),
348 UNCLASSIFIED,
349 3,
350 "Heap::roots_address()");
Steve Blockd0582a62009-12-15 09:54:21 +0000351 Add(ExternalReference::address_of_stack_limit().address(),
Steve Blocka7e24c12009-10-30 11:49:00 +0000352 UNCLASSIFIED,
353 4,
354 "StackGuard::address_of_jslimit()");
Steve Blockd0582a62009-12-15 09:54:21 +0000355 Add(ExternalReference::address_of_real_stack_limit().address(),
Steve Blocka7e24c12009-10-30 11:49:00 +0000356 UNCLASSIFIED,
357 5,
Steve Blockd0582a62009-12-15 09:54:21 +0000358 "StackGuard::address_of_real_jslimit()");
359 Add(ExternalReference::address_of_regexp_stack_limit().address(),
360 UNCLASSIFIED,
361 6,
Steve Blocka7e24c12009-10-30 11:49:00 +0000362 "RegExpStack::limit_address()");
363 Add(ExternalReference::new_space_start().address(),
364 UNCLASSIFIED,
Steve Blockd0582a62009-12-15 09:54:21 +0000365 7,
Steve Blocka7e24c12009-10-30 11:49:00 +0000366 "Heap::NewSpaceStart()");
Andrei Popescu402d9372010-02-26 13:31:12 +0000367 Add(ExternalReference::new_space_mask().address(),
Steve Blocka7e24c12009-10-30 11:49:00 +0000368 UNCLASSIFIED,
Steve Blockd0582a62009-12-15 09:54:21 +0000369 8,
Andrei Popescu402d9372010-02-26 13:31:12 +0000370 "Heap::NewSpaceMask()");
371 Add(ExternalReference::heap_always_allocate_scope_depth().address(),
372 UNCLASSIFIED,
373 9,
Steve Blocka7e24c12009-10-30 11:49:00 +0000374 "Heap::always_allocate_scope_depth()");
375 Add(ExternalReference::new_space_allocation_limit_address().address(),
376 UNCLASSIFIED,
Andrei Popescu402d9372010-02-26 13:31:12 +0000377 10,
Steve Blocka7e24c12009-10-30 11:49:00 +0000378 "Heap::NewSpaceAllocationLimitAddress()");
379 Add(ExternalReference::new_space_allocation_top_address().address(),
380 UNCLASSIFIED,
Andrei Popescu402d9372010-02-26 13:31:12 +0000381 11,
Steve Blocka7e24c12009-10-30 11:49:00 +0000382 "Heap::NewSpaceAllocationTopAddress()");
383#ifdef ENABLE_DEBUGGER_SUPPORT
384 Add(ExternalReference::debug_break().address(),
385 UNCLASSIFIED,
Andrei Popescu402d9372010-02-26 13:31:12 +0000386 12,
Steve Blocka7e24c12009-10-30 11:49:00 +0000387 "Debug::Break()");
388 Add(ExternalReference::debug_step_in_fp_address().address(),
389 UNCLASSIFIED,
Andrei Popescu402d9372010-02-26 13:31:12 +0000390 13,
Steve Blocka7e24c12009-10-30 11:49:00 +0000391 "Debug::step_in_fp_addr()");
392#endif
393 Add(ExternalReference::double_fp_operation(Token::ADD).address(),
394 UNCLASSIFIED,
Andrei Popescu402d9372010-02-26 13:31:12 +0000395 14,
Steve Blocka7e24c12009-10-30 11:49:00 +0000396 "add_two_doubles");
397 Add(ExternalReference::double_fp_operation(Token::SUB).address(),
398 UNCLASSIFIED,
Andrei Popescu402d9372010-02-26 13:31:12 +0000399 15,
Steve Blocka7e24c12009-10-30 11:49:00 +0000400 "sub_two_doubles");
401 Add(ExternalReference::double_fp_operation(Token::MUL).address(),
402 UNCLASSIFIED,
Andrei Popescu402d9372010-02-26 13:31:12 +0000403 16,
Steve Blocka7e24c12009-10-30 11:49:00 +0000404 "mul_two_doubles");
405 Add(ExternalReference::double_fp_operation(Token::DIV).address(),
406 UNCLASSIFIED,
Andrei Popescu402d9372010-02-26 13:31:12 +0000407 17,
Steve Blocka7e24c12009-10-30 11:49:00 +0000408 "div_two_doubles");
409 Add(ExternalReference::double_fp_operation(Token::MOD).address(),
410 UNCLASSIFIED,
Andrei Popescu402d9372010-02-26 13:31:12 +0000411 18,
Steve Blocka7e24c12009-10-30 11:49:00 +0000412 "mod_two_doubles");
413 Add(ExternalReference::compare_doubles().address(),
414 UNCLASSIFIED,
Andrei Popescu402d9372010-02-26 13:31:12 +0000415 19,
Steve Blocka7e24c12009-10-30 11:49:00 +0000416 "compare_doubles");
Steve Block6ded16b2010-05-10 14:33:55 +0100417 Add(ExternalReference::compile_array_pop_call().address(),
Steve Blocka7e24c12009-10-30 11:49:00 +0000418 UNCLASSIFIED,
Andrei Popescu402d9372010-02-26 13:31:12 +0000419 20,
Steve Block6ded16b2010-05-10 14:33:55 +0100420 "compile_array_pop");
421 Add(ExternalReference::compile_array_push_call().address(),
422 UNCLASSIFIED,
423 21,
424 "compile_array_push");
425#ifndef V8_INTERPRETED_REGEXP
426 Add(ExternalReference::re_case_insensitive_compare_uc16().address(),
427 UNCLASSIFIED,
428 22,
Steve Blocka7e24c12009-10-30 11:49:00 +0000429 "NativeRegExpMacroAssembler::CaseInsensitiveCompareUC16()");
430 Add(ExternalReference::re_check_stack_guard_state().address(),
431 UNCLASSIFIED,
Steve Block6ded16b2010-05-10 14:33:55 +0100432 23,
Steve Blocka7e24c12009-10-30 11:49:00 +0000433 "RegExpMacroAssembler*::CheckStackGuardState()");
434 Add(ExternalReference::re_grow_stack().address(),
435 UNCLASSIFIED,
Steve Block6ded16b2010-05-10 14:33:55 +0100436 24,
Steve Blocka7e24c12009-10-30 11:49:00 +0000437 "NativeRegExpMacroAssembler::GrowStack()");
Leon Clarkee46be812010-01-19 14:06:41 +0000438 Add(ExternalReference::re_word_character_map().address(),
439 UNCLASSIFIED,
Steve Block6ded16b2010-05-10 14:33:55 +0100440 25,
Leon Clarkee46be812010-01-19 14:06:41 +0000441 "NativeRegExpMacroAssembler::word_character_map");
Steve Block6ded16b2010-05-10 14:33:55 +0100442#endif // V8_INTERPRETED_REGEXP
Leon Clarkee46be812010-01-19 14:06:41 +0000443 // Keyed lookup cache.
444 Add(ExternalReference::keyed_lookup_cache_keys().address(),
445 UNCLASSIFIED,
Steve Block6ded16b2010-05-10 14:33:55 +0100446 26,
Leon Clarkee46be812010-01-19 14:06:41 +0000447 "KeyedLookupCache::keys()");
448 Add(ExternalReference::keyed_lookup_cache_field_offsets().address(),
449 UNCLASSIFIED,
Steve Block6ded16b2010-05-10 14:33:55 +0100450 27,
Leon Clarkee46be812010-01-19 14:06:41 +0000451 "KeyedLookupCache::field_offsets()");
Andrei Popescu402d9372010-02-26 13:31:12 +0000452 Add(ExternalReference::transcendental_cache_array_address().address(),
453 UNCLASSIFIED,
Steve Block6ded16b2010-05-10 14:33:55 +0100454 28,
Andrei Popescu402d9372010-02-26 13:31:12 +0000455 "TranscendentalCache::caches()");
Steve Blocka7e24c12009-10-30 11:49:00 +0000456}
457
458
459ExternalReferenceEncoder::ExternalReferenceEncoder()
460 : encodings_(Match) {
461 ExternalReferenceTable* external_references =
462 ExternalReferenceTable::instance();
463 for (int i = 0; i < external_references->size(); ++i) {
464 Put(external_references->address(i), i);
465 }
466}
467
468
469uint32_t ExternalReferenceEncoder::Encode(Address key) const {
470 int index = IndexOf(key);
471 return index >=0 ? ExternalReferenceTable::instance()->code(index) : 0;
472}
473
474
475const char* ExternalReferenceEncoder::NameOfAddress(Address key) const {
476 int index = IndexOf(key);
477 return index >=0 ? ExternalReferenceTable::instance()->name(index) : NULL;
478}
479
480
481int ExternalReferenceEncoder::IndexOf(Address key) const {
482 if (key == NULL) return -1;
483 HashMap::Entry* entry =
484 const_cast<HashMap &>(encodings_).Lookup(key, Hash(key), false);
485 return entry == NULL
486 ? -1
487 : static_cast<int>(reinterpret_cast<intptr_t>(entry->value));
488}
489
490
491void ExternalReferenceEncoder::Put(Address key, int index) {
492 HashMap::Entry* entry = encodings_.Lookup(key, Hash(key), true);
Steve Block6ded16b2010-05-10 14:33:55 +0100493 entry->value = reinterpret_cast<void*>(index);
Steve Blocka7e24c12009-10-30 11:49:00 +0000494}
495
496
497ExternalReferenceDecoder::ExternalReferenceDecoder()
498 : encodings_(NewArray<Address*>(kTypeCodeCount)) {
499 ExternalReferenceTable* external_references =
500 ExternalReferenceTable::instance();
501 for (int type = kFirstTypeCode; type < kTypeCodeCount; ++type) {
502 int max = external_references->max_id(type) + 1;
503 encodings_[type] = NewArray<Address>(max + 1);
504 }
505 for (int i = 0; i < external_references->size(); ++i) {
506 Put(external_references->code(i), external_references->address(i));
507 }
508}
509
510
511ExternalReferenceDecoder::~ExternalReferenceDecoder() {
512 for (int type = kFirstTypeCode; type < kTypeCodeCount; ++type) {
513 DeleteArray(encodings_[type]);
514 }
515 DeleteArray(encodings_);
516}
517
518
Steve Blocka7e24c12009-10-30 11:49:00 +0000519bool Serializer::serialization_enabled_ = false;
Steve Blockd0582a62009-12-15 09:54:21 +0000520bool Serializer::too_late_to_enable_now_ = false;
Leon Clarkee46be812010-01-19 14:06:41 +0000521ExternalReferenceDecoder* Deserializer::external_reference_decoder_ = NULL;
Steve Blocka7e24c12009-10-30 11:49:00 +0000522
523
Leon Clarkee46be812010-01-19 14:06:41 +0000524Deserializer::Deserializer(SnapshotByteSource* source) : source_(source) {
Steve Blockd0582a62009-12-15 09:54:21 +0000525}
526
527
528// This routine both allocates a new object, and also keeps
529// track of where objects have been allocated so that we can
530// fix back references when deserializing.
531Address Deserializer::Allocate(int space_index, Space* space, int size) {
532 Address address;
533 if (!SpaceIsLarge(space_index)) {
534 ASSERT(!SpaceIsPaged(space_index) ||
535 size <= Page::kPageSize - Page::kObjectStartOffset);
536 Object* new_allocation;
537 if (space_index == NEW_SPACE) {
538 new_allocation = reinterpret_cast<NewSpace*>(space)->AllocateRaw(size);
539 } else {
540 new_allocation = reinterpret_cast<PagedSpace*>(space)->AllocateRaw(size);
541 }
542 HeapObject* new_object = HeapObject::cast(new_allocation);
543 ASSERT(!new_object->IsFailure());
544 address = new_object->address();
545 high_water_[space_index] = address + size;
546 } else {
547 ASSERT(SpaceIsLarge(space_index));
548 ASSERT(size > Page::kPageSize - Page::kObjectStartOffset);
549 LargeObjectSpace* lo_space = reinterpret_cast<LargeObjectSpace*>(space);
550 Object* new_allocation;
551 if (space_index == kLargeData) {
552 new_allocation = lo_space->AllocateRaw(size);
553 } else if (space_index == kLargeFixedArray) {
554 new_allocation = lo_space->AllocateRawFixedArray(size);
555 } else {
556 ASSERT_EQ(kLargeCode, space_index);
557 new_allocation = lo_space->AllocateRawCode(size);
558 }
559 ASSERT(!new_allocation->IsFailure());
560 HeapObject* new_object = HeapObject::cast(new_allocation);
561 // Record all large objects in the same space.
562 address = new_object->address();
Andrei Popescu31002712010-02-23 13:46:05 +0000563 pages_[LO_SPACE].Add(address);
Steve Blockd0582a62009-12-15 09:54:21 +0000564 }
565 last_object_address_ = address;
566 return address;
567}
568
569
570// This returns the address of an object that has been described in the
571// snapshot as being offset bytes back in a particular space.
572HeapObject* Deserializer::GetAddressFromEnd(int space) {
573 int offset = source_->GetInt();
574 ASSERT(!SpaceIsLarge(space));
575 offset <<= kObjectAlignmentBits;
576 return HeapObject::FromAddress(high_water_[space] - offset);
577}
578
579
580// This returns the address of an object that has been described in the
581// snapshot as being offset bytes into a particular space.
582HeapObject* Deserializer::GetAddressFromStart(int space) {
583 int offset = source_->GetInt();
584 if (SpaceIsLarge(space)) {
585 // Large spaces have one object per 'page'.
586 return HeapObject::FromAddress(pages_[LO_SPACE][offset]);
587 }
588 offset <<= kObjectAlignmentBits;
589 if (space == NEW_SPACE) {
590 // New space has only one space - numbered 0.
591 return HeapObject::FromAddress(pages_[space][0] + offset);
592 }
593 ASSERT(SpaceIsPaged(space));
Leon Clarkee46be812010-01-19 14:06:41 +0000594 int page_of_pointee = offset >> kPageSizeBits;
Steve Blockd0582a62009-12-15 09:54:21 +0000595 Address object_address = pages_[space][page_of_pointee] +
596 (offset & Page::kPageAlignmentMask);
597 return HeapObject::FromAddress(object_address);
598}
599
600
601void Deserializer::Deserialize() {
602 // Don't GC while deserializing - just expand the heap.
603 AlwaysAllocateScope always_allocate;
604 // Don't use the free lists while deserializing.
605 LinearAllocationScope allocate_linearly;
606 // No active threads.
607 ASSERT_EQ(NULL, ThreadState::FirstInUse());
608 // No active handles.
609 ASSERT(HandleScopeImplementer::instance()->blocks()->is_empty());
Leon Clarked91b9f72010-01-27 17:25:45 +0000610 // Make sure the entire partial snapshot cache is traversed, filling it with
611 // valid object pointers.
612 partial_snapshot_cache_length_ = kPartialSnapshotCacheCapacity;
Steve Blockd0582a62009-12-15 09:54:21 +0000613 ASSERT_EQ(NULL, external_reference_decoder_);
614 external_reference_decoder_ = new ExternalReferenceDecoder();
Leon Clarked91b9f72010-01-27 17:25:45 +0000615 Heap::IterateStrongRoots(this, VISIT_ONLY_STRONG);
616 Heap::IterateWeakRoots(this, VISIT_ALL);
Leon Clarkee46be812010-01-19 14:06:41 +0000617}
618
619
620void Deserializer::DeserializePartial(Object** root) {
621 // Don't GC while deserializing - just expand the heap.
622 AlwaysAllocateScope always_allocate;
623 // Don't use the free lists while deserializing.
624 LinearAllocationScope allocate_linearly;
625 if (external_reference_decoder_ == NULL) {
626 external_reference_decoder_ = new ExternalReferenceDecoder();
627 }
628 VisitPointer(root);
629}
630
631
Leon Clarked91b9f72010-01-27 17:25:45 +0000632Deserializer::~Deserializer() {
633 ASSERT(source_->AtEOF());
Leon Clarkee46be812010-01-19 14:06:41 +0000634 if (external_reference_decoder_ != NULL) {
635 delete external_reference_decoder_;
636 external_reference_decoder_ = NULL;
637 }
Steve Blockd0582a62009-12-15 09:54:21 +0000638}
639
640
641// This is called on the roots. It is the driver of the deserialization
642// process. It is also called on the body of each function.
643void Deserializer::VisitPointers(Object** start, Object** end) {
644 // The space must be new space. Any other space would cause ReadChunk to try
645 // to update the remembered using NULL as the address.
646 ReadChunk(start, end, NEW_SPACE, NULL);
647}
648
649
650// This routine writes the new object into the pointer provided and then
651// returns true if the new object was in young space and false otherwise.
652// The reason for this strange interface is that otherwise the object is
653// written very late, which means the ByteArray map is not set up by the
654// time we need to use it to mark the space at the end of a page free (by
655// making it into a byte array).
656void Deserializer::ReadObject(int space_number,
657 Space* space,
658 Object** write_back) {
659 int size = source_->GetInt() << kObjectAlignmentBits;
660 Address address = Allocate(space_number, space, size);
661 *write_back = HeapObject::FromAddress(address);
662 Object** current = reinterpret_cast<Object**>(address);
663 Object** limit = current + (size >> kPointerSizeLog2);
Leon Clarkee46be812010-01-19 14:06:41 +0000664 if (FLAG_log_snapshot_positions) {
665 LOG(SnapshotPositionEvent(address, source_->position()));
666 }
Steve Blockd0582a62009-12-15 09:54:21 +0000667 ReadChunk(current, limit, space_number, address);
668}
669
670
671#define ONE_CASE_PER_SPACE(base_tag) \
672 case (base_tag) + NEW_SPACE: /* NOLINT */ \
673 case (base_tag) + OLD_POINTER_SPACE: /* NOLINT */ \
674 case (base_tag) + OLD_DATA_SPACE: /* NOLINT */ \
675 case (base_tag) + CODE_SPACE: /* NOLINT */ \
676 case (base_tag) + MAP_SPACE: /* NOLINT */ \
677 case (base_tag) + CELL_SPACE: /* NOLINT */ \
678 case (base_tag) + kLargeData: /* NOLINT */ \
679 case (base_tag) + kLargeCode: /* NOLINT */ \
680 case (base_tag) + kLargeFixedArray: /* NOLINT */
681
682
683void Deserializer::ReadChunk(Object** current,
684 Object** limit,
685 int space,
686 Address address) {
687 while (current < limit) {
688 int data = source_->Get();
689 switch (data) {
690#define RAW_CASE(index, size) \
691 case RAW_DATA_SERIALIZATION + index: { \
692 byte* raw_data_out = reinterpret_cast<byte*>(current); \
693 source_->CopyRaw(raw_data_out, size); \
694 current = reinterpret_cast<Object**>(raw_data_out + size); \
695 break; \
696 }
697 COMMON_RAW_LENGTHS(RAW_CASE)
698#undef RAW_CASE
699 case RAW_DATA_SERIALIZATION: {
700 int size = source_->GetInt();
701 byte* raw_data_out = reinterpret_cast<byte*>(current);
702 source_->CopyRaw(raw_data_out, size);
703 current = reinterpret_cast<Object**>(raw_data_out + size);
704 break;
705 }
706 case OBJECT_SERIALIZATION + NEW_SPACE: {
707 ReadObject(NEW_SPACE, Heap::new_space(), current);
708 if (space != NEW_SPACE) {
709 Heap::RecordWrite(address, static_cast<int>(
710 reinterpret_cast<Address>(current) - address));
711 }
712 current++;
713 break;
714 }
715 case OBJECT_SERIALIZATION + OLD_DATA_SPACE:
716 ReadObject(OLD_DATA_SPACE, Heap::old_data_space(), current++);
717 break;
718 case OBJECT_SERIALIZATION + OLD_POINTER_SPACE:
719 ReadObject(OLD_POINTER_SPACE, Heap::old_pointer_space(), current++);
720 break;
721 case OBJECT_SERIALIZATION + MAP_SPACE:
722 ReadObject(MAP_SPACE, Heap::map_space(), current++);
723 break;
724 case OBJECT_SERIALIZATION + CODE_SPACE:
725 ReadObject(CODE_SPACE, Heap::code_space(), current++);
Steve Blockd0582a62009-12-15 09:54:21 +0000726 break;
727 case OBJECT_SERIALIZATION + CELL_SPACE:
728 ReadObject(CELL_SPACE, Heap::cell_space(), current++);
729 break;
730 case OBJECT_SERIALIZATION + kLargeData:
731 ReadObject(kLargeData, Heap::lo_space(), current++);
732 break;
733 case OBJECT_SERIALIZATION + kLargeCode:
734 ReadObject(kLargeCode, Heap::lo_space(), current++);
Steve Blockd0582a62009-12-15 09:54:21 +0000735 break;
736 case OBJECT_SERIALIZATION + kLargeFixedArray:
737 ReadObject(kLargeFixedArray, Heap::lo_space(), current++);
738 break;
739 case CODE_OBJECT_SERIALIZATION + kLargeCode: {
740 Object* new_code_object = NULL;
741 ReadObject(kLargeCode, Heap::lo_space(), &new_code_object);
742 Code* code_object = reinterpret_cast<Code*>(new_code_object);
Steve Blockd0582a62009-12-15 09:54:21 +0000743 // Setting a branch/call to another code object from code.
744 Address location_of_branch_data = reinterpret_cast<Address>(current);
745 Assembler::set_target_at(location_of_branch_data,
746 code_object->instruction_start());
747 location_of_branch_data += Assembler::kCallTargetSize;
748 current = reinterpret_cast<Object**>(location_of_branch_data);
749 break;
750 }
751 case CODE_OBJECT_SERIALIZATION + CODE_SPACE: {
752 Object* new_code_object = NULL;
753 ReadObject(CODE_SPACE, Heap::code_space(), &new_code_object);
754 Code* code_object = reinterpret_cast<Code*>(new_code_object);
Steve Blockd0582a62009-12-15 09:54:21 +0000755 // Setting a branch/call to another code object from code.
756 Address location_of_branch_data = reinterpret_cast<Address>(current);
757 Assembler::set_target_at(location_of_branch_data,
758 code_object->instruction_start());
759 location_of_branch_data += Assembler::kCallTargetSize;
760 current = reinterpret_cast<Object**>(location_of_branch_data);
761 break;
762 }
763 ONE_CASE_PER_SPACE(BACKREF_SERIALIZATION) {
764 // Write a backreference to an object we unpacked earlier.
765 int backref_space = (data & kSpaceMask);
766 if (backref_space == NEW_SPACE && space != NEW_SPACE) {
767 Heap::RecordWrite(address, static_cast<int>(
768 reinterpret_cast<Address>(current) - address));
769 }
770 *current++ = GetAddressFromEnd(backref_space);
771 break;
772 }
773 ONE_CASE_PER_SPACE(REFERENCE_SERIALIZATION) {
774 // Write a reference to an object we unpacked earlier.
775 int reference_space = (data & kSpaceMask);
776 if (reference_space == NEW_SPACE && space != NEW_SPACE) {
777 Heap::RecordWrite(address, static_cast<int>(
778 reinterpret_cast<Address>(current) - address));
779 }
780 *current++ = GetAddressFromStart(reference_space);
781 break;
782 }
783#define COMMON_REFS_CASE(index, reference_space, address) \
784 case REFERENCE_SERIALIZATION + index: { \
785 ASSERT(SpaceIsPaged(reference_space)); \
786 Address object_address = \
787 pages_[reference_space][0] + (address << kObjectAlignmentBits); \
788 *current++ = HeapObject::FromAddress(object_address); \
789 break; \
790 }
791 COMMON_REFERENCE_PATTERNS(COMMON_REFS_CASE)
792#undef COMMON_REFS_CASE
793 ONE_CASE_PER_SPACE(CODE_BACKREF_SERIALIZATION) {
794 int backref_space = (data & kSpaceMask);
795 // Can't use Code::cast because heap is not set up yet and assertions
796 // will fail.
797 Code* code_object =
798 reinterpret_cast<Code*>(GetAddressFromEnd(backref_space));
799 // Setting a branch/call to previously decoded code object from code.
800 Address location_of_branch_data = reinterpret_cast<Address>(current);
801 Assembler::set_target_at(location_of_branch_data,
802 code_object->instruction_start());
803 location_of_branch_data += Assembler::kCallTargetSize;
804 current = reinterpret_cast<Object**>(location_of_branch_data);
805 break;
806 }
807 ONE_CASE_PER_SPACE(CODE_REFERENCE_SERIALIZATION) {
808 int backref_space = (data & kSpaceMask);
809 // Can't use Code::cast because heap is not set up yet and assertions
810 // will fail.
811 Code* code_object =
812 reinterpret_cast<Code*>(GetAddressFromStart(backref_space));
813 // Setting a branch/call to previously decoded code object from code.
814 Address location_of_branch_data = reinterpret_cast<Address>(current);
815 Assembler::set_target_at(location_of_branch_data,
816 code_object->instruction_start());
817 location_of_branch_data += Assembler::kCallTargetSize;
818 current = reinterpret_cast<Object**>(location_of_branch_data);
819 break;
820 }
821 case EXTERNAL_REFERENCE_SERIALIZATION: {
822 int reference_id = source_->GetInt();
823 Address address = external_reference_decoder_->Decode(reference_id);
824 *current++ = reinterpret_cast<Object*>(address);
825 break;
826 }
827 case EXTERNAL_BRANCH_TARGET_SERIALIZATION: {
828 int reference_id = source_->GetInt();
829 Address address = external_reference_decoder_->Decode(reference_id);
830 Address location_of_branch_data = reinterpret_cast<Address>(current);
831 Assembler::set_external_target_at(location_of_branch_data, address);
832 location_of_branch_data += Assembler::kExternalTargetSize;
833 current = reinterpret_cast<Object**>(location_of_branch_data);
834 break;
835 }
836 case START_NEW_PAGE_SERIALIZATION: {
837 int space = source_->Get();
838 pages_[space].Add(last_object_address_);
Steve Block6ded16b2010-05-10 14:33:55 +0100839 if (space == CODE_SPACE) {
840 CPU::FlushICache(last_object_address_, Page::kPageSize);
841 }
Steve Blockd0582a62009-12-15 09:54:21 +0000842 break;
843 }
844 case NATIVES_STRING_RESOURCE: {
845 int index = source_->Get();
846 Vector<const char> source_vector = Natives::GetScriptSource(index);
847 NativesExternalStringResource* resource =
848 new NativesExternalStringResource(source_vector.start());
849 *current++ = reinterpret_cast<Object*>(resource);
850 break;
851 }
Leon Clarkee46be812010-01-19 14:06:41 +0000852 case ROOT_SERIALIZATION: {
853 int root_id = source_->GetInt();
854 *current++ = Heap::roots_address()[root_id];
855 break;
856 }
Leon Clarked91b9f72010-01-27 17:25:45 +0000857 case PARTIAL_SNAPSHOT_CACHE_ENTRY: {
858 int cache_index = source_->GetInt();
859 *current++ = partial_snapshot_cache_[cache_index];
860 break;
861 }
862 case SYNCHRONIZE: {
863 // If we get here then that indicates that you have a mismatch between
864 // the number of GC roots when serializing and deserializing.
865 UNREACHABLE();
866 }
Steve Blockd0582a62009-12-15 09:54:21 +0000867 default:
868 UNREACHABLE();
869 }
870 }
871 ASSERT_EQ(current, limit);
872}
873
874
875void SnapshotByteSink::PutInt(uintptr_t integer, const char* description) {
876 const int max_shift = ((kPointerSize * kBitsPerByte) / 7) * 7;
877 for (int shift = max_shift; shift > 0; shift -= 7) {
878 if (integer >= static_cast<uintptr_t>(1u) << shift) {
Andrei Popescu402d9372010-02-26 13:31:12 +0000879 Put((static_cast<int>((integer >> shift)) & 0x7f) | 0x80, "IntPart");
Steve Blockd0582a62009-12-15 09:54:21 +0000880 }
881 }
Andrei Popescu402d9372010-02-26 13:31:12 +0000882 PutSection(static_cast<int>(integer & 0x7f), "IntLastPart");
Steve Blockd0582a62009-12-15 09:54:21 +0000883}
884
Steve Blocka7e24c12009-10-30 11:49:00 +0000885#ifdef DEBUG
Steve Blockd0582a62009-12-15 09:54:21 +0000886
887void Deserializer::Synchronize(const char* tag) {
888 int data = source_->Get();
889 // If this assert fails then that indicates that you have a mismatch between
890 // the number of GC roots when serializing and deserializing.
891 ASSERT_EQ(SYNCHRONIZE, data);
892 do {
893 int character = source_->Get();
894 if (character == 0) break;
895 if (FLAG_debug_serialization) {
896 PrintF("%c", character);
897 }
898 } while (true);
899 if (FLAG_debug_serialization) {
900 PrintF("\n");
901 }
902}
903
Steve Blocka7e24c12009-10-30 11:49:00 +0000904
905void Serializer::Synchronize(const char* tag) {
Steve Blockd0582a62009-12-15 09:54:21 +0000906 sink_->Put(SYNCHRONIZE, tag);
907 int character;
908 do {
909 character = *tag++;
910 sink_->PutSection(character, "TagCharacter");
911 } while (character != 0);
Steve Blocka7e24c12009-10-30 11:49:00 +0000912}
Steve Blockd0582a62009-12-15 09:54:21 +0000913
Steve Blocka7e24c12009-10-30 11:49:00 +0000914#endif
915
Steve Blockd0582a62009-12-15 09:54:21 +0000916Serializer::Serializer(SnapshotByteSink* sink)
917 : sink_(sink),
918 current_root_index_(0),
Andrei Popescu31002712010-02-23 13:46:05 +0000919 external_reference_encoder_(new ExternalReferenceEncoder),
Leon Clarkee46be812010-01-19 14:06:41 +0000920 large_object_total_(0) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000921 for (int i = 0; i <= LAST_SPACE; i++) {
Steve Blockd0582a62009-12-15 09:54:21 +0000922 fullness_[i] = 0;
Steve Blocka7e24c12009-10-30 11:49:00 +0000923 }
924}
925
926
Andrei Popescu31002712010-02-23 13:46:05 +0000927Serializer::~Serializer() {
928 delete external_reference_encoder_;
929}
930
931
Leon Clarked91b9f72010-01-27 17:25:45 +0000932void StartupSerializer::SerializeStrongReferences() {
Steve Blocka7e24c12009-10-30 11:49:00 +0000933 // No active threads.
934 CHECK_EQ(NULL, ThreadState::FirstInUse());
935 // No active or weak handles.
936 CHECK(HandleScopeImplementer::instance()->blocks()->is_empty());
937 CHECK_EQ(0, GlobalHandles::NumberOfWeakHandles());
Steve Blockd0582a62009-12-15 09:54:21 +0000938 // We don't support serializing installed extensions.
939 for (RegisteredExtension* ext = RegisteredExtension::first_extension();
940 ext != NULL;
941 ext = ext->next()) {
942 CHECK_NE(v8::INSTALLED, ext->state());
943 }
Leon Clarked91b9f72010-01-27 17:25:45 +0000944 Heap::IterateStrongRoots(this, VISIT_ONLY_STRONG);
Steve Blocka7e24c12009-10-30 11:49:00 +0000945}
946
947
Leon Clarked91b9f72010-01-27 17:25:45 +0000948void PartialSerializer::Serialize(Object** object) {
Leon Clarkee46be812010-01-19 14:06:41 +0000949 this->VisitPointer(object);
Leon Clarked91b9f72010-01-27 17:25:45 +0000950
951 // After we have done the partial serialization the partial snapshot cache
952 // will contain some references needed to decode the partial snapshot. We
953 // fill it up with undefineds so it has a predictable length so the
954 // deserialization code doesn't need to know the length.
955 for (int index = partial_snapshot_cache_length_;
956 index < kPartialSnapshotCacheCapacity;
957 index++) {
958 partial_snapshot_cache_[index] = Heap::undefined_value();
959 startup_serializer_->VisitPointer(&partial_snapshot_cache_[index]);
960 }
961 partial_snapshot_cache_length_ = kPartialSnapshotCacheCapacity;
Leon Clarkee46be812010-01-19 14:06:41 +0000962}
963
964
Steve Blocka7e24c12009-10-30 11:49:00 +0000965void Serializer::VisitPointers(Object** start, Object** end) {
Steve Blockd0582a62009-12-15 09:54:21 +0000966 for (Object** current = start; current < end; current++) {
967 if ((*current)->IsSmi()) {
968 sink_->Put(RAW_DATA_SERIALIZATION, "RawData");
969 sink_->PutInt(kPointerSize, "length");
970 for (int i = 0; i < kPointerSize; i++) {
971 sink_->Put(reinterpret_cast<byte*>(current)[i], "Byte");
972 }
Steve Blocka7e24c12009-10-30 11:49:00 +0000973 } else {
Steve Blockd0582a62009-12-15 09:54:21 +0000974 SerializeObject(*current, TAGGED_REPRESENTATION);
Steve Blocka7e24c12009-10-30 11:49:00 +0000975 }
976 }
977}
978
979
Leon Clarked91b9f72010-01-27 17:25:45 +0000980Object* SerializerDeserializer::partial_snapshot_cache_[
981 kPartialSnapshotCacheCapacity];
982int SerializerDeserializer::partial_snapshot_cache_length_ = 0;
983
984
985// This ensures that the partial snapshot cache keeps things alive during GC and
986// tracks their movement. When it is called during serialization of the startup
987// snapshot the partial snapshot is empty, so nothing happens. When the partial
988// (context) snapshot is created, this array is populated with the pointers that
989// the partial snapshot will need. As that happens we emit serialized objects to
990// the startup snapshot that correspond to the elements of this cache array. On
991// deserialization we therefore need to visit the cache array. This fills it up
992// with pointers to deserialized objects.
Steve Block6ded16b2010-05-10 14:33:55 +0100993void SerializerDeserializer::Iterate(ObjectVisitor* visitor) {
Leon Clarked91b9f72010-01-27 17:25:45 +0000994 visitor->VisitPointers(
995 &partial_snapshot_cache_[0],
996 &partial_snapshot_cache_[partial_snapshot_cache_length_]);
997}
998
999
1000// When deserializing we need to set the size of the snapshot cache. This means
1001// the root iteration code (above) will iterate over array elements, writing the
1002// references to deserialized objects in them.
1003void SerializerDeserializer::SetSnapshotCacheSize(int size) {
1004 partial_snapshot_cache_length_ = size;
1005}
1006
1007
1008int PartialSerializer::PartialSnapshotCacheIndex(HeapObject* heap_object) {
1009 for (int i = 0; i < partial_snapshot_cache_length_; i++) {
1010 Object* entry = partial_snapshot_cache_[i];
1011 if (entry == heap_object) return i;
1012 }
Andrei Popescu31002712010-02-23 13:46:05 +00001013
Leon Clarked91b9f72010-01-27 17:25:45 +00001014 // We didn't find the object in the cache. So we add it to the cache and
1015 // then visit the pointer so that it becomes part of the startup snapshot
1016 // and we can refer to it from the partial snapshot.
1017 int length = partial_snapshot_cache_length_;
1018 CHECK(length < kPartialSnapshotCacheCapacity);
1019 partial_snapshot_cache_[length] = heap_object;
1020 startup_serializer_->VisitPointer(&partial_snapshot_cache_[length]);
1021 // We don't recurse from the startup snapshot generator into the partial
1022 // snapshot generator.
1023 ASSERT(length == partial_snapshot_cache_length_);
1024 return partial_snapshot_cache_length_++;
1025}
1026
1027
1028int PartialSerializer::RootIndex(HeapObject* heap_object) {
Leon Clarkee46be812010-01-19 14:06:41 +00001029 for (int i = 0; i < Heap::kRootListLength; i++) {
1030 Object* root = Heap::roots_address()[i];
1031 if (root == heap_object) return i;
1032 }
1033 return kInvalidRootIndex;
1034}
1035
1036
Leon Clarked91b9f72010-01-27 17:25:45 +00001037// Encode the location of an already deserialized object in order to write its
1038// location into a later object. We can encode the location as an offset from
1039// the start of the deserialized objects or as an offset backwards from the
1040// current allocation pointer.
1041void Serializer::SerializeReferenceToPreviousObject(
1042 int space,
1043 int address,
1044 ReferenceRepresentation reference_representation) {
1045 int offset = CurrentAllocationAddress(space) - address;
1046 bool from_start = true;
1047 if (SpaceIsPaged(space)) {
1048 // For paged space it is simple to encode back from current allocation if
1049 // the object is on the same page as the current allocation pointer.
1050 if ((CurrentAllocationAddress(space) >> kPageSizeBits) ==
1051 (address >> kPageSizeBits)) {
1052 from_start = false;
1053 address = offset;
1054 }
1055 } else if (space == NEW_SPACE) {
1056 // For new space it is always simple to encode back from current allocation.
1057 if (offset < address) {
1058 from_start = false;
1059 address = offset;
1060 }
1061 }
1062 // If we are actually dealing with real offsets (and not a numbering of
1063 // all objects) then we should shift out the bits that are always 0.
1064 if (!SpaceIsLarge(space)) address >>= kObjectAlignmentBits;
1065 // On some architectures references between code objects are encoded
1066 // specially (as relative offsets). Such references have their own
1067 // special tags to simplify the deserializer.
1068 if (reference_representation == CODE_TARGET_REPRESENTATION) {
1069 if (from_start) {
1070 sink_->Put(CODE_REFERENCE_SERIALIZATION + space, "RefCodeSer");
1071 sink_->PutInt(address, "address");
1072 } else {
1073 sink_->Put(CODE_BACKREF_SERIALIZATION + space, "BackRefCodeSer");
1074 sink_->PutInt(address, "address");
1075 }
1076 } else {
1077 // Regular absolute references.
1078 CHECK_EQ(TAGGED_REPRESENTATION, reference_representation);
1079 if (from_start) {
1080 // There are some common offsets that have their own specialized encoding.
1081#define COMMON_REFS_CASE(tag, common_space, common_offset) \
1082 if (space == common_space && address == common_offset) { \
1083 sink_->PutSection(tag + REFERENCE_SERIALIZATION, "RefSer"); \
1084 } else /* NOLINT */
1085 COMMON_REFERENCE_PATTERNS(COMMON_REFS_CASE)
1086#undef COMMON_REFS_CASE
1087 { /* NOLINT */
1088 sink_->Put(REFERENCE_SERIALIZATION + space, "RefSer");
1089 sink_->PutInt(address, "address");
1090 }
1091 } else {
1092 sink_->Put(BACKREF_SERIALIZATION + space, "BackRefSer");
1093 sink_->PutInt(address, "address");
1094 }
1095 }
1096}
1097
1098
1099void StartupSerializer::SerializeObject(
Leon Clarkeeab96aa2010-01-27 16:31:12 +00001100 Object* o,
Leon Clarke888f6722010-01-27 15:57:47 +00001101 ReferenceRepresentation reference_representation) {
Leon Clarkeeab96aa2010-01-27 16:31:12 +00001102 CHECK(o->IsHeapObject());
1103 HeapObject* heap_object = HeapObject::cast(o);
Leon Clarked91b9f72010-01-27 17:25:45 +00001104
1105 if (address_mapper_.IsMapped(heap_object)) {
Leon Clarkeeab96aa2010-01-27 16:31:12 +00001106 int space = SpaceOfAlreadySerializedObject(heap_object);
Leon Clarked91b9f72010-01-27 17:25:45 +00001107 int address = address_mapper_.MappedTo(heap_object);
1108 SerializeReferenceToPreviousObject(space,
1109 address,
1110 reference_representation);
1111 } else {
1112 // Object has not yet been serialized. Serialize it here.
1113 ObjectSerializer object_serializer(this,
1114 heap_object,
1115 sink_,
1116 reference_representation);
1117 object_serializer.Serialize();
1118 }
1119}
1120
1121
1122void StartupSerializer::SerializeWeakReferences() {
1123 for (int i = partial_snapshot_cache_length_;
1124 i < kPartialSnapshotCacheCapacity;
1125 i++) {
1126 sink_->Put(ROOT_SERIALIZATION, "RootSerialization");
1127 sink_->PutInt(Heap::kUndefinedValueRootIndex, "root_index");
1128 }
1129 Heap::IterateWeakRoots(this, VISIT_ALL);
1130}
1131
1132
1133void PartialSerializer::SerializeObject(
1134 Object* o,
1135 ReferenceRepresentation reference_representation) {
1136 CHECK(o->IsHeapObject());
1137 HeapObject* heap_object = HeapObject::cast(o);
1138
1139 int root_index;
1140 if ((root_index = RootIndex(heap_object)) != kInvalidRootIndex) {
1141 sink_->Put(ROOT_SERIALIZATION, "RootSerialization");
1142 sink_->PutInt(root_index, "root_index");
1143 return;
1144 }
1145
1146 if (ShouldBeInThePartialSnapshotCache(heap_object)) {
1147 int cache_index = PartialSnapshotCacheIndex(heap_object);
1148 sink_->Put(PARTIAL_SNAPSHOT_CACHE_ENTRY, "PartialSnapshotCache");
1149 sink_->PutInt(cache_index, "partial_snapshot_cache_index");
1150 return;
1151 }
1152
1153 // Pointers from the partial snapshot to the objects in the startup snapshot
1154 // should go through the root array or through the partial snapshot cache.
1155 // If this is not the case you may have to add something to the root array.
1156 ASSERT(!startup_serializer_->address_mapper()->IsMapped(heap_object));
1157 // All the symbols that the partial snapshot needs should be either in the
1158 // root table or in the partial snapshot cache.
1159 ASSERT(!heap_object->IsSymbol());
1160
1161 if (address_mapper_.IsMapped(heap_object)) {
1162 int space = SpaceOfAlreadySerializedObject(heap_object);
1163 int address = address_mapper_.MappedTo(heap_object);
1164 SerializeReferenceToPreviousObject(space,
1165 address,
1166 reference_representation);
Steve Blockd0582a62009-12-15 09:54:21 +00001167 } else {
1168 // Object has not yet been serialized. Serialize it here.
1169 ObjectSerializer serializer(this,
1170 heap_object,
1171 sink_,
1172 reference_representation);
1173 serializer.Serialize();
1174 }
1175}
1176
1177
Steve Blockd0582a62009-12-15 09:54:21 +00001178void Serializer::ObjectSerializer::Serialize() {
1179 int space = Serializer::SpaceOfObject(object_);
1180 int size = object_->Size();
1181
1182 if (reference_representation_ == TAGGED_REPRESENTATION) {
1183 sink_->Put(OBJECT_SERIALIZATION + space, "ObjectSerialization");
1184 } else {
1185 CHECK_EQ(CODE_TARGET_REPRESENTATION, reference_representation_);
1186 sink_->Put(CODE_OBJECT_SERIALIZATION + space, "ObjectSerialization");
1187 }
1188 sink_->PutInt(size >> kObjectAlignmentBits, "Size in words");
1189
Leon Clarkee46be812010-01-19 14:06:41 +00001190 LOG(SnapshotPositionEvent(object_->address(), sink_->Position()));
1191
Steve Blockd0582a62009-12-15 09:54:21 +00001192 // Mark this object as already serialized.
1193 bool start_new_page;
Leon Clarked91b9f72010-01-27 17:25:45 +00001194 int offset = serializer_->Allocate(space, size, &start_new_page);
1195 serializer_->address_mapper()->AddMapping(object_, offset);
Steve Blockd0582a62009-12-15 09:54:21 +00001196 if (start_new_page) {
1197 sink_->Put(START_NEW_PAGE_SERIALIZATION, "NewPage");
1198 sink_->PutSection(space, "NewPageSpace");
1199 }
1200
1201 // Serialize the map (first word of the object).
1202 serializer_->SerializeObject(object_->map(), TAGGED_REPRESENTATION);
1203
1204 // Serialize the rest of the object.
1205 CHECK_EQ(0, bytes_processed_so_far_);
1206 bytes_processed_so_far_ = kPointerSize;
1207 object_->IterateBody(object_->map()->instance_type(), size, this);
1208 OutputRawData(object_->address() + size);
1209}
1210
1211
1212void Serializer::ObjectSerializer::VisitPointers(Object** start,
1213 Object** end) {
1214 Object** current = start;
1215 while (current < end) {
1216 while (current < end && (*current)->IsSmi()) current++;
1217 if (current < end) OutputRawData(reinterpret_cast<Address>(current));
1218
1219 while (current < end && !(*current)->IsSmi()) {
1220 serializer_->SerializeObject(*current, TAGGED_REPRESENTATION);
1221 bytes_processed_so_far_ += kPointerSize;
1222 current++;
1223 }
1224 }
1225}
1226
1227
1228void Serializer::ObjectSerializer::VisitExternalReferences(Address* start,
1229 Address* end) {
1230 Address references_start = reinterpret_cast<Address>(start);
1231 OutputRawData(references_start);
1232
1233 for (Address* current = start; current < end; current++) {
1234 sink_->Put(EXTERNAL_REFERENCE_SERIALIZATION, "ExternalReference");
1235 int reference_id = serializer_->EncodeExternalReference(*current);
1236 sink_->PutInt(reference_id, "reference id");
1237 }
1238 bytes_processed_so_far_ += static_cast<int>((end - start) * kPointerSize);
1239}
1240
1241
1242void Serializer::ObjectSerializer::VisitRuntimeEntry(RelocInfo* rinfo) {
1243 Address target_start = rinfo->target_address_address();
1244 OutputRawData(target_start);
1245 Address target = rinfo->target_address();
1246 uint32_t encoding = serializer_->EncodeExternalReference(target);
1247 CHECK(target == NULL ? encoding == 0 : encoding != 0);
1248 sink_->Put(EXTERNAL_BRANCH_TARGET_SERIALIZATION, "ExternalReference");
1249 sink_->PutInt(encoding, "reference id");
1250 bytes_processed_so_far_ += Assembler::kExternalTargetSize;
1251}
1252
1253
1254void Serializer::ObjectSerializer::VisitCodeTarget(RelocInfo* rinfo) {
1255 CHECK(RelocInfo::IsCodeTarget(rinfo->rmode()));
1256 Address target_start = rinfo->target_address_address();
1257 OutputRawData(target_start);
1258 Code* target = Code::GetCodeFromTargetAddress(rinfo->target_address());
1259 serializer_->SerializeObject(target, CODE_TARGET_REPRESENTATION);
1260 bytes_processed_so_far_ += Assembler::kCallTargetSize;
1261}
1262
1263
1264void Serializer::ObjectSerializer::VisitExternalAsciiString(
1265 v8::String::ExternalAsciiStringResource** resource_pointer) {
1266 Address references_start = reinterpret_cast<Address>(resource_pointer);
1267 OutputRawData(references_start);
1268 for (int i = 0; i < Natives::GetBuiltinsCount(); i++) {
1269 Object* source = Heap::natives_source_cache()->get(i);
1270 if (!source->IsUndefined()) {
1271 ExternalAsciiString* string = ExternalAsciiString::cast(source);
1272 typedef v8::String::ExternalAsciiStringResource Resource;
1273 Resource* resource = string->resource();
1274 if (resource == *resource_pointer) {
1275 sink_->Put(NATIVES_STRING_RESOURCE, "NativesStringResource");
1276 sink_->PutSection(i, "NativesStringResourceEnd");
1277 bytes_processed_so_far_ += sizeof(resource);
1278 return;
1279 }
1280 }
1281 }
1282 // One of the strings in the natives cache should match the resource. We
1283 // can't serialize any other kinds of external strings.
1284 UNREACHABLE();
1285}
1286
1287
1288void Serializer::ObjectSerializer::OutputRawData(Address up_to) {
1289 Address object_start = object_->address();
1290 int up_to_offset = static_cast<int>(up_to - object_start);
1291 int skipped = up_to_offset - bytes_processed_so_far_;
1292 // This assert will fail if the reloc info gives us the target_address_address
1293 // locations in a non-ascending order. Luckily that doesn't happen.
1294 ASSERT(skipped >= 0);
1295 if (skipped != 0) {
1296 Address base = object_start + bytes_processed_so_far_;
1297#define RAW_CASE(index, length) \
1298 if (skipped == length) { \
1299 sink_->PutSection(RAW_DATA_SERIALIZATION + index, "RawDataFixed"); \
1300 } else /* NOLINT */
1301 COMMON_RAW_LENGTHS(RAW_CASE)
1302#undef RAW_CASE
1303 { /* NOLINT */
1304 sink_->Put(RAW_DATA_SERIALIZATION, "RawData");
1305 sink_->PutInt(skipped, "length");
1306 }
1307 for (int i = 0; i < skipped; i++) {
1308 unsigned int data = base[i];
1309 sink_->PutSection(data, "Byte");
1310 }
1311 bytes_processed_so_far_ += skipped;
1312 }
1313}
1314
1315
1316int Serializer::SpaceOfObject(HeapObject* object) {
1317 for (int i = FIRST_SPACE; i <= LAST_SPACE; i++) {
1318 AllocationSpace s = static_cast<AllocationSpace>(i);
1319 if (Heap::InSpace(object, s)) {
1320 if (i == LO_SPACE) {
1321 if (object->IsCode()) {
1322 return kLargeCode;
1323 } else if (object->IsFixedArray()) {
1324 return kLargeFixedArray;
1325 } else {
1326 return kLargeData;
1327 }
1328 }
1329 return i;
1330 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001331 }
1332 UNREACHABLE();
Steve Blockd0582a62009-12-15 09:54:21 +00001333 return 0;
1334}
1335
1336
1337int Serializer::SpaceOfAlreadySerializedObject(HeapObject* object) {
1338 for (int i = FIRST_SPACE; i <= LAST_SPACE; i++) {
1339 AllocationSpace s = static_cast<AllocationSpace>(i);
1340 if (Heap::InSpace(object, s)) {
1341 return i;
1342 }
1343 }
1344 UNREACHABLE();
1345 return 0;
1346}
1347
1348
1349int Serializer::Allocate(int space, int size, bool* new_page) {
1350 CHECK(space >= 0 && space < kNumberOfSpaces);
1351 if (SpaceIsLarge(space)) {
1352 // In large object space we merely number the objects instead of trying to
1353 // determine some sort of address.
1354 *new_page = true;
Leon Clarkee46be812010-01-19 14:06:41 +00001355 large_object_total_ += size;
Steve Blockd0582a62009-12-15 09:54:21 +00001356 return fullness_[LO_SPACE]++;
1357 }
1358 *new_page = false;
1359 if (fullness_[space] == 0) {
1360 *new_page = true;
1361 }
1362 if (SpaceIsPaged(space)) {
1363 // Paged spaces are a little special. We encode their addresses as if the
1364 // pages were all contiguous and each page were filled up in the range
1365 // 0 - Page::kObjectAreaSize. In practice the pages may not be contiguous
1366 // and allocation does not start at offset 0 in the page, but this scheme
1367 // means the deserializer can get the page number quickly by shifting the
1368 // serialized address.
1369 CHECK(IsPowerOf2(Page::kPageSize));
1370 int used_in_this_page = (fullness_[space] & (Page::kPageSize - 1));
1371 CHECK(size <= Page::kObjectAreaSize);
1372 if (used_in_this_page + size > Page::kObjectAreaSize) {
1373 *new_page = true;
1374 fullness_[space] = RoundUp(fullness_[space], Page::kPageSize);
1375 }
1376 }
1377 int allocation_address = fullness_[space];
1378 fullness_[space] = allocation_address + size;
1379 return allocation_address;
Steve Blocka7e24c12009-10-30 11:49:00 +00001380}
1381
1382
1383} } // namespace v8::internal