summaryrefslogtreecommitdiffstats
path: root/js/src/jsapi-tests/testObjectSwap.cpp
blob: d326df6f3797b34ca1ad08f77ef61091d53171a8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*-
 * vim: set ts=8 sts=2 et sw=2 tw=80:
 */
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

/*
 * Test JSObject::swap.
 *
 * This test creates objects from a description of their configuration. Objects
 * are given unique property names and values. A list of configurations is
 * created and the result of swapping every combination checked.
 */

#include "mozilla/Sprintf.h"

#include "js/AllocPolicy.h"
#include "js/Vector.h"
#include "jsapi-tests/tests.h"
#include "vm/PlainObject.h"

#include "gc/StableCellHasher-inl.h"
#include "vm/JSObject-inl.h"

using namespace js;

struct NativeConfig {
  uint32_t propCount;
  uint32_t elementCount;
  bool inDictionaryMode;
};

struct ProxyConfig {
  bool inlineValues;
};

struct ObjectConfig {
  const JSClass* clasp;
  bool isNative;
  bool nurseryAllocated;
  bool hasUniqueId;
  union {
    NativeConfig native;
    ProxyConfig proxy;
  };
};

using ObjectConfigVector = Vector<ObjectConfig, 0, SystemAllocPolicy>;

static const JSClass TestProxyClasses[] = {
    PROXY_CLASS_DEF("TestProxy", JSCLASS_HAS_RESERVED_SLOTS(1 /* Min */)),
    PROXY_CLASS_DEF("TestProxy", JSCLASS_HAS_RESERVED_SLOTS(2)),
    PROXY_CLASS_DEF("TestProxy", JSCLASS_HAS_RESERVED_SLOTS(7)),
    PROXY_CLASS_DEF("TestProxy", JSCLASS_HAS_RESERVED_SLOTS(8)),
    PROXY_CLASS_DEF("TestProxy", JSCLASS_HAS_RESERVED_SLOTS(14 /* Max */))};

static const JSClass TestDOMClasses[] = {
    {"TestDOMObject", JSCLASS_IS_DOMJSCLASS | JSCLASS_HAS_RESERVED_SLOTS(0)},
    {"TestDOMObject", JSCLASS_IS_DOMJSCLASS | JSCLASS_HAS_RESERVED_SLOTS(1)},
    {"TestDOMObject", JSCLASS_IS_DOMJSCLASS | JSCLASS_HAS_RESERVED_SLOTS(2)},
    {"TestDOMObject", JSCLASS_IS_DOMJSCLASS | JSCLASS_HAS_RESERVED_SLOTS(7)},
    {"TestDOMObject", JSCLASS_IS_DOMJSCLASS | JSCLASS_HAS_RESERVED_SLOTS(8)},
    {"TestDOMObject", JSCLASS_IS_DOMJSCLASS | JSCLASS_HAS_RESERVED_SLOTS(20)}};

static const uint32_t TestPropertyCounts[] = {0, 1, 2, 7, 8, 20};

static const uint32_t TestElementCounts[] = {0, 20};

static bool Verbose = false;

class TenuredProxyHandler final : public Wrapper {
 public:
  static const TenuredProxyHandler singleton;
  constexpr TenuredProxyHandler() : Wrapper(0) {}
  bool canNurseryAllocate() const override { return false; }
};

const TenuredProxyHandler TenuredProxyHandler::singleton;

class NurseryProxyHandler final : public Wrapper {
 public:
  static const NurseryProxyHandler singleton;
  constexpr NurseryProxyHandler() : Wrapper(0) {}
  bool canNurseryAllocate() const override { return true; }
};

const NurseryProxyHandler NurseryProxyHandler::singleton;

