deps: update v8 to 4.3.61.21
[platform/upstream/nodejs.git] / deps / v8 / test / cctest / test-mark-compact.cc
1 // Copyright 2012 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 <stdlib.h>
29
30 #ifdef __linux__
31 #include <errno.h>
32 #include <fcntl.h>
33 #include <sys/stat.h>
34 #include <sys/types.h>
35 #include <unistd.h>
36 #endif
37
38 #include <utility>
39
40 #include "src/v8.h"
41
42 #include "src/full-codegen.h"
43 #include "src/global-handles.h"
44 #include "test/cctest/cctest.h"
45
46 using namespace v8::internal;
47 using v8::Just;
48
49
50 TEST(MarkingDeque) {
51   CcTest::InitializeVM();
52   int mem_size = 20 * kPointerSize;
53   byte* mem = NewArray<byte>(20*kPointerSize);
54   Address low = reinterpret_cast<Address>(mem);
55   Address high = low + mem_size;
56   MarkingDeque s;
57   s.Initialize(low, high);
58
59   Address original_address = reinterpret_cast<Address>(&s);
60   Address current_address = original_address;
61   while (!s.IsFull()) {
62     s.PushBlack(HeapObject::FromAddress(current_address));
63     current_address += kPointerSize;
64   }
65
66   while (!s.IsEmpty()) {
67     Address value = s.Pop()->address();
68     current_address -= kPointerSize;
69     CHECK_EQ(current_address, value);
70   }
71
72   CHECK_EQ(original_address, current_address);
73   DeleteArray(mem);
74 }
75
76
77 TEST(Promotion) {
78   CcTest::InitializeVM();
79   TestHeap* heap = CcTest::test_heap();
80   heap->ConfigureHeap(1, 1, 1, 0);
81
82   v8::HandleScope sc(CcTest::isolate());
83
84   // Allocate a fixed array in the new space.
85   int array_length =
86       (Page::kMaxRegularHeapObjectSize - FixedArray::kHeaderSize) /
87       (4 * kPointerSize);
88   Object* obj = heap->AllocateFixedArray(array_length).ToObjectChecked();
89   Handle<FixedArray> array(FixedArray::cast(obj));
90
91   // Array should be in the new space.
92   CHECK(heap->InSpace(*array, NEW_SPACE));
93
94   // Call mark compact GC, so array becomes an old object.
95   heap->CollectAllGarbage(Heap::kAbortIncrementalMarkingMask);
96   heap->CollectAllGarbage(Heap::kAbortIncrementalMarkingMask);
97
98   // Array now sits in the old space
99   CHECK(heap->InSpace(*array, OLD_POINTER_SPACE));
100 }
101
102
103 TEST(NoPromotion) {
104   CcTest::InitializeVM();
105   TestHeap* heap = CcTest::test_heap();
106   heap->ConfigureHeap(1, 1, 1, 0);
107
108   v8::HandleScope sc(CcTest::isolate());
109
110   // Allocate a big fixed array in the new space.
111   int array_length =
112       (Page::kMaxRegularHeapObjectSize - FixedArray::kHeaderSize) /
113       (2 * kPointerSize);
114   Object* obj = heap->AllocateFixedArray(array_length).ToObjectChecked();
115   Handle<FixedArray> array(FixedArray::cast(obj));
116
117   // Array should be in the new space.
118   CHECK(heap->InSpace(*array, NEW_SPACE));
119
120   // Simulate a full old space to make promotion fail.
121   SimulateFullSpace(heap->old_pointer_space());
122
123   // Call mark compact GC, and it should pass.
124   heap->CollectGarbage(OLD_POINTER_SPACE);
125 }
126
127
128 TEST(MarkCompactCollector) {
129   FLAG_incremental_marking = false;
130   FLAG_retain_maps_for_n_gc = 0;
131   CcTest::InitializeVM();
132   Isolate* isolate = CcTest::i_isolate();
133   TestHeap* heap = CcTest::test_heap();
134   Factory* factory = isolate->factory();
135
136   v8::HandleScope sc(CcTest::isolate());
137   Handle<GlobalObject> global(isolate->context()->global_object());
138
139   // call mark-compact when heap is empty
140   heap->CollectGarbage(OLD_POINTER_SPACE, "trigger 1");
141
142   // keep allocating garbage in new space until it fails
143   const int arraysize = 100;
144   AllocationResult allocation;
145   do {
146     allocation = heap->AllocateFixedArray(arraysize);
147   } while (!allocation.IsRetry());
148   heap->CollectGarbage(NEW_SPACE, "trigger 2");
149   heap->AllocateFixedArray(arraysize).ToObjectChecked();
150
151   // keep allocating maps until it fails
152   do {
153     allocation = heap->AllocateMap(JS_OBJECT_TYPE, JSObject::kHeaderSize);
154   } while (!allocation.IsRetry());
155   heap->CollectGarbage(MAP_SPACE, "trigger 3");
156   heap->AllocateMap(JS_OBJECT_TYPE, JSObject::kHeaderSize).ToObjectChecked();
157
158   { HandleScope scope(isolate);
159     // allocate a garbage
160     Handle<String> func_name = factory->InternalizeUtf8String("theFunction");
161     Handle<JSFunction> function = factory->NewFunction(func_name);
162     JSReceiver::SetProperty(global, func_name, function, SLOPPY).Check();
163
164     factory->NewJSObject(function);
165   }
166
167   heap->CollectGarbage(OLD_POINTER_SPACE, "trigger 4");
168
169   { HandleScope scope(isolate);
170     Handle<String> func_name = factory->InternalizeUtf8String("theFunction");
171     CHECK(Just(true) == JSReceiver::HasOwnProperty(global, func_name));
172     Handle<Object> func_value =
173         Object::GetProperty(global, func_name).ToHandleChecked();
174     CHECK(func_value->IsJSFunction());
175     Handle<JSFunction> function = Handle<JSFunction>::cast(func_value);
176     Handle<JSObject> obj = factory->NewJSObject(function);
177
178     Handle<String> obj_name = factory->InternalizeUtf8String("theObject");
179     JSReceiver::SetProperty(global, obj_name, obj, SLOPPY).Check();
180     Handle<String> prop_name = factory->InternalizeUtf8String("theSlot");
181     Handle<Smi> twenty_three(Smi::FromInt(23), isolate);
182     JSReceiver::SetProperty(obj, prop_name, twenty_three, SLOPPY).Check();
183   }
184
185   heap->CollectGarbage(OLD_POINTER_SPACE, "trigger 5");
186
187   { HandleScope scope(isolate);
188     Handle<String> obj_name = factory->InternalizeUtf8String("theObject");
189     CHECK(Just(true) == JSReceiver::HasOwnProperty(global, obj_name));
190     Handle<Object> object =
191         Object::GetProperty(global, obj_name).ToHandleChecked();
192     CHECK(object->IsJSObject());
193     Handle<String> prop_name = factory->InternalizeUtf8String("theSlot");
194     CHECK_EQ(*Object::GetProperty(object, prop_name).ToHandleChecked(),
195              Smi::FromInt(23));
196   }
197 }
198
199
200 // TODO(1600): compaction of map space is temporary removed from GC.
201 #if 0
202 static Handle<Map> CreateMap(Isolate* isolate) {
203   return isolate->factory()->NewMap(JS_OBJECT_TYPE, JSObject::kHeaderSize);
204 }
205
206
207 TEST(MapCompact) {
208   FLAG_max_map_space_pages = 16;
209   CcTest::InitializeVM();
210   Isolate* isolate = CcTest::i_isolate();
211   Factory* factory = isolate->factory();
212
213   {
214     v8::HandleScope sc;
215     // keep allocating maps while pointers are still encodable and thus
216     // mark compact is permitted.
217     Handle<JSObject> root = factory->NewJSObjectFromMap(CreateMap());
218     do {
219       Handle<Map> map = CreateMap();
220       map->set_prototype(*root);
221       root = factory->NewJSObjectFromMap(map);
222     } while (CcTest::heap()->map_space()->MapPointersEncodable());
223   }
224   // Now, as we don't have any handles to just allocated maps, we should
225   // be able to trigger map compaction.
226   // To give an additional chance to fail, try to force compaction which
227   // should be impossible right now.
228   CcTest::heap()->CollectAllGarbage(Heap::kForceCompactionMask);
229   // And now map pointers should be encodable again.
230   CHECK(CcTest::heap()->map_space()->MapPointersEncodable());
231 }
232 #endif
233
234
235 static int NumberOfWeakCalls = 0;
236 static void WeakPointerCallback(
237     const v8::WeakCallbackData<v8::Value, void>& data) {
238   std::pair<v8::Persistent<v8::Value>*, int>* p =
239       reinterpret_cast<std::pair<v8::Persistent<v8::Value>*, int>*>(
240           data.GetParameter());
241   DCHECK_EQ(1234, p->second);
242   NumberOfWeakCalls++;
243   p->first->Reset();
244 }
245
246
247 TEST(ObjectGroups) {
248   FLAG_incremental_marking = false;
249   CcTest::InitializeVM();
250   GlobalHandles* global_handles = CcTest::i_isolate()->global_handles();
251   TestHeap* heap = CcTest::test_heap();
252   NumberOfWeakCalls = 0;
253   v8::HandleScope handle_scope(CcTest::isolate());
254
255   Handle<Object> g1s1 =
256       global_handles->Create(heap->AllocateFixedArray(1).ToObjectChecked());
257   Handle<Object> g1s2 =
258       global_handles->Create(heap->AllocateFixedArray(1).ToObjectChecked());
259   Handle<Object> g1c1 =
260       global_handles->Create(heap->AllocateFixedArray(1).ToObjectChecked());
261   std::pair<Handle<Object>*, int> g1s1_and_id(&g1s1, 1234);
262   GlobalHandles::MakeWeak(g1s1.location(),
263                           reinterpret_cast<void*>(&g1s1_and_id),
264                           &WeakPointerCallback);
265   std::pair<Handle<Object>*, int> g1s2_and_id(&g1s2, 1234);
266   GlobalHandles::MakeWeak(g1s2.location(),
267                           reinterpret_cast<void*>(&g1s2_and_id),
268                           &WeakPointerCallback);
269   std::pair<Handle<Object>*, int> g1c1_and_id(&g1c1, 1234);
270   GlobalHandles::MakeWeak(g1c1.location(),
271                           reinterpret_cast<void*>(&g1c1_and_id),
272                           &WeakPointerCallback);
273
274   Handle<Object> g2s1 =
275       global_handles->Create(heap->AllocateFixedArray(1).ToObjectChecked());
276   Handle<Object> g2s2 =
277     global_handles->Create(heap->AllocateFixedArray(1).ToObjectChecked());
278   Handle<Object> g2c1 =
279     global_handles->Create(heap->AllocateFixedArray(1).ToObjectChecked());
280   std::pair<Handle<Object>*, int> g2s1_and_id(&g2s1, 1234);
281   GlobalHandles::MakeWeak(g2s1.location(),
282                           reinterpret_cast<void*>(&g2s1_and_id),
283                           &WeakPointerCallback);
284   std::pair<Handle<Object>*, int> g2s2_and_id(&g2s2, 1234);
285   GlobalHandles::MakeWeak(g2s2.location(),
286                           reinterpret_cast<void*>(&g2s2_and_id),
287                           &WeakPointerCallback);
288   std::pair<Handle<Object>*, int> g2c1_and_id(&g2c1, 1234);
289   GlobalHandles::MakeWeak(g2c1.location(),
290                           reinterpret_cast<void*>(&g2c1_and_id),
291                           &WeakPointerCallback);
292
293   Handle<Object> root = global_handles->Create(*g1s1);  // make a root.
294
295   // Connect group 1 and 2, make a cycle.
296   Handle<FixedArray>::cast(g1s2)->set(0, *g2s2);
297   Handle<FixedArray>::cast(g2s1)->set(0, *g1s1);
298
299   {
300     Object** g1_objects[] = { g1s1.location(), g1s2.location() };
301     Object** g2_objects[] = { g2s1.location(), g2s2.location() };
302     global_handles->AddObjectGroup(g1_objects, 2, NULL);
303     global_handles->SetReference(Handle<HeapObject>::cast(g1s1).location(),
304                                  g1c1.location());
305     global_handles->AddObjectGroup(g2_objects, 2, NULL);
306     global_handles->SetReference(Handle<HeapObject>::cast(g2s1).location(),
307                                  g2c1.location());
308   }
309   // Do a full GC
310   heap->CollectGarbage(OLD_POINTER_SPACE);
311
312   // All object should be alive.
313   CHECK_EQ(0, NumberOfWeakCalls);
314
315   // Weaken the root.
316   std::pair<Handle<Object>*, int> root_and_id(&root, 1234);
317   GlobalHandles::MakeWeak(root.location(),
318                           reinterpret_cast<void*>(&root_and_id),
319                           &WeakPointerCallback);
320   // But make children strong roots---all the objects (except for children)
321   // should be collectable now.
322   global_handles->ClearWeakness(g1c1.location());
323   global_handles->ClearWeakness(g2c1.location());
324
325   // Groups are deleted, rebuild groups.
326   {
327     Object** g1_objects[] = { g1s1.location(), g1s2.location() };
328     Object** g2_objects[] = { g2s1.location(), g2s2.location() };
329     global_handles->AddObjectGroup(g1_objects, 2, NULL);
330     global_handles->SetReference(Handle<HeapObject>::cast(g1s1).location(),
331                                  g1c1.location());
332     global_handles->AddObjectGroup(g2_objects, 2, NULL);
333     global_handles->SetReference(Handle<HeapObject>::cast(g2s1).location(),
334                                  g2c1.location());
335   }
336
337   heap->CollectGarbage(OLD_POINTER_SPACE);
338
339   // All objects should be gone. 5 global handles in total.
340   CHECK_EQ(5, NumberOfWeakCalls);
341
342   // And now make children weak again and collect them.
343   GlobalHandles::MakeWeak(g1c1.location(),
344                           reinterpret_cast<void*>(&g1c1_and_id),
345                           &WeakPointerCallback);
346   GlobalHandles::MakeWeak(g2c1.location(),
347                           reinterpret_cast<void*>(&g2c1_and_id),
348                           &WeakPointerCallback);
349
350   heap->CollectGarbage(OLD_POINTER_SPACE);
351   CHECK_EQ(7, NumberOfWeakCalls);
352 }
353
354
355 class TestRetainedObjectInfo : public v8::RetainedObjectInfo {
356  public:
357   TestRetainedObjectInfo() : has_been_disposed_(false) {}
358
359   bool has_been_disposed() { return has_been_disposed_; }
360
361   virtual void Dispose() {
362     DCHECK(!has_been_disposed_);
363     has_been_disposed_ = true;
364   }
365
366   virtual bool IsEquivalent(v8::RetainedObjectInfo* other) {
367     return other == this;
368   }
369
370   virtual intptr_t GetHash() { return 0; }
371
372   virtual const char* GetLabel() { return "whatever"; }
373
374  private:
375   bool has_been_disposed_;
376 };
377
378
379 TEST(EmptyObjectGroups) {
380   CcTest::InitializeVM();
381   GlobalHandles* global_handles = CcTest::i_isolate()->global_handles();
382
383   v8::HandleScope handle_scope(CcTest::isolate());
384
385   TestRetainedObjectInfo info;
386   global_handles->AddObjectGroup(NULL, 0, &info);
387   DCHECK(info.has_been_disposed());
388 }
389
390
391 #if defined(__has_feature)
392 #if __has_feature(address_sanitizer)
393 #define V8_WITH_ASAN 1
394 #endif
395 #endif
396
397
398 // Here is a memory use test that uses /proc, and is therefore Linux-only.  We
399 // do not care how much memory the simulator uses, since it is only there for
400 // debugging purposes. Testing with ASAN doesn't make sense, either.
401 #if defined(__linux__) && !defined(USE_SIMULATOR) && !defined(V8_WITH_ASAN)
402
403
404 static uintptr_t ReadLong(char* buffer, intptr_t* position, int base) {
405   char* end_address = buffer + *position;
406   uintptr_t result = strtoul(buffer + *position, &end_address, base);
407   CHECK(result != ULONG_MAX || errno != ERANGE);
408   CHECK(end_address > buffer + *position);
409   *position = end_address - buffer;
410   return result;
411 }
412
413
414 // The memory use computed this way is not entirely accurate and depends on
415 // the way malloc allocates memory.  That's why the memory use may seem to
416 // increase even though the sum of the allocated object sizes decreases.  It
417 // also means that the memory use depends on the kernel and stdlib.
418 static intptr_t MemoryInUse() {
419   intptr_t memory_use = 0;
420
421   int fd = open("/proc/self/maps", O_RDONLY);
422   if (fd < 0) return -1;
423
424   const int kBufSize = 10000;
425   char buffer[kBufSize];
426   int length = read(fd, buffer, kBufSize);
427   intptr_t line_start = 0;
428   CHECK_LT(length, kBufSize);  // Make the buffer bigger.
429   CHECK_GT(length, 0);  // We have to find some data in the file.
430   while (line_start < length) {
431     if (buffer[line_start] == '\n') {
432       line_start++;
433       continue;
434     }
435     intptr_t position = line_start;
436     uintptr_t start = ReadLong(buffer, &position, 16);
437     CHECK_EQ(buffer[position++], '-');
438     uintptr_t end = ReadLong(buffer, &position, 16);
439     CHECK_EQ(buffer[position++], ' ');
440     CHECK(buffer[position] == '-' || buffer[position] == 'r');
441     bool read_permission = (buffer[position++] == 'r');
442     CHECK(buffer[position] == '-' || buffer[position] == 'w');
443     bool write_permission = (buffer[position++] == 'w');
444     CHECK(buffer[position] == '-' || buffer[position] == 'x');
445     bool execute_permission = (buffer[position++] == 'x');
446     CHECK(buffer[position] == 's' || buffer[position] == 'p');
447     bool private_mapping = (buffer[position++] == 'p');
448     CHECK_EQ(buffer[position++], ' ');
449     uintptr_t offset = ReadLong(buffer, &position, 16);
450     USE(offset);
451     CHECK_EQ(buffer[position++], ' ');
452     uintptr_t major = ReadLong(buffer, &position, 16);
453     USE(major);
454     CHECK_EQ(buffer[position++], ':');
455     uintptr_t minor = ReadLong(buffer, &position, 16);
456     USE(minor);
457     CHECK_EQ(buffer[position++], ' ');
458     uintptr_t inode = ReadLong(buffer, &position, 10);
459     while (position < length && buffer[position] != '\n') position++;
460     if ((read_permission || write_permission || execute_permission) &&
461         private_mapping && inode == 0) {
462       memory_use += (end - start);
463     }
464
465     line_start = position;
466   }
467   close(fd);
468   return memory_use;
469 }
470
471
472 intptr_t ShortLivingIsolate() {
473   v8::Isolate* isolate = v8::Isolate::New();
474   { v8::Isolate::Scope isolate_scope(isolate);
475     v8::Locker lock(isolate);
476     v8::HandleScope handle_scope(isolate);
477     v8::Local<v8::Context> context = v8::Context::New(isolate);
478     CHECK(!context.IsEmpty());
479   }
480   isolate->Dispose();
481   return MemoryInUse();
482 }
483
484
485 TEST(RegressJoinThreadsOnIsolateDeinit) {
486   intptr_t size_limit = ShortLivingIsolate() * 2;
487   for (int i = 0; i < 10; i++) {
488     CHECK_GT(size_limit, ShortLivingIsolate());
489   }
490 }
491
492 #endif  // __linux__ and !USE_SIMULATOR