1// Copyright (C) 2016 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
3
4#include "qv4memberdata_p.h"
5#include <private/qv4mm_p.h>
6#include "qv4value_p.h"
7
8using namespace QV4;
9
10DEFINE_MANAGED_VTABLE(MemberData);
11
12static size_t nextPowerOfTwo(size_t s)
13{
14 --s;
15 s |= s >> 1;
16 s |= s >> 2;
17 s |= s >> 4;
18 s |= s >> 8;
19 s |= s >> 16;
20#if (QT_POINTER_SIZE == 8)
21 s |= s >> 32;
22#endif
23 ++s;
24 return s;
25}
26
27Heap::MemberData *MemberData::allocate(ExecutionEngine *e, uint n, Heap::MemberData *old)
28{
29 Q_ASSERT(!old || old->values.size <= n);
30 if (!n)
31 n = 4;
32
33 size_t alloc = MemoryManager::align(size: sizeof(Heap::MemberData) + (n - 1)*sizeof(Value));
34 // round up to next power of two to avoid quadratic behaviour for very large objects
35 alloc = nextPowerOfTwo(s: alloc);
36
37 // The above code can overflow in a number of interesting ways. All of those are unsigned,
38 // and therefore defined behavior. Still, apply some sane bounds.
39 const size_t intMax = std::numeric_limits<int>::max();
40 if (alloc > intMax)
41 alloc = intMax;
42
43 Heap::MemberData *m;
44 if (old) {
45 const size_t oldSize = sizeof(Heap::MemberData) + (old->values.size - 1) * sizeof(Value);
46 if (oldSize > alloc)
47 alloc = oldSize;
48 m = e->memoryManager->allocManaged<MemberData>(size: alloc);
49 // no write barrier required here
50 memcpy(dest: m, src: old, n: oldSize);
51 } else {
52 m = e->memoryManager->allocManaged<MemberData>(size: alloc);
53 m->init();
54 }
55
56 m->values.alloc = static_cast<uint>((alloc - sizeof(Heap::MemberData) + sizeof(Value))/sizeof(Value));
57 m->values.size = m->values.alloc;
58 return m;
59}
60

source code of qtdeclarative/src/qml/jsruntime/qv4memberdata.cpp