BEGIN_TEST(testObjectSwap) {
  AutoLeaveZeal noZeal(cx);

  ObjectConfigVector objectConfigs = CreateObjectConfigs();

  for (const ObjectConfig& config1 : objectConfigs) {
    for (const ObjectConfig& config2 : objectConfigs) {
      {
        uint32_t id1;
        RootedObject obj1(cx, CreateObject(config1, &id1));
        CHECK(obj1);

        uint32_t id2;
        RootedObject obj2(cx, CreateObject(config2, &id2));
        CHECK(obj2);

        if (Verbose) {
          fprintf(stderr, "Swap %p (%s) and %p (%s)\n", obj1.get(),
                  GetLocation(obj1), obj2.get(), GetLocation(obj2));
        }

        uint64_t uid1 = 0;
        if (config1.hasUniqueId) {
          uid1 = gc::GetUniqueIdInfallible(obj1);
        }
        uint64_t uid2 = 0;
        if (config2.hasUniqueId) {
          uid2 = gc::GetUniqueIdInfallible(obj2);
        }

        {
          AutoEnterOOMUnsafeRegion oomUnsafe;
          JSObject::swap(cx, obj1, obj2, oomUnsafe);
        }

        CHECK(CheckObject(obj1, config2, id2));
        CHECK(CheckObject(obj2, config1, id1));

        CHECK(CheckUniqueIds(obj1, config1.hasUniqueId, uid1, obj2,
                             config2.hasUniqueId, uid2));
      }

      if (Verbose) {
        fprintf(stderr, "\n");
      }
    }

    // JSObject::swap can suppress GC so ensure we clean up occasionally.
    JS_GC(cx);
  }

  return true;
}

ObjectConfigVector CreateObjectConfigs() {
  ObjectConfigVector configs;

  ObjectConfig config;

  for (bool nurseryAllocated : {false, true}) {
    config.nurseryAllocated = nurseryAllocated;

    for (bool hasUniqueId : {false, true}) {
      config.hasUniqueId = hasUniqueId;

      config.isNative = true;
      config.native = NativeConfig{0, false};

      for (const JSClass& jsClass : TestDOMClasses) {
        config.clasp = &jsClass;

        for (uint32_t propCount : TestPropertyCounts) {
          config.native.propCount = propCount;

          for (uint32_t elementCount : TestElementCounts) {
            config.native.elementCount = elementCount;

            for (bool inDictionaryMode : {false, true}) {
              if (inDictionaryMode && propCount == 0) {
                continue;
              }

              config.native.inDictionaryMode = inDictionaryMode;
              MOZ_RELEASE_ASSERT(configs.append(config));
            }
          }
        }
      }

      config.isNative = false;
      config.proxy = ProxyConfig{false};

      for (const JSClass& jsClass : TestProxyClasses) {
        config.clasp = &jsClass;

        for (bool inlineValues : {true, false}) {
          config.proxy.inlineValues = inlineValues;
          MOZ_RELEASE_ASSERT(configs.append(config));
        }
      }
    }
  }

  return configs;
}

const char* GetLocation(JSObject* obj) {
  return obj->isTenured() ? "tenured heap" : "nursery";
}

// Counter used to give slots and property names unique values.
uint32_t nextId = 0;

JSObject* CreateObject(const ObjectConfig& config, uint32_t* idOut) {
  *idOut = nextId;
  JSObject* obj =
      config.isNative ? CreateNativeObject(config) : CreateProxy(config);

  if (config.hasUniqueId) {
    uint64_t unused;
    if (!gc::GetOrCreateUniqueId(obj, &unused)) {
      return nullptr;
    }
  }

  return obj;
}

