deps: update v8 to 4.3.61.21
[platform/upstream/nodejs.git] / deps / v8 / test / cctest / test-serialize.cc
1 // Copyright 2007-2010 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 <signal.h>
29
30 #include <sys/stat.h>
31
32 #include "src/v8.h"
33
34 #include "src/bootstrapper.h"
35 #include "src/compilation-cache.h"
36 #include "src/debug.h"
37 #include "src/heap/spaces.h"
38 #include "src/objects.h"
39 #include "src/parser.h"
40 #include "src/runtime/runtime.h"
41 #include "src/scopeinfo.h"
42 #include "src/snapshot/natives.h"
43 #include "src/snapshot/serialize.h"
44 #include "src/snapshot/snapshot.h"
45 #include "test/cctest/cctest.h"
46
47 using namespace v8::internal;
48
49
50 bool DefaultSnapshotAvailable() {
51   return i::Snapshot::DefaultSnapshotBlob() != NULL;
52 }
53
54
55 void DisableTurbofan() {
56   const char* flag = "--turbo-filter=\"\"";
57   FlagList::SetFlagsFromString(flag, StrLength(flag));
58 }
59
60
61 // TestIsolate is used for testing isolate serialization.
62 class TestIsolate : public Isolate {
63  public:
64   static v8::Isolate* NewInitialized(bool enable_serializer) {
65     i::Isolate* isolate = new TestIsolate(enable_serializer);
66     v8::Isolate* v8_isolate = reinterpret_cast<v8::Isolate*>(isolate);
67     v8::Isolate::Scope isolate_scope(v8_isolate);
68     isolate->Init(NULL);
69     return v8_isolate;
70   }
71   explicit TestIsolate(bool enable_serializer) : Isolate(enable_serializer) {}
72 };
73
74
75 void WritePayload(const Vector<const byte>& payload, const char* file_name) {
76   FILE* file = v8::base::OS::FOpen(file_name, "wb");
77   if (file == NULL) {
78     PrintF("Unable to write to snapshot file \"%s\"\n", file_name);
79     exit(1);
80   }
81   size_t written = fwrite(payload.begin(), 1, payload.length(), file);
82   if (written != static_cast<size_t>(payload.length())) {
83     i::PrintF("Writing snapshot file failed.. Aborting.\n");
84     exit(1);
85   }
86   fclose(file);
87 }
88
89
90 static bool WriteToFile(Isolate* isolate, const char* snapshot_file) {
91   SnapshotByteSink sink;
92   StartupSerializer ser(isolate, &sink);
93   ser.Serialize();
94   SnapshotData snapshot_data(ser);
95   WritePayload(snapshot_data.RawData(), snapshot_file);
96   return true;
97 }
98
99
100 static void Serialize(v8::Isolate* isolate) {
101   // We have to create one context.  One reason for this is so that the builtins
102   // can be loaded from v8natives.js and their addresses can be processed.  This
103   // will clear the pending fixups array, which would otherwise contain GC roots
104   // that would confuse the serialization/deserialization process.
105   v8::Isolate::Scope isolate_scope(isolate);
106   {
107     v8::HandleScope scope(isolate);
108     v8::Context::New(isolate);
109   }
110
111   Isolate* internal_isolate = reinterpret_cast<Isolate*>(isolate);
112   internal_isolate->heap()->CollectAllAvailableGarbage("serialize");
113   WriteToFile(internal_isolate, FLAG_testing_serialization_file);
114 }
115
116
117 Vector<const uint8_t> ConstructSource(Vector<const uint8_t> head,
118                                       Vector<const uint8_t> body,
119                                       Vector<const uint8_t> tail, int repeats) {
120   int source_length = head.length() + body.length() * repeats + tail.length();
121   uint8_t* source = NewArray<uint8_t>(static_cast<size_t>(source_length));
122   CopyChars(source, head.start(), head.length());
123   for (int i = 0; i < repeats; i++) {
124     CopyChars(source + head.length() + i * body.length(), body.start(),
125               body.length());
126   }
127   CopyChars(source + head.length() + repeats * body.length(), tail.start(),
128             tail.length());
129   return Vector<const uint8_t>(const_cast<const uint8_t*>(source),
130                                source_length);
131 }
132
133
134 // Test that the whole heap can be serialized.
135 UNINITIALIZED_TEST(Serialize) {
136   DisableTurbofan();
137   if (DefaultSnapshotAvailable()) return;
138   v8::Isolate* isolate = TestIsolate::NewInitialized(true);
139   Serialize(isolate);
140 }
141
142
143 // Test that heap serialization is non-destructive.
144 UNINITIALIZED_TEST(SerializeTwice) {
145   DisableTurbofan();
146   if (DefaultSnapshotAvailable()) return;
147   v8::Isolate* isolate = TestIsolate::NewInitialized(true);
148   Serialize(isolate);
149   Serialize(isolate);
150 }
151
152
153 //----------------------------------------------------------------------------
154 // Tests that the heap can be deserialized.
155
156 v8::Isolate* InitializeFromFile(const char* snapshot_file) {
157   int len;
158   byte* str = ReadBytes(snapshot_file, &len);
159   if (!str) return NULL;
160   v8::Isolate* v8_isolate = NULL;
161   {
162     SnapshotData snapshot_data(Vector<const byte>(str, len));
163     Deserializer deserializer(&snapshot_data);
164     Isolate* isolate = new TestIsolate(false);
165     v8_isolate = reinterpret_cast<v8::Isolate*>(isolate);
166     v8::Isolate::Scope isolate_scope(v8_isolate);
167     isolate->Init(&deserializer);
168   }
169   DeleteArray(str);
170   return v8_isolate;
171 }
172
173
174 static v8::Isolate* Deserialize() {
175   v8::Isolate* isolate = InitializeFromFile(FLAG_testing_serialization_file);
176   CHECK(isolate);
177   return isolate;
178 }
179
180
181 static void SanityCheck(v8::Isolate* v8_isolate) {
182   Isolate* isolate = reinterpret_cast<Isolate*>(v8_isolate);
183   v8::HandleScope scope(v8_isolate);
184 #ifdef VERIFY_HEAP
185   isolate->heap()->Verify();
186 #endif
187   CHECK(isolate->global_object()->IsJSObject());
188   CHECK(isolate->native_context()->IsContext());
189   CHECK(isolate->heap()->string_table()->IsStringTable());
190   isolate->factory()->InternalizeOneByteString(STATIC_CHAR_VECTOR("Empty"));
191 }
192
193
194 UNINITIALIZED_DEPENDENT_TEST(Deserialize, Serialize) {
195   // The serialize-deserialize tests only work if the VM is built without
196   // serialization.  That doesn't matter.  We don't need to be able to
197   // serialize a snapshot in a VM that is booted from a snapshot.
198   DisableTurbofan();
199   if (DefaultSnapshotAvailable()) return;
200   v8::Isolate* isolate = Deserialize();
201   {
202     v8::HandleScope handle_scope(isolate);
203     v8::Isolate::Scope isolate_scope(isolate);
204
205     v8::Local<v8::Context> env = v8::Context::New(isolate);
206     env->Enter();
207
208     SanityCheck(isolate);
209   }
210   isolate->Dispose();
211 }
212
213
214 UNINITIALIZED_DEPENDENT_TEST(DeserializeFromSecondSerialization,
215                              SerializeTwice) {
216   DisableTurbofan();
217   if (DefaultSnapshotAvailable()) return;
218   v8::Isolate* isolate = Deserialize();
219   {
220     v8::Isolate::Scope isolate_scope(isolate);
221     v8::HandleScope handle_scope(isolate);
222
223     v8::Local<v8::Context> env = v8::Context::New(isolate);
224     env->Enter();
225
226     SanityCheck(isolate);
227   }
228   isolate->Dispose();
229 }
230
231
232 UNINITIALIZED_DEPENDENT_TEST(DeserializeAndRunScript2, Serialize) {
233   DisableTurbofan();
234   if (DefaultSnapshotAvailable()) return;
235   v8::Isolate* isolate = Deserialize();
236   {
237     v8::Isolate::Scope isolate_scope(isolate);
238     v8::HandleScope handle_scope(isolate);
239
240
241     v8::Local<v8::Context> env = v8::Context::New(isolate);
242     env->Enter();
243
244     const char* c_source = "\"1234\".length";
245     v8::Local<v8::String> source = v8::String::NewFromUtf8(isolate, c_source);
246     v8::Local<v8::Script> script = v8::Script::Compile(source);
247     CHECK_EQ(4, script->Run()->Int32Value());
248   }
249   isolate->Dispose();
250 }
251
252
253 UNINITIALIZED_DEPENDENT_TEST(DeserializeFromSecondSerializationAndRunScript2,
254                              SerializeTwice) {
255   DisableTurbofan();
256   if (DefaultSnapshotAvailable()) return;
257   v8::Isolate* isolate = Deserialize();
258   {
259     v8::Isolate::Scope isolate_scope(isolate);
260     v8::HandleScope handle_scope(isolate);
261
262     v8::Local<v8::Context> env = v8::Context::New(isolate);
263     env->Enter();
264
265     const char* c_source = "\"1234\".length";
266     v8::Local<v8::String> source = v8::String::NewFromUtf8(isolate, c_source);
267     v8::Local<v8::Script> script = v8::Script::Compile(source);
268     CHECK_EQ(4, script->Run()->Int32Value());
269   }
270   isolate->Dispose();
271 }
272
273
274 UNINITIALIZED_TEST(PartialSerialization) {
275   DisableTurbofan();
276   if (DefaultSnapshotAvailable()) return;
277   v8::Isolate* v8_isolate = TestIsolate::NewInitialized(true);
278   Isolate* isolate = reinterpret_cast<Isolate*>(v8_isolate);
279   v8_isolate->Enter();
280   {
281     Heap* heap = isolate->heap();
282
283     v8::Persistent<v8::Context> env;
284     {
285       HandleScope scope(isolate);
286       env.Reset(v8_isolate, v8::Context::New(v8_isolate));
287     }
288     DCHECK(!env.IsEmpty());
289     {
290       v8::HandleScope handle_scope(v8_isolate);
291       v8::Local<v8::Context>::New(v8_isolate, env)->Enter();
292     }
293     // Make sure all builtin scripts are cached.
294     {
295       HandleScope scope(isolate);
296       for (int i = 0; i < Natives::GetBuiltinsCount(); i++) {
297         isolate->bootstrapper()->NativesSourceLookup(i);
298       }
299     }
300     heap->CollectAllGarbage(Heap::kNoGCFlags);
301     heap->CollectAllGarbage(Heap::kNoGCFlags);
302
303     Object* raw_foo;
304     {
305       v8::HandleScope handle_scope(v8_isolate);
306       v8::Local<v8::String> foo = v8::String::NewFromUtf8(v8_isolate, "foo");
307       DCHECK(!foo.IsEmpty());
308       raw_foo = *(v8::Utils::OpenHandle(*foo));
309     }
310
311     int file_name_length = StrLength(FLAG_testing_serialization_file) + 10;
312     Vector<char> startup_name = Vector<char>::New(file_name_length + 1);
313     SNPrintF(startup_name, "%s.startup", FLAG_testing_serialization_file);
314
315     {
316       v8::HandleScope handle_scope(v8_isolate);
317       v8::Local<v8::Context>::New(v8_isolate, env)->Exit();
318     }
319     env.Reset();
320
321     SnapshotByteSink startup_sink;
322     StartupSerializer startup_serializer(isolate, &startup_sink);
323     startup_serializer.SerializeStrongReferences();
324
325     SnapshotByteSink partial_sink;
326     PartialSerializer partial_serializer(isolate, &startup_serializer,
327                                          &partial_sink);
328     partial_serializer.Serialize(&raw_foo);
329
330     startup_serializer.SerializeWeakReferences();
331
332     SnapshotData startup_snapshot(startup_serializer);
333     SnapshotData partial_snapshot(partial_serializer);
334
335     WritePayload(partial_snapshot.RawData(), FLAG_testing_serialization_file);
336     WritePayload(startup_snapshot.RawData(), startup_name.start());
337
338     startup_name.Dispose();
339   }
340   v8_isolate->Exit();
341   v8_isolate->Dispose();
342 }
343
344
345 UNINITIALIZED_DEPENDENT_TEST(PartialDeserialization, PartialSerialization) {
346   DisableTurbofan();
347   if (DefaultSnapshotAvailable()) return;
348   int file_name_length = StrLength(FLAG_testing_serialization_file) + 10;
349   Vector<char> startup_name = Vector<char>::New(file_name_length + 1);
350   SNPrintF(startup_name, "%s.startup", FLAG_testing_serialization_file);
351
352   v8::Isolate* v8_isolate = InitializeFromFile(startup_name.start());
353   CHECK(v8_isolate);
354   startup_name.Dispose();
355   {
356     v8::Isolate::Scope isolate_scope(v8_isolate);
357
358     const char* file_name = FLAG_testing_serialization_file;
359
360     int snapshot_size = 0;
361     byte* snapshot = ReadBytes(file_name, &snapshot_size);
362
363     Isolate* isolate = reinterpret_cast<Isolate*>(v8_isolate);
364     HandleScope handle_scope(isolate);
365     Handle<Object> root;
366     Handle<FixedArray> outdated_contexts;
367     // Intentionally empty handle. The deserializer should not come across
368     // any references to the global proxy in this test.
369     Handle<JSGlobalProxy> global_proxy = Handle<JSGlobalProxy>::null();
370     {
371       SnapshotData snapshot_data(Vector<const byte>(snapshot, snapshot_size));
372       Deserializer deserializer(&snapshot_data);
373       root =
374           deserializer.DeserializePartial(isolate, global_proxy,
375                                           &outdated_contexts).ToHandleChecked();
376       CHECK_EQ(0, outdated_contexts->length());
377       CHECK(root->IsString());
378     }
379
380     Handle<Object> root2;
381     {
382       SnapshotData snapshot_data(Vector<const byte>(snapshot, snapshot_size));
383       Deserializer deserializer(&snapshot_data);
384       root2 =
385           deserializer.DeserializePartial(isolate, global_proxy,
386                                           &outdated_contexts).ToHandleChecked();
387       CHECK(root2->IsString());
388       CHECK(root.is_identical_to(root2));
389     }
390
391     DeleteArray(snapshot);
392   }
393   v8_isolate->Dispose();
394 }
395
396
397 UNINITIALIZED_TEST(ContextSerialization) {
398   DisableTurbofan();
399   if (DefaultSnapshotAvailable()) return;
400   v8::Isolate* v8_isolate = TestIsolate::NewInitialized(true);
401   Isolate* isolate = reinterpret_cast<Isolate*>(v8_isolate);
402   Heap* heap = isolate->heap();
403   {
404     v8::Isolate::Scope isolate_scope(v8_isolate);
405
406     v8::Persistent<v8::Context> env;
407     {
408       HandleScope scope(isolate);
409       env.Reset(v8_isolate, v8::Context::New(v8_isolate));
410     }
411     DCHECK(!env.IsEmpty());
412     {
413       v8::HandleScope handle_scope(v8_isolate);
414       v8::Local<v8::Context>::New(v8_isolate, env)->Enter();
415     }
416     // Make sure all builtin scripts are cached.
417     {
418       HandleScope scope(isolate);
419       for (int i = 0; i < Natives::GetBuiltinsCount(); i++) {
420         isolate->bootstrapper()->NativesSourceLookup(i);
421       }
422     }
423     // If we don't do this then we end up with a stray root pointing at the
424     // context even after we have disposed of env.
425     heap->CollectAllGarbage(Heap::kNoGCFlags);
426
427     int file_name_length = StrLength(FLAG_testing_serialization_file) + 10;
428     Vector<char> startup_name = Vector<char>::New(file_name_length + 1);
429     SNPrintF(startup_name, "%s.startup", FLAG_testing_serialization_file);
430
431     {
432       v8::HandleScope handle_scope(v8_isolate);
433       v8::Local<v8::Context>::New(v8_isolate, env)->Exit();
434     }
435
436     i::Object* raw_context = *v8::Utils::OpenPersistent(env);
437
438     env.Reset();
439
440     SnapshotByteSink startup_sink;
441     StartupSerializer startup_serializer(isolate, &startup_sink);
442     startup_serializer.SerializeStrongReferences();
443
444     SnapshotByteSink partial_sink;
445     PartialSerializer partial_serializer(isolate, &startup_serializer,
446                                          &partial_sink);
447     partial_serializer.Serialize(&raw_context);
448     startup_serializer.SerializeWeakReferences();
449
450     SnapshotData startup_snapshot(startup_serializer);
451     SnapshotData partial_snapshot(partial_serializer);
452
453     WritePayload(partial_snapshot.RawData(), FLAG_testing_serialization_file);
454     WritePayload(startup_snapshot.RawData(), startup_name.start());
455
456     startup_name.Dispose();
457   }
458   v8_isolate->Dispose();
459 }
460
461
462 UNINITIALIZED_DEPENDENT_TEST(ContextDeserialization, ContextSerialization) {
463   DisableTurbofan();
464   if (DefaultSnapshotAvailable()) return;
465   int file_name_length = StrLength(FLAG_testing_serialization_file) + 10;
466   Vector<char> startup_name = Vector<char>::New(file_name_length + 1);
467   SNPrintF(startup_name, "%s.startup", FLAG_testing_serialization_file);
468
469   v8::Isolate* v8_isolate = InitializeFromFile(startup_name.start());
470   CHECK(v8_isolate);
471   startup_name.Dispose();
472   {
473     v8::Isolate::Scope isolate_scope(v8_isolate);
474
475     const char* file_name = FLAG_testing_serialization_file;
476
477     int snapshot_size = 0;
478     byte* snapshot = ReadBytes(file_name, &snapshot_size);
479
480     Isolate* isolate = reinterpret_cast<Isolate*>(v8_isolate);
481     HandleScope handle_scope(isolate);
482     Handle<Object> root;
483     Handle<FixedArray> outdated_contexts;
484     Handle<JSGlobalProxy> global_proxy =
485         isolate->factory()->NewUninitializedJSGlobalProxy();
486     {
487       SnapshotData snapshot_data(Vector<const byte>(snapshot, snapshot_size));
488       Deserializer deserializer(&snapshot_data);
489       root =
490           deserializer.DeserializePartial(isolate, global_proxy,
491                                           &outdated_contexts).ToHandleChecked();
492       CHECK(root->IsContext());
493       CHECK(Handle<Context>::cast(root)->global_proxy() == *global_proxy);
494       CHECK_EQ(1, outdated_contexts->length());
495     }
496
497     Handle<Object> root2;
498     {
499       SnapshotData snapshot_data(Vector<const byte>(snapshot, snapshot_size));
500       Deserializer deserializer(&snapshot_data);
501       root2 =
502           deserializer.DeserializePartial(isolate, global_proxy,
503                                           &outdated_contexts).ToHandleChecked();
504       CHECK(root2->IsContext());
505       CHECK(!root.is_identical_to(root2));
506     }
507     DeleteArray(snapshot);
508   }
509   v8_isolate->Dispose();
510 }
511
512
513 UNINITIALIZED_TEST(CustomContextSerialization) {
514   DisableTurbofan();
515   if (DefaultSnapshotAvailable()) return;
516   v8::Isolate* v8_isolate = TestIsolate::NewInitialized(true);
517   Isolate* isolate = reinterpret_cast<Isolate*>(v8_isolate);
518   {
519     v8::Isolate::Scope isolate_scope(v8_isolate);
520
521     v8::Persistent<v8::Context> env;
522     {
523       HandleScope scope(isolate);
524       env.Reset(v8_isolate, v8::Context::New(v8_isolate));
525     }
526     DCHECK(!env.IsEmpty());
527     {
528       v8::HandleScope handle_scope(v8_isolate);
529       v8::Local<v8::Context>::New(v8_isolate, env)->Enter();
530       // After execution, e's function context refers to the global object.
531       CompileRun(
532           "var e;"
533           "(function() {"
534           "  e = function(s) { return eval (s); }"
535           "})();"
536           "var o = this;"
537           "var r = Math.random() + Math.cos(0);"
538           "var f = (function(a, b) { return a + b; }).bind(1, 2, 3);"
539           "var s = parseInt('12345');");
540
541       Vector<const uint8_t> source = ConstructSource(
542           STATIC_CHAR_VECTOR("function g() { return [,"),
543           STATIC_CHAR_VECTOR("1,"),
544           STATIC_CHAR_VECTOR("];} a = g(); b = g(); b.push(1);"), 100000);
545       v8::Handle<v8::String> source_str = v8::String::NewFromOneByte(
546           v8_isolate, source.start(), v8::String::kNormalString,
547           source.length());
548       CompileRun(source_str);
549       source.Dispose();
550     }
551     // Make sure all builtin scripts are cached.
552     {
553       HandleScope scope(isolate);
554       for (int i = 0; i < Natives::GetBuiltinsCount(); i++) {
555         isolate->bootstrapper()->NativesSourceLookup(i);
556       }
557     }
558     // If we don't do this then we end up with a stray root pointing at the
559     // context even after we have disposed of env.
560     isolate->heap()->CollectAllAvailableGarbage("snapshotting");
561
562     int file_name_length = StrLength(FLAG_testing_serialization_file) + 10;
563     Vector<char> startup_name = Vector<char>::New(file_name_length + 1);
564     SNPrintF(startup_name, "%s.startup", FLAG_testing_serialization_file);
565
566     {
567       v8::HandleScope handle_scope(v8_isolate);
568       v8::Local<v8::Context>::New(v8_isolate, env)->Exit();
569     }
570
571     i::Object* raw_context = *v8::Utils::OpenPersistent(env);
572
573     env.Reset();
574
575     SnapshotByteSink startup_sink;
576     StartupSerializer startup_serializer(isolate, &startup_sink);
577     startup_serializer.SerializeStrongReferences();
578
579     SnapshotByteSink partial_sink;
580     PartialSerializer partial_serializer(isolate, &startup_serializer,
581                                          &partial_sink);
582     partial_serializer.Serialize(&raw_context);
583     startup_serializer.SerializeWeakReferences();
584
585     SnapshotData startup_snapshot(startup_serializer);
586     SnapshotData partial_snapshot(partial_serializer);
587
588     WritePayload(partial_snapshot.RawData(), FLAG_testing_serialization_file);
589     WritePayload(startup_snapshot.RawData(), startup_name.start());
590
591     startup_name.Dispose();
592   }
593   v8_isolate->Dispose();
594 }
595
596
597 UNINITIALIZED_DEPENDENT_TEST(CustomContextDeserialization,
598                              CustomContextSerialization) {
599   DisableTurbofan();
600   FLAG_crankshaft = false;
601   if (DefaultSnapshotAvailable()) return;
602   int file_name_length = StrLength(FLAG_testing_serialization_file) + 10;
603   Vector<char> startup_name = Vector<char>::New(file_name_length + 1);
604   SNPrintF(startup_name, "%s.startup", FLAG_testing_serialization_file);
605
606   v8::Isolate* v8_isolate = InitializeFromFile(startup_name.start());
607   CHECK(v8_isolate);
608   startup_name.Dispose();
609   {
610     v8::Isolate::Scope isolate_scope(v8_isolate);
611
612     const char* file_name = FLAG_testing_serialization_file;
613
614     int snapshot_size = 0;
615     byte* snapshot = ReadBytes(file_name, &snapshot_size);
616
617     Isolate* isolate = reinterpret_cast<Isolate*>(v8_isolate);
618     HandleScope handle_scope(isolate);
619     Handle<Object> root;
620     Handle<FixedArray> outdated_contexts;
621     Handle<JSGlobalProxy> global_proxy =
622         isolate->factory()->NewUninitializedJSGlobalProxy();
623     {
624       SnapshotData snapshot_data(Vector<const byte>(snapshot, snapshot_size));
625       Deserializer deserializer(&snapshot_data);
626       root =
627           deserializer.DeserializePartial(isolate, global_proxy,
628                                           &outdated_contexts).ToHandleChecked();
629       CHECK_EQ(2, outdated_contexts->length());
630       CHECK(root->IsContext());
631       Handle<Context> context = Handle<Context>::cast(root);
632       CHECK(context->global_proxy() == *global_proxy);
633       Handle<String> o = isolate->factory()->NewStringFromAsciiChecked("o");
634       Handle<JSObject> global_object(context->global_object(), isolate);
635       Handle<Object> property = JSObject::GetDataProperty(global_object, o);
636       CHECK(property.is_identical_to(global_proxy));
637
638       v8::Handle<v8::Context> v8_context = v8::Utils::ToLocal(context);
639       v8::Context::Scope context_scope(v8_context);
640       double r = CompileRun("r")->ToNumber(v8_isolate)->Value();
641       CHECK(r >= 1 && r <= 2);
642       int f = CompileRun("f()")->ToNumber(v8_isolate)->Int32Value();
643       CHECK_EQ(5, f);
644       f = CompileRun("e('f()')")->ToNumber(v8_isolate)->Int32Value();
645       CHECK_EQ(5, f);
646       v8::Handle<v8::String> s = CompileRun("s")->ToString(v8_isolate);
647       CHECK(s->Equals(v8_str("12345")));
648       int a = CompileRun("a.length")->ToNumber(v8_isolate)->Int32Value();
649       CHECK_EQ(100001, a);
650       int b = CompileRun("b.length")->ToNumber(v8_isolate)->Int32Value();
651       CHECK_EQ(100002, b);
652     }
653     DeleteArray(snapshot);
654   }
655   v8_isolate->Dispose();
656 }
657
658
659 TEST(PerIsolateSnapshotBlobs) {
660   DisableTurbofan();
661   const char* source1 = "function f() { return 42; }";
662   const char* source2 =
663       "function f() { return g() * 2; }"
664       "function g() { return 43; }"
665       "/./.test('a')";
666
667   v8::StartupData data1 = v8::V8::CreateSnapshotDataBlob(source1);
668   v8::StartupData data2 = v8::V8::CreateSnapshotDataBlob(source2);
669
670   v8::Isolate::CreateParams params1;
671   params1.snapshot_blob = &data1;
672   v8::Isolate* isolate1 = v8::Isolate::New(params1);
673   {
674     v8::Isolate::Scope i_scope(isolate1);
675     v8::HandleScope h_scope(isolate1);
676     v8::Local<v8::Context> context = v8::Context::New(isolate1);
677     delete[] data1.data;  // We can dispose of the snapshot blob now.
678     v8::Context::Scope c_scope(context);
679     CHECK_EQ(42, CompileRun("f()")->ToInt32(isolate1)->Int32Value());
680     CHECK(CompileRun("this.g")->IsUndefined());
681   }
682   isolate1->Dispose();
683
684   v8::Isolate::CreateParams params2;
685   params2.snapshot_blob = &data2;
686   v8::Isolate* isolate2 = v8::Isolate::New(params2);
687   {
688     v8::Isolate::Scope i_scope(isolate2);
689     v8::HandleScope h_scope(isolate2);
690     v8::Local<v8::Context> context = v8::Context::New(isolate2);
691     delete[] data2.data;  // We can dispose of the snapshot blob now.
692     v8::Context::Scope c_scope(context);
693     CHECK_EQ(86, CompileRun("f()")->ToInt32(isolate2)->Int32Value());
694     CHECK_EQ(43, CompileRun("g()")->ToInt32(isolate2)->Int32Value());
695   }
696   isolate2->Dispose();
697 }
698
699
700 TEST(PerIsolateSnapshotBlobsWithLocker) {
701   DisableTurbofan();
702   v8::Isolate* isolate0 = v8::Isolate::New();
703   {
704     v8::Locker locker(isolate0);
705     v8::Isolate::Scope i_scope(isolate0);
706     v8::HandleScope h_scope(isolate0);
707     v8::Local<v8::Context> context = v8::Context::New(isolate0);
708     v8::Context::Scope c_scope(context);
709     CHECK_EQ(1, CompileRun("Math.cos(0)")->ToInt32(isolate0)->Int32Value());
710   }
711   isolate0->Dispose();
712
713   const char* source1 = "function f() { return 42; }";
714
715   v8::StartupData data1 = v8::V8::CreateSnapshotDataBlob(source1);
716
717   v8::Isolate::CreateParams params1;
718   params1.snapshot_blob = &data1;
719   v8::Isolate* isolate1 = v8::Isolate::New(params1);
720   {
721     v8::Locker locker(isolate1);
722     v8::Isolate::Scope i_scope(isolate1);
723     v8::HandleScope h_scope(isolate1);
724     v8::Local<v8::Context> context = v8::Context::New(isolate1);
725     delete[] data1.data;  // We can dispose of the snapshot blob now.
726     v8::Context::Scope c_scope(context);
727     CHECK_EQ(42, CompileRun("f()")->ToInt32(isolate1)->Int32Value());
728   }
729   isolate1->Dispose();
730 }
731
732
733 TEST(TestThatAlwaysSucceeds) {
734 }
735
736
737 TEST(TestThatAlwaysFails) {
738   bool ArtificialFailure = false;
739   CHECK(ArtificialFailure);
740 }
741
742
743 DEPENDENT_TEST(DependentTestThatAlwaysFails, TestThatAlwaysSucceeds) {
744   bool ArtificialFailure2 = false;
745   CHECK(ArtificialFailure2);
746 }
747
748
749 int CountBuiltins() {
750   // Check that we have not deserialized any additional builtin.
751   HeapIterator iterator(CcTest::heap());
752   DisallowHeapAllocation no_allocation;
753   int counter = 0;
754   for (HeapObject* obj = iterator.next(); obj != NULL; obj = iterator.next()) {
755     if (obj->IsCode() && Code::cast(obj)->kind() == Code::BUILTIN) counter++;
756   }
757   return counter;
758 }
759
760
761 static Handle<SharedFunctionInfo> CompileScript(
762     Isolate* isolate, Handle<String> source, Handle<String> name,
763     ScriptData** cached_data, v8::ScriptCompiler::CompileOptions options) {
764   return Compiler::CompileScript(
765       source, name, 0, 0, false, false, Handle<Object>(),
766       Handle<Context>(isolate->native_context()), NULL, cached_data, options,
767       NOT_NATIVES_CODE, false);
768 }
769
770
771 TEST(SerializeToplevelOnePlusOne) {
772   FLAG_serialize_toplevel = true;
773   LocalContext context;
774   Isolate* isolate = CcTest::i_isolate();
775   isolate->compilation_cache()->Disable();  // Disable same-isolate code cache.
776
777   v8::HandleScope scope(CcTest::isolate());
778
779   const char* source = "1 + 1";
780
781   Handle<String> orig_source = isolate->factory()
782                                    ->NewStringFromUtf8(CStrVector(source))
783                                    .ToHandleChecked();
784   Handle<String> copy_source = isolate->factory()
785                                    ->NewStringFromUtf8(CStrVector(source))
786                                    .ToHandleChecked();
787   CHECK(!orig_source.is_identical_to(copy_source));
788   CHECK(orig_source->Equals(*copy_source));
789
790   ScriptData* cache = NULL;
791
792   Handle<SharedFunctionInfo> orig =
793       CompileScript(isolate, orig_source, Handle<String>(), &cache,
794                     v8::ScriptCompiler::kProduceCodeCache);
795
796   int builtins_count = CountBuiltins();
797
798   Handle<SharedFunctionInfo> copy;
799   {
800     DisallowCompilation no_compile_expected(isolate);
801     copy = CompileScript(isolate, copy_source, Handle<String>(), &cache,
802                          v8::ScriptCompiler::kConsumeCodeCache);
803   }
804
805   CHECK_NE(*orig, *copy);
806   CHECK(Script::cast(copy->script())->source() == *copy_source);
807
808   Handle<JSFunction> copy_fun =
809       isolate->factory()->NewFunctionFromSharedFunctionInfo(
810           copy, isolate->native_context());
811   Handle<JSObject> global(isolate->context()->global_object());
812   Handle<Object> copy_result =
813       Execution::Call(isolate, copy_fun, global, 0, NULL).ToHandleChecked();
814   CHECK_EQ(2, Handle<Smi>::cast(copy_result)->value());
815
816   CHECK_EQ(builtins_count, CountBuiltins());
817
818   delete cache;
819 }
820
821
822 TEST(CodeCachePromotedToCompilationCache) {
823   FLAG_serialize_toplevel = true;
824   LocalContext context;
825   Isolate* isolate = CcTest::i_isolate();
826
827   v8::HandleScope scope(CcTest::isolate());
828
829   const char* source = "1 + 1";
830
831   Handle<String> src = isolate->factory()
832                            ->NewStringFromUtf8(CStrVector(source))
833                            .ToHandleChecked();
834   ScriptData* cache = NULL;
835
836   CompileScript(isolate, src, src, &cache,
837                 v8::ScriptCompiler::kProduceCodeCache);
838
839   DisallowCompilation no_compile_expected(isolate);
840   Handle<SharedFunctionInfo> copy = CompileScript(
841       isolate, src, src, &cache, v8::ScriptCompiler::kConsumeCodeCache);
842
843   CHECK(isolate->compilation_cache()
844             ->LookupScript(src, src, 0, 0, false, false,
845                            isolate->native_context(), SLOPPY)
846             .ToHandleChecked()
847             .is_identical_to(copy));
848
849   delete cache;
850 }
851
852
853 TEST(SerializeToplevelInternalizedString) {
854   FLAG_serialize_toplevel = true;
855   LocalContext context;
856   Isolate* isolate = CcTest::i_isolate();
857   isolate->compilation_cache()->Disable();  // Disable same-isolate code cache.
858
859   v8::HandleScope scope(CcTest::isolate());
860
861   const char* source = "'string1'";
862
863   Handle<String> orig_source = isolate->factory()
864                                    ->NewStringFromUtf8(CStrVector(source))
865                                    .ToHandleChecked();
866   Handle<String> copy_source = isolate->factory()
867                                    ->NewStringFromUtf8(CStrVector(source))
868                                    .ToHandleChecked();
869   CHECK(!orig_source.is_identical_to(copy_source));
870   CHECK(orig_source->Equals(*copy_source));
871
872   Handle<JSObject> global(isolate->context()->global_object());
873   ScriptData* cache = NULL;
874
875   Handle<SharedFunctionInfo> orig =
876       CompileScript(isolate, orig_source, Handle<String>(), &cache,
877                     v8::ScriptCompiler::kProduceCodeCache);
878   Handle<JSFunction> orig_fun =
879       isolate->factory()->NewFunctionFromSharedFunctionInfo(
880           orig, isolate->native_context());
881   Handle<Object> orig_result =
882       Execution::Call(isolate, orig_fun, global, 0, NULL).ToHandleChecked();
883   CHECK(orig_result->IsInternalizedString());
884
885   int builtins_count = CountBuiltins();
886
887   Handle<SharedFunctionInfo> copy;
888   {
889     DisallowCompilation no_compile_expected(isolate);
890     copy = CompileScript(isolate, copy_source, Handle<String>(), &cache,
891                          v8::ScriptCompiler::kConsumeCodeCache);
892   }
893   CHECK_NE(*orig, *copy);
894   CHECK(Script::cast(copy->script())->source() == *copy_source);
895
896   Handle<JSFunction> copy_fun =
897       isolate->factory()->NewFunctionFromSharedFunctionInfo(
898           copy, isolate->native_context());
899   CHECK_NE(*orig_fun, *copy_fun);
900   Handle<Object> copy_result =
901       Execution::Call(isolate, copy_fun, global, 0, NULL).ToHandleChecked();
902   CHECK(orig_result.is_identical_to(copy_result));
903   Handle<String> expected =
904       isolate->factory()->NewStringFromAsciiChecked("string1");
905
906   CHECK(Handle<String>::cast(copy_result)->Equals(*expected));
907   CHECK_EQ(builtins_count, CountBuiltins());
908
909   delete cache;
910 }
911
912
913 TEST(SerializeToplevelLargeCodeObject) {
914   FLAG_serialize_toplevel = true;
915   LocalContext context;
916   Isolate* isolate = CcTest::i_isolate();
917   isolate->compilation_cache()->Disable();  // Disable same-isolate code cache.
918
919   v8::HandleScope scope(CcTest::isolate());
920
921   Vector<const uint8_t> source =
922       ConstructSource(STATIC_CHAR_VECTOR("var j=1; try { if (j) throw 1;"),
923                       STATIC_CHAR_VECTOR("for(var i=0;i<1;i++)j++;"),
924                       STATIC_CHAR_VECTOR("} catch (e) { j=7; } j"), 10000);
925   Handle<String> source_str =
926       isolate->factory()->NewStringFromOneByte(source).ToHandleChecked();
927
928   Handle<JSObject> global(isolate->context()->global_object());
929   ScriptData* cache = NULL;
930
931   Handle<SharedFunctionInfo> orig =
932       CompileScript(isolate, source_str, Handle<String>(), &cache,
933                     v8::ScriptCompiler::kProduceCodeCache);
934
935   CHECK(isolate->heap()->InSpace(orig->code(), LO_SPACE));
936
937   Handle<SharedFunctionInfo> copy;
938   {
939     DisallowCompilation no_compile_expected(isolate);
940     copy = CompileScript(isolate, source_str, Handle<String>(), &cache,
941                          v8::ScriptCompiler::kConsumeCodeCache);
942   }
943   CHECK_NE(*orig, *copy);
944
945   Handle<JSFunction> copy_fun =
946       isolate->factory()->NewFunctionFromSharedFunctionInfo(
947           copy, isolate->native_context());
948
949   Handle<Object> copy_result =
950       Execution::Call(isolate, copy_fun, global, 0, NULL).ToHandleChecked();
951
952   int result_int;
953   CHECK(copy_result->ToInt32(&result_int));
954   CHECK_EQ(7, result_int);
955
956   delete cache;
957   source.Dispose();
958 }
959
960
961 TEST(SerializeToplevelLargeStrings) {
962   FLAG_serialize_toplevel = true;
963   LocalContext context;
964   Isolate* isolate = CcTest::i_isolate();
965   Factory* f = isolate->factory();
966   isolate->compilation_cache()->Disable();  // Disable same-isolate code cache.
967
968   v8::HandleScope scope(CcTest::isolate());
969
970   Vector<const uint8_t> source_s = ConstructSource(
971       STATIC_CHAR_VECTOR("var s = \""), STATIC_CHAR_VECTOR("abcdef"),
972       STATIC_CHAR_VECTOR("\";"), 1000000);
973   Vector<const uint8_t> source_t = ConstructSource(
974       STATIC_CHAR_VECTOR("var t = \""), STATIC_CHAR_VECTOR("uvwxyz"),
975       STATIC_CHAR_VECTOR("\"; s + t"), 999999);
976   Handle<String> source_str =
977       f->NewConsString(f->NewStringFromOneByte(source_s).ToHandleChecked(),
978                        f->NewStringFromOneByte(source_t).ToHandleChecked())
979           .ToHandleChecked();
980
981   Handle<JSObject> global(isolate->context()->global_object());
982   ScriptData* cache = NULL;
983
984   Handle<SharedFunctionInfo> orig =
985       CompileScript(isolate, source_str, Handle<String>(), &cache,
986                     v8::ScriptCompiler::kProduceCodeCache);
987
988   Handle<SharedFunctionInfo> copy;
989   {
990     DisallowCompilation no_compile_expected(isolate);
991     copy = CompileScript(isolate, source_str, Handle<String>(), &cache,
992                          v8::ScriptCompiler::kConsumeCodeCache);
993   }
994   CHECK_NE(*orig, *copy);
995
996   Handle<JSFunction> copy_fun =
997       isolate->factory()->NewFunctionFromSharedFunctionInfo(
998           copy, isolate->native_context());
999
1000   Handle<Object> copy_result =
1001       Execution::Call(isolate, copy_fun, global, 0, NULL).ToHandleChecked();
1002
1003   CHECK_EQ(6 * 1999999, Handle<String>::cast(copy_result)->length());
1004   Handle<Object> property = JSObject::GetDataProperty(
1005       isolate->global_object(), f->NewStringFromAsciiChecked("s"));
1006   CHECK(isolate->heap()->InSpace(HeapObject::cast(*property), LO_SPACE));
1007   property = JSObject::GetDataProperty(isolate->global_object(),
1008                                        f->NewStringFromAsciiChecked("t"));
1009   CHECK(isolate->heap()->InSpace(HeapObject::cast(*property), LO_SPACE));
1010   // Make sure we do not serialize too much, e.g. include the source string.
1011   CHECK_LT(cache->length(), 13000000);
1012
1013   delete cache;
1014   source_s.Dispose();
1015   source_t.Dispose();
1016 }
1017
1018
1019 TEST(SerializeToplevelThreeBigStrings) {
1020   FLAG_serialize_toplevel = true;
1021   LocalContext context;
1022   Isolate* isolate = CcTest::i_isolate();
1023   Factory* f = isolate->factory();
1024   isolate->compilation_cache()->Disable();  // Disable same-isolate code cache.
1025
1026   v8::HandleScope scope(CcTest::isolate());
1027
1028   Vector<const uint8_t> source_a =
1029       ConstructSource(STATIC_CHAR_VECTOR("var a = \""), STATIC_CHAR_VECTOR("a"),
1030                       STATIC_CHAR_VECTOR("\";"), 700000);
1031   Handle<String> source_a_str =
1032       f->NewStringFromOneByte(source_a).ToHandleChecked();
1033
1034   Vector<const uint8_t> source_b =
1035       ConstructSource(STATIC_CHAR_VECTOR("var b = \""), STATIC_CHAR_VECTOR("b"),
1036                       STATIC_CHAR_VECTOR("\";"), 600000);
1037   Handle<String> source_b_str =
1038       f->NewStringFromOneByte(source_b).ToHandleChecked();
1039
1040   Vector<const uint8_t> source_c =
1041       ConstructSource(STATIC_CHAR_VECTOR("var c = \""), STATIC_CHAR_VECTOR("c"),
1042                       STATIC_CHAR_VECTOR("\";"), 500000);
1043   Handle<String> source_c_str =
1044       f->NewStringFromOneByte(source_c).ToHandleChecked();
1045
1046   Handle<String> source_str =
1047       f->NewConsString(
1048              f->NewConsString(source_a_str, source_b_str).ToHandleChecked(),
1049              source_c_str).ToHandleChecked();
1050
1051   Handle<JSObject> global(isolate->context()->global_object());
1052   ScriptData* cache = NULL;
1053
1054   Handle<SharedFunctionInfo> orig =
1055       CompileScript(isolate, source_str, Handle<String>(), &cache,
1056                     v8::ScriptCompiler::kProduceCodeCache);
1057
1058   Handle<SharedFunctionInfo> copy;
1059   {
1060     DisallowCompilation no_compile_expected(isolate);
1061     copy = CompileScript(isolate, source_str, Handle<String>(), &cache,
1062                          v8::ScriptCompiler::kConsumeCodeCache);
1063   }
1064   CHECK_NE(*orig, *copy);
1065
1066   Handle<JSFunction> copy_fun =
1067       isolate->factory()->NewFunctionFromSharedFunctionInfo(
1068           copy, isolate->native_context());
1069
1070   USE(Execution::Call(isolate, copy_fun, global, 0, NULL));
1071
1072   CHECK_EQ(600000 + 700000, CompileRun("(a + b).length")->Int32Value());
1073   CHECK_EQ(500000 + 600000, CompileRun("(b + c).length")->Int32Value());
1074   Heap* heap = isolate->heap();
1075   CHECK(heap->InSpace(
1076       *v8::Utils::OpenHandle(*CompileRun("a")->ToString(CcTest::isolate())),
1077       OLD_DATA_SPACE));
1078   CHECK(heap->InSpace(
1079       *v8::Utils::OpenHandle(*CompileRun("b")->ToString(CcTest::isolate())),
1080       OLD_DATA_SPACE));
1081   CHECK(heap->InSpace(
1082       *v8::Utils::OpenHandle(*CompileRun("c")->ToString(CcTest::isolate())),
1083       OLD_DATA_SPACE));
1084
1085   delete cache;
1086   source_a.Dispose();
1087   source_b.Dispose();
1088   source_c.Dispose();
1089 }
1090
1091
1092 class SerializerOneByteResource
1093     : public v8::String::ExternalOneByteStringResource {
1094  public:
1095   SerializerOneByteResource(const char* data, size_t length)
1096       : data_(data), length_(length) {}
1097   virtual const char* data() const { return data_; }
1098   virtual size_t length() const { return length_; }
1099
1100  private:
1101   const char* data_;
1102   size_t length_;
1103 };
1104
1105
1106 class SerializerTwoByteResource : public v8::String::ExternalStringResource {
1107  public:
1108   SerializerTwoByteResource(const char* data, size_t length)
1109       : data_(AsciiToTwoByteString(data)), length_(length) {}
1110   ~SerializerTwoByteResource() { DeleteArray<const uint16_t>(data_); }
1111
1112   virtual const uint16_t* data() const { return data_; }
1113   virtual size_t length() const { return length_; }
1114
1115  private:
1116   const uint16_t* data_;
1117   size_t length_;
1118 };
1119
1120
1121 TEST(SerializeToplevelExternalString) {
1122   FLAG_serialize_toplevel = true;
1123   LocalContext context;
1124   Isolate* isolate = CcTest::i_isolate();
1125   isolate->compilation_cache()->Disable();  // Disable same-isolate code cache.
1126
1127   v8::HandleScope scope(CcTest::isolate());
1128
1129   // Obtain external internalized one-byte string.
1130   SerializerOneByteResource one_byte_resource("one_byte", 8);
1131   Handle<String> one_byte_string =
1132       isolate->factory()->NewStringFromAsciiChecked("one_byte");
1133   one_byte_string = isolate->factory()->InternalizeString(one_byte_string);
1134   one_byte_string->MakeExternal(&one_byte_resource);
1135   CHECK(one_byte_string->IsExternalOneByteString());
1136   CHECK(one_byte_string->IsInternalizedString());
1137
1138   // Obtain external internalized two-byte string.
1139   SerializerTwoByteResource two_byte_resource("two_byte", 8);
1140   Handle<String> two_byte_string =
1141       isolate->factory()->NewStringFromAsciiChecked("two_byte");
1142   two_byte_string = isolate->factory()->InternalizeString(two_byte_string);
1143   two_byte_string->MakeExternal(&two_byte_resource);
1144   CHECK(two_byte_string->IsExternalTwoByteString());
1145   CHECK(two_byte_string->IsInternalizedString());
1146
1147   const char* source =
1148       "var o = {}               \n"
1149       "o.one_byte = 7;          \n"
1150       "o.two_byte = 8;          \n"
1151       "o.one_byte + o.two_byte; \n";
1152   Handle<String> source_string = isolate->factory()
1153                                      ->NewStringFromUtf8(CStrVector(source))
1154                                      .ToHandleChecked();
1155
1156   Handle<JSObject> global(isolate->context()->global_object());
1157   ScriptData* cache = NULL;
1158
1159   Handle<SharedFunctionInfo> orig =
1160       CompileScript(isolate, source_string, Handle<String>(), &cache,
1161                     v8::ScriptCompiler::kProduceCodeCache);
1162
1163   Handle<SharedFunctionInfo> copy;
1164   {
1165     DisallowCompilation no_compile_expected(isolate);
1166     copy = CompileScript(isolate, source_string, Handle<String>(), &cache,
1167                          v8::ScriptCompiler::kConsumeCodeCache);
1168   }
1169   CHECK_NE(*orig, *copy);
1170
1171   Handle<JSFunction> copy_fun =
1172       isolate->factory()->NewFunctionFromSharedFunctionInfo(
1173           copy, isolate->native_context());
1174
1175   Handle<Object> copy_result =
1176       Execution::Call(isolate, copy_fun, global, 0, NULL).ToHandleChecked();
1177
1178   CHECK_EQ(15.0f, copy_result->Number());
1179
1180   delete cache;
1181 }
1182
1183
1184 TEST(SerializeToplevelLargeExternalString) {
1185   FLAG_serialize_toplevel = true;
1186   LocalContext context;
1187   Isolate* isolate = CcTest::i_isolate();
1188   isolate->compilation_cache()->Disable();  // Disable same-isolate code cache.
1189
1190   Factory* f = isolate->factory();
1191
1192   v8::HandleScope scope(CcTest::isolate());
1193
1194   // Create a huge external internalized string to use as variable name.
1195   Vector<const uint8_t> string =
1196       ConstructSource(STATIC_CHAR_VECTOR(""), STATIC_CHAR_VECTOR("abcdef"),
1197                       STATIC_CHAR_VECTOR(""), 999999);
1198   Handle<String> name = f->NewStringFromOneByte(string).ToHandleChecked();
1199   SerializerOneByteResource one_byte_resource(
1200       reinterpret_cast<const char*>(string.start()), string.length());
1201   name = f->InternalizeString(name);
1202   name->MakeExternal(&one_byte_resource);
1203   CHECK(name->IsExternalOneByteString());
1204   CHECK(name->IsInternalizedString());
1205   CHECK(isolate->heap()->InSpace(*name, LO_SPACE));
1206
1207   // Create the source, which is "var <literal> = 42; <literal>".
1208   Handle<String> source_str =
1209       f->NewConsString(
1210              f->NewConsString(f->NewStringFromAsciiChecked("var "), name)
1211                  .ToHandleChecked(),
1212              f->NewConsString(f->NewStringFromAsciiChecked(" = 42; "), name)
1213                  .ToHandleChecked()).ToHandleChecked();
1214
1215   Handle<JSObject> global(isolate->context()->global_object());
1216   ScriptData* cache = NULL;
1217
1218   Handle<SharedFunctionInfo> orig =
1219       CompileScript(isolate, source_str, Handle<String>(), &cache,
1220                     v8::ScriptCompiler::kProduceCodeCache);
1221
1222   Handle<SharedFunctionInfo> copy;
1223   {
1224     DisallowCompilation no_compile_expected(isolate);
1225     copy = CompileScript(isolate, source_str, Handle<String>(), &cache,
1226                          v8::ScriptCompiler::kConsumeCodeCache);
1227   }
1228   CHECK_NE(*orig, *copy);
1229
1230   Handle<JSFunction> copy_fun =
1231       f->NewFunctionFromSharedFunctionInfo(copy, isolate->native_context());
1232
1233   Handle<Object> copy_result =
1234       Execution::Call(isolate, copy_fun, global, 0, NULL).ToHandleChecked();
1235
1236   CHECK_EQ(42.0f, copy_result->Number());
1237
1238   delete cache;
1239   string.Dispose();
1240 }
1241
1242
1243 TEST(SerializeToplevelExternalScriptName) {
1244   FLAG_serialize_toplevel = true;
1245   LocalContext context;
1246   Isolate* isolate = CcTest::i_isolate();
1247   isolate->compilation_cache()->Disable();  // Disable same-isolate code cache.
1248
1249   Factory* f = isolate->factory();
1250
1251   v8::HandleScope scope(CcTest::isolate());
1252
1253   const char* source =
1254       "var a = [1, 2, 3, 4];"
1255       "a.reduce(function(x, y) { return x + y }, 0)";
1256
1257   Handle<String> source_string =
1258       f->NewStringFromUtf8(CStrVector(source)).ToHandleChecked();
1259
1260   const SerializerOneByteResource one_byte_resource("one_byte", 8);
1261   Handle<String> name =
1262       f->NewExternalStringFromOneByte(&one_byte_resource).ToHandleChecked();
1263   CHECK(name->IsExternalOneByteString());
1264   CHECK(!name->IsInternalizedString());
1265
1266   Handle<JSObject> global(isolate->context()->global_object());
1267   ScriptData* cache = NULL;
1268
1269   Handle<SharedFunctionInfo> orig =
1270       CompileScript(isolate, source_string, name, &cache,
1271                     v8::ScriptCompiler::kProduceCodeCache);
1272
1273   Handle<SharedFunctionInfo> copy;
1274   {
1275     DisallowCompilation no_compile_expected(isolate);
1276     copy = CompileScript(isolate, source_string, name, &cache,
1277                          v8::ScriptCompiler::kConsumeCodeCache);
1278   }
1279   CHECK_NE(*orig, *copy);
1280
1281   Handle<JSFunction> copy_fun =
1282       f->NewFunctionFromSharedFunctionInfo(copy, isolate->native_context());
1283
1284   Handle<Object> copy_result =
1285       Execution::Call(isolate, copy_fun, global, 0, NULL).ToHandleChecked();
1286
1287   CHECK_EQ(10.0f, copy_result->Number());
1288
1289   delete cache;
1290 }
1291
1292
1293 static bool toplevel_test_code_event_found = false;
1294
1295
1296 static void SerializerCodeEventListener(const v8::JitCodeEvent* event) {
1297   if (event->type == v8::JitCodeEvent::CODE_ADDED &&
1298       memcmp(event->name.str, "Script:~test", 12) == 0) {
1299     toplevel_test_code_event_found = true;
1300   }
1301 }
1302
1303
1304 v8::ScriptCompiler::CachedData* ProduceCache(const char* source) {
1305   v8::ScriptCompiler::CachedData* cache;
1306   v8::Isolate* isolate1 = v8::Isolate::New();
1307   {
1308     v8::Isolate::Scope iscope(isolate1);
1309     v8::HandleScope scope(isolate1);
1310     v8::Local<v8::Context> context = v8::Context::New(isolate1);
1311     v8::Context::Scope context_scope(context);
1312
1313     v8::Local<v8::String> source_str = v8_str(source);
1314     v8::ScriptOrigin origin(v8_str("test"));
1315     v8::ScriptCompiler::Source source(source_str, origin);
1316     v8::Local<v8::UnboundScript> script = v8::ScriptCompiler::CompileUnbound(
1317         isolate1, &source, v8::ScriptCompiler::kProduceCodeCache);
1318     const v8::ScriptCompiler::CachedData* data = source.GetCachedData();
1319     CHECK(data);
1320     // Persist cached data.
1321     uint8_t* buffer = NewArray<uint8_t>(data->length);
1322     MemCopy(buffer, data->data, data->length);
1323     cache = new v8::ScriptCompiler::CachedData(
1324         buffer, data->length, v8::ScriptCompiler::CachedData::BufferOwned);
1325
1326     v8::Local<v8::Value> result = script->BindToCurrentContext()->Run();
1327     CHECK(result->ToString(isolate1)->Equals(v8_str("abcdef")));
1328   }
1329   isolate1->Dispose();
1330   return cache;
1331 }
1332
1333
1334 TEST(SerializeToplevelIsolates) {
1335   FLAG_serialize_toplevel = true;
1336
1337   const char* source = "function f() { return 'abc'; }; f() + 'def'";
1338   v8::ScriptCompiler::CachedData* cache = ProduceCache(source);
1339
1340   v8::Isolate* isolate2 = v8::Isolate::New();
1341   isolate2->SetJitCodeEventHandler(v8::kJitCodeEventDefault,
1342                                    SerializerCodeEventListener);
1343   toplevel_test_code_event_found = false;
1344   {
1345     v8::Isolate::Scope iscope(isolate2);
1346     v8::HandleScope scope(isolate2);
1347     v8::Local<v8::Context> context = v8::Context::New(isolate2);
1348     v8::Context::Scope context_scope(context);
1349
1350     v8::Local<v8::String> source_str = v8_str(source);
1351     v8::ScriptOrigin origin(v8_str("test"));
1352     v8::ScriptCompiler::Source source(source_str, origin, cache);
1353     v8::Local<v8::UnboundScript> script;
1354     {
1355       DisallowCompilation no_compile(reinterpret_cast<Isolate*>(isolate2));
1356       script = v8::ScriptCompiler::CompileUnbound(
1357           isolate2, &source, v8::ScriptCompiler::kConsumeCodeCache);
1358     }
1359     CHECK(!cache->rejected);
1360     v8::Local<v8::Value> result = script->BindToCurrentContext()->Run();
1361     CHECK(result->ToString(isolate2)->Equals(v8_str("abcdef")));
1362   }
1363   DCHECK(toplevel_test_code_event_found);
1364   isolate2->Dispose();
1365 }
1366
1367
1368 TEST(SerializeToplevelFlagChange) {
1369   FLAG_serialize_toplevel = true;
1370
1371   const char* source = "function f() { return 'abc'; }; f() + 'def'";
1372   v8::ScriptCompiler::CachedData* cache = ProduceCache(source);
1373
1374   v8::Isolate* isolate2 = v8::Isolate::New();
1375
1376   FLAG_allow_natives_syntax = true;  // Flag change should trigger cache reject.
1377   FlagList::EnforceFlagImplications();
1378   {
1379     v8::Isolate::Scope iscope(isolate2);
1380     v8::HandleScope scope(isolate2);
1381     v8::Local<v8::Context> context = v8::Context::New(isolate2);
1382     v8::Context::Scope context_scope(context);
1383
1384     v8::Local<v8::String> source_str = v8_str(source);
1385     v8::ScriptOrigin origin(v8_str("test"));
1386     v8::ScriptCompiler::Source source(source_str, origin, cache);
1387     v8::ScriptCompiler::CompileUnbound(isolate2, &source,
1388                                        v8::ScriptCompiler::kConsumeCodeCache);
1389     CHECK(cache->rejected);
1390   }
1391   isolate2->Dispose();
1392 }
1393
1394
1395 TEST(SerializeToplevelBitFlip) {
1396   FLAG_serialize_toplevel = true;
1397
1398   const char* source = "function f() { return 'abc'; }; f() + 'def'";
1399   v8::ScriptCompiler::CachedData* cache = ProduceCache(source);
1400
1401   // Random bit flip.
1402   const_cast<uint8_t*>(cache->data)[337] ^= 0x40;
1403
1404   v8::Isolate* isolate2 = v8::Isolate::New();
1405   {
1406     v8::Isolate::Scope iscope(isolate2);
1407     v8::HandleScope scope(isolate2);
1408     v8::Local<v8::Context> context = v8::Context::New(isolate2);
1409     v8::Context::Scope context_scope(context);
1410
1411     v8::Local<v8::String> source_str = v8_str(source);
1412     v8::ScriptOrigin origin(v8_str("test"));
1413     v8::ScriptCompiler::Source source(source_str, origin, cache);
1414     v8::ScriptCompiler::CompileUnbound(isolate2, &source,
1415                                        v8::ScriptCompiler::kConsumeCodeCache);
1416     CHECK(cache->rejected);
1417   }
1418   isolate2->Dispose();
1419 }
1420
1421
1422 TEST(SerializeWithHarmonyScoping) {
1423   FLAG_serialize_toplevel = true;
1424
1425   const char* source1 = "'use strict'; let x = 'X'";
1426   const char* source2 = "'use strict'; let y = 'Y'";
1427   const char* source3 = "'use strict'; x + y";
1428
1429   v8::ScriptCompiler::CachedData* cache;
1430
1431   v8::Isolate* isolate1 = v8::Isolate::New();
1432   {
1433     v8::Isolate::Scope iscope(isolate1);
1434     v8::HandleScope scope(isolate1);
1435     v8::Local<v8::Context> context = v8::Context::New(isolate1);
1436     v8::Context::Scope context_scope(context);
1437
1438     CompileRun(source1);
1439     CompileRun(source2);
1440
1441     v8::Local<v8::String> source_str = v8_str(source3);
1442     v8::ScriptOrigin origin(v8_str("test"));
1443     v8::ScriptCompiler::Source source(source_str, origin);
1444     v8::Local<v8::UnboundScript> script = v8::ScriptCompiler::CompileUnbound(
1445         isolate1, &source, v8::ScriptCompiler::kProduceCodeCache);
1446     const v8::ScriptCompiler::CachedData* data = source.GetCachedData();
1447     CHECK(data);
1448     // Persist cached data.
1449     uint8_t* buffer = NewArray<uint8_t>(data->length);
1450     MemCopy(buffer, data->data, data->length);
1451     cache = new v8::ScriptCompiler::CachedData(
1452         buffer, data->length, v8::ScriptCompiler::CachedData::BufferOwned);
1453
1454     v8::Local<v8::Value> result = script->BindToCurrentContext()->Run();
1455     CHECK(result->ToString(isolate1)->Equals(v8_str("XY")));
1456   }
1457   isolate1->Dispose();
1458
1459   v8::Isolate* isolate2 = v8::Isolate::New();
1460   {
1461     v8::Isolate::Scope iscope(isolate2);
1462     v8::HandleScope scope(isolate2);
1463     v8::Local<v8::Context> context = v8::Context::New(isolate2);
1464     v8::Context::Scope context_scope(context);
1465
1466     // Reverse order of prior running scripts.
1467     CompileRun(source2);
1468     CompileRun(source1);
1469
1470     v8::Local<v8::String> source_str = v8_str(source3);
1471     v8::ScriptOrigin origin(v8_str("test"));
1472     v8::ScriptCompiler::Source source(source_str, origin, cache);
1473     v8::Local<v8::UnboundScript> script;
1474     {
1475       DisallowCompilation no_compile(reinterpret_cast<Isolate*>(isolate2));
1476       script = v8::ScriptCompiler::CompileUnbound(
1477           isolate2, &source, v8::ScriptCompiler::kConsumeCodeCache);
1478     }
1479     v8::Local<v8::Value> result = script->BindToCurrentContext()->Run();
1480     CHECK(result->ToString(isolate2)->Equals(v8_str("XY")));
1481   }
1482   isolate2->Dispose();
1483 }
1484
1485
1486 TEST(SerializeInternalReference) {
1487 #ifdef V8_TARGET_ARCH_ARM64
1488   return;
1489 #endif  // V8_TARGET_ARCH_ARM64
1490   // Disable experimental natives that are loaded after deserialization.
1491   FLAG_turbo_deoptimization = false;
1492   FLAG_context_specialization = false;
1493   FLAG_always_opt = true;
1494   const char* flag = "--turbo-filter=foo";
1495   FlagList::SetFlagsFromString(flag, StrLength(flag));
1496
1497   const char* source =
1498       "var foo = (function(stdlib, foreign, heap) {"
1499       "  function foo(i) {"
1500       "    i = i|0;"
1501       "    var j = 0;"
1502       "    switch (i) {"
1503       "      case 0:"
1504       "      case 1: j = 1; break;"
1505       "      case 2:"
1506       "      case 3: j = 2; break;"
1507       "      case 4:"
1508       "      case 5: j = foo(3) + 1; break;"
1509       "      default: j = 0; break;"
1510       "    }"
1511       "    return j + 10;"
1512       "  }"
1513       "  return { foo: foo };"
1514       "})(this, {}, undefined).foo;"
1515       "foo(1);";
1516
1517   v8::StartupData data = v8::V8::CreateSnapshotDataBlob(source);
1518   CHECK(data.data);
1519
1520   v8::Isolate::CreateParams params;
1521   params.snapshot_blob = &data;
1522   v8::Isolate* isolate = v8::Isolate::New(params);
1523   {
1524     v8::Isolate::Scope i_scope(isolate);
1525     v8::HandleScope h_scope(isolate);
1526     v8::Local<v8::Context> context = v8::Context::New(isolate);
1527     delete[] data.data;  // We can dispose of the snapshot blob now.
1528     v8::Context::Scope c_scope(context);
1529     v8::Handle<v8::Function> foo =
1530         v8::Handle<v8::Function>::Cast(CompileRun("foo"));
1531
1532     // There are at least 6 internal references.
1533     int mask = RelocInfo::ModeMask(RelocInfo::INTERNAL_REFERENCE) |
1534                RelocInfo::ModeMask(RelocInfo::INTERNAL_REFERENCE_ENCODED);
1535     RelocIterator it(v8::Utils::OpenHandle(*foo)->code(), mask);
1536     for (int i = 0; i < 6; ++i) {
1537       CHECK(!it.done());
1538       it.next();
1539     }
1540
1541     CHECK(v8::Utils::OpenHandle(*foo)->code()->is_turbofanned());
1542     CHECK_EQ(11, CompileRun("foo(0)")->ToInt32(isolate)->Int32Value());
1543     CHECK_EQ(11, CompileRun("foo(1)")->ToInt32(isolate)->Int32Value());
1544     CHECK_EQ(12, CompileRun("foo(2)")->ToInt32(isolate)->Int32Value());
1545     CHECK_EQ(12, CompileRun("foo(3)")->ToInt32(isolate)->Int32Value());
1546     CHECK_EQ(23, CompileRun("foo(4)")->ToInt32(isolate)->Int32Value());
1547     CHECK_EQ(23, CompileRun("foo(5)")->ToInt32(isolate)->Int32Value());
1548     CHECK_EQ(10, CompileRun("foo(6)")->ToInt32(isolate)->Int32Value());
1549   }
1550   isolate->Dispose();
1551 }