v8  3.25.30(node0.11.13)
V8 is Google's open source JavaScript engine
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Pages
test-weakmaps.cc
Go to the documentation of this file.
1 // Copyright 2011 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 <utility>
29 
30 #include "v8.h"
31 
32 #include "global-handles.h"
33 #include "snapshot.h"
34 #include "cctest.h"
35 
36 using namespace v8::internal;
37 
38 
39 static Isolate* GetIsolateFrom(LocalContext* context) {
40  return reinterpret_cast<Isolate*>((*context)->GetIsolate());
41 }
42 
43 
44 static Handle<JSWeakMap> AllocateJSWeakMap(Isolate* isolate) {
45  Factory* factory = isolate->factory();
46  Heap* heap = isolate->heap();
48  Handle<JSObject> weakmap_obj = factory->NewJSObjectFromMap(map);
49  Handle<JSWeakMap> weakmap(JSWeakMap::cast(*weakmap_obj));
50  // Do not use handles for the hash table, it would make entries strong.
51  Object* table_obj = ObjectHashTable::Allocate(heap, 1)->ToObjectChecked();
52  ObjectHashTable* table = ObjectHashTable::cast(table_obj);
53  weakmap->set_table(table);
54  weakmap->set_next(Smi::FromInt(0));
55  return weakmap;
56 }
57 
58 static void PutIntoWeakMap(Handle<JSWeakMap> weakmap,
59  Handle<JSObject> key,
60  Handle<Object> value) {
64  value);
65  weakmap->set_table(*table);
66 }
67 
68 static int NumberOfWeakCalls = 0;
69 static void WeakPointerCallback(
71  std::pair<v8::Persistent<v8::Value>*, int>* p =
72  reinterpret_cast<std::pair<v8::Persistent<v8::Value>*, int>*>(
73  data.GetParameter());
74  ASSERT_EQ(1234, p->second);
75  NumberOfWeakCalls++;
76  p->first->Reset();
77 }
78 
79 
80 TEST(Weakness) {
81  FLAG_incremental_marking = false;
82  LocalContext context;
83  Isolate* isolate = GetIsolateFrom(&context);
84  Factory* factory = isolate->factory();
85  Heap* heap = isolate->heap();
86  HandleScope scope(isolate);
87  Handle<JSWeakMap> weakmap = AllocateJSWeakMap(isolate);
88  GlobalHandles* global_handles = isolate->global_handles();
89 
90  // Keep global reference to the key.
91  Handle<Object> key;
92  {
93  HandleScope scope(isolate);
95  Handle<JSObject> object = factory->NewJSObjectFromMap(map);
96  key = global_handles->Create(*object);
97  }
98  CHECK(!global_handles->IsWeak(key.location()));
99 
100  // Put entry into weak map.
101  {
102  HandleScope scope(isolate);
103  PutIntoWeakMap(weakmap,
105  Handle<Smi>(Smi::FromInt(23), isolate));
106  }
107  CHECK_EQ(1, ObjectHashTable::cast(weakmap->table())->NumberOfElements());
108 
109  // Force a full GC.
110  heap->CollectAllGarbage(false);
111  CHECK_EQ(0, NumberOfWeakCalls);
112  CHECK_EQ(1, ObjectHashTable::cast(weakmap->table())->NumberOfElements());
113  CHECK_EQ(
114  0, ObjectHashTable::cast(weakmap->table())->NumberOfDeletedElements());
115 
116  // Make the global reference to the key weak.
117  {
118  HandleScope scope(isolate);
119  std::pair<Handle<Object>*, int> handle_and_id(&key, 1234);
120  GlobalHandles::MakeWeak(key.location(),
121  reinterpret_cast<void*>(&handle_and_id),
122  &WeakPointerCallback);
123  }
124  CHECK(global_handles->IsWeak(key.location()));
125 
126  // Force a full GC.
127  // Perform two consecutive GCs because the first one will only clear
128  // weak references whereas the second one will also clear weak maps.
129  heap->CollectAllGarbage(false);
130  CHECK_EQ(1, NumberOfWeakCalls);
131  CHECK_EQ(1, ObjectHashTable::cast(weakmap->table())->NumberOfElements());
132  CHECK_EQ(
133  0, ObjectHashTable::cast(weakmap->table())->NumberOfDeletedElements());
134  heap->CollectAllGarbage(false);
135  CHECK_EQ(1, NumberOfWeakCalls);
136  CHECK_EQ(0, ObjectHashTable::cast(weakmap->table())->NumberOfElements());
137  CHECK_EQ(
138  1, ObjectHashTable::cast(weakmap->table())->NumberOfDeletedElements());
139 }
140 
141 
142 TEST(Shrinking) {
143  LocalContext context;
144  Isolate* isolate = GetIsolateFrom(&context);
145  Factory* factory = isolate->factory();
146  Heap* heap = isolate->heap();
147  HandleScope scope(isolate);
148  Handle<JSWeakMap> weakmap = AllocateJSWeakMap(isolate);
149 
150  // Check initial capacity.
151  CHECK_EQ(32, ObjectHashTable::cast(weakmap->table())->Capacity());
152 
153  // Fill up weak map to trigger capacity change.
154  {
155  HandleScope scope(isolate);
157  for (int i = 0; i < 32; i++) {
158  Handle<JSObject> object = factory->NewJSObjectFromMap(map);
159  PutIntoWeakMap(weakmap, object, Handle<Smi>(Smi::FromInt(i), isolate));
160  }
161  }
162 
163  // Check increased capacity.
164  CHECK_EQ(128, ObjectHashTable::cast(weakmap->table())->Capacity());
165 
166  // Force a full GC.
167  CHECK_EQ(32, ObjectHashTable::cast(weakmap->table())->NumberOfElements());
168  CHECK_EQ(
169  0, ObjectHashTable::cast(weakmap->table())->NumberOfDeletedElements());
170  heap->CollectAllGarbage(false);
171  CHECK_EQ(0, ObjectHashTable::cast(weakmap->table())->NumberOfElements());
172  CHECK_EQ(
173  32, ObjectHashTable::cast(weakmap->table())->NumberOfDeletedElements());
174 
175  // Check shrunk capacity.
176  CHECK_EQ(32, ObjectHashTable::cast(weakmap->table())->Capacity());
177 }
178 
179 
180 // Test that weak map values on an evacuation candidate which are not reachable
181 // by other paths are correctly recorded in the slots buffer.
182 TEST(Regress2060a) {
183  FLAG_always_compact = true;
184  LocalContext context;
185  Isolate* isolate = GetIsolateFrom(&context);
186  Factory* factory = isolate->factory();
187  Heap* heap = isolate->heap();
188  HandleScope scope(isolate);
189  Handle<JSFunction> function =
190  factory->NewFunction(factory->function_string(), factory->null_value());
191  Handle<JSObject> key = factory->NewJSObject(function);
192  Handle<JSWeakMap> weakmap = AllocateJSWeakMap(isolate);
193 
194  // Start second old-space page so that values land on evacuation candidate.
195  Page* first_page = heap->old_pointer_space()->anchor()->next_page();
196  factory->NewFixedArray(900 * KB / kPointerSize, TENURED);
197 
198  // Fill up weak map with values on an evacuation candidate.
199  {
200  HandleScope scope(isolate);
201  for (int i = 0; i < 32; i++) {
202  Handle<JSObject> object = factory->NewJSObject(function, TENURED);
203  CHECK(!heap->InNewSpace(object->address()));
204  CHECK(!first_page->Contains(object->address()));
205  PutIntoWeakMap(weakmap, key, object);
206  }
207  }
208 
209  // Force compacting garbage collection.
210  CHECK(FLAG_always_compact);
212 }
213 
214 
215 // Test that weak map keys on an evacuation candidate which are reachable by
216 // other strong paths are correctly recorded in the slots buffer.
217 TEST(Regress2060b) {
218  FLAG_always_compact = true;
219 #ifdef VERIFY_HEAP
220  FLAG_verify_heap = true;
221 #endif
222 
223  LocalContext context;
224  Isolate* isolate = GetIsolateFrom(&context);
225  Factory* factory = isolate->factory();
226  Heap* heap = isolate->heap();
227  HandleScope scope(isolate);
228  Handle<JSFunction> function =
229  factory->NewFunction(factory->function_string(), factory->null_value());
230 
231  // Start second old-space page so that keys land on evacuation candidate.
232  Page* first_page = heap->old_pointer_space()->anchor()->next_page();
233  factory->NewFixedArray(900 * KB / kPointerSize, TENURED);
234 
235  // Fill up weak map with keys on an evacuation candidate.
237  for (int i = 0; i < 32; i++) {
238  keys[i] = factory->NewJSObject(function, TENURED);
239  CHECK(!heap->InNewSpace(keys[i]->address()));
240  CHECK(!first_page->Contains(keys[i]->address()));
241  }
242  Handle<JSWeakMap> weakmap = AllocateJSWeakMap(isolate);
243  for (int i = 0; i < 32; i++) {
244  PutIntoWeakMap(weakmap,
245  keys[i],
246  Handle<Smi>(Smi::FromInt(i), isolate));
247  }
248 
249  // Force compacting garbage collection. The subsequent collections are used
250  // to verify that key references were actually updated.
251  CHECK(FLAG_always_compact);
255 }
Handle< JSObject > NewJSObject(Handle< JSFunction > constructor, PretenureFlag pretenure=NOT_TENURED)
Definition: factory.cc:1319
#define CHECK_EQ(expected, value)
Definition: checks.h:252
enable upcoming ES6 features enable harmony block scoping enable harmony enable harmony proxies enable harmony generators enable harmony numeric enable harmony string enable harmony math functions harmony_scoping harmony_symbols harmony_collections harmony_iteration harmony_strings harmony_scoping harmony_maths tracks arrays with only smi values Optimize object Array DOM strings and string pretenure call new trace pretenuring decisions of HAllocate instructions track fields with only smi values track fields with heap values track_fields track_fields Enables optimizations which favor memory size over execution speed use string slices optimization filter maximum number of GVN fix point iterations use function inlining use allocation folding eliminate write barriers targeting allocations in optimized code maximum source size in bytes considered for a single inlining maximum cumulative number of AST nodes considered for inlining crankshaft harvests type feedback from stub cache trace check elimination phase hydrogen tracing filter trace hydrogen to given file name trace inlining decisions trace store elimination trace all use positions trace global value numbering trace hydrogen escape analysis trace the tracking of allocation sites trace map generalization environment for every instruction deoptimize every n garbage collections put a break point before deoptimizing deoptimize uncommon cases use on stack replacement trace array bounds check elimination perform array index dehoisting use load elimination use store elimination use constant folding eliminate unreachable code number of stress runs when picking a function to watch for shared function not JSFunction itself flushes the cache of optimized code for closures on every GC functions with arguments object maximum number of escape analysis fix point iterations allow uint32 values on optimize frames if they are used only in safe operations track concurrent recompilation artificial compilation delay in ms concurrent on stack replacement do not emit check maps for constant values that have a leaf deoptimize the optimized code if the layout of the maps changes number of stack frames inspected by the profiler percentage of ICs that must have type info to allow optimization extra verbose compilation tracing generate extra emit comments in code disassembly enable use of SSE3 instructions if available enable use of CMOV instruction if available enable use of VFP3 instructions if available enable use of NEON instructions if enable use of SDIV and UDIV instructions if enable loading bit constant by means of movw movt instruction enable unaligned accesses for enable use of d16 d31 registers on ARM this requires VFP3 force all emitted branches to be in long expose natives in global object expose freeBuffer extension expose gc extension under the specified name expose externalize string extension number of stack frames to capture disable builtin natives files print name of functions for which code is generated use random jit cookie to mask large constants trace lazy optimization use adaptive optimizations always try to OSR functions trace optimize function deoptimization minimum length for automatic enable preparsing maximum number of optimization attempts before giving up cache prototype transitions trace debugging JSON request response trace out of bounds accesses to external arrays trace_js_array_abuse automatically set the debug break flag when debugger commands are in the queue abort by crashing maximum length of function source code printed in a stack trace max size of the new max size of the old max size of executable always perform global GCs print one trace line following each garbage collection do not print trace line after scavenger collection print statistics of the maximum memory committed for the heap in only print modified registers Don t break for ASM_UNIMPLEMENTED_BREAK macros print stack trace when an illegal exception is thrown randomize hashes to avoid predictable hash Fixed seed to use to hash property keys(0 means random)" "(with snapshots this option cannot override the baked-in seed)") DEFINE_bool(profile_deserialization
bool Contains(Address addr)
Definition: spaces.h:377
void CollectAllGarbage(int flags, const char *gc_reason=NULL, const GCCallbackFlags gc_callback_flags=kNoGCCallbackFlags)
Definition: heap.cc:731
enable upcoming ES6 features enable harmony block scoping enable harmony enable harmony proxies enable harmony generators enable harmony numeric enable harmony string enable harmony math functions harmony_scoping harmony_symbols harmony_collections harmony_iteration harmony_strings harmony_scoping harmony_maths tracks arrays with only smi values Optimize object Array DOM strings and string pretenure call new trace pretenuring decisions of HAllocate instructions track fields with only smi values track fields with heap values track_fields track_fields Enables optimizations which favor memory size over execution speed use string slices optimization filter maximum number of GVN fix point iterations use function inlining use allocation folding eliminate write barriers targeting allocations in optimized code maximum source size in bytes considered for a single inlining maximum cumulative number of AST nodes considered for inlining crankshaft harvests type feedback from stub cache trace check elimination phase hydrogen tracing filter trace hydrogen to given file name trace inlining decisions trace store elimination trace all use positions trace global value numbering trace hydrogen escape analysis trace the tracking of allocation sites trace map generalization environment for every instruction deoptimize every n garbage collections put a break point before deoptimizing deoptimize uncommon cases use on stack replacement trace array bounds check elimination perform array index dehoisting use load elimination use store elimination use constant folding eliminate unreachable code number of stress runs when picking a function to watch for shared function not JSFunction itself flushes the cache of optimized code for closures on every GC functions with arguments object maximum number of escape analysis fix point iterations allow uint32 values on optimize frames if they are used only in safe operations track concurrent recompilation artificial compilation delay in ms concurrent on stack replacement do not emit check maps for constant values that have a leaf map
Definition: flags.cc:350
bool InNewSpace(Object *object)
Definition: heap-inl.h:307
static Smi * FromInt(int value)
Definition: objects-inl.h:1209
const int KB
Definition: globals.h:245
#define CHECK(condition)
Definition: checks.h:75
Factory * factory()
Definition: isolate.h:995
Handle< JSObject > NewJSObjectFromMap(Handle< Map > map, PretenureFlag pretenure=NOT_TENURED, bool allocate_properties=true, Handle< AllocationSite > allocation_site=Handle< AllocationSite >::null())
Definition: factory.cc:1421
Handle< JSFunction > NewFunction(Handle< String > name, Handle< Object > prototype)
Definition: factory.cc:1663
Handle< Object > Create(Object *value)
static const int kNoGCFlags
Definition: heap.h:1257
const int kPointerSize
Definition: globals.h:268
GlobalHandles * global_handles()
Definition: isolate.h:918
Handle< FixedArray > NewFixedArray(int size, PretenureFlag pretenure=NOT_TENURED)
Definition: factory.cc:53
OldSpace * old_pointer_space()
Definition: heap.h:638
static const int kSize
Definition: objects.h:9807
V8_INLINE P * GetParameter() const
Definition: v8.h:451
static MUST_USE_RESULT MaybeObject * Allocate(Heap *heap, int at_least_space_for, MinimumCapacity capacity_option=USE_DEFAULT_MINIMUM_CAPACITY, PretenureFlag pretenure=NOT_TENURED)
static ObjectHashTable * cast(Object *obj)
Definition: objects.h:4226
static void MakeWeak(Object **location, void *parameter, WeakCallback weak_callback)
static JSWeakMap * cast(Object *obj)
#define ASSERT_EQ(v1, v2)
Definition: checks.h:330
static bool IsWeak(Object **location)
static const int kHeaderSize
Definition: objects.h:2757
Page * next_page()
Definition: spaces-inl.h:238
static Handle< ObjectHashTable > Put(Handle< ObjectHashTable > table, Handle< Object > key, Handle< Object > value)
Definition: objects.cc:15775
Handle< Map > NewMap(InstanceType type, int instance_size, ElementsKind elements_kind=TERMINAL_FAST_ELEMENTS_KIND)
Definition: factory.cc:809
static JSObject * cast(Object *obj)