JSObject* CreateNativeObject(const ObjectConfig& config) {
  MOZ_ASSERT(config.isNative);

  NewObjectKind kind = config.nurseryAllocated ? GenericObject : TenuredObject;
  Rooted<NativeObject*> obj(cx,
                            NewBuiltinClassInstance(cx, config.clasp, kind));
  if (!obj) {
    return nullptr;
  }

  MOZ_RELEASE_ASSERT(IsInsideNursery(obj) == config.nurseryAllocated);

  for (uint32_t i = 0; i < JSCLASS_RESERVED_SLOTS(config.clasp); i++) {
    JS::SetReservedSlot(obj, i, Int32Value(nextId++));
  }

  if (config.native.inDictionaryMode) {
    // Put object in dictionary mode by defining a non-last property and
    // deleting it later.
    MOZ_RELEASE_ASSERT(config.native.propCount != 0);
    if (!JS_DefineProperty(cx, obj, "dummy", 0, JSPROP_ENUMERATE)) {
      return nullptr;
    }
  }

  for (uint32_t i = 0; i < config.native.propCount; i++) {
    RootedId name(cx, CreatePropName(nextId++));
    if (name.isVoid()) {
      return nullptr;
    }

    if (!JS_DefinePropertyById(cx, obj, name, nextId++, JSPROP_ENUMERATE)) {
      return nullptr;
    }
  }

  if (config.native.elementCount) {
    if (!obj->ensureElements(cx, config.native.elementCount)) {
      return nullptr;
    }
    for (uint32_t i = 0; i < config.native.elementCount; i++) {
      obj->setDenseInitializedLength(i + 1);
      obj->initDenseElement(i, Int32Value(nextId++));
    }
    MOZ_ASSERT(obj->hasDynamicElements());
  }

  if (config.native.inDictionaryMode) {
    JS::ObjectOpResult result;
    JS_DeleteProperty(cx, obj, "dummy", result);
    MOZ_RELEASE_ASSERT(result.ok());
  }

  MOZ_RELEASE_ASSERT(obj->inDictionaryMode() == config.native.inDictionaryMode);

  return obj;
}

JSObject* CreateProxy(const ObjectConfig& config) {
  RootedValue priv(cx, Int32Value(nextId++));

  RootedObject expando(cx, NewPlainObject(cx));
  RootedValue expandoId(cx, Int32Value(nextId++));
  if (!expando || !JS_SetProperty(cx, expando, "id", expandoId)) {
    return nullptr;
  }

  ProxyOptions options;
  options.setClass(config.clasp);
  options.setLazyProto(true);

  const Wrapper* handler;
  if (config.nurseryAllocated) {
    handler = &NurseryProxyHandler::singleton;
  } else {
    handler = &TenuredProxyHandler::singleton;
  }

  RootedObject obj(cx, NewProxyObject(cx, handler, priv, nullptr, options));
  if (!obj) {
    return nullptr;
  }

  Rooted<ProxyObject*> proxy(cx, &obj->as<ProxyObject>());
  proxy->setExpando(expando);

  for (uint32_t i = 0; i < JSCLASS_RESERVED_SLOTS(config.clasp); i++) {
    JS::SetReservedSlot(proxy, i, Int32Value(nextId++));
  }

  if (!config.proxy.inlineValues) {
    // To create a proxy with non-inline values we must swap the proxy with an
    // object with a different size.
    NewObjectKind kind =
        config.nurseryAllocated ? GenericObject : TenuredObject;
    RootedObject dummy(cx,
                       NewBuiltinClassInstance(cx, &TestDOMClasses[0], kind));
    if (!dummy) {
      return nullptr;
    }

    AutoEnterOOMUnsafeRegion oomUnsafe;
    JSObject::swap(cx, obj, dummy, oomUnsafe);
    proxy = &dummy->as<ProxyObject>();
  }

  MOZ_RELEASE_ASSERT(IsInsideNursery(proxy) == config.nurseryAllocated);
  MOZ_RELEASE_ASSERT(proxy->usingInlineValueArray() ==
                     config.proxy.inlineValues);

  return proxy;
}

bool CheckObject(HandleObject obj, const ObjectConfig& config, uint32_t id) {
  CHECK(obj->is<NativeObject>() == config.isNative);
  CHECK(obj->getClass() == config.clasp);

  uint32_t reservedSlots = JSCLASS_RESERVED_SLOTS(config.clasp);

  if (Verbose) {
    fprintf(stderr, "Check %p is a %s object with %u reserved slots", obj.get(),
            config.isNative ? "native" : "proxy", reservedSlots);
    if (config.isNative) {
      fprintf(stderr,
              ", %u properties, %u elements and %s in dictionary mode\n",
              config.native.propCount, config.native.elementCount,
              config.native.inDictionaryMode ? "is" : "is not");
    } else {
      fprintf(stderr, " with %s values\n",
              config.proxy.inlineValues ? "inline" : "out-of-line");
    }
  }

  if (!config.isNative) {
    CHECK(GetProxyPrivate(obj) == Int32Value(id++));

    Value expandoValue = GetProxyExpando(obj);
    CHECK(expandoValue.isObject());

    RootedObject expando(cx, &expandoValue.toObject());
    RootedValue expandoId(cx);
    JS_GetProperty(cx, expando, "id", &expandoId);
    CHECK(expandoId == Int32Value(id++));
  }

  for (uint32_t i = 0; i < reservedSlots; i++) {
    CHECK(JS::GetReservedSlot(obj, i) == Int32Value(id++));
  }

  if (config.isNative) {
    Rooted<NativeObject*> nobj(cx, &obj->as<NativeObject>());
    uint32_t propCount = GetPropertyCount(nobj);

    CHECK(propCount == config.native.propCount);

    for (uint32_t i = 0; i < config.native.propCount; i++) {
      RootedId name(cx, CreatePropName(id++));
      CHECK(!name.isVoid());

      RootedValue value(cx);
      CHECK(JS_GetPropertyById(cx, obj, name, &value));
      CHECK(value == Int32Value(id++));
    }

    CHECK(nobj->getDenseInitializedLength() == config.native.elementCount);
    for (uint32_t i = 0; i < config.native.elementCount; i++) {
      Value value = nobj->getDenseElement(i);
      CHECK(value == Int32Value(id++));
    }
  }

  return true;
}

bool CheckUniqueIds(HandleObject obj1, bool hasUniqueId1, uint64_t uid1,
                    HandleObject obj2, bool hasUniqueId2, uint64_t uid2) {
  if (uid1 && uid2) {
    MOZ_RELEASE_ASSERT(uid1 != uid2);
  }

  // Check unique IDs are NOT swapped.
  CHECK(CheckUniqueId(obj1, hasUniqueId1, uid1));
  CHECK(CheckUniqueId(obj2, hasUniqueId2, uid2));

  // Check unique IDs are different if present.
  if (gc::HasUniqueId(obj1) && gc::HasUniqueId(obj2)) {
    CHECK(gc::GetUniqueIdInfallible(obj1) != gc::GetUniqueIdInfallible(obj2));
  }

  return true;
}

bool CheckUniqueId(HandleObject obj, bool hasUniqueId, uint64_t uid) {
  if (hasUniqueId) {
    CHECK(gc::HasUniqueId(obj));
    CHECK(gc::GetUniqueIdInfallible(obj) == uid);
  } else {
    // Swap may add a unique ID to an object.
  }

  if (obj->is<NativeObject>()) {
    CHECK(!obj->zone()->uniqueIds().has(obj));
  }
  return true;
}

uint32_t GetPropertyCount(NativeObject* obj) {
  uint32_t count = 0;
  for (ShapePropertyIter<NoGC> iter(obj->shape()); !iter.done(); iter++) {
    count++;
  }

  return count;
}

jsid CreatePropName(uint32_t id) {
  char buffer[32];
  SprintfLiteral(buffer, "prop%u", id);

  RootedString atom(cx, JS_AtomizeString(cx, buffer));
  if (!atom) {
    return jsid::Void();
  }

  return jsid::NonIntAtom(atom);
}

END_TEST(testObjectSwap)